code
stringlengths
17
6.64M
def compute_columns(datum_names: List[str], datum_types: List[str], requested_annotations: List[str], cuboid_datum: Optional[str]=None, with_ontology_table: bool=True) -> List[str]: "Method to parse requested datums, types, and annotations into keys for fetching from wicker.\n\n Parameters\n ----------\n datum_names: List\n List of datum names to load.\n\n datum_types: List\n List of datum types i.e, 'image', 'point_cloud', 'radar_point_cloud'.\n\n requested_annotations: List\n List of annotation types to load i.e. 'bounding_box_3d', 'depth' etc.\n\n cuboid_datum: str, default: None\n Optional datum name to restrict loading of bounding_box_3d annotations to a single datum.\n For example if we do not desire to load bounding_box_3d for both the lidar datum and every\n image datum, we would set this field to 'lidar'.\n\n with_ontology_table: bool, default: True\n Flag to add loading of ontology tables\n\n Returns\n -------\n columns_to_load: List\n A list of keys to fetch from wicker.\n " columns_to_load = ['scene_index', 'scene_uri', 'sample_index_in_scene'] for (datum_name, datum_type) in zip(datum_names, datum_types): fields = ['timestamp', 'pose', 'extrinsics', 'datum_type'] if (datum_type == 'image'): fields.extend(['intrinsics', 'rgb', 'distortion']) elif (datum_type == 'point_cloud'): fields.extend(['point_cloud', 'extra_channels']) elif (datum_type == 'radar_point_cloud'): fields.extend(['point_cloud', 'extra_channels', 'velocity', 'covariance']) if (requested_annotations is not None): fields.extend(requested_annotations) for annotation in fields: if ((datum_type, annotation) in ILLEGAL_COMBINATIONS): continue if ((annotation == 'bounding_box_3d') and (cuboid_datum is not None)): if (datum_name != cuboid_datum): continue columns_to_load.append(gen_wicker_key(datum_name, annotation)) if (with_ontology_table and (requested_annotations is not None)): for ann in requested_annotations: if (ann in ANNOTATION_REGISTRY): if (ann == 'depth'): continue columns_to_load.append(gen_wicker_key('ontology', ann)) return columns_to_load
class DGPS3Dataset(S3Dataset): '\n S3Dataset for data stored in dgp synchronized scene format in wicker. This is a baseclass\n inteded for use with all DGP wicker datasets. It handles conversion from wicker binary formats\n to DGP datum and annotation objects\n ' def __init__(self, *args: Any, wicker_sample_index: Optional[List[List[int]]]=None, **kwargs: Any) -> None: "S3Dataset for data stored in dgp synchronized scene format in wicker. This is a baseclass\n inteded for use with all DGP wicker datasets. It handles conversion from wicker binary formats\n to DGP datum and annotation objects.\n\n Parameters\n ----------\n wicker_sample_index: List[List[int]], default: None\n A mapping from this dataset's index to a list of wicker indexes. If None, a mappind for all\n single frames will be generated. \n " super().__init__(*args, **kwargs) self.wicker_sample_index: List[List[int]] = [[]] if (wicker_sample_index is None): N = super().__len__() self.wicker_sample_index = [[k] for k in range(N)] else: self.wicker_sample_index = wicker_sample_index self._ontology_table: Optional[Dict[(str, Ontology)]] = None @property def ontology_table(self) -> Optional[Dict[(str, Ontology)]]: 'Return the ontology table if any.\n\n Returns\n -------\n ontology_table: Dict\n The ontology table or None if an ontology table has not been assigned with self._create_ontology_table.\n ' return self._ontology_table def __len__(self) -> int: ' Number of samples in dataset\n\n Returns\n -------\n length: int\n The number of samples in the dataset\n ' return len(self.wicker_sample_index) def _create_ontology_table(self, raw_wicker_sample: Dict[(str, Any)]) -> Dict[(str, Ontology)]: '"Create ontology table based on given wicker item.\n\n Parameters\n ----------\n raw_wicker_sample: Dict\n A raw wicker sample containing ontology keys, ex: ontology___bounding_box_3d etc.\n\n Returns\n -------\n ontology_table: Dict\n A dictionary keyed by annotation name holding an ontology for that annotation.\n ' ontology_table = {} ontology_keys = [key for key in raw_wicker_sample if ('ontology' in key)] for key in ontology_keys: (_, ontology_type) = parse_wicker_key(key) serializer = OntologySerializer(ontology_type) ontology_table[ontology_type] = serializer.unserialize(raw_wicker_sample[key]) return ontology_table def _process_raw_wicker_sample(self, raw_wicker_sample: Dict[(str, Any)]) -> Dict[(str, Dict[(str, Any)])]: 'Parse raw data from wicker into datums/fields.\n\n Parameters\n ----------\n raw_wicker_sample: Dict\n The raw output from wicker S3Dataset.\n\n Returns\n -------\n sample_dict: Dict[str, Dict[str,Any]]\n A dictionary keyed by datum name holding DGP SynchronizedScene like datums.\n ' ontology_table = self._create_ontology_table(raw_wicker_sample) if (self.ontology_table is None): self._ontology_table = ontology_table else: assert (set(ontology_table.keys()) == set(self.ontology_table.keys())) for field in self.ontology_table: assert (self.ontology_table[field] == ontology_table[field]) output_dict: Dict[(str, Dict[(str, Any)])] = defaultdict(OrderedDict) for (key, raw) in raw_wicker_sample.items(): if (key in ['scene_uri', 'scene_index', 'sample_index_in_scene']): output_dict['meta'][key] = raw continue if ('ontology' in key): continue (datum_name, field) = parse_wicker_key(key) serializer = FIELD_TO_WICKER_SERIALIZER[field]() if hasattr(serializer, 'ontology'): serializer.ontology = self.ontology_table[field] output_dict[datum_name]['datum_name'] = datum_name output_dict[datum_name][field] = serializer.unserialize(raw) if ('meta' in output_dict): output_dict['meta']['datum_name'] = 'meta' output_dict['meta']['datum_type'] = 'meta' return output_dict def __getitem__(self, index: int) -> List[Dict[(str, Dict[(str, Any)])]]: '"Get the dataset item at index.\n\n Parameters\n ----------\n index: int\n The index to get.\n\n Returns\n -------\n context: List\n A context window with samples as dicts keyed by datum name.\n ' wicker_samples = self.wicker_sample_index[index] context = [] for idx in wicker_samples: raw = super().__getitem__(idx) sample = self._process_raw_wicker_sample(raw) context.append(sample) return context
def gen_wicker_key(datum_name: str, field: str) -> str: "Generate a key from a datum name and field i.e 'rgb', 'pose' etc\n\n Parameters\n ----------\n datum_name: str\n The name of the datum\n\n field: str\n The field of the datum\n\n Returns\n -------\n key: str\n The wicker key name formed from datum_name and field\n " return f'{datum_name}{WICKER_KEY_SEPARATOR}{field}'
def parse_wicker_key(key: str) -> Tuple[(str, str)]: 'Parse a wicker dataset key into a datum and field combination\n\n Parameters\n ----------\n key: str\n The wicker key name formed from datum_name and field\n\n Returns\n -------\n datum_name: str\n The name of the datum\n\n field: str\n The field of the datum\n ' return tuple(key.split(WICKER_KEY_SEPARATOR))
def wicker_types_from_sample(sample: List[List[Dict]], ontology_table: Optional[Dict]=None, skip_camera_cuboids: bool=True) -> Dict[(str, Any)]: 'Get the wicker keys and types from an existing dgp sample.\n\n Parameters\n ----------\n sample: List[List[Dict]]\n SynchronizedSceneDataset-style sample datum.\n\n ontology_table: Dict, default: None\n A dictionary mapping annotation key(s) to Ontology(s).\n\n skip_camera_cuboids: bool, default: True\n Flag to skip processing bounding_box_3d for image datums\n\n Returns\n -------\n wicker_types: List\n The Wicker schema types corresponding to the `wicker_keys`.\n ' wicker_types = {} for datum in sample: datum_name = datum['datum_name'] datum_type = datum['datum_type'] for (k, v) in datum.items(): if ((k == 'datum_name') or ((datum_type, k) in ILLEGAL_COMBINATIONS)): continue if ((datum_type == 'image') and (k == 'bounding_box_3d') and skip_camera_cuboids): continue key = gen_wicker_key(datum_name, k) serializer = FIELD_TO_WICKER_SERIALIZER[k] wicker_types[key] = serializer().schema(key, v) if (ontology_table is not None): for (k, v) in ontology_table.items(): key = gen_wicker_key('ontology', k) wicker_types[key] = ws.OntologySerializer(k).schema(key, v) wicker_types['scene_index'] = IntField('scene_index') wicker_types['sample_index_in_scene'] = IntField('sample_index_in_scene') wicker_types['scene_uri'] = StringField('scene_uri') return wicker_types
def dgp_to_wicker_sample(sample: List[List[Dict]], wicker_keys: List[str], scene_index: Optional[int], sample_index_in_scene: Optional[int], ontology_table: Optional[Dict], scene_uri: Optional[str]) -> Dict: 'Convert a DGP sample to the Wicker format.\n\n Parameters\n ----------\n sample: List[List[Dict]]\n SynchronizedSceneDataset-style sample datum.\n\n wicker_keys: List[str]\n Keys to be used in Wicker.\n\n scene_index: int, default: None\n Index of current scene.\n\n sample_index_in_scene: int, default: None\n Index of the sample in current scene.\n\n ontology_table: Dict, default: None\n A dictionary mapping annotation key(s) to Ontology(s).\n\n scene_uri: str\n Relative path to this specific scene json file.\n\n Returns\n -------\n wicker_sample: Dict\n DGP sample in the Wicker format.\n ' wicker_sample = {} for datum in sample: datum_name = datum['datum_name'] for (k, v) in datum.items(): key = gen_wicker_key(datum_name, k) if (key not in wicker_keys): continue serializer = FIELD_TO_WICKER_SERIALIZER[k] wicker_sample[key] = serializer().serialize(v) if (ontology_table is not None): for (k, v) in ontology_table.items(): key = gen_wicker_key('ontology', k) wicker_sample[key] = ws.OntologySerializer(k).serialize(v) wicker_sample['scene_index'] = scene_index wicker_sample['sample_index_in_scene'] = sample_index_in_scene wicker_sample['scene_uri'] = scene_uri return wicker_sample
def get_scenes(scene_dataset_json: str, data_uri: Optional[str]=None) -> List[Tuple[(int, str, str)]]: 'Get all the scene files from scene_dataset_json\n\n Parameters\n ----------\n scene_dataset_json: str\n Path ot dataset json in s3 or local.\n\n data_uri: str, default: None\n Optional path to location of raw data. If None, we assume the data is stored alongside scene_dataset_json.\n\n Returns\n -------\n scenes: List[int,str,str]\n A list of tuples(<index>, <split name>, <path to scene.json>) for each scene in scene_dataset_json.\n ' if (data_uri is None): data_uri = os.path.dirname(scene_dataset_json) dataset = open_pbobject(scene_dataset_json, SceneDataset) split_id_to_name = {dataset_pb2.TRAIN: 'train', dataset_pb2.VAL: 'val', dataset_pb2.TEST: 'test', dataset_pb2.TRAIN_OVERFIT: 'train_overfit'} scenes = [] for k in dataset.scene_splits: files = [(split_id_to_name[k], os.path.join(data_uri, f)) for f in dataset.scene_splits[k].filenames] scenes.extend(files) logger.info(f'found {len(files)} in split {split_id_to_name[k]}') logger.info(f'found {len(scenes)} in {scene_dataset_json}') scenes = [(k, *x) for (k, x) in enumerate(scenes)] return scenes
def chunk_scenes(scenes: List[Tuple[(int, str, str)]], max_len: int=200, chunk_size: int=100) -> List[Tuple[(int, str, str, Tuple[(int, int)])]]: 'Split each scene into chunks of max length chunk_size samples.\n\n Parameters\n ----------\n scenes: List[str,str]\n List of scene split/path tuples.\n\n max_len: int, default: 200\n Expected maximum length of each scene.\n\n chunk_size: int, default: 100\n Maximum size of each chunk.\n\n Returns\n -------\n scenes: List[Tuple[int,str,str,Tuple[int,int]]]\n A list of scenes with (<index>, <split>, <path>, (<sample index start>, <sample index end>)) tuples\n ' new_scenes = [] for c in range((max_len // chunk_size)): chunk = (int((c * chunk_size)), int(((c + 1) * chunk_size))) new_scenes.extend([(*x, chunk) for x in scenes]) return new_scenes
def local_spark() -> pyspark.SparkContext: 'Generate a spark context for local testing of small datasets\n\n Returns\n -------\n spark_context: A spark context\n ' spark = pyspark.sql.SparkSession.builder.master('local[*]').appName('dgp2wicker').config('spark.driver.memory', '56G').config('spark.executor.memory', '56G').config('spark.dynamicAllocation.enabled', 'true').config('spark.dynamicAllocation.maxExecutors', '4').config('spark.dynamicAllocation.minExecutors', '1').config('spark.executor.cores', '1').config('spark.task.maxFailures', '4').config('spark.driver.maxResultSize', '4G').config('spark.python.worker.memory', '24G').getOrCreate() return spark.sparkContext
def ingest_dgp_to_wicker(scene_dataset_json: str, wicker_dataset_name: str, wicker_dataset_version: str, dataset_kwargs: Dict, spark_context: pyspark.SparkContext, pipeline: Optional[List[Callable]]=None, max_num_scenes: int=None, max_len: int=1000, chunk_size: int=1000, skip_camera_cuboids: bool=True, num_partitions: int=None, num_repartitions: int=None, is_pd: bool=False, data_uri: str=None, alternate_scene_uri: str=None) -> Dict[(str, int)]: "Ingest DGP dataset into Wicker datastore\n\n Parameters\n ----------\n scene_dataset_json: str\n Path to scenes dataset json.\n\n wicker_dataset_name: str\n Name of the dataset used in Wicker datastore.\n\n wicker_dataset_version: str\n Semantic version of the dataset (i.e., xxx.xxx.xxx).\n\n spark_context: pyspark.SparkContext, default: None\n A spark context. If None, will generate one using dgp2wicker.ingest.local_spark() and default settings\n\n dataset_kwargs: dict\n Arguments for dataloader.\n\n spark_context: A spark context, default: None\n A spark context. If None, will use a local spark context.\n\n pipeline: List[Callable], default: None\n A list of transformations to apply to every sample.\n\n max_num_scenes: int, default: None\n An optional upper bound on the number of scenes to process. Typically used for testing.\n\n max_len: int, default: 1000\n Maximum expected length of a scene\n\n chunk_size: int, default: 1000\n Chunk size to split scenes into. If less than max_len, the same scene will be downloaded\n multiple times.\n\n skip_camera_cuboids: bool, default: True\n Optional to flag to skip converting 'bounding_box_3d' for image_datum types.\n\n num_partitions: int, default: None\n Number of partitions to map scenes over. If None, defaults to number of scenes\n\n num_repartitions: int, default: None\n Number of partitions to shuffle all samples over. If none, defaults to num_scenes*5\n\n is_pd: bool, default: False\n Flag to indicate if the dataset to laod is a Parallel Domain dataset. If true, the scenes\n will be loaded with ParallelDomainScene with use_virtual_cameras set to False.\n\n data_uri: str\n Optional path to raw data location if raw data is not stored alongside scene_dataset_json.\n\n alternate_scene_uri:\n If provided, download additional scene data from an alternate location. This happens before the\n scene containing scene_json_uri is downloaded and everything in scene_json_uri's location will\n overwrite this. This also expects that the scenes are structured as /<scene_dir>/scene.json\n and so any addtional data for this scene should be in alternate_scene_uri/<scene_dir>.\n This is useful if for some reason a scene json and an additional annotation are in a different location\n than the rest of the scene data.\n\n " def open_scene(scene_json_uri: str, temp_dir: str, dataset_kwargs: Dict[(str, Any)], alternate_scene_uri: Optional[str]=None) -> Union[(SynchronizedScene, ParallelDomainScene)]: 'Utility function to download a scene and open it\n\n Parameters\n ----------\n scene_json_uri: str\n Path to scene json.\n\n temp_dir: str\n Path to directory to store scene if downloaded from s3. Not used if scene_json is local\n\n dataset_kwargs: dict\n Arguments for data loader. i.e, datum_names, requested annotations etc. If this is a PD scene\n the dataset_kwargs should contain an `is_pd` key set to True.\n\n alternate_scene_uri: str, default = None\n Optional additional location to sync\n\n Returns\n -------\n dataset: A DGP dataset\n ' scene_dir_uri = os.path.dirname(scene_json_uri) scene_json = os.path.basename(scene_json_uri) if scene_dir_uri.startswith('s3://'): local_path = temp_dir assert (not temp_dir.startswith('s3')), f'{temp_dir}' if (alternate_scene_uri is not None): alternate_scene_dir = os.path.join(alternate_scene_uri, os.path.basename(scene_dir_uri)) logger.info(f'downloading additional scene data from {alternate_scene_dir} to {local_path}') sync_dir(alternate_scene_dir, local_path) logger.info(f'downloading scene from {scene_dir_uri} to {local_path}') sync_dir(scene_dir_uri, local_path) else: local_path = scene_dir_uri logger.info(f'Using local scene from {scene_dir_uri}') dataset_kwargs = deepcopy(dataset_kwargs) dataset_kwargs['scene_json'] = os.path.join(local_path, scene_json) is_pd = dataset_kwargs.pop('is_pd') if is_pd: dataset_kwargs['use_virtual_camera_datums'] = False dataset = ParallelDomainScene(**dataset_kwargs) else: dataset = SynchronizedScene(**dataset_kwargs) return dataset def process_scene(partition: List[Tuple[(int, str, str, Tuple[(int, int)])]], dataset_kwargs: Dict, pipeline: List[Callable], wicker_types: List[str]) -> Generator[(Tuple[(str, Any)], None, None)]: 'Main task to parrallelize. This takes a list of scene chunks and sequentially\n downloads the scene to a temporary directory, opens the scene, applies any transformations,\n and yields wicker serialized samples.\n\n Parameters\n ----------\n partition: tuple\n A list of scenes to process with this spark partition.\n Each entry should be a tuple with <index in dataset, split, scene_uri, (chunk start, chunk end)>.\n\n dataset_kwargs: Dict\n Arguments for data loader. See open_scene for details.\n\n pipeline: List[Callable]\n List of transformations to apply to samples.\n\n wicker_types: List\n A list of keys in the wicker schema.\n\n Returns\n -------\n wicker_sample: (split, sample)\n Yields a wicker converted sample\n ' for scene_info in partition: yield_count = 0 (global_scene_index, split, scene_json_uri, chunk) = scene_info (chunk_start, chunk_end) = chunk scene_dir_uri = os.path.dirname(scene_json_uri) scene_json = os.path.basename(scene_json_uri) st = time.time() with tempfile.TemporaryDirectory() as temp_dir: try: dataset = open_scene(scene_json_uri, temp_dir, dataset_kwargs, alternate_scene_uri=alternate_scene_uri) except Exception as e: logger.error(f'Failed to open {scene_json_uri}, skipping...') logger.error(e) traceback.print_exc() continue ontology_table = dataset.dataset_metadata.ontology_table for i in range(chunk_start, chunk_end): if (i >= len(dataset)): break try: (_, sample_index_in_scene, _) = dataset.dataset_item_index[i] sample = dataset[i][0] for transform in pipeline: sample = transform(sample) wicker_sample = dgp_to_wicker_sample(sample, wicker_keys=wicker_types.keys(), scene_index=int(global_scene_index), sample_index_in_scene=int(sample_index_in_scene), ontology_table=ontology_table, scene_uri=os.path.join(os.path.basename(scene_dir_uri), scene_json)) assert (wicker_sample is not None) for (k, v) in wicker_sample.items(): assert (v is not None), f'{k} has invalid wicker serialized item' yield_count += 1 (yield (split, deepcopy(wicker_sample))) except Exception as e: logger.error('failed to get sample, skipping...') logger.error(e) traceback.print_exc() continue dt = (time.time() - st) logger.info(f'Finished {global_scene_index} {split}/{scene_dir_uri}, chunk:{chunk_start}->{chunk_end}. Yielded {yield_count}, took {dt:.2f} seconds') dataset_kwargs['is_pd'] = is_pd if (pipeline is None): pipeline = [] scenes = get_scenes(scene_dataset_json, data_uri=data_uri) if (max_num_scenes is not None): scenes = scenes[:int(max_num_scenes)] if (num_partitions is None): num_partitions = len(scenes) if (num_repartitions is None): num_repartitions = (5 * len(scenes)) (_, _, scene_json_uri) = scenes[0] with tempfile.TemporaryDirectory() as temp_dir: dataset = open_scene(scene_json_uri, temp_dir, dataset_kwargs, alternate_scene_uri=alternate_scene_uri) logger.info(f'Got dataset with {len(dataset)} samples') sample = dataset[0][0] for transform in pipeline: sample = transform(sample) ontology_table = dataset.dataset_metadata.ontology_table wicker_types = wicker_types_from_sample(sample=sample, ontology_table=ontology_table, skip_camera_cuboids=skip_camera_cuboids) wicker_dataset_schema = wicker.schema.DatasetSchema(primary_keys=['scene_index', 'sample_index_in_scene'], fields=list(wicker_types.values())) scenes = chunk_scenes(scenes, max_len=max_len, chunk_size=chunk_size) scene_shuffle_idx = np.random.permutation(len(scenes)).tolist() scenes = [scenes[i] for i in scene_shuffle_idx] if (len(scenes) < 2): wsp.SPARK_PARTITION_SIZE = 3 if (spark_context is None): spark_context = local_spark() process = partial(process_scene, dataset_kwargs=dataset_kwargs, pipeline=pipeline, wicker_types=wicker_types) rdd = spark_context.parallelize(scenes, numSlices=num_partitions).mapPartitions(process).repartition(num_repartitions) return wsp.persist_wicker_dataset(wicker_dataset_name, wicker_dataset_version, wicker_dataset_schema, rdd)
class CustomInstallCommand(install): 'Custom install command' def run(self): install.run(self)
class CustomDevelopCommand(develop): 'Custom develop command' def run(self): develop.run(self)
def s3_is_configured(): 'Utility to check if there is a valid s3 dataset path configured' wicker_config_path = os.getenv('WICKER_CONFIG_PATH', os.path.expanduser('~/wickerconfig.json')) with open(wicker_config_path, 'r', encoding='utf-8') as f: wicker_config = json.loads(f.read()) return wicker_config['aws_s3_config']['s3_datasets_path'].startswith('s3://')
class TestDDGP2Wicker(unittest.TestCase): def setUp(self): 'Create a local dgp dataset for testing' self.dataset = SynchronizedSceneDataset(TEST_WICKER_DATASET_JSON, split='train', datum_names=['LIDAR', 'CAMERA_01'], forward_context=0, backward_context=0, requested_annotations=('bounding_box_2d', 'bounding_box_3d')) def test_keys(self): 'Sanity check the key parsing' (datum_key, datum_field) = ('CAMERA_01', 'timestamp') key = gen_wicker_key(datum_key, datum_field) (datum_key2, datum_field2) = parse_wicker_key(key) assert (datum_key == datum_key2) assert (datum_field == datum_field2) def test_schema(self): 'Sanity check the schema generation' sample = self.dataset[0][0] ontology_table = self.dataset.dataset_metadata.ontology_table wicker_types = wicker_types_from_sample(sample, ontology_table, skip_camera_cuboids=True) expected_keys = ['CAMERA_01____timestamp', 'CAMERA_01____rgb', 'CAMERA_01____intrinsics', 'CAMERA_01____distortion', 'CAMERA_01____extrinsics', 'CAMERA_01____pose', 'CAMERA_01____bounding_box_2d', 'CAMERA_01____datum_type', 'LIDAR____timestamp', 'LIDAR____extrinsics', 'LIDAR____pose', 'LIDAR____point_cloud', 'LIDAR____extra_channels', 'LIDAR____bounding_box_3d', 'LIDAR____datum_type', 'ontology____bounding_box_2d', 'ontology____bounding_box_3d', 'scene_index', 'sample_index_in_scene', 'scene_uri'] assert (set(expected_keys) == set(wicker_types.keys())) def test_conversion(self): 'Test serializers and conversion to wicker formats' sample = self.dataset[0][0] ontology_table = self.dataset.dataset_metadata.ontology_table wicker_types = wicker_types_from_sample(sample, ontology_table, skip_camera_cuboids=True) sample_dict = {datum['datum_name']: datum for datum in sample} wicker_sample = dgp_to_wicker_sample(sample=sample, wicker_keys=list(wicker_types.keys()), scene_index=0, sample_index_in_scene=0, ontology_table=ontology_table, scene_uri='scene/scene.json') assert (set(wicker_sample.keys()) == set(wicker_types.keys())) for (key, raw) in wicker_sample.items(): if (key in ('scene_index', 'sample_index_in_scene', 'scene_uri')): continue (datum_key, datum_field) = parse_wicker_key(key) if (datum_key == 'ontology'): serializer = ws.OntologySerializer(datum_field) elif (datum_field in FIELD_TO_WICKER_SERIALIZER): serializer = FIELD_TO_WICKER_SERIALIZER[datum_field]() else: print(f'{key} not supported') continue if hasattr(serializer, 'ontology'): serializer.ontology = ontology_table[datum_field] unserialized = serializer.unserialize(raw) if (datum_field == 'rgb'): assert isinstance(unserialized, Image) org_im = np.array(sample_dict[datum_key]['rgb']) new_im = np.array(unserialized) psnr = cv2.PSNR(org_im, new_im) assert (psnr > 40) elif (datum_field in ('point_cloud', 'extra_channels', 'intrinsics')): org = sample_dict[datum_key][datum_field] assert np.allclose(org, unserialized) elif (datum_field in ('pose', 'extrinsics')): org = sample_dict[datum_key][datum_field] assert np.allclose(org.matrix, unserialized.matrix) elif (datum_key != 'ontology'): org = sample_dict[datum_key][datum_field] assert (org == unserialized) @unittest.skipUnless(s3_is_configured(), 'Requires S3') def test_ingest(self): 'Test ingestion' wsp.SPARK_PARTITION_SIZE = 12 output = ingest_dgp_to_wicker(scene_dataset_json=TEST_WICKER_DATASET_JSON, wicker_dataset_name=TEST_WICKER_DATASET_NAME, wicker_dataset_version=TEST_WICKER_DATASET_VERSION, dataset_kwargs=TEST_WICKER_DATASET_KWARGS, spark_context=None, pipeline=None, max_num_scenes=None, max_len=1000, chunk_size=1000, skip_camera_cuboids=True, num_partitions=None, num_repartitions=None, is_pd=False, data_uri=None) assert (output['train'] == 6) assert (output['val'] == 6) @unittest.skipUnless(s3_is_configured(), 'Requires S3') def test_ingest_cli(self): 'Test ingestion via the cli' wsp.SPARK_PARTITION_SIZE = 12 cmd = f'''--scene-dataset-json {TEST_WICKER_DATASET_JSON} ''' cmd += f'''--wicker-dataset-name {TEST_WICKER_DATASET_NAME} ''' cmd += f'''--wicker-dataset-version {TEST_WICKER_DATASET_VERSION} ''' cmd += '--datum-names CAMERA_01,LIDAR\n' cmd += '--requested-annotations bounding_box_2d,bounding_box_3d\n' cmd += '--only-annotated-datums\n' cmd += '--half-size-images\n' cmd += '--add-lidar-points' runner = CliRunner() result = runner.invoke(ingest, cmd) assert (result.exit_code == 0) @unittest.skipUnless(s3_is_configured(), 'Requires S3') def test_dataset(self): 'Test That we can read a dataset from wicker' self.test_ingest() columns = compute_columns(datum_names=['CAMERA_01', 'LIDAR'], datum_types=['image', 'point_cloud'], requested_annotations=['bounding_box_2d', 'bounding_box_3d'], cuboid_datum='LIDAR', with_ontology_table=True) dataset = DGPS3Dataset(dataset_name=TEST_WICKER_DATASET_NAME, dataset_version=TEST_WICKER_DATASET_VERSION, dataset_partition_name='train', columns_to_load=columns) sample = dataset[0][0] expected_camera_fields = {'extrinsics', 'bounding_box_2d', 'pose', 'datum_name', 'datum_type', 'distortion', 'intrinsics', 'rgb', 'timestamp'} expected_lidar_fields = {'pose', 'datum_name', 'datum_type', 'extra_channels', 'point_cloud', 'bounding_box_3d', 'extrinsics', 'timestamp'} assert (set(sample['CAMERA_01'].keys()) == expected_camera_fields) assert isinstance(sample['CAMERA_01']['rgb'], Image) assert (set(sample['LIDAR'].keys()) == expected_lidar_fields) assert (set(dataset.ontology_table.keys()) == {'bounding_box_2d', 'bounding_box_3d'})
class BaseAgentDataset(): 'A base class representing a Agent Dataset. Provides utilities for parsing and slicing\n DGP format agent datasets.\n\n Parameters\n ----------\n Agent_dataset_metadata: DatasetMetadata\n Dataset metadata object that encapsulates dataset-level agents metadata for\n both operating modes (scene or JSON).\n\n agent_groups: list[AgentContainer]\n List of AgentContainer objects to be included in the dataset.\n\n split: str, default: None\n Split of dataset to read ("train" | "val" | "test" | "train_overfit").\n If the split is None, the split type is not known and the dataset can\n be used for unsupervised / self-supervised learning.\n ' def __init__(self, Agent_dataset_metadata, agent_groups, split=None): logging.info(f'Instantiating dataset with {len(agent_groups)} scenes.') self.Agent_dataset_metadata = Agent_dataset_metadata self.split = split self.agent_groups = agent_groups self.dataset_item_index = self._build_item_index() @staticmethod def _load_agents_data(agent_group, ontology_table, feature_ontology_table): 'Call loading method from agent_group to load agent slice data and agent track data.\n\n Parameters\n ----------\n agent_group: AgentContainer\n Group of agents from a scene.\n\n ontology_table: dict[str->dgp.annotations.Ontology]\n A dictionary mapping annotation type key(s) to Ontology(s)\n\n feature_ontology_table: dict, default: None\n A dictionary mapping feature type key(s) to Ontology(s).\n\n Returns\n -------\n agent_group: AgentContainer\n An AgentContainer objects with agents loaded.\n ' agent_group.load_agent_data(ontology_table, feature_ontology_table) return agent_group @staticmethod def _extract_agent_groups_from_agent_dataset_json(agent_dataset_json, requested_agent_type, split='train', use_diskcache=True): 'Extract agent container objects from the agent dataset JSON\n for the appropriate split.\n\n Parameters\n ----------\n agent_dataset_json: str\n Path of the dataset.json\n\n requested_agent_type: str, default: \'train\'\n Split of dataset to read ("train" | "val" | "test" | "train_overfit").\n\n split: str, default: \'train\'\n Split of dataset to read ("train" | "val" | "test" | "train_overfit").\n\n use_diskcache: bool, default: True\n If True, cache ScenePb2 object using diskcache. If False, save the object in memory.\n NOTE: Setting use_diskcache to False would exhaust the memory if have a large number of scenes in this\n scene dataset.\n\n Returns\n -------\n scene_containers: list\n List of SceneContainer objects.\n ' assert (split in ('train', 'val', 'test', 'train_overfit')) split_enum = {'train': dataset_pb2.TRAIN, 'val': dataset_pb2.VAL, 'test': dataset_pb2.TEST, 'train_overfit': dataset_pb2.TRAIN_OVERFIT}[split] if (not agent_dataset_json.startswith('s3://')): assert os.path.exists(agent_dataset_json), 'Path {} does not exist'.format(agent_dataset_json) logging.info('Loading dataset from {}, split={}'.format(agent_dataset_json, split)) agent_dataset_root = os.path.dirname(agent_dataset_json) agent_dataset = open_pbobject(agent_dataset_json, AgentsPb2) logging.info('Generating agents for split={}'.format(split)) st = time.time() agent_jsons = [os.path.join(agent_dataset_root, _f) for _f in list(agent_dataset.agents_splits[split_enum].filenames)] with Pool(cpu_count()) as proc: agent_containers = list(proc.map(partial(AgentDataset._get_agent_container, requested_agent_type=requested_agent_type, use_diskcache=use_diskcache), agent_jsons)) logging.info('Scene generation completed in {:.2f}s'.format((time.time() - st))) return agent_containers @staticmethod def _get_agent_container(agent_json, requested_agent_type, use_diskcache=True): 'Extract scene objects and calibration from the scene dataset JSON\n for the appropriate split.\n\n Parameters\n ----------\n agent_json: str\n Path of the agent_scene.json\n\n requested_agent_type: str, default: \'train\'\n Split of dataset to read ("train" | "val" | "test" | "train_overfit").\n\n use_diskcache: bool, default: True\n If True, cache ScenePb2 object using diskcache. If False, save the object in memory.\n NOTE: Setting use_diskcache to False would exhaust the memory if have a large number of scenes in this\n scene dataset.\n\n Returns\n -------\n scene_containers: list\n List of SceneContainer objects.\n ' agent_dir = os.path.dirname(agent_json) logging.debug(f'Loading agents from {agent_json}') agent_container = AgentContainer(agent_json, requested_agent_type, directory=agent_dir, use_diskcache=use_diskcache) return agent_container def _build_item_index(self): 'Builds an index of dataset items that refer to the scene index,\n sample index and selected datum names. __getitem__ indexes into this look up table.\n\n Returns\n -------\n item_index: list\n List of dataset items that contain index into\n (scene_idx, sample_idx_in_scene, (datum_name_1, datum_name_2, ...)).\n ' raise NotImplementedError def __len__(self): 'Return the length of the dataset.' raise NotImplementedError def __getitem__(self, index): 'Get the dataset item at index.' raise NotImplementedError def __hash__(self): 'Hashes the dataset instance that is consistent across Python instances.' logging.debug('Hashing dataset with dataset directory, split and datum-index') return int(hashlib.sha1(((self.Agent_dataset_metadata.directory.encode() + str(self.dataset_item_index).encode()) + str(self.split).encode())).hexdigest(), 16)
class AgentContainer(): 'Object-oriented container for holding agent information from a scene.\n ' RANDOM_STR = ''.join([str(random.randint(0, 9)) for _ in range(5)]) cache_suffix = os.environ.get('DGP_SCENE_CACHE_SUFFIX', RANDOM_STR) cache_dir = os.path.join(DGP_CACHE_DIR, f'dgp_diskcache_{cache_suffix}') AGENT_GROUP_CACHE = Cache(cache_dir) def __init__(self, agent_file_path, requested_agent_type, directory=None, use_diskcache=True): 'Initialize a scene with a agent group object and optionally provide the\n directory containing the agent.json to gather additional information\n for directory-based dataset loading mode.\n\n Parameters\n ----------\n agent_file_path: str\n Path to the agent object containing agent tracks and agent slices.\n\n requested_agent_type: str, default: \'train\'\n Split of dataset to read ("train" | "val" | "test" | "train_overfit").\n\n directory: str, default: None\n Directory containing scene_<sha1>.json.\n\n use_diskcache: bool, default: True\n If True, cache AgentGroupPb2 object using diskcache. If False, save the object in memory.\n NOTE: Setting use_diskcache to False would exhaust the memory if have a large number of scenes.\n ' self.agent_file_path = agent_file_path self.directory = directory self.use_diskcache = use_diskcache self.requested_agent_type = requested_agent_type self._agent_group = None self.sample_id_to_agent_snapshots = {} self.instance_id_to_agent_snapshots = {} logging.debug(f'Loading agent-based dataset from {self.directory}') @property def agent_group(self): ' Returns agent group.\n - If self.use_diskcache is True: returns the cached `_agent_group` if available, otherwise load the\n agent group and cache it.\n - If self.use_diskcache is False: returns `_agent_group` in memory if the instance has attribute\n `_agent_group`, otherwise load the agent group and save it in memory.\n NOTE: Setting use_diskcache to False would exhaust the memory if have a large number of agent groups.\n ' if self.use_diskcache: if (self.agent_file_path in AgentContainer.AGENT_GROUP_CACHE): _agent_group = AgentContainer.AGENT_GROUP_CACHE.get(self.agent_file_path) if (_agent_group is not None): return _agent_group _agent_group = open_pbobject(self.agent_file_path, AgentGroupPb2) AgentContainer.AGENT_GROUP_CACHE.add(self.agent_file_path, _agent_group) return _agent_group else: if (self._agent_group is None): self._agent_group = open_pbobject(self.agent_file_path, AgentGroupPb2) return self._agent_group def __repr__(self): return 'AgentContainer[{}][agents: {}]'.format(self.directory, len(self.instance_id_to_agent_snapshots)) @property def ontology_files(self): "Returns the ontology files for the agent group.\n\n Returns\n -------\n ontology_files: dict\n Maps annotation_key -> filename.\n\n For example:\n filename = agent.ontology_files['bounding_box_2d']\n " ontology_files = {ANNOTATION_TYPE_ID_TO_KEY[ann_id]: os.path.join(self.directory, ONTOLOGY_FOLDER, '{}.json'.format(f)) for (ann_id, f) in self.agent_group.agent_ontologies.items()} return ontology_files @property def feature_ontology_files(self): "Returns the feature ontology files for a agent group.\n\n Returns\n -------\n ontology_files: dict\n Maps annotation_key -> filename.\n\n For example:\n filename = agent.feature_ontology_files['agent_3d']\n " feature_ontology_files = {FEATURE_TYPE_ID_TO_KEY[feature_id]: os.path.join(self.directory, FEATURE_ONTOLOGY_FOLDER, '{}.json'.format(f)) for (feature_id, f) in self.agent_group.feature_ontologies.items()} return feature_ontology_files @property @lru_cache(maxsize=None) def metadata_index(self): 'Helper for building metadata index.\n\n TODO: Need to verify that the hashes are unique, and these lru-cached\n properties are consistent across disk-cached reads.\n ' logging.debug(f'Building metadata index for agent group {self.agent_file_path}') agent_group = self.agent_group return {'log_id': agent_group.log, 'agent_group_name': agent_group.name, 'agent_group_description': agent_group.description} def agent_slice(self, sample_id): 'Return AgentSnapshotList in a frame.' return self.sample_id_to_agent_snapshots[sample_id] def agent_track(self, instance_id): 'Return AgentSnapshotList in a track.' return self.instance_id_to_agent_snapshots[instance_id] def load_agent_data(self, ontology_table, feature_ontology_table): 'Load agent slice data and agent track data.\n\n Parameters\n ----------\n ontology_table: dict[str->dgp.annotations.Ontology]\n Ontology object *per annotation type*.\n The original ontology table.\n {\n "bounding_box_2d": BoundingBoxOntology[<ontology_sha>],\n "autolabel_model_1/bounding_box_2d": BoundingBoxOntology[<ontology_sha>],\n "semantic_segmentation_2d": SemanticSegmentationOntology[<ontology_sha>]\n "bounding_box_3d": BoundingBoxOntology[<ontology_sha>],\n }\n\n feature_ontology_table: dict[str->dgp.features.FeatureOntology]\n Ontology object *per feature type*.\n The original feature ontology table.\n {\n "agent_2d": AgentFeatureOntology,\n "agent_3d": AgentFeatureOntology,\n "ego_intention": AgentFeatureOntology\n }\n\n ' agent_slices_path = self.agent_group.agents_slices_file agent_tracks_path = self.agent_group.agent_tracks_file if ((agent_slices_path is None) or (agent_tracks_path is None)): logging.debug('Skipping agent_group {} due to missing agents'.format(self.agent_group)) return [] agents_slices_file = os.path.join(self.directory, agent_slices_path) agent_tracks_file = os.path.join(self.directory, agent_tracks_path) agents_slices_pb2 = open_pbobject(agents_slices_file, AgentsSlicesPb2) agent_tracks_pb2 = open_pbobject(agent_tracks_file, AgentTracksPb2) agent_ontology = ontology_table[AGENT_TYPE_TO_ANNOTATION_TYPE[self.requested_agent_type]] for agent_slice in agents_slices_pb2.agents_slices: agents_list = AGENT_REGISTRY[self.requested_agent_type].load(agent_slice.agent_snapshots, agent_ontology, feature_ontology_table) self.sample_id_to_agent_snapshots[agent_slice.slice_id.index] = agents_list for track in agent_tracks_pb2.agent_tracks: self.instance_id_to_agent_snapshots[track.instance_id] = AGENT_REGISTRY[self.requested_agent_type].load(track.agent_snapshots, agent_ontology, feature_ontology_table)
class AgentDataset(BaseAgentDataset): 'Dataset for agent-centric prediction or planning use cases, works just like normal SynchronizedSceneDataset,\n but guaranteeing trajectory of main agent is present in any fetched sample.\n\n Parameters\n ----------\n scene_dataset_json: str\n Full path to the scene dataset json holding collections of paths to scene json.\n\n agents_dataset_json: str\n Full path to the agent dataset json holding collections of paths to scene json.\n\n split: str, default: \'train\'\n Split of dataset to read ("train" | "val" | "test" | "train_overfit").\n\n datum_names: list, default: None\n Select list of datum names for synchronization (see self.select_datums(datum_names)).\n\n requested_agent_type: tuple, default: None\n Tuple of agent type, i.e. (\'agent_2d\', \'agent_3d\'). Only one type of agent can be requested.\n\n requested_main_agent_classes: tuple, default: \'car\'\n Tuple of main agent types, i.e. (\'car\', \'pedestrian\').\n The string should be the same as dataset_metadata.ontology_table.\n\n forward_context: int, default: 0\n Forward context in frames [T+1, ..., T+forward]\n\n backward_context: int, default: 0\n Backward context in frames [T-backward, ..., T-1]\n\n min_main_agent_forward: int, default: 0\n Minimum forward samples for main agent. The main-agent will be guaranteed to appear\n minimum samples in forward context; i.e., the main-agent will appear in number of\n [min_main_agent_forward, forward_context] samples in forward direction.\n\n min_main_agent_backward: int, default: 0\n Minimum backward samples for main agent. The main-agent will be guaranteed to appear\n minimum samples in backward context; i.e., the main-agent will appear in number of\n [min_main_agent_backward, backward_context] samples in backward direction.\n\n generate_depth_from_datum: str, default: None\n Datum name of the point cloud. If is not None, then the depth map will be generated for the camera using\n the desired point cloud.\n\n batch_per_agent: bool, default: False\n Include whole trajectory of an agent in each batch fetch, this is designed to be used for inference.\n If True, backward_context = forward_context = 0 implicitly.\n\n use_diskcache: bool, default: True\n If True, cache ScenePb2 object using diskcache. If False, save the object in memory.\n NOTE: Setting use_diskcache to False would exhaust the memory if have a large number of scenes.\n\n ' def __init__(self, scene_dataset_json, agents_dataset_json, split='train', datum_names=None, requested_agent_type='agent_3d', requested_main_agent_classes=('car',), requested_feature_types=None, requested_autolabels=None, forward_context=0, backward_context=0, min_main_agent_forward=0, min_main_agent_backward=0, generate_depth_from_datum=None, batch_per_agent=False, use_diskcache=True): if (requested_agent_type is not None): assert (requested_agent_type in AGENT_REGISTRY), 'Invalid agent type requested!' self.requested_agent_type = requested_agent_type else: self.requested_agent_type = () if (requested_feature_types is not None): assert all(((requested_feature_type in ALL_FEATURE_TYPES) for requested_feature_type in requested_feature_types)), 'Invalid feature type requested!' self.requested_feature_types = requested_feature_types else: self.requested_feature_types = () self.batch_per_agent = batch_per_agent self.generate_depth_from_datum = generate_depth_from_datum datum_names = (sorted(set(datum_names)) if datum_names else set([])) self.selected_datums = [_d.lower() for _d in datum_names] if (len(self.selected_datums) != 0): self.synchronized_dataset = SynchronizedSceneDataset(scene_dataset_json, split=split, backward_context=backward_context, requested_autolabels=requested_autolabels, forward_context=forward_context, datum_names=self.selected_datums, use_diskcache=use_diskcache) assert ((min_main_agent_backward <= backward_context) and (min_main_agent_forward <= forward_context)), 'Provide valid minimum context for main agent.' if batch_per_agent: backward_context = forward_context = 0 self.forward_context = forward_context self.backward_context = backward_context self.min_main_agent_forward = (min_main_agent_forward if min_main_agent_forward else forward_context) self.min_main_agent_backward = (min_main_agent_backward if min_main_agent_forward else backward_context) agent_groups = AgentDataset._extract_agent_groups_from_agent_dataset_json(agents_dataset_json, requested_agent_type, split=split) agent_metadata = AgentMetadata.from_agent_containers(agent_groups, requested_agent_type, requested_feature_types) name_to_id = agent_metadata.ontology_table[AGENT_TYPE_TO_ANNOTATION_TYPE[requested_agent_type]].name_to_id self.requested_main_agent_classes = tuple([(name_to_id[atype] + 1) for atype in requested_main_agent_classes]) with Pool(cpu_count()) as proc: agent_groups = list(proc.map(partial(self._load_agents_data, ontology_table=agent_metadata.ontology_table, feature_ontology_table=agent_metadata.feature_ontology_table), agent_groups)) super().__init__(agent_metadata, agent_groups=agent_groups) if batch_per_agent: self._build_agent_index() def _build_agent_index(self): 'Build an index of agents grouped by instance id. This index is used to index dataset by agent track.\n\n Returns\n -------\n agent_item_index: list\n List of dataset items that contain index into.\n (main_agent_id, scene_idx, sample_idx_in_scene_start, sample_idx_in_scene_end, [datum_name ...]).\n ' self.dataset_agent_index = defaultdict(list) logging.info('Building agent index, this will take a while.') for index in range(len(self.dataset_item_index)): (scene_idx, sample_idx_in_scene, main_agent_id, datum_names) = self.dataset_item_index[index] main_agent_id_and_scene_idx = f'{str(scene_idx)}_{str(main_agent_id)}' if (main_agent_id_and_scene_idx not in self.dataset_agent_index): self.dataset_agent_index[main_agent_id_and_scene_idx] = [(- 1), (- 1), float('inf'), (- 1), []] self.dataset_agent_index[main_agent_id_and_scene_idx] = [main_agent_id, scene_idx, min(sample_idx_in_scene, self.dataset_agent_index[main_agent_id_and_scene_idx][2]), max(sample_idx_in_scene, self.dataset_agent_index[main_agent_id_and_scene_idx][3]), datum_names] self.dataset_agent_index = [v for (k, v) in self.dataset_agent_index.items()] def _build_item_index(self): 'Builds an index of dataset items that refer to the scene index, agent index,\n sample index and datum_within_scene index. This refers to a particular dataset\n split. __getitem__ indexes into this look up table.\n\n Synchronizes at the sample-level and only adds sample indices if context frames are available.\n This is enforced by adding sample indices that fall in (bacwkard_context, N-forward_context) range.\n\n Returns\n -------\n item_index: list\n List of dataset items that contain index into\n (scene_idx, sample_idx_in_scene, (main_agent_idx, main_agent_id), [datum_name ...]).\n ' logging.info(f'Building index for {self.__class__.__name__}, this will take a while.') st = time.time() with Pool(cpu_count()) as proc: item_index = proc.starmap(self._item_index_for_scene, [(scene_idx,) for scene_idx in range(len(self.agent_groups))]) logging.info(f'Index built in {(time.time() - st):.2f}s.') assert (len(item_index) > 0), 'Failed to index items in the dataset.' item_index = list(itertools.chain.from_iterable(item_index)) item_index = [item for item in item_index if (item is not None)] item_lengths = [len(item_tup) for item_tup in item_index] assert all([(l == item_lengths[0]) for l in item_lengths]), 'All sample items are not of the same length, datum names might be missing.' return item_index def _item_index_for_scene(self, scene_idx): agent_group = self.agent_groups[scene_idx] num_samples = len(agent_group.sample_id_to_agent_snapshots) instance_id_to_trajectory = defaultdict(list) instance_id_to_segment_idx = defaultdict(int) for (sample_id, agents_slice) in agent_group.sample_id_to_agent_snapshots.items(): for agent_snapshot in agents_slice: if (agent_snapshot.class_id not in self.requested_main_agent_classes): continue instance_index_prefix = f'{str(scene_idx)}_{str(agent_snapshot.instance_id)}' segment_idx_start = (instance_id_to_segment_idx[instance_index_prefix] if (instance_index_prefix in instance_id_to_segment_idx) else 0) for segment_idx in range(segment_idx_start, num_samples): instance_index_id = f'{instance_index_prefix}_{segment_idx}' if ((instance_index_id in instance_id_to_trajectory) and ((instance_id_to_trajectory[instance_index_id][(- 1)][1] + 1) != sample_id)): continue instance_id_to_trajectory[instance_index_id].append((scene_idx, sample_id, agent_snapshot.instance_id, self.selected_datums)) instance_id_to_segment_idx[instance_index_prefix] = segment_idx break item_index = [] trajectory_min_length = ((self.min_main_agent_backward + self.min_main_agent_forward) + 1) for id_ in instance_id_to_trajectory: trajectory_length = len(instance_id_to_trajectory[id_]) if (trajectory_length >= trajectory_min_length): first_sample_idx = instance_id_to_trajectory[id_][0][1] final_sample_idx = instance_id_to_trajectory[id_][(- 1)][1] beg = (self.min_main_agent_backward if ((self.min_main_agent_backward + first_sample_idx) > self.backward_context) else self.backward_context) end = (trajectory_length - (self.min_main_agent_forward if ((self.min_main_agent_forward + final_sample_idx) < num_samples) else self.forward_context)) if (end > beg): item_index.append(instance_id_to_trajectory[id_][beg:end]) return list(itertools.chain.from_iterable(item_index)) def __len__(self): 'Return the length of the dataset.' return (len(self.dataset_agent_index) if self.batch_per_agent else len(self.dataset_item_index)) def __getitem__(self, index): 'Get the dataset item at index.\n\n Parameters\n ----------\n index: int\n Index of item to get.\n\n Returns\n -------\n datums: list of OrderedDict\n List of datum_data at (scene_idx, sample_idx_in_scene, datum_name). \n Datum_names can be image, point_cloud, radar_point_cloud, etc.\n\n agents: AgentSnapshotList\n AgentSnapshotList in a frame.\n\n main_agent_id: int\n Instance ID of main agent.\n\n main_agent_idx: int \n Index of main agent in AgentSlice.\n\n Returns a list of OrderedDict(s).\n Outer list corresponds to temporal ordering of samples. Each element is\n a OrderedDict(s) corresponding to synchronized datums and agents.\n ' assert (self.dataset_item_index is not None), 'Index is not built, select datums before getting elements.' if self.batch_per_agent: (main_agent_id, scene_idx, sample_idx_in_scene_start, sample_idx_in_scene_end, datum_names) = self.dataset_agent_index[index] else: (scene_idx, sample_idx_in_scene, main_agent_id, datum_names) = self.dataset_item_index[index] sample_idx_in_scene_start = (sample_idx_in_scene - self.backward_context) sample_idx_in_scene_end = (sample_idx_in_scene + self.forward_context) context_window = [] for qsample_idx_in_scene in range(sample_idx_in_scene_start, (sample_idx_in_scene_end + 1)): datums = [] if (len(datum_names) > 0): for datum_name in datum_names: datum_data = self.synchronized_dataset.get_datum_data(scene_idx, qsample_idx_in_scene, datum_name) datums.append(datum_data) agents_in_sample = self.agent_groups[scene_idx].agent_slice(qsample_idx_in_scene) instance_matched = [(agent.instance_id == main_agent_id) for agent in agents_in_sample] main_agent_idx_in_agents_slice = (instance_matched.index(True) if any(instance_matched) else None) synchronized_sample = OrderedDict({'datums': datums, 'agents': agents_in_sample, 'main_agent_id': main_agent_id, 'main_agent_idx': main_agent_idx_in_agents_slice}) context_window.append(synchronized_sample) return context_window
class AgentDatasetLite(BaseAgentDataset): 'Dataset for agent-centric prediction or planning use cases. It provide two mode of accessing agent, by track\n and by frame. If \'batch_per_agent\' is set true, then the data iterate per track, note, the length of the track\n could vary. Otherwise, the data iterate per frame and each sample contains all agents in the frame.\n\n Parameters\n ----------\n scene_dataset_json: str\n Full path to the scene dataset json holding collections of paths to scene json.\n\n agents_dataset_json: str\n Full path to the agent dataset json holding collections of paths to scene json.\n\n split: str, default: \'train\'\n Split of dataset to read ("train" | "val" | "test" | "train_overfit").\n\n datum_names: list, default: None\n Select list of datum names for synchronization (see self.select_datums(datum_names)).\n\n requested_agent_type: tuple, default: None\n Tuple of agent type, i.e. (\'agent_2d\', \'agent_3d\'). Only one type of agent can be requested.\n\n requested_main_agent_classes: tuple, default: \'car\'\n Tuple of main agent types, i.e. (\'car\', \'pedestrian\').\n The string should be the same as dataset_metadata.ontology_table.\n\n forward_context: int, default: 0\n Forward context in frames [T+1, ..., T+forward]\n\n backward_context: int, default: 0\n Backward context in frames [T-backward, ..., T-1]\n\n batch_per_agent: bool, default: False\n Include whole trajectory of an agent in each batch fetch.\n If True, backward_context = forward_context = 0 implicitly.\n\n use_diskcache: bool, default: True\n If True, cache ScenePb2 object using diskcache. If False, save the object in memory.\n NOTE: Setting use_diskcache to False would exhaust the memory if have a large number of scenes.\n\n ' def __init__(self, scene_dataset_json, agents_dataset_json, split='train', datum_names=None, requested_agent_type='agent_3d', requested_main_agent_classes=('car',), requested_feature_types=None, requested_autolabels=None, forward_context=0, backward_context=0, batch_per_agent=False, use_diskcache=True): if (requested_agent_type is not None): assert (requested_agent_type in AGENT_REGISTRY), 'Invalid agent type requested!' self.requested_agent_type = requested_agent_type else: self.requested_agent_type = () if (requested_feature_types is not None): assert all(((requested_feature_type in ALL_FEATURE_TYPES) for requested_feature_type in requested_feature_types)), 'Invalid feature type requested!' self.requested_feature_types = requested_feature_types else: self.requested_feature_types = () self.batch_per_agent = batch_per_agent datum_names = (sorted(set(datum_names)) if datum_names else set([])) self.selected_datums = [_d.lower() for _d in datum_names] if (len(self.selected_datums) != 0): self.synchronized_dataset = SynchronizedSceneDataset(scene_dataset_json, split=split, backward_context=backward_context, requested_autolabels=requested_autolabels, forward_context=forward_context, datum_names=self.selected_datums, use_diskcache=use_diskcache) if batch_per_agent: backward_context = forward_context = 0 self.forward_context = forward_context self.backward_context = backward_context agent_groups = AgentDataset._extract_agent_groups_from_agent_dataset_json(agents_dataset_json, requested_agent_type, split=split) agent_metadata = AgentMetadata.from_agent_containers(agent_groups, requested_agent_type, requested_feature_types) name_to_id = agent_metadata.ontology_table[AGENT_TYPE_TO_ANNOTATION_TYPE[requested_agent_type]].name_to_id self.requested_main_agent_classes = tuple([(name_to_id[atype] + 1) for atype in requested_main_agent_classes]) with Pool(cpu_count()) as proc: agent_groups = list(proc.map(partial(self._load_agents_data, ontology_table=agent_metadata.ontology_table, feature_ontology_table=agent_metadata.feature_ontology_table), agent_groups)) super().__init__(agent_metadata, agent_groups=agent_groups) def _build_item_index(self): 'Builds an index of dataset items that refer to the scene index, agent index,\n sample index and datum_within_scene index. This refers to a particular dataset\n split. __getitem__ indexes into this look up table.\n\n Synchronizes at the sample-level and only adds sample indices if context frames are available.\n This is enforced by adding sample indices that fall in (bacwkard_context, N-forward_context) range.\n\n Returns\n -------\n item_index: list\n List of dataset items that contain index into\n (scene_idx, sample_idx_in_scene, (main_agent_idx, main_agent_id), [datum_name ...]).\n ' logging.info(f'Building index for {self.__class__.__name__}, this will take a while.') st = time.time() if self.batch_per_agent: with Pool(cpu_count()) as proc: item_index = proc.starmap(partial(self._agent_index_for_scene, selected_datums=self.selected_datums), [(scene_idx, agent_group) for (scene_idx, agent_group) in enumerate(self.agent_groups)]) else: with Pool(cpu_count()) as proc: item_index = proc.starmap(partial(self._item_index_for_scene, backward_context=self.backward_context, forward_context=self.forward_context, selected_datums=self.selected_datums), [(scene_idx, agent_group) for (scene_idx, agent_group) in enumerate(self.agent_groups)]) logging.info(f'Index built in {(time.time() - st):.2f}s.') assert (len(item_index) > 0), 'Failed to index items in the dataset.' item_index = list(itertools.chain.from_iterable(item_index)) item_index = [item for item in item_index if (item is not None)] item_lengths = [len(item_tup) for item_tup in item_index] assert all([(l == item_lengths[0]) for l in item_lengths]), 'All sample items are not of the same length, datum names might be missing.' return item_index @staticmethod def _item_index_for_scene(scene_idx, agent_group, backward_context, forward_context, selected_datums): sample_range = np.arange(backward_context, (len(agent_group.sample_id_to_agent_snapshots) - forward_context)) scene_item_index = [(scene_idx, sample_idx, selected_datums) for sample_idx in sample_range] return scene_item_index @staticmethod def _agent_index_for_scene(scene_idx, agent_group, selected_datums): scene_item_index = [(scene_idx, instance_id, selected_datums) for instance_id in agent_group.instance_id_to_agent_snapshots] return scene_item_index def __len__(self): 'Return the length of the dataset.' return len(self.dataset_item_index) def __getitem__(self, index): 'Get the dataset item at index.\n\n Parameters\n ----------\n index: int\n Index of item to get.\n\n Returns\n -------\n datums: list of OrderedDict\n List of datum_data at (scene_idx, sample_idx_in_scene, datum_name).\n Datum_names can be image, point_cloud, radar_point_cloud, etc.\n\n Agents: AgentSnapshotList\n A list of agent snapshots.\n\n Returns a list of OrderedDict(s).\n Outer list corresponds to temporal ordering of samples. Each element is\n a OrderedDict(s) corresponding to synchronized datums and agents.\n ' assert (self.dataset_item_index is not None), 'Index is not built, select datums before getting elements.' context_window = [] if self.batch_per_agent: (scene_idx, instance_id, datum_names) = self.dataset_item_index[index] track = self.agent_groups[scene_idx].agent_track(instance_id) ontology = track.ontology type_of_track = type(track) for agent_snapshot in track: qsample_idx_in_scene = agent_snapshot.sample_idx datums = [] if (len(datum_names) > 0): for datum_name in datum_names: datum_data = self.synchronized_dataset.get_datum_data(scene_idx, qsample_idx_in_scene, datum_name) datums.append(datum_data) synchronized_sample = OrderedDict({'datums': datums, 'agents': type_of_track(ontology, [agent_snapshot])}) context_window.append(synchronized_sample) else: (scene_idx, sample_idx_in_scene, datum_names) = self.dataset_item_index[index] sample_idx_in_scene_start = (sample_idx_in_scene - self.backward_context) sample_idx_in_scene_end = (sample_idx_in_scene + self.forward_context) for qsample_idx_in_scene in range(sample_idx_in_scene_start, (sample_idx_in_scene_end + 1)): datums = [] if (len(datum_names) > 0): for datum_name in datum_names: datum_data = self.synchronized_dataset.get_datum_data(scene_idx, qsample_idx_in_scene, datum_name) datums.append(datum_data) agents_in_sample = self.agent_groups[scene_idx].agent_slice(qsample_idx_in_scene) synchronized_sample = OrderedDict({'datums': datums, 'agents': agents_in_sample}) context_window.append(synchronized_sample) return context_window
class AgentMetadata(): 'A Wrapper agents metadata class to support two entrypoints for agents dataset\n (reading from agents.json).\n\n Parameters\n ----------\n agent_groups: list[AgentContainer]\n List of AgentContainer objects to be included in the dataset.\n\n directory: str\n Directory of agent_dataset.\n\n feature_ontology_table: dict, default: None\n A dictionary mapping feature type key(s) to Ontology(s), i.e.:\n {\n "agent_2d": AgentFeatureOntology[<ontology_sha>],\n "agent_3d": AgentFeatureOntology[<ontology_sha>]\n }\n ontology_table: dict, default: None\n A dictionary mapping annotation key(s) to Ontology(s), i.e.:\n {\n "bounding_box_2d": BoundingBoxOntology[<ontology_sha>],\n "autolabel_model_1/bounding_box_2d": BoundingBoxOntology[<ontology_sha>],\n "semantic_segmentation_2d": SemanticSegmentationOntology[<ontology_sha>]\n }\n ' def __init__(self, agent_groups, directory, feature_ontology_table=None, ontology_table=None): assert (directory is not None), 'Dataset directory is required, and cannot be None.' self.agent_groups = agent_groups self.directory = directory self.feature_ontology_table = feature_ontology_table self.ontology_table = ontology_table @classmethod def from_agent_containers(cls, agent_containers, requested_agent_types=None, requested_feature_types=None): "Load DatasetMetadata from Scene Dataset JSON.\n\n Parameters\n ----------\n agent_containers: list of AgentContainer\n List of AgentContainer objects.\n\n requested_agent_types: List(str)\n List of agent types, such as ['agent_3d', 'agent_2d']\n\n requested_feature_types: List(str)\n List of feature types, such as ['parked_car', 'ego_intention']\n\n Raises\n ------\n Exception\n Raised if an ontology from an agent container is not in our ontology registry.\n " assert len(agent_containers), 'SceneContainers is empty.' requested_agent_types = ([] if (requested_agent_types is None) else requested_agent_types) if ((not requested_agent_types) or (not requested_feature_types)): return cls(agent_containers, directory=os.path.dirname(agent_containers[0].directory), feature_ontology_table={}, ontology_table={}) feature_ontology_table = {} dataset_ontology_table = {} logging.info('Building ontology table.') st = time.time() unique_scenes = {os.path.basename(f): agent_container for agent_container in agent_containers for (_, _, filenames) in os.walk(os.path.join(agent_container.directory, FEATURE_ONTOLOGY_FOLDER)) for f in filenames} for (_, agent_container) in unique_scenes.items(): for (feature_ontology_key, ontology_file) in agent_container.feature_ontology_files.items(): if (feature_ontology_key in FEATURE_ONTOLOGY_REGISTRY): if (feature_ontology_key not in requested_feature_types): continue feature_ontology_spec = FEATURE_ONTOLOGY_REGISTRY[feature_ontology_key] if (feature_ontology_spec is None): continue if (feature_ontology_key not in feature_ontology_table): feature_ontology_table[feature_ontology_key] = feature_ontology_spec.load(ontology_file) else: assert (feature_ontology_table[feature_ontology_key] == feature_ontology_spec.load(ontology_file)), 'Inconsistent ontology for key {}.'.format(feature_ontology_key) else: raise Exception(f'Ontology for key {feature_ontology_key} not found in registry!') for (ontology_key, ontology_file) in agent_container.ontology_files.items(): if (ontology_key in ONTOLOGY_REGISTRY): if (ANNOTATION_TYPE_TO_AGENT_TYPE[ontology_key] not in requested_agent_types): continue ontology_spec = ONTOLOGY_REGISTRY[ontology_key] if (ontology_spec is None): continue if (ontology_key not in dataset_ontology_table): dataset_ontology_table[ontology_key] = ontology_spec.load(ontology_file) else: assert (dataset_ontology_table[ontology_key] == ontology_spec.load(ontology_file)), 'Inconsistent ontology for key {}.'.format(ontology_key) else: raise Exception(f'Ontology for key {ontology_key} not found in registry!') logging.info(f'Ontology table built in {(time.time() - st):.2f}s.') return cls(agent_containers, directory=os.path.dirname(agent_containers[0].directory), feature_ontology_table=feature_ontology_table, ontology_table=dataset_ontology_table) @staticmethod def get_dataset_splits(agents_json): 'Get a list of splits in the agent_json.json.\n\n Parameters\n ----------\n agents_json: str\n Full path to the agents json holding agent metadata, agent splits.\n\n Returns\n -------\n agents_splits: list of str\n List of agents splits (train | val | test | train_overfit).\n\n ' assert agents_json.endswith('.json'), 'Please provide a dataset.json file.' agents = open_pbobject(agents_json, AgentsPb2) return [dataset_pb2.DatasetSplit.DESCRIPTOR.values_by_number[split_index].name.lower() for split_index in agents.agents_splits]
class _ParallelDomainDataset(_SynchronizedDataset): 'Dataset for PD data. Works just like normal SynchronizedSceneDataset,\n with special keyword datum name "lidar". When this datum is requested,\n all lidars are coalesced into a single "lidar" datum.\n\n Parameters\n ----------\n dataset_metadata: DatasetMetadata\n Dataset metadata, populated from scene dataset JSON\n\n scenes: list[SceneContainer], default: None\n List of SceneContainers parsed from scene dataset JSON\n\n datum_names: list, default: None\n Select list of datum names for synchronization (see self.select_datums(datum_names)).\n\n requested_annotations: tuple, default: None\n Tuple of annotation types, i.e. (\'bounding_box_2d\', \'bounding_box_3d\'). Should be equivalent\n to directory containing annotation from dataset root.\n\n requested_autolabels: tuple[str], default: None\n Tuple of annotation types similar to `requested_annotations`, but associated with a particular autolabeling model.\n Expected format is "<model_id>/<annotation_type>"\n\n forward_context: int, default: 0\n Forward context in frames [T+1, ..., T+forward]\n\n backward_context: int, default: 0\n Backward context in frames [T-backward, ..., T-1]\n\n generate_depth_from_datum: str, default: None\n Datum name of the point cloud. If is not None, then the depth map will be generated for the camera using\n the desired point cloud.\n\n only_annotated_datums: bool, default: False\n If True, only datums with annotations matching the requested annotation types are returned.\n\n use_virtual_camera_datums: bool, default: True\n If True, uses virtual camera datums. See dgp.datasets.pd_dataset.VIRTUAL_CAMERA_DATUM_NAMES for more details.\n\n accumulation_context: dict, default None\n Dictionary of datum names containing a tuple of (backward_context, forward_context) for sensor accumulation.\n For example, \'accumulation_context={\'lidar\':(3,1)} accumulates lidar points over the past three time steps and\n one forward step. Only valid for lidar and radar datums.\n\n transform_accumulated_box_points: bool, default: False\n Flag to use cuboid pose and instance id to warp points when using lidar accumulation.\n\n autolabel_root: str, default: None\n Path to autolabels.\n ' def __init__(self, dataset_metadata, scenes=None, datum_names=None, requested_annotations=None, requested_autolabels=None, forward_context=0, backward_context=0, generate_depth_from_datum=None, only_annotated_datums=False, use_virtual_camera_datums=True, accumulation_context=None, transform_accumulated_box_points=False, autolabel_root=None): self.coalesce_point_cloud = ((datum_names is not None) and (COALESCED_LIDAR_DATUM_NAME in datum_names)) self.use_virtual_camera_datums = use_virtual_camera_datums if self.coalesce_point_cloud: self._datum_name_to_index = {datum_name: datum_idx for (datum_idx, datum_name) in enumerate(datum_names)} new_datum_names = [datum_name for datum_name in datum_names if (COALESCED_LIDAR_DATUM_NAME != datum_name)] new_datum_names.extend(LIDAR_DATUM_NAMES) if use_virtual_camera_datums: new_datum_names.extend(VIRTUAL_CAMERA_DATUM_NAMES) if ((accumulation_context is not None) and (COALESCED_LIDAR_DATUM_NAME in accumulation_context)): acc_context = accumulation_context.pop(COALESCED_LIDAR_DATUM_NAME) updated_acc = {datum_name: acc_context for datum_name in LIDAR_DATUM_NAMES} accumulation_context.update(updated_acc) logging.info('Datum names with lidar datums={}'.format(new_datum_names)) datum_names = new_datum_names super().__init__(dataset_metadata=dataset_metadata, scenes=scenes, datum_names=datum_names, requested_annotations=requested_annotations, requested_autolabels=requested_autolabels, forward_context=forward_context, backward_context=backward_context, generate_depth_from_datum=generate_depth_from_datum, only_annotated_datums=only_annotated_datums, accumulation_context=accumulation_context, transform_accumulated_box_points=transform_accumulated_box_points, autolabel_root=autolabel_root) def coalesce_pc_data(self, items): 'Combine set of point cloud datums into a single point cloud.\n\n Parameters\n ----------\n items: list\n List of OrderedDict, containing parsed point cloud or image data.\n\n Returns\n -------\n coalesced_pc: OrderedDict\n OrderedDict containing coalesced point cloud and associated metadata.\n ' pc_items = [item for item in items if (POINT_CLOUD_KEY in item)] assert self.coalesce_point_cloud assert (len(pc_items) == len(LIDAR_DATUM_NAMES)) if (len(self.requested_autolabels) > 0): logging.warning('autolabels were requested, however point cloud coalesce does not support coalescing autolabels') coalesced_pc = OrderedDict() (X_V_merged, bbox_3d_V_merged, instance_ids_merged) = ([], [], []) total_bounding_box_3d = 0 for item in pc_items: X_S = item[POINT_CLOUD_KEY] p_VS = item['extrinsics'] X_V_merged.append((p_VS * X_S)) if ('bounding_box_3d' in item): total_bounding_box_3d += len(item['bounding_box_3d']) for bbox_3d in item['bounding_box_3d']: if (bbox_3d.instance_id not in instance_ids_merged): instance_ids_merged.append(bbox_3d.instance_id) bbox_3d_V_merged.append((p_VS * bbox_3d)) coalesced_pc['datum_name'] = COALESCED_LIDAR_DATUM_NAME coalesced_pc['timestamp'] = pc_items[0]['timestamp'] coalesced_pc[POINT_CLOUD_KEY] = np.vstack(X_V_merged) coalesced_pc['extra_channels'] = np.vstack([item['extra_channels'] for item in pc_items]) coalesced_pc['extrinsics'] = Pose() p_LS = pc_items[0]['pose'] p_VS = pc_items[0]['extrinsics'] p_LV = (p_LS * p_VS.inverse()) coalesced_pc['pose'] = p_LV if len(bbox_3d_V_merged): ontology = pc_items[0]['bounding_box_3d'].ontology coalesced_pc['bounding_box_3d'] = BoundingBox3DAnnotationList(ontology, bbox_3d_V_merged) if ('bounding_box_3d' in coalesced_pc.keys()): assert (len(coalesced_pc['bounding_box_3d']) <= total_bounding_box_3d) return coalesced_pc def coalesce_sample(self, sample): 'Coalesce a point cloud for a single sample.\n\n Parameters\n ----------\n sample: list\n List of OrderedDict, containing parsed point cloud or image data.\n ' items_dict = OrderedDict() items_dict[self._datum_name_to_index[COALESCED_LIDAR_DATUM_NAME]] = self.coalesce_pc_data(sample) items_dict.update({self._datum_name_to_index[item['datum_name']]: item for item in sample if ((POINT_CLOUD_KEY not in item) and (item['datum_name'] not in VIRTUAL_CAMERA_DATUM_NAMES))}) if self.use_virtual_camera_datums: virtual_camera_datums = [item for item in sample if (item['datum_name'] in VIRTUAL_CAMERA_DATUM_NAMES)] virtual_camera_datums = {(idx + len(items_dict)): item for (idx, item) in enumerate(virtual_camera_datums)} items_dict.update(virtual_camera_datums) indices_and_items_sorted = sorted(list(items_dict.items()), key=(lambda tup: tup[0])) aligned_items = list(map((lambda tup: tup[1]), indices_and_items_sorted)) return aligned_items def __getitem__(self, idx): sample_data = super().__getitem__(idx) if self.coalesce_point_cloud: if ((self.forward_context > 0) or (self.backward_context > 0)): sample_data = [self.coalesce_sample(t_item) for t_item in sample_data] else: sample_data = [self.coalesce_sample(sample_data[0])] return sample_data
class ParallelDomainSceneDataset(_ParallelDomainDataset): '\n Refer to SynchronizedSceneDataset for parameters.\n ' def __init__(self, scene_dataset_json, split='train', datum_names=None, requested_annotations=None, requested_autolabels=None, backward_context=0, forward_context=0, generate_depth_from_datum=None, only_annotated_datums=False, use_virtual_camera_datums=True, skip_missing_data=False, accumulation_context=None, dataset_root=None, transform_accumulated_box_points=False, use_diskcache=True, autolabel_root=None): if (not use_diskcache): logging.warning('Instantiating a dataset with use_diskcache=False may exhaust memory with a large dataset.') scenes = BaseDataset._extract_scenes_from_scene_dataset_json(scene_dataset_json, split, requested_autolabels, is_datums_synchronized=True, skip_missing_data=skip_missing_data, dataset_root=dataset_root, use_diskcache=use_diskcache, autolabel_root=autolabel_root) dataset_metadata = DatasetMetadata.from_scene_containers(scenes, requested_annotations, requested_autolabels, autolabel_root=autolabel_root) super().__init__(dataset_metadata, scenes=scenes, datum_names=datum_names, requested_annotations=requested_annotations, requested_autolabels=requested_autolabels, backward_context=backward_context, forward_context=forward_context, generate_depth_from_datum=generate_depth_from_datum, only_annotated_datums=only_annotated_datums, use_virtual_camera_datums=use_virtual_camera_datums, accumulation_context=accumulation_context, transform_accumulated_box_points=transform_accumulated_box_points, autolabel_root=autolabel_root)
class ParallelDomainScene(_ParallelDomainDataset): '\n Refer to SynchronizedScene for parameters.\n ' def __init__(self, scene_json, datum_names=None, requested_annotations=None, requested_autolabels=None, backward_context=0, forward_context=0, generate_depth_from_datum=None, only_annotated_datums=False, use_virtual_camera_datums=True, skip_missing_data=False, accumulation_context=None, transform_accumulated_box_points=False, use_diskcache=True, autolabel_root=None): if (not use_diskcache): logging.warning('Instantiating a dataset with use_diskcache=False may exhaust memory with a large dataset.') scene = BaseDataset._extract_scene_from_scene_json(scene_json, requested_autolabels, is_datums_synchronized=True, skip_missing_data=skip_missing_data, use_diskcache=use_diskcache, autolabel_root=autolabel_root) dataset_metadata = DatasetMetadata.from_scene_containers([scene], requested_annotations, requested_autolabels, autolabel_root=autolabel_root) super().__init__(dataset_metadata, scenes=[scene], datum_names=datum_names, requested_annotations=requested_annotations, requested_autolabels=requested_autolabels, backward_context=backward_context, forward_context=forward_context, generate_depth_from_datum=generate_depth_from_datum, only_annotated_datums=only_annotated_datums, use_virtual_camera_datums=use_virtual_camera_datums, accumulation_context=accumulation_context, transform_accumulated_box_points=transform_accumulated_box_points)
class _SynchronizedDataset(BaseDataset): 'Multi-modal dataset with sample-level synchronization.\n See BaseDataset for input parameters for the parent class.\n\n Parameters\n ----------\n dataset_metadata: DatasetMetadata\n Dataset metadata, populated from scene dataset JSON\n\n scenes: list[SceneContainer], default: None\n List of SceneContainers parsed from scene dataset JSON\n\n datum_names: list, default: None\n Select list of datum names for synchronization (see self.select_datums(datum_names)).\n\n requested_annotations: tuple, default: None\n Tuple of annotation types, i.e. (\'bounding_box_2d\', \'bounding_box_3d\'). Should be equivalent\n to directory containing annotation from dataset root.\n\n requested_autolabels: tuple[str], default: None\n Tuple of annotation types similar to `requested_annotations`, but associated with a particular autolabeling model.\n Expected format is "<model_id>/<annotation_type>"\n\n backward_context: int, default: 0\n Backward context in frames [T-backward, ..., T-1]\n\n forward_context: int, default: 0\n Forward context in frames [T+1, ..., T+forward]\n\n accumulation_context: dict, default None\n Dictionary of datum names containing a tuple of (backward_context, forward_context) for sensor accumulation. For example, \'accumulation_context={\'lidar\':(3,1)}\n accumulates lidar points over the past three time steps and one forward step. Only valid for lidar and radar datums.\n\n generate_depth_from_datum: str, default: None\n Datum name of the point cloud. If is not None, then the depth map will be generated for the camera using\n the desired point cloud.\n\n only_annotated_datums: bool, default: False\n If True, only datums with annotations matching the requested annotation types are returned.\n\n transform_accumulated_box_points: bool, default: False\n Flag to use cuboid pose and instance id to warp points when using lidar accumulation.\n\n autolabel_root: str, default: None\n Path to autolabels.\n\n ignore_raw_datum: Optional[list[str]], default: None\n Optionally pass a list of datum types to skip loading their raw data (but still load their annotations). For\n example, ignore_raw_datum=[\'image\'] will skip loading the image rgb data. The rgb key will be set to None.\n This is useful when only annotations or extrinsics are needed. Allowed values are any combination of\n \'image\',\'point_cloud\',\'radar_point_cloud\' \n ' def __init__(self, dataset_metadata, scenes=None, datum_names=None, requested_annotations=None, requested_autolabels=None, forward_context=0, backward_context=0, accumulation_context=None, generate_depth_from_datum=None, only_annotated_datums=False, transform_accumulated_box_points=False, autolabel_root=None, ignore_raw_datum=None): self.set_context(backward=backward_context, forward=forward_context, accumulation_context=accumulation_context) self.generate_depth_from_datum = generate_depth_from_datum self.only_annotated_datums = (only_annotated_datums if (requested_annotations or requested_autolabels) else False) self.transform_accumulated_box_points = transform_accumulated_box_points super().__init__(dataset_metadata, scenes=scenes, datum_names=datum_names, requested_annotations=requested_annotations, requested_autolabels=requested_autolabels, autolabel_root=autolabel_root, ignore_raw_datum=ignore_raw_datum) def _build_item_index(self): '\n Synchronizes at the sample-level and only adds sample indices if context frames are available.\n This is enforced by adding sample indices that fall in (bacwkard_context, N-forward_context) range.\n\n Returns\n -------\n item_index: list\n List of dataset items that contain index into\n [(scene_idx, sample_within_scene_idx, [datum_names]), ...].\n ' logging.info(f'{self.__class__.__name__} :: Building item index for {len(self.scenes)} scenes, this will take a while.') st = time.time() (acc_back, acc_forward) = (0, 0) if self.accumulation_context: acc_context = [(v[0], v[1]) for v in self.accumulation_context.values()] (acc_back, acc_forward) = np.max(acc_context, 0) with Pool(cpu_count()) as proc: item_index = proc.starmap(partial(_SynchronizedDataset._item_index_for_scene, backward_context=(self.backward_context + acc_back), forward_context=(self.forward_context + acc_forward), only_annotated_datums=self.only_annotated_datums), [(scene_idx, scene) for (scene_idx, scene) in enumerate(self.scenes)]) logging.info(f'Index built in {(time.time() - st):.2f}s.') assert (len(item_index) > 0), 'Failed to index items in the dataset.' item_index = list(itertools.chain.from_iterable(item_index)) item_index = [item for item in item_index if (item is not None)] item_lengths = [len(item_tup) for item_tup in item_index] assert all([(l == item_lengths[0]) for l in item_lengths]), 'All sample items are not of the same length, datum names might be missing.' return item_index @staticmethod def _item_index_for_scene(scene_idx, scene, backward_context, forward_context, only_annotated_datums): st = time.time() logging.debug(f'Indexing scene items for {scene.scene_path}') if (not only_annotated_datums): sample_range = np.arange(backward_context, (len(scene.datum_index) - forward_context)) scene_item_index = [(scene_idx, sample_idx, scene.selected_datums) for sample_idx in sample_range] logging.debug(f'No annotation filter--- Scene item index built in {(time.time() - st):.2f}s.') else: sample_range = np.arange(0, len(scene.datum_index)) annotated_samples = scene.annotation_index[scene.datum_index[sample_range]].any(axis=(1, 2)) scene_item_index = [] for idx in range(backward_context, (len(scene.datum_index) - forward_context)): if all(annotated_samples.data[(idx - backward_context):((idx + 1) + forward_context)]): scene_item_index.append((scene_idx, sample_range[idx], scene.selected_datums)) logging.debug(f'Annotation filter -- Scene item index built in {(time.time() - st):.2f}s.') return scene_item_index def set_context(self, backward=1, forward=1, accumulation_context=None): 'Set the context size and strides.\n\n Parameters\n ----------\n backward: int, optional\n Backward context in frames [T-backward, ..., T-1]. Default: 1.\n\n forward: int, optional\n Forward context in frames [T+1, ..., T+forward]. Default: 1.\n\n accumulation_context: dict, optional\n Dictionary of accumulation context. Default: None\n ' assert ((backward >= 0) and (forward >= 0)), 'Provide valid context' if accumulation_context: for (k, v) in accumulation_context.items(): assert (v[0] >= 0), f'Provide valid accumulation backward context for {k}' assert (v[1] >= 0), f'Provide valid accumulation forward context for {k}' if (v[1] > 0): logging.warning(f'Forward accumulation context is enabled for {k}. Doing so at inference time is not suggested, is this intentional?') self.backward_context = backward self.forward_context = forward self.accumulation_context = accumulation_context if self.accumulation_context: self.accumulation_context = {k.lower(): v for (k, v) in self.accumulation_context.items()} def get_context_indices(self, sample_idx): 'Utility to get the context sample indices given the sample_idx.\n\n Parameters\n ----------\n sample_idx: int\n Sample index (T).\n\n Returns\n -------\n context_indices: list\n Sample context indices for T, i.e. [T-1, T, T+1, T+2] if\n backward_context=1, forward_context=2.\n ' return list(range((sample_idx - self.backward_context), ((sample_idx + self.forward_context) + 1))) def __len__(self): 'Return the length of the dataset.' return len(self.dataset_item_index) def get_datum_data(self, scene_idx, sample_idx_in_scene, datum_name): 'Get the datum at (scene_idx, sample_idx_in_scene, datum_name) with labels (optionally)\n\n Parameters\n ----------\n scene_idx: int\n Scene index.\n\n sample_idx_in_scene: int\n Sample index within the scene.\n\n datum_name: str\n Datum within the sample.\n\n Raises\n ------\n ValueError\n Raised if the type of the requested datum is unsupported.\n ' datum = self.get_datum(scene_idx, sample_idx_in_scene, datum_name) datum_type = datum.datum.WhichOneof('datum_oneof') if (datum_type == 'image'): (datum_data, annotations) = self.get_image_from_datum(scene_idx, sample_idx_in_scene, datum_name) if self.generate_depth_from_datum: datum_data['depth'] = get_depth_from_point_cloud(self, scene_idx, sample_idx_in_scene, datum_name, self.generate_depth_from_datum.lower()) elif (datum_type == 'point_cloud'): (datum_data, annotations) = self.get_point_cloud_from_datum(scene_idx, sample_idx_in_scene, datum_name) elif (datum_type == 'file_datum'): (datum_data, annotations) = self.get_file_meta_from_datum(scene_idx, sample_idx_in_scene, datum_name) elif (datum_type == 'radar_point_cloud'): (datum_data, annotations) = self.get_radar_point_cloud_from_datum(scene_idx, sample_idx_in_scene, datum_name) else: raise ValueError('Unknown datum type: {}'.format(datum_type)) if annotations: datum_data.update(annotations) datum_data['datum_type'] = datum_type return datum_data def __getitem__(self, index): 'Get the dataset item at index.\n\n Parameters\n ----------\n index: int\n Index of item to get.\n\n Returns\n -------\n data: list of list of OrderedDict\n\n "timestamp": int\n Timestamp of the image in microseconds.\n\n "datum_name": str\n Sensor name from which the data was collected\n\n "rgb": PIL.Image (mode=RGB)\n Image in RGB format.\n\n "intrinsics": np.ndarray\n Camera intrinsics.\n\n "extrinsics": Pose\n Camera extrinsics with respect to the world frame.\n\n "pose": Pose\n Pose of sensor with respect to the world/global frame\n\n Returns a list of list of OrderedDict(s).\n Outer list corresponds to temporal ordering of samples. Each element is\n a list of OrderedDict(s) corresponding to synchronized datums.\n\n In other words, __getitem__ returns a nested list with the ordering as\n follows: (C, D, I), where\n C = forward_context + backward_context + 1,\n D = len(datum_names)\n I = OrderedDict item\n ' assert (self.dataset_item_index is not None), 'Index is not built, select datums before getting elements.' (scene_idx, sample_idx_in_scene, datum_names) = self.dataset_item_index[index] datums_with_context = dict() for datum_name in datum_names: (acc_back, acc_forward) = (0, 0) if self.accumulation_context: accumulation_context = self.accumulation_context.get(datum_name.lower(), (0, 0)) (acc_back, acc_forward) = accumulation_context datum_list = [self.get_datum_data(scene_idx, (sample_idx_in_scene + offset), datum_name) for offset in range(((- 1) * (self.backward_context + acc_back)), ((self.forward_context + acc_forward) + 1))] if ((acc_back != 0) or (acc_forward != 0)): assert ('point_cloud' in datum_list[0]), 'Accumulation is only defined for radar and lidar currently.' datum_list = [accumulate_points(datum_list[(k - acc_back):((k + acc_forward) + 1)], datum_list[k], self.transform_accumulated_box_points) for k in range(acc_back, (len(datum_list) - acc_forward))] datums_with_context[datum_name] = datum_list context_window = [] for t in range(((self.backward_context + self.forward_context) + 1)): context_window.append([datums_with_context[datum_name][t] for datum_name in datum_names]) return context_window
class SynchronizedSceneDataset(_SynchronizedDataset): 'Main entry-point for multi-modal dataset with sample-level\n synchronization using scene directories as input.\n\n Note: This class is primarily used for self-supervised learning tasks where\n the default mode of operation is learning from a collection of scene\n directories.\n\n Parameters\n ----------\n scene_dataset_json: str\n Full path to the scene dataset json holding collections of paths to scene json.\n\n split: str, default: \'train\'\n Split of dataset to read ("train" | "val" | "test" | "train_overfit").\n\n datum_names: list, default: None\n Select list of datum names for synchronization (see self.select_datums(datum_names)).\n\n requested_annotations: tuple, default: None\n Tuple of annotation types, i.e. (\'bounding_box_2d\', \'bounding_box_3d\'). Should be equivalent\n to directory containing annotation from dataset root.\n\n requested_autolabels: tuple[str], default: None\n Tuple of annotation types similar to `requested_annotations`, but associated with a particular autolabeling model.\n Expected format is "<model_id>/<annotation_type>"\n\n backward_context: int, default: 0\n Backward context in frames [T-backward, ..., T-1]\n\n forward_context: int, default: 0\n Forward context in frames [T+1, ..., T+forward]\n\n accumulation_context: dict, default None\n Dictionary of datum names containing a tuple of (backward_context, forward_context) for sensor accumulation.\n For example, \'accumulation_context={\'lidar\':(3,1)} accumulates lidar points over the past three time steps and\n one forward step. Only valid for lidar and radar datums.\n\n generate_depth_from_datum: str, default: None\n Datum name of the point cloud. If is not None, then the depth map will be generated for the camera using\n the desired point cloud.\n\n only_annotated_datums: bool, default: False\n If True, only datums with annotations matching the requested annotation types are returned.\n\n skip_missing_data: bool, default: False\n If True, check for missing files and skip during datum index building.\n\n dataset_root: str\n Optional path to dataset root folder. Useful if dataset scene json is not in the same directory as the rest of the data.\n\n transform_accumulated_box_points: bool, default: False\n Flag to use cuboid pose and instance id to warp points when using lidar accumulation.\n\n use_diskcache: bool, default: True\n If True, cache ScenePb2 object using diskcache. If False, save the object in memory.\n NOTE: Setting use_diskcache to False would exhaust the memory if have a large number of scenes.\n\n autolabel_root: str, default: None\n Path to autolabels if not stored inside scene root. Note this must still respect the scene structure, i.e,\n autolabel_root = \'/some-autolabels\' means the autolabel scene.json is found at\n /some-autolabels/<scene-dir>/autolabels/my-model/scene.json.\n\n ignore_raw_datum: Optional[list[str]], default: None\n Optionally pass a list of datum types to skip loading their raw data (but still load their annotations). For\n example, ignore_raw_datum=[\'image\'] will skip loading the image rgb data. The rgb key will be set to None.\n This is useful when only annotations or extrinsics are needed. Allowed values are any combination of\n \'image\',\'point_cloud\',\'radar_point_cloud\'\n\n Refer to _SynchronizedDataset for remaining parameters.\n ' def __init__(self, scene_dataset_json, split='train', datum_names=None, requested_annotations=None, requested_autolabels=None, backward_context=0, forward_context=0, accumulation_context=None, generate_depth_from_datum=None, only_annotated_datums=False, skip_missing_data=False, dataset_root=None, transform_accumulated_box_points=False, use_diskcache=True, autolabel_root=None, ignore_raw_datum=None): if (not use_diskcache): logging.warning('Instantiating a dataset with use_diskcache=False may exhaust memory with a large dataset.') scenes = BaseDataset._extract_scenes_from_scene_dataset_json(scene_dataset_json, split, requested_autolabels, is_datums_synchronized=True, skip_missing_data=skip_missing_data, dataset_root=dataset_root, use_diskcache=use_diskcache, autolabel_root=autolabel_root) dataset_metadata = DatasetMetadata.from_scene_containers(scenes, requested_annotations, requested_autolabels, autolabel_root=autolabel_root) super().__init__(dataset_metadata, scenes=scenes, datum_names=datum_names, requested_annotations=requested_annotations, requested_autolabels=requested_autolabels, backward_context=backward_context, forward_context=forward_context, accumulation_context=accumulation_context, generate_depth_from_datum=generate_depth_from_datum, only_annotated_datums=only_annotated_datums, transform_accumulated_box_points=transform_accumulated_box_points, autolabel_root=autolabel_root, ignore_raw_datum=ignore_raw_datum)
class SynchronizedScene(_SynchronizedDataset): 'Main entry-point for multi-modal dataset with sample-level\n synchronization using a single scene JSON as input.\n\n Note: This class can be used to introspect a single scene given a scene\n directory with its associated scene JSON.\n\n Parameters\n ----------\n scene_json: str\n Full path to the scene json.\n\n datum_names: list, default: None\n Select list of datum names for synchronization (see self.select_datums(datum_names)).\n\n requested_annotations: tuple, default: None\n Tuple of annotation types, i.e. (\'bounding_box_2d\', \'bounding_box_3d\'). Should be equivalent\n to directory containing annotation from dataset root.\n\n requested_autolabels: tuple[str], default: None\n Tuple of annotation types similar to `requested_annotations`, but associated with a particular autolabeling model.\n Expected format is "<model_id>/<annotation_type>"\n\n backward_context: int, default: 0\n Backward context in frames [T-backward, ..., T-1]\n\n forward_context: int, default: 0\n Forward context in frames [T+1, ..., T+forward]\n\n accumulation_context: dict, default None\n Dictionary of datum names containing a tuple of (backward_context, forward_context) for sensor accumulation.\n For example, \'accumulation_context={\'lidar\':(3,1)} accumulates lidar points over the past three time steps and\n one forward step. Only valid for lidar and radar datums.\n\n generate_depth_from_datum: str, default: None\n Datum name of the point cloud. If is not None, then the depth map will be generated for the camera using\n the desired point cloud.\n\n only_annotated_datums: bool, default: False\n If True, only datums with annotations matching the requested annotation types are returned.\n\n transform_accumulated_box_points: bool, default: False\n Flag to use cuboid pose and instance id to warp points when using lidar accumulation.\n\n use_diskcache: bool, default: True\n If True, cache ScenePb2 object using diskcache. If False, save the object in memory.\n NOTE: Setting use_diskcache to False would exhaust the memory if have a large number of scenes.\n\n autolabel_root: str, default: None\n Path to autolabels if not stored inside scene root. Note this must still respect the scene structure, i.e,\n autolabel_root = \'/some-autolabels\' means the autolabel scene.json is found at\n /some-autolabels/<scene-dir>/autolabels/my-model/scene.json.\n\n ignore_raw_datum: Optional[list[str]], default: None\n Optionally pass a list of datum types to skip loading their raw data (but still load their annotations). For\n example, ignore_raw_datum=[\'image\'] will skip loading the image rgb data. The rgb key will be set to None.\n This is useful when only annotations or extrinsics are needed. Allowed values are any combination of\n \'image\',\'point_cloud\',\'radar_point_cloud\'\n\n Refer to _SynchronizedDataset for remaining parameters.\n ' def __init__(self, scene_json, datum_names=None, requested_annotations=None, requested_autolabels=None, backward_context=0, forward_context=0, accumulation_context=None, generate_depth_from_datum=None, only_annotated_datums=False, transform_accumulated_box_points=False, use_diskcache=True, autolabel_root=None, ignore_raw_datum=None): if (not use_diskcache): logging.warning('Instantiating a dataset with use_diskcache=False may exhaust memory with a large dataset.') scene = BaseDataset._extract_scene_from_scene_json(scene_json, requested_autolabels, is_datums_synchronized=True, use_diskcache=use_diskcache, autolabel_root=autolabel_root) dataset_metadata = DatasetMetadata.from_scene_containers([scene], requested_annotations, requested_autolabels, autolabel_root=autolabel_root) super().__init__(dataset_metadata, scenes=[scene], datum_names=datum_names, requested_annotations=requested_annotations, requested_autolabels=requested_autolabels, backward_context=backward_context, forward_context=forward_context, accumulation_context=accumulation_context, generate_depth_from_datum=generate_depth_from_datum, only_annotated_datums=only_annotated_datums, transform_accumulated_box_points=transform_accumulated_box_points, autolabel_root=autolabel_root, ignore_raw_datum=ignore_raw_datum)
class FeatureOntology(): 'Feature ontology object. At bare minimum, we expect ontologies to provide:\n ID: (int) identifier for feature field name\n Name: (str) string identifier for feature field name\n\n Based on the task, additional fields may be populated. Refer to `dataset.proto` and `ontology.proto`\n specifications for more details. Can be constructed from file or from deserialized proto object.\n\n Parameters\n ----------\n feature_ontology_pb2: OntologyPb2\n Deserialized ontology object.\n ' VOID_ID = 255 VOID_CLASS = 'Void' def __init__(self, feature_ontology_pb2): self._ontology = feature_ontology_pb2 if isinstance(self._ontology, FeatureOntologyPb2): self._name_to_id = OrderedDict(sorted([(ontology_item.name, ontology_item.id) for ontology_item in self._ontology.items])) self._id_to_name = OrderedDict(sorted([(ontology_item.id, ontology_item.name) for ontology_item in self._ontology.items])) self._id_to_feature_value_type = OrderedDict(sorted([(ontology_item.id, ontology_item.feature_value_type) for ontology_item in self._ontology.items])) else: raise TypeError('Unexpected type {}, expected FeatureOntologyV2'.format(type(self._ontology))) self._feature_ids = sorted(self._id_to_name.keys()) self._feature_names = [self._id_to_name[c_id] for c_id in self._feature_ids] @classmethod def load(cls, ontology_file): 'Construct an ontology from an ontology JSON.\n\n Parameters\n ----------\n ontology_file: str\n Path to ontology JSON\n\n Raises\n ------\n FileNotFoundError\n Raised if ontology_file does not exist.\n TypeError\n Raised if we could not read an ontology out of the ontology file.\n ' if os.path.exists(ontology_file): feature_ontology_pb2 = open_feature_ontology_pbobject(ontology_file) else: raise FileNotFoundError('Could not find {}'.format(ontology_file)) if (feature_ontology_pb2 is not None): return cls(feature_ontology_pb2) raise TypeError('Could not open ontology {}'.format(ontology_file)) def to_proto(self): 'Serialize ontology. Only supports exporting in OntologyV2.\n\n Returns\n -------\n OntologyPb2\n Serialized ontology\n ' return FeatureOntologyPb2(items=[FeatureOntologyItem(name=name, id=feature_id, feature_value_type=self.id_to_feature_value_type[feature_id]) for (feature_id, name) in self._id_to_name.items()]) def save(self, save_dir): 'Write out ontology items to `<sha>.json`. SHA generated from Ontology proto object.\n\n Parameters\n ----------\n save_dir: str\n Directory in which to save serialized ontology.\n\n Returns\n -------\n output_ontology_file: str\n Path to serialized ontology file.\n ' os.makedirs(save_dir, exist_ok=True) return save_pbobject_as_json(self.to_proto(), save_path=save_dir) @property def num_classes(self): return len(self._feature_ids) @property def class_names(self): return self._feature_names @property def class_ids(self): return self._feature_ids @property def name_to_id(self): return self._name_to_id @property def id_to_name(self): return self._id_to_name @property def id_to_feature_value_type(self): return self._id_to_feature_value_type @property def hexdigest(self): 'Hash object' return generate_uid_from_pbobject(self.to_proto()) def __eq__(self, other): return (self.hexdigest == other.hexdigest) def __repr__(self): return '{}[{}]'.format(self.__class__.__name__, os.path.basename(self.hexdigest))
class AgentFeatureOntology(FeatureOntology): 'Agent feature ontologies derive directly from Ontology'
def tqdm(*args, **kwargs): kwargs['disable'] = DGP_DISABLE_TQDM return _tqdm(*args, **kwargs)
def points_in_cuboid(query_points, cuboid): 'Tests if a point is contained by a cuboid. Assumes points are in the same frame as the cuboid, \n i.e, cuboid.pose translates points in the cuboid local frame to the query_point frame.\n\n Parameters\n ----------\n query_points: np.ndarray\n Numpy array shape (N,3) of points.\n\n cuboid: dgp.utils.structures.bounding_box_3d.BoundingBox3D\n Cuboid in same reference frame as query points\n\n Returns\n -------\n in_view: np.ndarray\n Numpy boolean array shape (N,) where a True entry denotes a point insided the cuboid\n ' corners = cuboid.corners a = (corners[1] - corners[0]) b = (corners[3] - corners[0]) c = (corners[4] - corners[0]) ma = np.linalg.norm(a) mb = np.linalg.norm(b) mc = np.linalg.norm(c) a = (a / ma) b = (b / mb) c = (c / mc) v = (query_points - corners[0]) proj_a = np.dot(v, a) proj_b = np.dot(v, b) proj_c = np.dot(v, c) in_view = np.logical_and.reduce([(proj_a >= 0), (proj_b >= 0), (proj_c >= 0), (proj_a <= ma), (proj_b <= mb), (proj_c <= mc)]) return in_view
def accumulate_points(point_datums, target_datum, transform_boxes=False): "Accumulates lidar or radar points by transforming all datums in point_datums to the frame used in target_datum.\n\n Parameters\n ----------\n point_datums: list[dict]\n List of datum dictionaries to accumulate\n\n target_datum: dict\n A single datum to use as the reference frame and reference time.\n\n transform_boxes: bool, optional\n Flag to denote if cuboid annotations and instance ids should be used to warp points to the target frame.\n Only valid for Lidar.\n Default: False.\n\n Returns\n -------\n p_target: dict\n A new datum with accumulated points and an additional field 'accumulation_offset_t'\n that indicates the delta in microseconds between the target_datum and the given point.\n " assert ('point_cloud' in point_datums[0]), 'Accumulation is only defined for radar and lidar currently.' p_target = deepcopy(target_datum) pose_target_w = p_target['pose'].inverse() new_fields = defaultdict(list) target_boxes = {} if (transform_boxes and ('bounding_box_3d' in target_datum)): target_boxes = {box.instance_id: box for box in target_datum['bounding_box_3d']} for (_, p) in enumerate(point_datums): pose_p2p1 = (pose_target_w * p['pose']) new_points = (pose_p2p1 * p['point_cloud']) new_fields['point_cloud'].append(new_points) if ('velocity' in p_target): new_vel = ((pose_p2p1 * (p['point_cloud'] + p['velocity'])) - new_points) new_fields['velocity'].append(new_vel) if ('covariance' in p_target): R = pose_p2p1.rotation_matrix new_cov = ((R @ p['covariance']) @ R.T) new_fields['covariance'].append(new_cov) if ('extra_channels' in p_target): new_fields['extra_channels'].append(p['extra_channels']) dt = (p_target['timestamp'] - p['timestamp']) new_fields['accumulation_offset_t'].append((dt * np.ones(len(new_points)))) if (transform_boxes and ('bounding_box_3d' in p)): if ('velocity' in p): continue for _box in p['bounding_box_3d']: if (_box.instance_id not in target_boxes): continue box = deepcopy(_box) box._pose = (pose_p2p1 * box.pose) in_box = points_in_cuboid(new_fields['point_cloud'][(- 1)], box) if np.any(in_box): points_to_move = new_fields['point_cloud'][(- 1)][in_box] pose_p2box1 = (target_boxes[box.instance_id].pose * box.pose.inverse()) moved_points = (pose_p2box1 * points_to_move) new_fields['point_cloud'][(- 1)][in_box] = moved_points for k in new_fields: p_target[k] = np.concatenate(new_fields[k], axis=0) return p_target
def is_empty_annotation(annotation_file, annotation_type): 'Check if JSON style annotation files are empty\n\n Parameters\n ----------\n annotation_file: str\n Path to JSON file containing annotations for 2D/3D bounding boxes\n\n annotation_type: object\n Protobuf pb2 object we want to load into.\n\n Returns\n -------\n bool:\n True if empty annotation, otherwise False\n ' with open(annotation_file, encoding=locale.getpreferredencoding()) as _f: annotations = open_pbobject(annotation_file, annotation_type) return (len(list(annotations.annotations)) == 0)
@diskcache(protocol='npz') def get_depth_from_point_cloud(dataset, scene_idx, sample_idx_in_scene, cam_datum_name, pc_datum_name): "Generate the depth map in the camera view using the provided point cloud\n datum within the sample.\n\n Parameters\n ----------\n dataset: dgp.dataset.BaseDataset\n Inherited base dataset to augment with depth data.\n\n scene_idx: int\n Index of the scene.\n\n sample_idx_in_scene: int\n Index of the sample within the scene at scene_idx.\n\n cam_datum_name: str\n Name of camera datum within the sample.\n\n pc_datum_name: str\n Name of the point cloud datum within the sample.\n\n Returns\n -------\n depth: np.ndarray\n Depth map from the camera's viewpoint.\n " pc_datum = dataset.get_datum(scene_idx, sample_idx_in_scene, pc_datum_name) pc_datum_type = pc_datum.datum.WhichOneof('datum_oneof') assert (pc_datum_type == 'point_cloud'), 'Depth cannot be generated from {} {} {}'.format(pc_datum_type, pc_datum_name, pc_datum) (pc_datum_data, _) = dataset.get_point_cloud_from_datum(scene_idx, sample_idx_in_scene, pc_datum_name) X_W = (pc_datum_data['pose'] * pc_datum_data['point_cloud']) cam_datum = dataset.get_datum(scene_idx, sample_idx_in_scene, cam_datum_name) cam_datum_type = cam_datum.datum.WhichOneof('datum_oneof') assert (cam_datum_type == 'image'), 'Depth cannot be projected onto {} '.format(cam_datum_type) (cam_datum_data, _) = dataset.get_image_from_datum(scene_idx, sample_idx_in_scene, cam_datum_name) p_WC = cam_datum_data['pose'] camera = Camera(K=cam_datum_data['intrinsics'], p_cw=p_WC.inverse()) (W, H) = cam_datum_data['rgb'].size[:2] return generate_depth_map(camera, X_W, (H, W))
def clear_cache(directory=DGP_CACHE_DIR): 'Clear DGP cache to avoid growing disk-usage.\n\n Parameters\n ----------\n directory: str, optional\n A pathname to the directory used by DGP for caching. Default: DGP_CACHE_DIR.\n ' if os.path.isdir(directory): logging.info('Clearing dgp disk-cache.') try: shutil.rmtree(directory) except OSError as e: logging.warning('Failed to clear cache {}'.format(e))
def diskcache(protocol='npz', cache_dir=None): 'Disk-caching method/function decorator that caches results into\n dgp cache for arbitrary pickle-able / numpy objects.\n\n Parameters\n ----------\n protocol: str, optional\n Serialization protocol. Choices: {npz, pkl}. Default: "npz" (numpy).\n\n cache_dir: str, optional\n Directory to cache instead of the default DGP cache. Default: None.\n ' assert (protocol in ('npz', 'pkl')), 'Unknown protocol {}'.format(protocol) logging.info('Using dgp disk-cache.') if (cache_dir is None): cache_dir = DGP_CACHE_DIR os.makedirs(cache_dir, exist_ok=True) def wrapped_diskcache(func): def serialize(_result, _filename, _protocol): 'Serialize result based on protocol' if (_protocol == 'npz'): np.savez_compressed(_filename, data=_result) elif (protocol == 'pkl'): with open(_filename, 'wb') as f: pickle.dump(_result, f) else: raise ValueError('Unknown serialization protocol {}'.format(_protocol)) def deserialize(_filename, _protocol): 'De-serialize result based on protocol' if (_protocol == 'npz'): return np.load(_filename)['data'] elif (_protocol == 'pkl'): with open(_filename, 'rb') as f: return pickle.load(f) else: raise ValueError('Unknown de-serialization protocol {}'.format(_protocol)) @wraps(func) def wrapped_func(*args, **kwargs): try: data = pickle.dumps((args, kwargs, func.__name__)) h = hashlib.md5(data) except Exception as e: raise Exception('Failed to hash: (args={}, kwargs={}): {}'.format(args, kwargs, str(e))) from e filename = os.path.join(cache_dir, '{}.{}'.format(h.hexdigest(), protocol)) try: if os.path.exists(filename): logging.info('Attempting to load disk-cached object {} [{:.2f} MiB] .'.format(filename, ((os.stat(filename).st_size / 1024) / 1024))) result = deserialize(filename, protocol) logging.info('Successfully loaded disk-cached object ({} at {}) .'.format(result.__class__.__name__, filename)) return result except: logging.info('Failed to load cached object {}'.format(filename)) result = func(*args, **kwargs) serialize(result, filename, protocol) return result return wrapped_func return wrapped_diskcache
def add_options(**kwargs): 'Decorator function to add a list of Click options to a Click subcommand.\n\n Parameters\n ----------\n **kwargs: dict\n The `options` keyword argument shall be a list of string options to extend a Click CLI.\n ' def _add_options(func): return functools.reduce((lambda x, opt: opt(x)), kwargs['options'], func) return _add_options
def init_s3_client(use_ssl=False): 'Initiate S3 AWS client.\n\n Parameters\n ----------\n use_ssl: bool, optional\n Use secure sockets layer. Provieds better security to s3, but\n can fail intermittently in a multithreaded environment. Default: False.\n\n Returns\n -------\n service: boto3.client\n S3 resource service client.\n ' global S3_CLIENT_SSL global S3_CLIENT_NO_SSL if use_ssl: if (S3_CLIENT_SSL is None): S3_CLIENT_SSL = boto3.client('s3') return S3_CLIENT_SSL if (not S3_CLIENT_NO_SSL): S3_CLIENT_NO_SSL = boto3.client('s3', use_ssl=False) return S3_CLIENT_NO_SSL
def s3_recursive_list(s3_prefix): "List all files contained in an s3 location recursively and also return their md5_sums\n NOTE: this is different from 'aws s3 ls' in that it will not return directories, but instead\n the full paths to the files contained in any directories (which is what s3 is actually tracking)\n\n Parameters\n ----------\n s3_prefix: str\n s3 prefix which we want the returned files to have\n\n Returns\n -------\n all_files: list[str]\n List of files (with full path including 's3://...')\n\n md5_sums: list[str]\n md5 sum for each of the files as returned by boto3 'ETag' field\n " assert s3_prefix.startswith('s3://') (bucket_name, prefix) = convert_uri_to_bucket_path(s3_prefix, strip_trailing_slash=False) s3_client = init_s3_client(use_ssl=False) s3_metadata = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=prefix) if ('Contents' not in s3_metadata): return ([], []) paginator = s3_client.get_paginator('list_objects_v2').paginate(Bucket=bucket_name, Prefix=prefix) s3_metadata = [single_object for page in paginator for single_object in page['Contents']] all_files = [os.path.join('s3://', bucket_name, _file_metadata['Key']) for _file_metadata in s3_metadata] md5_sums = [_file_metadata['ETag'].strip('"') for _file_metadata in s3_metadata] return (all_files, md5_sums)
def return_last_value(retry_state): 'Return the result of the last call attempt.\n\n Parameters\n ----------\n retry_state: tenacity.RetryCallState\n Retry-state metadata for a flaky call.\n ' return retry_state.outcome.result()
def is_false(value): return (value is False)
@tenacity.retry(stop=tenacity.stop_after_attempt(3), retry=tenacity.retry_if_result(is_false), retry_error_callback=return_last_value) def s3_copy(source_path, target_path, verbose=True): 'Copy single file from local to s3, s3 to local, or s3 to s3.\n\n Parameters\n ----------\n source_path: str\n Path of file to copy\n\n target_path: str\n Path to copy file to\n\n verbose: bool, optional\n If True print some helpful messages. Default: True.\n\n Returns\n -------\n bool: True if successful\n ' if verbose: logging.getLogger().setLevel(logging.DEBUG) success = False command_str = 'aws s3 cp --acl bucket-owner-full-control {} {}'.format(source_path, target_path) logging.debug("Copying file with '{}'".format(command_str)) try: subprocess.check_output(command_str, shell=True) success = True except subprocess.CalledProcessError as e: success = False logging.error('{} failed with error code {}'.format(command_str, e.returncode)) logging.error(e.output) if verbose: logging.info('Done copying file') return success
def parallel_s3_copy(source_paths, target_paths, threadpool_size=None): 'Copy files from local to s3, s3 to local, or s3 to s3 using a threadpool.\n Retry the operation if any files fail to copy. Throw an AssertionError if it fails the 2nd time.\n\n Parameters\n ----------\n source_paths: List of str\n Full paths of files to copy.\n\n target_paths: List of str\n Full paths to copy files to.\n\n threadpool_size: int\n Number of threads to use to fetch these files. If not specified, will default to\n number of cores on the machine.\n\n ' if (threadpool_size is None): threadpool_size = cpu_count() s3_and_destination = zip(source_paths, target_paths) with Pool(threadpool_size) as thread_pool: s3_copy_function = functools.partial(s3_copy) success_list = thread_pool.starmap(s3_copy_function, s3_and_destination) num_success = sum(success_list) logging.info(f'{num_success} / {len(success_list)} files copied successfully.') for (success, source, target) in zip(success_list, source_paths, target_paths): if (not success): assert s3_copy(source, target), f'Failed to copy {source} to {target} on 2nd try'
@tenacity.retry(stop=tenacity.stop_after_attempt(3), retry=tenacity.retry_if_result(is_false), retry_error_callback=return_last_value) def sync_dir(source, target, file_ext=None, verbose=True): "Sync a directory from source to target (either local to s3, s3 to s3, s3 to local)\n\n Parameters\n ----------\n source: str\n Directory from which we want to sync files\n\n target: str\n Directory to which all files will be synced\n\n file_ext: str, optional\n Only sync files ending with this extension. Eg: 'csv' or 'json'. If None, sync all files. Default: None.\n\n verbose: bool, optional\n If True, log some helpful messages. Default: True.\n\n Returns\n -------\n bool: True if operation was successful\n " if verbose: logging.getLogger().setLevel(logging.DEBUG) assert (source.startswith('s3://') or target.startswith('s3://')) additional_flags = '' if (file_ext is not None): additional_flags = f'--exclude=* --include=*{file_ext}' command_str = 'aws s3 sync --quiet --acl bucket-owner-full-control {} {} {}'.format(additional_flags, source, target) success = False logging.debug("Syncing with '{}'".format(command_str)) try: subprocess.check_output(command_str, shell=True) success = True except subprocess.CalledProcessError as e: success = False logging.error('{} failed with error code {}'.format(command_str, e.returncode)) logging.error(e.output) if verbose: logging.info('Done syncing') return success
def parallel_s3_sync(source_paths, target_paths, threadpool_size=None): 'Copy directories from local to s3, s3 to local, or s3 to s3 using a threadpool.\n Retry the operation if any files fail to sync. Throw an AssertionError if it fails the 2nd time.\n\n Parameters\n ----------\n source_paths: List of str\n Directories from which we want to sync files.\n\n target_paths: List of str\n Directories to which all files will be synced.\n\n threadpool_size: int\n Number of threads to use to fetch these files. If not specified, will default to\n number of cores on the machine.\n\n ' if (threadpool_size is None): threadpool_size = cpu_count() s3_and_destination = zip(source_paths, target_paths) with Pool(threadpool_size) as thread_pool: s3_sync_function = functools.partial(sync_dir) success_list = thread_pool.starmap(s3_sync_function, s3_and_destination) num_success = sum(success_list) logging.info(f'{num_success} / {len(success_list)} files copied successfully.') for (success, source, target) in zip(success_list, source_paths, target_paths): if (not success): assert sync_dir(source, target), f'Failed to copy {source} to {target} on 2nd try'
def sync_dir_safe(source, target, verbose=True): 'Sync a directory from local to s3 by first ensuring that NONE of the files in `target`\n have been edited in `source` (new files can exist in `source` that are not in `target`)\n (NOTE: only checks files from `target` that exist in `source`)\n\n Parameters\n ----------\n source: str\n Directory from which we want to sync files\n\n target: str\n Directory to which all files will be synced\n\n verbose: bool, optional\n If True, log some helpful messages. Default: True.\n\n Returns\n -------\n files_fail_to_sync: list\n List of files fail to sync to S3 due to md5sum mismatch.\n ' assert ((not source.startswith('s3://')) and target.startswith('s3://')) (target_files, target_file_md5_sums) = s3_recursive_list(os.path.join(target, '')) rel_target_files = [os.path.relpath(_f, target) for _f in target_files] files_fail_to_sync = [] for (rel_target_file, target_file_md5_sum) in zip(rel_target_files, target_file_md5_sums): local_file = os.path.join(source, rel_target_file) if os.path.exists(local_file): local_file_md5_sum = hashlib.md5(open(local_file, 'rb').read()).hexdigest() if (local_file_md5_sum != target_file_md5_sum): files_fail_to_sync.append(rel_target_file) logging.error('Cannot sync to s3, you have made changes to "{}" locally'.format(rel_target_file)) sync_dir(source, target, verbose=verbose) if verbose: logging.info('{} | {} files synced to S3'.format((len(rel_target_files) - len(files_fail_to_sync)), len(rel_target_files))) return files_fail_to_sync
def s3_bucket(bucket_name): 'Instantiate S3 bucket object from its bucket name\n\n Parameters\n ----------\n bucket_name : str\n Bucket name to instantiate.\n\n Returns\n -------\n S3 bucket\n ' return boto3.session.Session().resource('s3').Bucket(bucket_name)
def list_s3_objects(bucket_name, url): 'List all files within a valid S3 bucket\n\n Parameters\n ----------\n bucket_name : str\n AWS S3 root bucket name\n\n url : str\n The remote URL of the object to be fetched\n ' return list(s3_bucket(bucket_name).objects.filter(Prefix=url))
def exists_s3_object(bucket_name, url): 'Uses a valid S3 bucket to check the existence of a remote file as AWS URL.\n\n Parameters\n ----------\n bucket_name : str\n AWS S3 root bucket name\n\n url : str\n The remote URL of the object to be fetched\n\n Returns\n -------\n bool:\n Wether or not the object exists in S3.\n ' return (len(list(s3_bucket(bucket_name).objects.filter(Prefix=url))) != 0)
def convert_uri_to_bucket_path(uri, strip_trailing_slash=True): "Parse a URI into a bucket and path.\n\n Parameters\n ----------\n uri: str\n A full s3 path (e.g. 's3://<s3-bucket>/<s3-prefix>')\n\n strip_trailing_slash: bool, optional\n If True, we strip any trailing slash in `s3_path` before returning it\n (i.e. s3_path='<s3-prefix>' is returned for uri='s3://<s3-bucket>/<s3-prefix>/').\n Otherwise, we do not strip it\n (i.e. s3_path='<s3-prefix>' is returned for uri='s3://<s3-bucket>/<s3-prefix>/').\n\n If there is no trailing slash in `uri` then there will be no trailing slash in `s3_path` regardless\n of the value of this parameter.\n Default: True.\n\n Returns\n -------\n str:\n The bucket of the S3 object (e.g. '<s3-bucket>')\n\n str:\n The path within the bucket of the S3 object (e.g. '<s3-prefix>')\n " s3_uri = urlparse(uri) s3_path = s3_uri.path.lstrip('/') if strip_trailing_slash: s3_path = s3_path.rstrip('/') return (s3_uri.netloc, s3_path)
def parallel_download_s3_objects(s3_files, destination_filepaths, bucket_name, process_pool_size=None): 'Download a list of s3 objects using a processpool.\n\n Parameters\n ----------\n s3_files: list\n List of all files from s3 to download\n\n destination_filepaths: list\n List of where to download all files locally\n\n bucket_name: str\n S3 bucket to pull from\n\n process_pool_size: int, optional\n Number of threads to use to fetch these files. If not specified, will default to\n number of cores on the machine. Default: None.\n ' if (process_pool_size is None): process_pool_size = cpu_count() s3_and_destination = zip(s3_files, destination_filepaths) with Pool(process_pool_size, init_s3_client) as proc: results = proc.starmap(functools.partial(download_s3_object_to_path, bucket_name), s3_and_destination) failed_files = [os.path.join('s3://', bucket_name, s3_file) for (result, s3_file) in zip(results, s3_files) if (not result)] assert (len(failed_files) == 0), 'Failed downloading {}/{} files:\n{}'.format(len(failed_files), len(results), '\n'.join(failed_files))
def parallel_upload_s3_objects(source_filepaths, s3_destinations, bucket_name, process_pool_size=None): 'Upload a list of s3 objects using a processpool.\n\n Parameters\n ----------\n source_filepaths: list\n List of all local files to upload.\n\n s3_destinations: list\n Paths relative to bucket in S3 where files are uploaded.\n\n bucket_name: str\n S3 bucket to upload to.\n\n process_pool_size: int, optional\n Number of threads to use to fetch these files. If not specified, will default to\n number of cores on the machine. Default: None.\n ' if (process_pool_size is None): process_pool_size = cpu_count() s3_and_destination = zip(source_filepaths, s3_destinations) with Pool(process_pool_size, init_s3_client) as proc: proc.starmap(functools.partial(upload_file_to_s3, bucket_name), s3_and_destination)
def download_s3_object_to_path(bucket_name, s3_path, local_path): 'Download an object from s3 to a path on the local filesystem.\n\n Parameters\n ----------\n bucket_name: str\n S3 bucket from which to fetch.\n\n s3_path: str\n The path on the s3 bucket to the file to fetch.\n\n local_path: str\n Path on the local filesystem to place the object.\n\n Returns\n -------\n bool\n True if successful, False if not.\n ' s3_client = init_s3_client() logging.debug('Downloading file {} => {}'.format(s3_path, local_path)) try: os.makedirs(os.path.dirname(local_path), exist_ok=True) except OSError: pass try: s3_client.download_file(bucket_name, s3_path, local_path) return True except botocore.exceptions.ClientError: logging.error('Traceback downloading {}:\n{}'.format(os.path.join('s3://', bucket_name, s3_path), traceback.format_exc())) return False
def delete_s3_object(bucket_name, object_key, verbose=True): 'Delete an object in s3.\n\n Parameters\n ----------\n bucket_name: str\n S3 bucket of the object to delete.\n\n object_key: str\n Key name of the object to delete.\n\n verbose: bool, optional\n If True print messages. Default: True.\n\n ' s3_client = init_s3_client() if verbose: logging.warning('Deleting S3 Object {}'.format(os.path.join('s3://', bucket_name, object_key))) s3_client.delete_object(Bucket=bucket_name, Key=object_key)
def upload_file_to_s3(bucket_name, local_file_path, bucket_rel_path): '\n Parameters\n ----------\n bucket_name : str\n AWS S3 root bucket name\n\n local_file_path: str\n Local path to file we want to upload\n\n bucket_rel_path: str\n Path where file is uploaded, relative to S3 bucket root\n\n Returns\n -------\n s3_url: str\n s3_url to which file was uploaded\n e.g. "s3://<s3-bucket>/<task-name>/<wandb-run>/<model-weights-file>"\n\n ' assert os.path.exists(local_file_path) s3_bucket(bucket_name).upload_file(local_file_path, bucket_rel_path) return os.path.join('s3://', bucket_name, bucket_rel_path)
def get_s3_object(bucket_name, url): 'Uses a valid S3 bucket to retrieve a file from a remote AWS URL.\n Raises ValueError if non-existent.\n\n Parameters\n ----------\n bucket_name : str\n AWS S3 root bucket name\n\n url : str\n The remote URL of the object to be fetched\n\n Returns\n -------\n S3 object\n\n Raises\n ------\n ValueError\n Raised if `url` cannot be found in S3.\n ' result = list(s3_bucket(bucket_name).objects.filter(Prefix=url)) if (not result): raise ValueError(url, 'cannot be found!') return result[0]
def get_string_from_s3_file(bucket_name, url): 'Uses a valid S3 bucket to retrieve an UTF-8 decoded string from a remote AWS URL.\n Raises ValueError if non-existent.\n\n Parameters\n ----------\n bucket_name : str\n AWS S3 root bucket name\n\n url : str\n The remote URL of the object to be fetched\n\n Returns\n -------\n A string representation of the remote file\n ' s3_obj = get_s3_object(bucket_name, url) return s3_obj.get()['Body'].read().decode('utf-8')
def open_remote_json(s3_path): 'Loads a remote JSON file\n\n Parameters\n ----------\n s3_path: str\n Full s3 path to JSON file\n\n Returns\n -------\n dict:\n Loaded JSON\n ' assert (s3_path.startswith('s3://') and s3_path.endswith('.json')) (bucket, rel_path) = convert_uri_to_bucket_path(s3_path) return json.loads(get_string_from_s3_file(bucket, rel_path))
class RemoteArtifactFile(): def __init__(self, artifact): 'Context manager for a remote file on S3.\n\n Parameters\n ----------\n artifact : mgp.remote_pb2.RemoteArtifact\n Remote artifact object that contains the url and the sha1sum of the file\n\n url : str\n The remote URL of the object to be fetched\n\n Returns\n -------\n bool\n ' self._artifact = artifact self._dirname = None url = artifact.url.value self._bucket = url.split('//')[(- 1)].split('/')[0] self._url = url self._relpath = url[((url.rfind(self._bucket) + len(self._bucket)) + 1):] self._s3_client = init_s3_client() _s3_bucket = boto3.session.Session().resource('s3').Bucket(self._bucket) assert exists_s3_object(_s3_bucket, self._relpath), 'Remote artifact does not exist {}'.format(self._url) def __enter__(self): self._dirname = tempfile.TemporaryDirectory() local_path = os.path.join(self._dirname.name, os.path.basename(self._relpath)) logging.info('Downloading {} to {}'.format(self._url, local_path)) self._s3_client.download_file(self._bucket, self._relpath, local_path) sha1 = hashlib.sha1(open(local_path, 'rb').read()).hexdigest() assert (sha1 == self._artifact.sha1), 'sha1sum inconsistent {} != {}'.format(sha1, self._artifact.sha1) return local_path def __exit__(self, *args): self._dirname.__exit__(*args)
def list_prefixes_in_s3_dir(s3_path): '\n List prefixes in S3 path.\n *CAVEAT*: This function was only tested for S3 path that contains purely one-level prefix, i.e. no regular objects.\n Parameters\n ----------\n s3_path: str\n An S3 path.\n Returns\n -------\n prefixes: List of str\n List of prefixes under `s3_path`\n ' s3_client = init_s3_client() assert s3_path.startswith('s3://') (bucket, path) = convert_uri_to_bucket_path(s3_path) prefixes = [] kwargs = {'Bucket': bucket, 'Prefix': os.path.join(path, ''), 'Delimiter': '/'} while True: response = s3_client.list_objects_v2(**kwargs) for obj in response['CommonPrefixes']: prefixes.append(os.path.basename(obj['Prefix'].rstrip('/'))) try: kwargs['ContinuationToken'] = response['NextContinuationToken'] except KeyError: break return prefixes
def list_prefixes_in_s3(s3_prefix): '\n List prefixes in S3 path.\n *CAVEAT*: This function was only tested for S3 prefix for files. E.g., if the bucket looks like the following,\n - s3://aa/bb/cc_v01.json\n - s3://aa/bb/cc_v02.json\n - s3://aa/bb/cc_v03.json\n then list_prefixes_in_s3("s3://aa/bb/cc_v") returns [\'cc_v01.json\', \'cc_v02.json\', \'cc_v03.json\']\n Parameters\n ----------\n s3_prefix: str\n An S3 prefix.\n Returns\n -------\n prefixes: List of str\n List of basename prefixes that starts with `s3_prefix`.\n ' (bucket_name, prefix) = convert_uri_to_bucket_path(s3_prefix) bucket = s3_bucket(bucket_name) prefixes = [os.path.basename(obj.key) for obj in bucket.objects.filter(Prefix=prefix)] return prefixes
def get_split_to_scenes(dataset): '\n Retrieve a dictionary of split to scenes of a DGP-compliant scene dataset.\n\n Parameters\n ----------\n dataset: dgp.proto.dataset_pb2.SceneDataset\n SceneDataset proto object.\n\n Returns\n -------\n split_to_scene_json: dict\n A dictionary of split to a list of scene JSONs.\n\n split_to_scene_dir: dict\n A dictionary of split to a list of scene_dirs.\n ' split_to_scene_json = OrderedDict() split_to_scene_dir = OrderedDict() for (k, v) in dataset_pb2.DatasetSplit.DESCRIPTOR.values_by_number.items(): scene_jsons = dataset.scene_splits[k].filenames split_to_scene_json[v.name] = scene_jsons split_to_scene_dir[v.name] = [os.path.dirname(scene_json) for scene_json in scene_jsons] assert (len(set(split_to_scene_dir[v.name])) == len(split_to_scene_dir[v.name])) return (split_to_scene_json, split_to_scene_dir)
def open_pbobject(path, pb_class): 'Load JSON as a protobuf (pb2) object.\n\n Any calls to load protobuf objects from JSON in this repository should be through this function.\n Returns `None` if the loading failed.\n\n Parameters\n ----------\n path: str\n Local JSON file path or remote scene dataset JSON URI to load.\n\n pb_class: object\n Protobuf pb2 object we want to load into.\n\n Returns\n ----------\n pb_object: pb2 object\n Desired pb2 object to be opened.\n ' assert path.endswith('.json'), 'File extension for {} needs to be json.'.format(path) if path.startswith('s3://'): return open_remote_pb_object(path, pb_class) assert os.path.exists(path), f'Path not found: {path}' with open(path, 'r', encoding='UTF-8') as json_file: pb_object = Parse(json_file.read(), pb_class()) return pb_object
def parse_pbobject(source, pb_class): 'Like open_pboject but source can be a path or a bytestring\n\n Parameters\n ----------\n source: str or bytes\n Local JSON file path, remote s3 path to object, or bytestring of serialized object\n\n pb_class: object\n Protobuf pb2 object we want to load into.\n\n Returns\n -------\n pb_object: pb2 object or None\n Desired pb2 ojbect to be parsed or None if loading fails\n ' if isinstance(source, str): return open_pbobject(source, pb_class) elif isinstance(source, bytes): pb_object = pb_class() pb_object.ParseFromString(source) return pb_object else: logging.error(f'cannot parse type {type(source)}')
def open_remote_pb_object(s3_object_uri, pb_class): 'Load JSON as a protobuf (pb2) object from S3 remote\n\n Parameters\n ----------\n s3_object_uri: str\n Remote scene dataset JSON URI.\n\n pb_class: object\n Protobuf pb2 object we want to load into.\n\n Returns\n ----------\n pb_object: pb2 object\n Desired pb2 object to be opened.\n\n Raises\n ------\n ValueError\n Raised if s3_object_uri is not a valid S3 path.\n ' if s3_object_uri.startswith('s3://'): (bucket_name, s3_base_path) = convert_uri_to_bucket_path(s3_object_uri) else: raise ValueError('Expected path to S3 bucket but got {}'.format(s3_object_uri)) pb_object = Parse(get_string_from_s3_file(bucket_name, s3_base_path), pb_class()) return pb_object
def save_pbobject_as_json(pb_object, save_path): '\n Save protobuf (pb2) object to JSON file with our standard indent, key ordering, and other\n settings.\n\n Any calls to save protobuf objects to JSON in this repository should be through this function.\n\n Parameters\n ----------\n pb_object: object\n Protobuf pb2 object we want to save to file\n\n save_path: str\n If save path is a JSON, serialized object is saved to that path. If save path is directory,\n the `pb_object` is saved in <save_path>/<pb_object_sha>.json.\n\n Returns\n -------\n save_path: str\n Returns path to saved pb_object JSON\n ' if os.path.isdir(save_path): save_path = os.path.join(save_path, (generate_uid_from_pbobject(pb_object) + '.json')) assert save_path.endswith('.json'), 'File extension for {} needs to be json.'.format(save_path) with open(save_path, 'w', encoding='UTF-8') as _f: json.dump(MessageToDict(pb_object, including_default_value_fields=True, preserving_proto_field_name=True), _f, indent=2, sort_keys=True) return save_path
def open_ontology_pbobject(ontology_file): 'Open ontology objects, first attempt to open V2 before trying V1.\n\n Parameters\n ----------\n ontology_file: str or bytes\n JSON ontology file path to load or bytestring.\n\n Returns\n -------\n ontology: Ontology object\n Desired Ontology pb2 object to be opened (either V2 or V1). Returns\n None if neither fails to load.\n ' try: ontology = parse_pbobject(ontology_file, OntologyV2Pb2) if (ontology is not None): logging.info('Successfully loaded Ontology V2 spec.') return ontology except Exception: logging.error('Failed to load ontology file with V2 spec, trying V1 spec.') try: ontology = parse_pbobject(ontology_file, OntologyV1Pb2) if (ontology is not None): logging.info('Successfully loaded Ontology V1 spec.') return ontology except Exception: if isinstance(ontology_file, str): logging.error((('Failed to load ontology file' + ontology_file) + 'with V1 spec also, returning None.')) else: logging.error('Failed to load ontology file with V1 spec also, returning None.')
def open_feature_ontology_pbobject(ontology_file): 'Open feature ontology objects.\n\n Parameters\n ----------\n ontology_file: str\n JSON ontology file path to load.\n\n Returns\n -------\n ontology: FeatureOntology object\n Desired Feature Ontology pb2 object to be opened. Returns\n None if neither fails to load.\n ' try: ontology = open_pbobject(ontology_file, FeatureOntologyPb2) if (ontology is not None): logging.info('Successfully loaded FeatureOntology spec.') return ontology except Exception: logging.error((('Failed to load ontology file' + ontology_file) + '.'))
def generate_uid_from_pbobject(pb_object): 'Given a pb object, return the deterministic SHA1 hash hexdigest.\n Used for creating unique IDs.\n\n Parameters\n ----------\n pb_object: object\n A protobuf pb2 object to be hashed.\n\n Returns\n -------\n Hexdigest of annotation content\n ' json_string = json.dumps(MessageToDict(pb_object, including_default_value_fields=True, preserving_proto_field_name=True), indent=2, sort_keys=True) out = StringIO() out.write(json_string) uid = hashlib.sha1(out.getvalue().encode('utf-8')).hexdigest() out.close() return uid
def get_latest_scene(s3_scene_jsons): "From a list of 'scene.json' and/or 'scene_<sha1>.json' paths in s3,\n return a Scene object for the one with the latest timestamp.\n Parameters\n ----------\n s3_scene_jsons: List[str]\n List of 'scene.json' or 'scene_<sha1>.json' paths in s3\n Returns\n -------\n latest_scene: dgp.proto.scene_pb2.Scene\n Scene pb object with the latest creation timestamp.\n scene_json_path: str\n S3 Path to the latest scene JSON.\n Notes\n -----\n This function can be called on the output:\n out, _ = s3_recursive_list(os.path.join(scene_s3_dir, 'scene')\n which is grabbing all 'scene*' files from the Scene directory\n " scenes = [open_remote_pb_object(scene_json, Scene) for scene_json in s3_scene_jsons] creation_ts = [_s.creation_date.ToMicroseconds() for _s in scenes] index = creation_ts.index(max(creation_ts)) return (scenes[index], s3_scene_jsons[index])
def get_scene_statistics(scene, verbose=True): 'Given a DGP scene, return simple statistics (counts) of the scene.\n\n Parameters\n ----------\n scene: dgp.proto.scene_pb2.Scene\n Scene Object.\n\n verbose: bool, optional\n Print the stats if True. Default: True.\n\n Returns\n --------\n scene_stats: OrderedDict\n num_samples: int\n Number of samples in the Scene\n num_images: int\n Number of image datums in the Scene.\n num_point_clouds: int\n Number of point_cloud datums in the Scene.\n <datum_type>_<annotation_type>: int\n Number of <datum_type> with associated <annotation_type> annotation files.\n ' num_samples = len(scene.samples) (num_images, num_point_clouds) = (0, 0) annotation_counts = defaultdict(int) datum_index = {datum.key: idx for (idx, datum) in enumerate(scene.data)} for sample in scene.samples: for datum_key in sample.datum_keys: datum = scene.data[datum_index[datum_key]] if datum.datum.HasField('image'): num_images += 1 elif datum.datum.HasField('point_cloud'): num_point_clouds += 1 else: continue datum_type = datum.datum.WhichOneof('datum_oneof') datum_value = getattr(datum.datum, datum_type) annotations = datum_value.annotations for key in annotations: name = annotations_pb2.AnnotationType.DESCRIPTOR.values_by_number[key].name annotation_counts['{}_{}'.format(datum_type.upper(), name)] += 1 if verbose: print(('-' * 80)) sample_info = 'Samples: {},\t Images: {},\t Point Clouds: {}\n\t'.format(num_samples, num_images, num_point_clouds) sample_info += ', '.join(['{}: {}'.format(k, v) for (k, v) in annotation_counts.items()]) print(('Scene: {}\n\t'.format(scene.name) + sample_info)) return OrderedDict({'num_samples': num_samples, 'num_images': num_images, 'num_point_clouds': num_point_clouds, **annotation_counts})
def _get_bounding_box_annotation_info(annotation_enum): 'Returns datum_type, annotation_pb given an ontology\n Parameters\n ----------\n annotation_enum: dgp.proto.annotations_pb2.AnnotationType\n Annotation type enum\n\n Returns\n -------\n str, dgp.proto.annotations_pb2.[AnnotationClass]\n The datum type, and annotation class corresponding to the annotation enum\n\n Raises\n ------\n Exception\n Raised if annotation_enum value does not map to a supported box type.\n ' if (annotation_enum == annotations_pb2.BOUNDING_BOX_3D): return ('point_cloud', annotations_pb2.BoundingBox3DAnnotations) elif (annotation_enum == annotations_pb2.BOUNDING_BOX_2D): return ('image', annotations_pb2.BoundingBox2DAnnotations) else: raise Exception('Annotation info not supported')
def get_scene_class_statistics(scene, scene_dir, annotation_enum, ontology=None): 'Given a DGP scene, return class counts of the annotations in the scene.\n\n Parameters\n ----------\n scene: dgp.proto.scene_pb2.Scene\n Scene Object.\n\n scene_dir: string\n s3 URL or local path to scene.\n\n annotation_enum: dgp.proto.ontology_pb2.AnnotationType\n Annotation type enum\n\n ontology: dgp.proto.ontology_pb2.Ontology or None\n Stats will be computed for this ontology. If None, the ontology will be read from the scene.\n\n Returns\n --------\n scene_stats: OrderedDict\n class_name: int\n Counts of annotations for each class.\n ' (datum_type, annotation_pb) = _get_bounding_box_annotation_info(annotation_enum) if (ontology is not None): class_counts = OrderedDict({item.name: 0 for item in ontology.items}) id_name_map = {item.id: item.name for item in ontology.items} ontology_sha = generate_uid_from_pbobject(ontology) assert (annotation_enum in scene.ontologies), 'Given annotation_enum not in scene.ontologies!' assert (scene.ontologies[annotation_enum] == ontology_sha), 'Input ontology does not match Scene ontology!' else: ontology_path = os.path.join(scene_dir, ONTOLOGY_FOLDER, (scene.ontologies[annotation_enum] + '.json')) ontology = Ontology(open_ontology_pbobject(ontology_path)) id_name_map = ontology.id_to_name class_counts = OrderedDict({name: 0 for name in ontology.name_to_id}) for datum in scene.data: if (not (datum.datum.WhichOneof('datum_oneof') == datum_type)): continue datum_value = getattr(datum.datum, datum_type) annotations = datum_value.annotations if (annotation_enum not in annotations): continue annotation_path = os.path.join(scene_dir, annotations[annotation_enum]) if annotation_path.startswith('s3://'): annotation_object = open_remote_pb_object(annotation_path, annotation_pb) else: annotation_object = open_pbobject(annotation_path, annotation_pb) for annotation in annotation_object.annotations: class_counts[id_name_map[annotation.class_id]] += 1 return class_counts
class BoundingBox2D(): '2D bounding box object.\n\n Parameters\n ----------\n box: np.ndarray[np.float32]\n Array of 4 floats describing bounding box coordinates. Can be either ([l, t, r, b] or [l, t, w, h]).\n\n class_id: int, default: GENERIC_OBJECT_CLASS\n Integer class ID (0 reserved for background).\n\n instance_id: int, default: None\n Unique instance ID for bounding box. If None provided, the ID is a hash of the bounding box\n location and class.\n\n color: tuple, default: (0, 0, 0)\n RGB tuple for bounding box color\n\n attributes: dict, default: None\n Dictionary of attributes associated with bounding box. If None provided,\n defaults to empty dict.\n\n mode: str, default: ltwh\n One of "ltwh" or "ltrb". Corresponds to "[left, top, width, height]" representation\n or "[left, top, right, bottom]"\n\n Raises\n ------\n Exception\n Raised if the value of mode is unsupported.\n ' def __init__(self, box, class_id=GENERIC_OBJECT_CLASS, instance_id=None, color=(0, 0, 0), attributes=None, mode='ltwh'): assert (box.dtype in (np.float32, np.float64)) assert (box.shape[0] == 4) assert (class_id != 0), '0 is reserved for background, your class must have a different ID' self._box = box self.l = box[0] self.t = box[1] if (mode == 'ltwh'): self.w = box[2] self.h = box[3] elif (mode == 'ltrb'): self.w = (box[2] - box[0]) self.h = (box[3] - box[1]) else: raise Exception(f"Bounding box must be initialized as 'ltrb' or 'ltwh', cannot recognize {mode}") self._class_id = class_id self._instance_id = instance_id self._color = color self._attributes = (dict(attributes) if (attributes is not None) else {}) def intersection_over_union(self, other): 'Compute intersection over union of this box against other(s).\n\n Parameters\n ----------\n other: BoundingBox2D\n A separate BoundingBox2D instance to compute IoU against.\n\n Raises\n ------\n NotImplementedError\n Unconditionally\n ' raise NotImplementedError @property def ltrb(self): return np.array([self.l, self.t, (self.l + self.w), (self.t + self.h)], dtype=np.float32) @property def ltwh(self): return np.array([self.l, self.t, self.w, self.h], dtype=np.float32) @property def class_id(self): return self._class_id @class_id.setter def class_id(self, class_id): self._class_id = class_id @property def instance_id(self): if (self._instance_id is None): return self.hexdigest return self._instance_id @property def area(self): return (self.w * self.h) @property def color(self): return self._color @property def attributes(self): return self._attributes @property def hexdigest(self): return hashlib.md5((self.ltrb.tobytes() + bytes(self._class_id))).hexdigest() def __repr__(self): return '{}[{}, Class: {}, Attributes: {}]'.format(self.__class__.__name__, list(self.ltrb), self.class_id, self.attributes) def __eq__(self, other): return (self.hexdigest == other.hexdigest) def render(self, image): 'Render bounding boxes on an image.\n\n Parameters\n ----------\n image: PIL.Image or np.ndarray\n Background image on which boxes are rendered\n\n Returns\n -------\n image: PIL.Image or np.ndarray\n Image with boxes rendered\n ' raise NotImplementedError def to_proto(self): 'Serialize bounding box to proto object.\n\n NOTE: Does not serialize class or instance information, just box geometry.\n To serialize a complete annotation, see `dgp/annotations/bounding_box_2d_annotation.py`\n\n Returns\n -------\n BoundingBox2D.pb2\n As defined in `proto/annotations.proto`\n ' return annotations_pb2.BoundingBox2D(x=int(self.l), y=int(self.t), w=int(self.w), h=int(self.h))
class InstanceMask2D(): '2D instance mask object.\n\n Parameters\n ----------\n mask: np.ndarray[bool, np.uint8, np.int64]\n 2D boolean array describiing instance mask.\n\n class_id: int, default: GENERIC_OBJECT_CLASS\n Integer class ID (0 reserved for background).\n\n instance_id: int, default: None\n Unique instance ID for instance mask. If None provided, the ID is a hash of the instance mask,\n location and class.\n\n attributes: dict, default: None\n Dictionary of attributes associated with instance mask. If None provided,\n defaults to empty dict.\n ' def __init__(self, mask, class_id=GENERIC_OBJECT_CLASS, instance_id=None, color=(0, 0, 0), attributes=None): assert (mask.dtype in (bool, np.uint8, np.int64)) self._bitmask = mask self._class_id = class_id self._instance_id = instance_id self._color = color self._attributes = (dict(attributes) if (attributes is not None) else {}) def intersection_over_union(self, other): 'Compute intersection over union of this box against other(s).\n\n Parameters\n ----------\n other: InstanceMask2D\n Another instance of InstanceMask2D to compute IoU against.\n\n Raises\n ------\n NotImplementedError\n Unconditionally.\n ' raise NotImplementedError @property def bitmask(self): return self._bitmask @property def class_id(self): return self._class_id @class_id.setter def class_id(self, class_id): self._class_id = class_id @property def color(self): return self._color @property def instance_id(self): if (self._instance_id is None): return self.hexdigest return self._instance_id @property def area(self): 'Compute intersection over union of this box against other(s).' return np.sum(self.bitmask) @property def attributes(self): return self._attributes @property def hexdigest(self): return hashlib.md5(((self.bitmask.tobytes() + bytes(self._class_id)) + bytes(self._instance_id))).hexdigest() def __repr__(self): return '{}[Class: {}, Attributes: {}]'.format(self.__class__.__name__, self.class_id, self.attributes) def __eq__(self, other): return (self.hexdigest == other.hexdigest) def render(self, image): 'Render instance masks on an image.\n\n Parameters\n ----------\n image: PIL.Image or np.ndarray\n Background image on which boxes are rendered\n\n Returns\n -------\n image: PIL.Image or np.ndarray\n Image with boxes rendered\n ' raise NotImplementedError @property def rle(self): _rle = mask_util.encode(np.array(self.bitmask, np.uint8, order='F')) return RLEMask(_rle['size'], _rle['counts'])
class RLEMask(): 'Container of RLE-encoded mask.\n\n See https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocotools/mask.py for RLE format.\n\n Parameters\n ----------\n size: list[int] or np.ndarray[int]\n Height and width of mask.\n counts: list[int]\n Count-encoding of RLE format.\n ' def __init__(self, size, counts): self.size = size self.counts = counts def to_dict(self): return OrderedDict([('size', self.size), ('counts', self.counts)])
class KeyLine2D(): '2D keyline object.\n\n Parameters\n ----------\n line: np.ndarray[np.float32]\n Array of N*2 floats describing keyline coordinates [x, y].\n\n class_id: int, default: GENERIC_OBJECT_CLASS\n Integer class ID\n\n instance_id: int, default: None\n Unique instance ID for keyline. If None provided, the ID is a hash of the keyline\n location and class.\n\n color: tuple, default: (0, 0, 0)\n RGB tuple for keyline color\n\n attributes: dict, default: None\n Dictionary of attributes associated with keyline. If None provided,\n defaults to empty dict.\n\n ' def __init__(self, line, class_id=GENERIC_OBJECT_CLASS, instance_id=None, color=(0, 0, 0), attributes=None): assert (line.dtype in (np.float32, np.float64)) assert (line.shape[1] == 2) self._point = line self.x = [] self.y = [] for point in line: self.x.append(point[0]) self.y.append(point[1]) self._class_id = class_id self._instance_id = instance_id self._color = color self._attributes = (dict(attributes) if (attributes is not None) else {}) @property def xy(self): return np.array([self.x, self.y], dtype=np.float32) @property def class_id(self): return self._class_id @property def instance_id(self): if (self._instance_id is None): return self.hexdigest return self._instance_id @property def color(self): return self._color @property def attributes(self): return self._attributes @property def hexdigest(self): return hashlib.md5((self.xy.tobytes() + bytes(self._class_id))).hexdigest() def __repr__(self): return '{}[{}, Class: {}, Attributes: {}]'.format(self.__class__.__name__, list(self.xy), self.class_id, self.attributes) def __eq__(self, other): return (self.hexdigest == other.hexdigest) def to_proto(self): 'Serialize keyline to proto object.\n\n NOTE: Does not serialize class or instance information, just line geometry.\n To serialize a complete annotation, see `dgp/annotations/key_line_2d_annotation.py`\n\n Returns\n -------\n KeyLine2D.pb2\n As defined in `proto/annotations.proto`\n ' return [annotations_pb2.KeyPoint2D(x=int(self.x[j]), y=int(self.y[j])) for (j, k) in enumerate(self.x)]
class KeyLine3D(): '3D keyline object.\n\n Parameters\n ----------\n line: np.ndarray[np.float32]\n Array of (N,3) floats describing keyline coordinates [x, y, z].\n\n class_id: int, default: GENERIC_OBJECT_CLASS_ID\n Integer class ID\n\n instance_id: int, default: None\n Unique instance ID for keyline. If None provided, the ID is a hash of the keyline\n location and class.\n\n color: tuple, default: (0, 0, 0)\n RGB tuple for keyline color\n\n attributes: dict, default: None\n Dictionary of attributes associated with keyline. If None provided,\n defaults to empty dict.\n\n ' def __init__(self, line, class_id=GENERIC_OBJECT_CLASS_ID, instance_id=None, color=(0, 0, 0), attributes=None): assert (line.dtype in (np.float32, np.float64)) assert (line.shape[1] == 3) self._point = line self.x = [] self.y = [] self.z = [] for point in line: self.x.append(point[0]) self.y.append(point[1]) self.z.append(point[2]) self._class_id = class_id self._instance_id = instance_id self._color = color self._attributes = (dict(attributes) if (attributes is not None) else {}) @property def xyz(self): return np.array([self.x, self.y, self.z], dtype=np.float32) @property def class_id(self): return self._class_id @property def instance_id(self): if (self._instance_id is None): return self.hexdigest return self._instance_id @property def color(self): return self._color @property def attributes(self): return self._attributes @property def hexdigest(self): return hashlib.md5((self.xyz.tobytes() + bytes(self._class_id))).hexdigest() def __repr__(self): return '{}[{}, Class: {}, Attributes: {}]'.format(self.__class__.__name__, list(self.xyz), self.class_id, self.attributes) def __eq__(self, other): return (self.hexdigest == other.hexdigest) def to_proto(self): 'Serialize keyline to proto object.\n\n Does not serialize class or instance information, just line geometry.\n To serialize a complete annotation, see `dgp/annotations/key_line_3d_annotation.py`\n\n Returns\n -------\n KeyLine3D.pb2\n As defined in `proto/annotations.proto`\n ' return [annotations_pb2.KeyPoint3D(x=int(self.x[j]), y=int(self.y[j]), z=int(self.z[j])) for (j, _) in enumerate(self.x)]
class KeyPoint2D(): '2D keypoint object.\n\n Parameters\n ----------\n point: np.ndarray[np.float32]\n Array of 2 floats describing keypoint coordinates [x, y].\n\n class_id: int, default: GENERIC_OBJECT_CLASS\n Integer class ID (0 reserved for background).\n\n instance_id: int, default: None\n Unique instance ID for keypoint. If None provided, the ID is a hash of the keypoint\n location and class.\n\n color: tuple, default: (0, 0, 0)\n RGB tuple for keypoint color\n\n attributes: dict, default: None\n Dictionary of attributes associated with keypoint. If None provided,\n defaults to empty dict.\n\n ' def __init__(self, point, class_id=GENERIC_OBJECT_CLASS, instance_id=None, color=(0, 0, 0), attributes=None): assert (point.dtype in (np.float32, np.float64)) assert (point.shape[0] == 2) assert (class_id != 0), '0 is reserved for background, your class must have a different ID' self._point = point self.x = point[0] self.y = point[1] self._class_id = class_id self._instance_id = instance_id self._color = color self._attributes = (dict(attributes) if (attributes is not None) else {}) @property def xy(self): return np.array([self.x, self.y], dtype=np.float32) @property def class_id(self): return self._class_id @property def instance_id(self): if (self._instance_id is None): return self.hexdigest return self._instance_id @property def color(self): return self._color @property def attributes(self): return self._attributes @property def hexdigest(self): return hashlib.md5((self.xy.tobytes() + bytes(self._class_id))).hexdigest() def __repr__(self): return '{}[{}, Class: {}, Attributes: {}]'.format(self.__class__.__name__, list(self.xy), self.class_id, self.attributes) def __eq__(self, other): return (self.hexdigest == other.hexdigest) def to_proto(self): 'Serialize keypoint to proto object.\n\n NOTE: Does not serialize class or instance information, just point geometry.\n To serialize a complete annotation, see `dgp/annotations/key_point_2d_annotation.py`\n\n Returns\n -------\n KeyPoint2D.pb2\n As defined in `proto/annotations.proto`\n ' return annotations_pb2.KeyPoint2D(x=int(self.x), y=int(self.y))
class KeyPoint3D(): '3D keypoint object.\n\n Parameters\n ----------\n point: np.ndarray[np.float32]\n Array of 3 floats describing keypoint coordinates [x, y, z].\n\n class_id: int, default: GENERIC_OBJECT_CLASS_ID\n Integer class ID (0 reserved for background).\n\n instance_id: int, default: None\n Unique instance ID for keypoint. If None provided, the ID is a hash of the keypoint\n location and class.\n\n color: tuple, default: (0, 0, 0)\n RGB tuple for keypoint color\n\n attributes: dict, default: None\n Dictionary of attributes associated with keypoint. If None provided,\n defaults to empty dict.\n\n ' def __init__(self, point, class_id=GENERIC_OBJECT_CLASS_ID, instance_id=None, color=(0, 0, 0), attributes=None): assert (point.dtype in (np.float32, np.float64)) assert (point.shape[0] == 3) self._point = point self.x = point[0] self.y = point[1] self.z = point[2] self._class_id = class_id self._instance_id = instance_id self._color = color self._attributes = (dict(attributes) if (attributes is not None) else {}) @property def xyz(self): return np.array([self.x, self.y, self.z], dtype=np.float32) @property def class_id(self): return self._class_id @property def instance_id(self): if (self._instance_id is None): return self.hexdigest return self._instance_id @property def color(self): return self._color @property def attributes(self): return self._attributes @property def hexdigest(self): return hashlib.md5((self.xyz.tobytes() + bytes(self._class_id))).hexdigest() def __repr__(self): return '{}[{}, Class: {}, Attributes: {}]'.format(self.__class__.__name__, list(self.xyz), self.class_id, self.attributes) def __eq__(self, other): return (self.hexdigest == other.hexdigest) def to_proto(self): 'Serialize keypoint to proto object.\n\n Does not serialize class or instance information, just point geometry.\n To serialize a complete annotation, see `dgp/annotations/key_point_3d_annotation.py`\n\n Returns\n -------\n KeyPoint3D.pb2\n As defined in `proto/annotations.proto`\n ' return annotations_pb2.KeyPoint3D(x=int(self.x), y=int(self.y), z=int(self.z))
def assert_between(value, low, high, low_inclusive=True, high_inclusive=True): '\n Assert ``value`` is inside the specified range.\n Parameters\n ----------\n value : comparable\n Value to be asserted.\n\n low : comparable\n Range lower bound.\n\n high : comparable\n Range upper bound.\n\n low_inclusive : bool, optional\n Allow case when value == low. Default: True.\n\n high_inclusive : bool, optional\n Allow case when value == high. Default: True.\n ' if low_inclusive: assert_greater_equal(value, low) else: assert_greater(value, low) if high_inclusive: assert_less_equal(value, high) else: assert_less(value, high)
@lru_cache(maxsize=None) def meshgrid(B, H, W, dtype, device, normalized=False): 'Create mesh-grid given batch size, height and width dimensions.\n\n Parameters\n ----------\n B: int\n Batch size\n H: int\n Grid Height\n W: int\n Batch size\n dtype: torch.dtype\n Tensor dtype\n device: str\n Tensor device\n normalized: bool\n Normalized image coordinates or integer-grid.\n\n Returns\n -------\n xs: torch.Tensor\n Batched mesh-grid x-coordinates (BHW).\n ys: torch.Tensor\n Batched mesh-grid y-coordinates (BHW).\n ' if normalized: xs = torch.linspace((- 1), 1, W, device=device, dtype=dtype) ys = torch.linspace((- 1), 1, H, device=device, dtype=dtype) else: xs = torch.linspace(0, (W - 1), W, device=device, dtype=dtype) ys = torch.linspace(0, (H - 1), H, device=device, dtype=dtype) (ys, xs) = torch.meshgrid([ys, xs]) return (xs.repeat([B, 1, 1]), ys.repeat([B, 1, 1]))
@lru_cache(maxsize=None) def image_grid(B, H, W, dtype, device, normalized=False): 'Create an image mesh grid with shape B3HW given image shape BHW\n\n Parameters\n ----------\n B: int\n Batch size\n H: int\n Grid Height\n W: int\n Batch size\n dtype: str\n Tensor dtype\n device: str\n Tensor device\n normalized: bool\n Normalized image coordinates or integer-grid.\n\n Returns\n -------\n grid: torch.Tensor\n Mesh-grid for the corresponding image shape (B3HW)\n ' (xs, ys) = meshgrid(B, H, W, dtype, device, normalized=normalized) ones = torch.ones_like(xs) grid = torch.stack([xs, ys, ones], dim=1) return grid
def load_midas_net(name: str) -> tuple[(nn.Module, Compose)]: 'Load a frozen pre-trained Midas network from the PyTorch Hub.\n From: https://arxiv.org/abs/1907.01341 & https://arxiv.org/abs/2103.13413\n\n Pre-processing: ImageNet standarization & resizing (provided by `tfm`).\n Pre-processing: Bicubic resizing.\n\n Training shapes: Images are resized such that the height/width are 384 or 512 and aspect ratio is retained.\n See https://github.com/isl-org/MiDaS/blob/1645b7e1675301fdfac03640738fe5a6531e17d6/midas/transforms.py#L48 for\n additional details\n\n Prediction:\n ```\n # Prediction is made in scaleless disparity.\n img: np.array (unit8)\n pred = net(tfm(img))\n ```\n\n :param name: (str) Model configuration to load.\n :return: (nn.Module, Any) Loaded model & pre-processing transforms.\n ' net = torch.hub.load('intel-isl/MiDaS', name).eval() for p in net.parameters(): p.requires_grad = False tfms = torch.hub.load('intel-isl/MiDaS', 'transforms') if ('DPT' in name): tfm = tfms.dpt_transform elif ('BEiT' in name): tfm = tfms.beit512_transform elif (name == 'MiDaS_small'): tfm = tfms.small_transform else: tfm = tfms.default_transform return (net, tfm)
class NewCRFDepth(nn.Module): '\n Depth network based on neural window FC-CRFs architecture.\n ' def __init__(self, version=None, inv_depth=False, pretrained=None, frozen_stages=(- 1), min_depth=0.1, max_depth=100.0, **kwargs): super().__init__() self.inv_depth = inv_depth self.with_auxiliary_head = False self.with_neck = False norm_cfg = dict(type='BN', requires_grad=True) window_size = int(version[(- 2):]) if (version[:(- 2)] == 'base'): embed_dim = 128 depths = [2, 2, 18, 2] num_heads = [4, 8, 16, 32] in_channels = [128, 256, 512, 1024] elif (version[:(- 2)] == 'large'): embed_dim = 192 depths = [2, 2, 18, 2] num_heads = [6, 12, 24, 48] in_channels = [192, 384, 768, 1536] elif (version[:(- 2)] == 'tiny'): embed_dim = 96 depths = [2, 2, 6, 2] num_heads = [3, 6, 12, 24] in_channels = [96, 192, 384, 768] backbone_cfg = dict(embed_dim=embed_dim, depths=depths, num_heads=num_heads, window_size=window_size, ape=False, drop_path_rate=0.3, patch_norm=True, use_checkpoint=False, frozen_stages=frozen_stages) embed_dim = 512 decoder_cfg = dict(in_channels=in_channels, in_index=[0, 1, 2, 3], pool_scales=(1, 2, 3, 6), channels=embed_dim, dropout_ratio=0.0, num_classes=32, norm_cfg=norm_cfg, align_corners=False) self.backbone = SwinTransformer(**backbone_cfg) v_dim = (decoder_cfg['num_classes'] * 4) win = 7 crf_dims = [128, 256, 512, 1024] v_dims = [64, 128, 256, embed_dim] self.crf3 = NewCRF(input_dim=in_channels[3], embed_dim=crf_dims[3], window_size=win, v_dim=v_dims[3], num_heads=32) self.crf2 = NewCRF(input_dim=in_channels[2], embed_dim=crf_dims[2], window_size=win, v_dim=v_dims[2], num_heads=16) self.crf1 = NewCRF(input_dim=in_channels[1], embed_dim=crf_dims[1], window_size=win, v_dim=v_dims[1], num_heads=8) self.crf0 = NewCRF(input_dim=in_channels[0], embed_dim=crf_dims[0], window_size=win, v_dim=v_dims[0], num_heads=4) self.decoder = PSP(**decoder_cfg) self.disp_head1 = DispHead(input_dim=crf_dims[0]) self.up_mode = 'bilinear' if (self.up_mode == 'mask'): self.mask_head = nn.Sequential(nn.Conv2d(crf_dims[0], 64, 3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(64, (16 * 9), 1, padding=0)) self.min_depth = min_depth self.max_depth = max_depth self.init_weights(pretrained=pretrained) def init_weights(self, pretrained=None): 'Initialize the weights in backbone and heads.\n\n Args:\n pretrained (str, optional): Path to pre-trained weights.\n Defaults to None.\n ' print(f'== Load encoder backbone from: {pretrained}') self.backbone.init_weights(pretrained=pretrained) self.decoder.init_weights() if self.with_auxiliary_head: if isinstance(self.auxiliary_head, nn.ModuleList): for aux_head in self.auxiliary_head: aux_head.init_weights() else: self.auxiliary_head.init_weights() def upsample_mask(self, disp, mask): ' Upsample disp [H/4, W/4, 1] -> [H, W, 1] using convex combination ' (N, _, H, W) = disp.shape mask = mask.view(N, 1, 9, 4, 4, H, W) mask = torch.softmax(mask, dim=2) up_disp = F.unfold(disp, kernel_size=3, padding=1) up_disp = up_disp.view(N, 1, 9, 1, 1, H, W) up_disp = torch.sum((mask * up_disp), dim=2) up_disp = up_disp.permute(0, 1, 4, 2, 5, 3) return up_disp.reshape(N, 1, (4 * H), (4 * W)) def forward(self, imgs): feats = self.backbone(imgs) if self.with_neck: feats = self.neck(feats) ppm_out = self.decoder(feats) e3 = self.crf3(feats[3], ppm_out) e3 = nn.PixelShuffle(2)(e3) e2 = self.crf2(feats[2], e3) e2 = nn.PixelShuffle(2)(e2) e1 = self.crf1(feats[1], e2) e1 = nn.PixelShuffle(2)(e1) e0 = self.crf0(feats[0], e1) if (self.up_mode == 'mask'): mask = self.mask_head(e0) d1 = self.disp_head1(e0, 1) d1 = self.upsample_mask(d1, mask) else: d1 = self.disp_head1(e0, 4) depth = (d1 * self.max_depth) return depth
class DispHead(nn.Module): def __init__(self, input_dim=100): super(DispHead, self).__init__() self.conv1 = nn.Conv2d(input_dim, 1, 3, padding=1) self.sigmoid = nn.Sigmoid() def forward(self, x, scale): x = self.sigmoid(self.conv1(x)) if (scale > 1): x = upsample(x, scale_factor=scale) return x
class DispUnpack(nn.Module): def __init__(self, input_dim=100, hidden_dim=128): super(DispUnpack, self).__init__() self.conv1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1) self.conv2 = nn.Conv2d(hidden_dim, 16, 3, padding=1) self.relu = nn.ReLU(inplace=True) self.sigmoid = nn.Sigmoid() self.pixel_shuffle = nn.PixelShuffle(4) def forward(self, x, output_size): x = self.relu(self.conv1(x)) x = self.sigmoid(self.conv2(x)) x = self.pixel_shuffle(x) return x
def upsample(x, scale_factor=2, mode='bilinear', align_corners=False): 'Upsample input tensor by a factor of 2\n ' return F.interpolate(x, scale_factor=scale_factor, mode=mode, align_corners=align_corners)
def resize(input, size=None, scale_factor=None, mode='nearest', align_corners=None, warning=True): if warning: if ((size is not None) and align_corners): (input_h, input_w) = tuple((int(x) for x in input.shape[2:])) (output_h, output_w) = tuple((int(x) for x in size)) if ((output_h > input_h) or (output_w > output_h)): if (((output_h > 1) and (output_w > 1) and (input_h > 1) and (input_w > 1)) and ((output_h - 1) % (input_h - 1)) and ((output_w - 1) % (input_w - 1))): warnings.warn(f'When align_corners={align_corners}, the output would more aligned if input size {(input_h, input_w)} is `x+1` and out size {(output_h, output_w)} is `nx+1`') if isinstance(size, torch.Size): size = tuple((int(x) for x in size)) return F.interpolate(input, size, scale_factor, mode, align_corners)
def normal_init(module, mean=0, std=1, bias=0): if (hasattr(module, 'weight') and (module.weight is not None)): nn.init.normal_(module.weight, mean, std) if (hasattr(module, 'bias') and (module.bias is not None)): nn.init.constant_(module.bias, bias)
def is_module_wrapper(module): module_wrappers = (DataParallel, DistributedDataParallel) return isinstance(module, module_wrappers)
def get_dist_info(): if (TORCH_VERSION < '1.0'): initialized = dist._initialized elif dist.is_available(): initialized = dist.is_initialized() else: initialized = False if initialized: rank = dist.get_rank() world_size = dist.get_world_size() else: rank = 0 world_size = 1 return (rank, world_size)
def load_state_dict(module, state_dict, strict=False, logger=None): "Load state_dict to a module.\n\n This method is modified from :meth:`torch.nn.Module.load_state_dict`.\n Default value for ``strict`` is set to ``False`` and the message for\n param mismatch will be shown even if strict is False.\n\n Args:\n module (Module): Module that receives the state_dict.\n state_dict (OrderedDict): Weights.\n strict (bool): whether to strictly enforce that the keys\n in :attr:`state_dict` match the keys returned by this module's\n :meth:`~torch.nn.Module.state_dict` function. Default: ``False``.\n logger (:obj:`logging.Logger`, optional): Logger to log the error\n message. If not specified, print function will be used.\n " unexpected_keys = [] all_missing_keys = [] err_msg = [] metadata = getattr(state_dict, '_metadata', None) state_dict = state_dict.copy() if (metadata is not None): state_dict._metadata = metadata def load(module, prefix=''): if is_module_wrapper(module): module = module.module local_metadata = ({} if (metadata is None) else metadata.get(prefix[:(- 1)], {})) module._load_from_state_dict(state_dict, prefix, local_metadata, True, all_missing_keys, unexpected_keys, err_msg) for (name, child) in module._modules.items(): if (child is not None): load(child, ((prefix + name) + '.')) load(module) load = None missing_keys = [key for key in all_missing_keys if ('num_batches_tracked' not in key)] if unexpected_keys: err_msg.append(f'''unexpected key in source state_dict: {', '.join(unexpected_keys)} ''') if missing_keys: err_msg.append(f'''missing keys in source state_dict: {', '.join(missing_keys)} ''') (rank, _) = get_dist_info() if ((len(err_msg) > 0) and (rank == 0)): err_msg.insert(0, 'The model and loaded state dict do not match exactly\n') err_msg = '\n'.join(err_msg) if strict: raise RuntimeError(err_msg) elif (logger is not None): logger.warning(err_msg) else: print(err_msg)
def load_url_dist(url, model_dir=None): 'In distributed setting, this function only download checkpoint at local\n rank 0.' (rank, world_size) = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if (rank == 0): checkpoint = model_zoo.load_url(url, model_dir=model_dir) if (world_size > 1): torch.distributed.barrier() if (rank > 0): checkpoint = model_zoo.load_url(url, model_dir=model_dir) return checkpoint
def get_torchvision_models(): model_urls = dict() for (_, name, ispkg) in pkgutil.walk_packages(torchvision.models.__path__): if ispkg: continue _zoo = import_module(f'torchvision.models.{name}') if hasattr(_zoo, 'model_urls'): _urls = getattr(_zoo, 'model_urls') model_urls.update(_urls) return model_urls
def _load_checkpoint(filename, map_location=None): 'Load checkpoint from somewhere (modelzoo, file, url).\n\n Args:\n filename (str): Accept local filepath, URL, ``torchvision://xxx``,\n ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for\n details.\n map_location (str | None): Same as :func:`torch.load`. Default: None.\n\n Returns:\n dict | OrderedDict: The loaded checkpoint. It can be either an\n OrderedDict storing model weights or a dict containing other\n information, which depends on the checkpoint.\n ' if filename.startswith('modelzoo://'): warnings.warn('The URL scheme of "modelzoo://" is deprecated, please use "torchvision://" instead') model_urls = get_torchvision_models() model_name = filename[11:] checkpoint = load_url_dist(model_urls[model_name]) else: if (not osp.isfile(filename)): raise IOError(f'{filename} is not a checkpoint file') checkpoint = torch.load(filename, map_location=map_location) return checkpoint
def load_checkpoint(model, filename, map_location='cpu', strict=False, logger=None): 'Load checkpoint from a file or URI.\n\n Args:\n model (Module): Module to load checkpoint.\n filename (str): Accept local filepath, URL, ``torchvision://xxx``,\n ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for\n details.\n map_location (str): Same as :func:`torch.load`.\n strict (bool): Whether to allow different params for the model and\n checkpoint.\n logger (:mod:`logging.Logger` or None): The logger for error message.\n\n Returns:\n dict or OrderedDict: The loaded checkpoint.\n ' checkpoint = _load_checkpoint(filename, map_location) if (not isinstance(checkpoint, dict)): raise RuntimeError(f'No state_dict found in checkpoint file {filename}') if ('state_dict' in checkpoint): state_dict = checkpoint['state_dict'] elif ('model' in checkpoint): state_dict = checkpoint['model'] else: state_dict = checkpoint if list(state_dict.keys())[0].startswith('module.'): state_dict = {k[7:]: v for (k, v) in state_dict.items()} if sorted(list(state_dict.keys()))[0].startswith('encoder'): state_dict = {k.replace('encoder.', ''): v for (k, v) in state_dict.items() if k.startswith('encoder.')} if (state_dict.get('absolute_pos_embed') is not None): absolute_pos_embed = state_dict['absolute_pos_embed'] (N1, L, C1) = absolute_pos_embed.size() (N2, C2, H, W) = model.absolute_pos_embed.size() if ((N1 != N2) or (C1 != C2) or (L != (H * W))): logger.warning('Error in loading absolute_pos_embed, pass') else: state_dict['absolute_pos_embed'] = absolute_pos_embed.view(N2, H, W, C2).permute(0, 3, 1, 2) relative_position_bias_table_keys = [k for k in state_dict.keys() if ('relative_position_bias_table' in k)] for table_key in relative_position_bias_table_keys: table_pretrained = state_dict[table_key] table_current = model.state_dict()[table_key] (L1, nH1) = table_pretrained.size() (L2, nH2) = table_current.size() if (nH1 != nH2): logger.warning(f'Error in loading {table_key}, pass') elif (L1 != L2): S1 = int((L1 ** 0.5)) S2 = int((L2 ** 0.5)) table_pretrained_resized = F.interpolate(table_pretrained.permute(1, 0).view(1, nH1, S1, S1), size=(S2, S2), mode='bicubic') state_dict[table_key] = table_pretrained_resized.view(nH2, L2).permute(1, 0) load_state_dict(model, state_dict, strict, logger) return checkpoint
class PPM(nn.ModuleList): 'Pooling Pyramid Module used in PSPNet.\n\n Args:\n pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid\n Module.\n in_channels (int): Input channels.\n channels (int): Channels after modules, before conv_seg.\n conv_cfg (dict|None): Config of conv layers.\n norm_cfg (dict|None): Config of norm layers.\n act_cfg (dict): Config of activation layers.\n align_corners (bool): align_corners argument of F.interpolate.\n ' def __init__(self, pool_scales, in_channels, channels, conv_cfg, norm_cfg, act_cfg, align_corners): super(PPM, self).__init__() self.pool_scales = pool_scales self.align_corners = align_corners self.in_channels = in_channels self.channels = channels self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.act_cfg = act_cfg for pool_scale in pool_scales: if (pool_scale == 1): norm_cfg = dict(type='GN', requires_grad=True, num_groups=256) self.append(nn.Sequential(nn.AdaptiveAvgPool2d(pool_scale), ConvModule(self.in_channels, self.channels, 1, conv_cfg=self.conv_cfg, norm_cfg=norm_cfg, act_cfg=self.act_cfg))) def forward(self, x): 'Forward function.' ppm_outs = [] for ppm in self: ppm_out = ppm(x) upsampled_ppm_out = resize(ppm_out, size=x.size()[2:], mode='bilinear', align_corners=self.align_corners) ppm_outs.append(upsampled_ppm_out) return ppm_outs
class BaseDecodeHead(nn.Module): "Base class for BaseDecodeHead.\n\n Args:\n in_channels (int|Sequence[int]): Input channels.\n channels (int): Channels after modules, before conv_seg.\n num_classes (int): Number of classes.\n dropout_ratio (float): Ratio of dropout layer. Default: 0.1.\n conv_cfg (dict|None): Config of conv layers. Default: None.\n norm_cfg (dict|None): Config of norm layers. Default: None.\n act_cfg (dict): Config of activation layers.\n Default: dict(type='ReLU')\n in_index (int|Sequence[int]): Input feature index. Default: -1\n input_transform (str|None): Transformation type of input features.\n Options: 'resize_concat', 'multiple_select', None.\n 'resize_concat': Multiple feature maps will be resize to the\n same size as first one and than concat together.\n Usually used in FCN head of HRNet.\n 'multiple_select': Multiple feature maps will be bundle into\n a list and passed into decode head.\n None: Only one select feature map is allowed.\n Default: None.\n loss_decode (dict): Config of decode loss.\n Default: dict(type='CrossEntropyLoss').\n ignore_index (int | None): The label index to be ignored. When using\n masked BCE loss, ignore_index should be set to None. Default: 255\n sampler (dict|None): The config of segmentation map sampler.\n Default: None.\n align_corners (bool): align_corners argument of F.interpolate.\n Default: False.\n " def __init__(self, in_channels, channels, *, num_classes, dropout_ratio=0.1, conv_cfg=None, norm_cfg=None, act_cfg=dict(type='ReLU'), in_index=(- 1), input_transform=None, loss_decode=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), ignore_index=255, sampler=None, align_corners=False): super(BaseDecodeHead, self).__init__() self._init_inputs(in_channels, in_index, input_transform) self.channels = channels self.num_classes = num_classes self.dropout_ratio = dropout_ratio self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.act_cfg = act_cfg self.in_index = in_index self.ignore_index = ignore_index self.align_corners = align_corners if (dropout_ratio > 0): self.dropout = nn.Dropout2d(dropout_ratio) else: self.dropout = None self.fp16_enabled = False def extra_repr(self): 'Extra repr.' s = f'input_transform={self.input_transform}, ignore_index={self.ignore_index}, align_corners={self.align_corners}' return s def _init_inputs(self, in_channels, in_index, input_transform): "Check and initialize input transforms.\n\n The in_channels, in_index and input_transform must match.\n Specifically, when input_transform is None, only single feature map\n will be selected. So in_channels and in_index must be of type int.\n When input_transform\n\n Args:\n in_channels (int|Sequence[int]): Input channels.\n in_index (int|Sequence[int]): Input feature index.\n input_transform (str|None): Transformation type of input features.\n Options: 'resize_concat', 'multiple_select', None.\n 'resize_concat': Multiple feature maps will be resize to the\n same size as first one and than concat together.\n Usually used in FCN head of HRNet.\n 'multiple_select': Multiple feature maps will be bundle into\n a list and passed into decode head.\n None: Only one select feature map is allowed.\n " if (input_transform is not None): assert (input_transform in ['resize_concat', 'multiple_select']) self.input_transform = input_transform self.in_index = in_index if (input_transform is not None): assert isinstance(in_channels, (list, tuple)) assert isinstance(in_index, (list, tuple)) assert (len(in_channels) == len(in_index)) if (input_transform == 'resize_concat'): self.in_channels = sum(in_channels) else: self.in_channels = in_channels else: assert isinstance(in_channels, int) assert isinstance(in_index, int) self.in_channels = in_channels def init_weights(self): 'Initialize weights of classification layer.' def _transform_inputs(self, inputs): 'Transform inputs for decoder.\n\n Args:\n inputs (list[Tensor]): List of multi-level img features.\n\n Returns:\n Tensor: The transformed inputs\n ' if (self.input_transform == 'resize_concat'): inputs = [inputs[i] for i in self.in_index] upsampled_inputs = [resize(input=x, size=inputs[0].shape[2:], mode='bilinear', align_corners=self.align_corners) for x in inputs] inputs = torch.cat(upsampled_inputs, dim=1) elif (self.input_transform == 'multiple_select'): inputs = [inputs[i] for i in self.in_index] else: inputs = inputs[self.in_index] return inputs def forward(self, inputs): 'Placeholder of forward function.' pass def forward_train(self, inputs, img_metas, gt_semantic_seg, train_cfg): "Forward function for training.\n Args:\n inputs (list[Tensor]): List of multi-level img features.\n img_metas (list[dict]): List of image info dict where each dict\n has: 'img_shape', 'scale_factor', 'flip', and may also contain\n 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.\n For details on the values of these keys see\n `mmseg/datasets/pipelines/formatting.py:Collect`.\n gt_semantic_seg (Tensor): Semantic segmentation masks\n used if the architecture supports semantic segmentation task.\n train_cfg (dict): The training config.\n\n Returns:\n dict[str, Tensor]: a dictionary of loss components\n " seg_logits = self.forward(inputs) losses = self.losses(seg_logits, gt_semantic_seg) return losses def forward_test(self, inputs, img_metas, test_cfg): "Forward function for testing.\n\n Args:\n inputs (list[Tensor]): List of multi-level img features.\n img_metas (list[dict]): List of image info dict where each dict\n has: 'img_shape', 'scale_factor', 'flip', and may also contain\n 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'.\n For details on the values of these keys see\n `mmseg/datasets/pipelines/formatting.py:Collect`.\n test_cfg (dict): The testing config.\n\n Returns:\n Tensor: Output segmentation map.\n " return self.forward(inputs)
class UPerHead(BaseDecodeHead): def __init__(self, pool_scales=(1, 2, 3, 6), **kwargs): super(UPerHead, self).__init__(input_transform='multiple_select', **kwargs) self.lateral_convs = nn.ModuleList() self.fpn_convs = nn.ModuleList() for in_channels in self.in_channels: l_conv = ConvModule(in_channels, self.channels, 1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, act_cfg=self.act_cfg, inplace=True) fpn_conv = ConvModule(self.channels, self.channels, 3, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, act_cfg=self.act_cfg, inplace=True) self.lateral_convs.append(l_conv) self.fpn_convs.append(fpn_conv) def forward(self, inputs): 'Forward function.' inputs = self._transform_inputs(inputs) laterals = [lateral_conv(inputs[i]) for (i, lateral_conv) in enumerate(self.lateral_convs)] used_backbone_levels = len(laterals) for i in range((used_backbone_levels - 1), 0, (- 1)): prev_shape = laterals[(i - 1)].shape[2:] laterals[(i - 1)] += resize(laterals[i], size=prev_shape, mode='bilinear', align_corners=self.align_corners) fpn_outs = [self.fpn_convs[i](laterals[i]) for i in range((used_backbone_levels - 1))] fpn_outs.append(laterals[(- 1)]) return fpn_outs[0]
class PSP(BaseDecodeHead): 'Unified Perceptual Parsing for Scene Understanding.\n\n This head is the implementation of `UPerNet\n <https://arxiv.org/abs/1807.10221>`_.\n\n Args:\n pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid\n Module applied on the last feature. Default: (1, 2, 3, 6).\n ' def __init__(self, pool_scales=(1, 2, 3, 6), **kwargs): super(PSP, self).__init__(input_transform='multiple_select', **kwargs) self.psp_modules = PPM(pool_scales, self.in_channels[(- 1)], self.channels, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, act_cfg=self.act_cfg, align_corners=self.align_corners) self.bottleneck = ConvModule((self.in_channels[(- 1)] + (len(pool_scales) * self.channels)), self.channels, 3, padding=1, conv_cfg=self.conv_cfg, norm_cfg=self.norm_cfg, act_cfg=self.act_cfg) def psp_forward(self, inputs): 'Forward function of PSP module.' x = inputs[(- 1)] psp_outs = [x] psp_outs.extend(self.psp_modules(x)) psp_outs = torch.cat(psp_outs, dim=1) output = self.bottleneck(psp_outs) return output def forward(self, inputs): 'Forward function.' inputs = self._transform_inputs(inputs) return self.psp_forward(inputs)
def load_newcrfs_net(scene: str, max_depth: Optional[float]=None) -> nn.Module: 'Load a frozen pre-trained NeWCRFs network.\n From https://arxiv.org/abs/2203.01502.\n\n Pre-processing: ImageNet standarization & resizing.\n\n Training shapes:\n - Outdoor: (Kitti) (352, 1216)\n - Indoor: (NYUD) (480, 640)\n\n Prediction:\n ```\n # Prediction is made in METRIC DEPTH, not disparity.\n img: torch.Tensor\n pred = net(ops.standardize(img))\n ```\n\n :param scene: (str) Model type to load. {`indoor`, `outdoor`}\n :param max_depth: (None|float) Maximum expected metric depth.\n :return: (nn.Module) Loaded network.\n ' if (scene not in SCENES): raise ValueError(f'Invalid NeWCRFs model. ({scene} vs. {SCENES})') max_depth = (max_depth or (10 if (scene == 'indoor') else 80)) if (max_depth <= 0): raise ValueError(f'Max depth must be a positive number. Got {max_depth}.') net = nn.DataParallel(NewCRFDepth(version='large07', inv_depth=False, max_depth=max_depth, pretrained=None)) ckpt_file = (PATHS['newcrfs_indoor'] if (scene == 'indoor') else PATHS['newcrfs_outdoor']) ckpt = torch.load(ckpt_file, map_location='cpu') net.load_state_dict(ckpt['model']) net = net.eval() for p in net.parameters(): p.requires_grad = False return net