Repository: rowanz/neural-motifs Branch: master Commit: d05a251b705c Files: 98 Total size: 1.0 MB Directory structure: gitextract_tbpjfk2p/ ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── config.py ├── data/ │ └── stanford_filtered/ │ └── README.md ├── dataloaders/ │ ├── __init__.py │ ├── blob.py │ ├── image_transforms.py │ ├── mscoco.py │ └── visual_genome.py ├── docs/ │ ├── LICENSE.md │ ├── _config.yaml │ ├── _includes/ │ │ └── image.html │ ├── _layouts/ │ │ └── default.html │ ├── index.md │ └── upload.sh ├── lib/ │ ├── __init__.py │ ├── draw_rectangles/ │ │ ├── draw_rectangles.c │ │ ├── draw_rectangles.pyx │ │ └── setup.py │ ├── evaluation/ │ │ ├── __init__.py │ │ ├── sg_eval.py │ │ ├── sg_eval_all_rel_cates.py │ │ ├── sg_eval_slow.py │ │ └── test_sg_eval.py │ ├── fpn/ │ │ ├── anchor_targets.py │ │ ├── box_intersections_cpu/ │ │ │ ├── bbox.c │ │ │ ├── bbox.pyx │ │ │ └── setup.py │ │ ├── box_utils.py │ │ ├── generate_anchors.py │ │ ├── make.sh │ │ ├── nms/ │ │ │ ├── Makefile │ │ │ ├── build.py │ │ │ ├── functions/ │ │ │ │ └── nms.py │ │ │ └── src/ │ │ │ ├── cuda/ │ │ │ │ ├── Makefile │ │ │ │ ├── nms_kernel.cu │ │ │ │ └── nms_kernel.h │ │ │ ├── nms_cuda.c │ │ │ └── nms_cuda.h │ │ ├── proposal_assignments/ │ │ │ ├── proposal_assignments_det.py │ │ │ ├── proposal_assignments_gtbox.py │ │ │ ├── proposal_assignments_postnms.py │ │ │ ├── proposal_assignments_rel.py │ │ │ └── rel_assignments.py │ │ └── roi_align/ │ │ ├── Makefile │ │ ├── __init__.py │ │ ├── _ext/ │ │ │ ├── __init__.py │ │ │ └── roi_align/ │ │ │ └── __init__.py │ │ ├── build.py │ │ ├── functions/ │ │ │ ├── __init__.py │ │ │ └── roi_align.py │ │ ├── modules/ │ │ │ ├── __init__.py │ │ │ └── roi_align.py │ │ └── src/ │ │ ├── cuda/ │ │ │ ├── Makefile │ │ │ ├── roi_align_kernel.cu │ │ │ └── roi_align_kernel.h │ │ ├── roi_align_cuda.c │ │ └── roi_align_cuda.h │ ├── get_dataset_counts.py │ ├── get_union_boxes.py │ ├── lstm/ │ │ ├── __init__.py │ │ ├── decoder_rnn.py │ │ └── highway_lstm_cuda/ │ │ ├── __init__.py │ │ ├── _ext/ │ │ │ ├── __init__.py │ │ │ └── highway_lstm_layer/ │ │ │ └── __init__.py │ │ ├── alternating_highway_lstm.py │ │ ├── build.py │ │ ├── make.sh │ │ └── src/ │ │ ├── highway_lstm_cuda.c │ │ ├── highway_lstm_cuda.h │ │ ├── highway_lstm_kernel.cu │ │ └── highway_lstm_kernel.h │ ├── object_detector.py │ ├── pytorch_misc.py │ ├── rel_model.py │ ├── rel_model_stanford.py │ ├── resnet.py │ ├── sparse_targets.py │ ├── surgery.py │ └── word_vectors.py ├── misc/ │ ├── __init__.py │ ├── motifs.py │ ├── object_types.txt │ └── relation_types.txt ├── models/ │ ├── _visualize.py │ ├── eval_rel_count.py │ ├── eval_rels.py │ ├── train_detector.py │ └── train_rels.py └── scripts/ ├── eval_models_sgcls.sh ├── eval_models_sgdet.sh ├── pretrain_detector.sh ├── refine_for_detection.sh ├── train_models_sgcls.sh ├── train_motifnet.sh └── train_stanford.sh ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # dotenv .env # virtualenv .venv venv/ ENV/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2018 Rowan Zellers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: Makefile ================================================ export PATH := /usr/local/cuda-9.1/bin:$(PATH) all: draw_rectangles box_intersections nms roi_align lstm draw_rectangles: cd lib/draw_rectangles; python setup.py build_ext --inplace box_intersections: cd lib/fpn/box_intersections_cpu; python setup.py build_ext --inplace nms: cd lib/fpn/nms; make roi_align: cd lib/fpn/roi_align; make lstm: cd lib/lstm/highway_lstm_cuda; ./make.sh ================================================ FILE: README.md ================================================ # neural-motifs ### Like this work, or scene understanding in general? You might be interested in checking out my brand new dataset VCR: Visual Commonsense Reasoning, at [visualcommonsense.com](https://visualcommonsense.com)! This repository contains data and code for the paper [Neural Motifs: Scene Graph Parsing with Global Context (CVPR 2018)](https://arxiv.org/abs/1711.06640v2) For the project page (as well as links to the baseline checkpoints), check out [rowanzellers.com/neuralmotifs](https://rowanzellers.com/neuralmotifs). If the paper significantly inspires you, we request that you cite our work: ### Bibtex ``` @inproceedings{zellers2018scenegraphs, title={Neural Motifs: Scene Graph Parsing with Global Context}, author={Zellers, Rowan and Yatskar, Mark and Thomson, Sam and Choi, Yejin}, booktitle = "Conference on Computer Vision and Pattern Recognition", year={2018} } ``` # Setup 0. Install python3.6 and pytorch 3. I recommend the [Anaconda distribution](https://repo.continuum.io/archive/). To install PyTorch if you haven't already, use ```conda install pytorch=0.3.0 torchvision=0.2.0 cuda90 -c pytorch```. 1. Update the config file with the dataset paths. Specifically: - Visual Genome (the VG_100K folder, image_data.json, VG-SGG.h5, and VG-SGG-dicts.json). See data/stanford_filtered/README.md for the steps I used to download these. - You'll also need to fix your PYTHONPATH: ```export PYTHONPATH=/home/rowan/code/scene-graph``` 2. Compile everything. run ```make``` in the main directory: this compiles the Bilinear Interpolation operation for the RoIs as well as the Highway LSTM. 3. Pretrain VG detection. The old version involved pretraining COCO as well, but we got rid of that for simplicity. Run ./scripts/pretrain_detector.sh Note: You might have to modify the learning rate and batch size, particularly if you don't have 3 Titan X GPUs (which is what I used). [You can also download the pretrained detector checkpoint here.](https://drive.google.com/open?id=11zKRr2OF5oclFL47kjFYBOxScotQzArX) 4. Train VG scene graph classification: run ./scripts/train_models_sgcls.sh 2 (will run on GPU 2). OR, download the MotifNet-cls checkpoint here: [Motifnet-SGCls/PredCls](https://drive.google.com/open?id=12qziGKYjFD3LAnoy4zDT3bcg5QLC0qN6). 5. Refine for detection: run ./scripts/refine_for_detection.sh 2 or download the [Motifnet-SGDet](https://drive.google.com/open?id=1thd_5uSamJQaXAPVGVOUZGAOfGCYZYmb) checkpoint. 6. Evaluate: Refer to the scripts ./scripts/eval_models_sg[cls/det].sh. # help Feel free to open an issue if you encounter trouble getting it to work! ================================================ FILE: config.py ================================================ """ Configuration file! """ import os from argparse import ArgumentParser import numpy as np ROOT_PATH = os.path.dirname(os.path.realpath(__file__)) DATA_PATH = os.path.join(ROOT_PATH, 'data') def path(fn): return os.path.join(DATA_PATH, fn) def stanford_path(fn): return os.path.join(DATA_PATH, 'stanford_filtered', fn) # ============================================================================= # Update these with where your data is stored ~~~~~~~~~~~~~~~~~~~~~~~~~ VG_IMAGES = '/home/rowan/datasets2/VG_100K_2/VG_100K' RCNN_CHECKPOINT_FN = path('faster_rcnn_500k.h5') IM_DATA_FN = stanford_path('image_data.json') VG_SGG_FN = stanford_path('VG-SGG.h5') VG_SGG_DICT_FN = stanford_path('VG-SGG-dicts.json') PROPOSAL_FN = stanford_path('proposals.h5') COCO_PATH = '/home/rowan/datasets/mscoco' # ============================================================================= # ============================================================================= MODES = ('sgdet', 'sgcls', 'predcls') BOX_SCALE = 1024 # Scale at which we have the boxes IM_SCALE = 592 # Our images will be resized to this res without padding # Proposal assignments BG_THRESH_HI = 0.5 BG_THRESH_LO = 0.0 RPN_POSITIVE_OVERLAP = 0.7 # IOU < thresh: negative example RPN_NEGATIVE_OVERLAP = 0.3 # Max number of foreground examples RPN_FG_FRACTION = 0.5 FG_FRACTION = 0.25 # Total number of examples RPN_BATCHSIZE = 256 ROIS_PER_IMG = 256 REL_FG_FRACTION = 0.25 RELS_PER_IMG = 256 RELS_PER_IMG_REFINE = 64 BATCHNORM_MOMENTUM = 0.01 ANCHOR_SIZE = 16 ANCHOR_RATIOS = (0.23232838, 0.63365731, 1.28478321, 3.15089189) #(0.5, 1, 2) ANCHOR_SCALES = (2.22152954, 4.12315647, 7.21692515, 12.60263013, 22.7102731) #(4, 8, 16, 32) class ModelConfig(object): """Wrapper class for model hyperparameters.""" def __init__(self): """ Defaults """ self.coco = None self.ckpt = None self.save_dir = None self.lr = None self.batch_size = None self.val_size = None self.l2 = None self.clip = None self.num_gpus = None self.num_workers = None self.print_interval = None self.gt_box = None self.mode = None self.refine = None self.ad3 = False self.test = False self.adam = False self.multi_pred=False self.cache = None self.model = None self.use_proposals=False self.use_resnet=False self.use_tanh=False self.use_bias = False self.limit_vision=False self.num_epochs=None self.old_feats=False self.order=None self.det_ckpt=None self.nl_edge=None self.nl_obj=None self.hidden_dim=None self.pass_in_obj_feats_to_decoder = None self.pass_in_obj_feats_to_edge = None self.pooling_dim = None self.rec_dropout = None self.parser = self.setup_parser() self.args = vars(self.parser.parse_args()) print("~~~~~~~~ Hyperparameters used: ~~~~~~~") for x, y in self.args.items(): print("{} : {}".format(x, y)) self.__dict__.update(self.args) if len(self.ckpt) != 0: self.ckpt = os.path.join(ROOT_PATH, self.ckpt) else: self.ckpt = None if len(self.cache) != 0: self.cache = os.path.join(ROOT_PATH, self.cache) else: self.cache = None if len(self.save_dir) == 0: self.save_dir = None else: self.save_dir = os.path.join(ROOT_PATH, self.save_dir) if not os.path.exists(self.save_dir): os.mkdir(self.save_dir) assert self.val_size >= 0 if self.mode not in MODES: raise ValueError("Invalid mode: mode must be in {}".format(MODES)) if self.model not in ('motifnet', 'stanford'): raise ValueError("Invalid model {}".format(self.model)) if self.ckpt is not None and not os.path.exists(self.ckpt): raise ValueError("Ckpt file ({}) doesnt exist".format(self.ckpt)) def setup_parser(self): """ Sets up an argument parser :return: """ parser = ArgumentParser(description='training code') # Options to deprecate parser.add_argument('-coco', dest='coco', help='Use COCO (default to VG)', action='store_true') parser.add_argument('-ckpt', dest='ckpt', help='Filename to load from', type=str, default='') parser.add_argument('-det_ckpt', dest='det_ckpt', help='Filename to load detection parameters from', type=str, default='') parser.add_argument('-save_dir', dest='save_dir', help='Directory to save things to, such as checkpoints/save', default='', type=str) parser.add_argument('-ngpu', dest='num_gpus', help='cuantos GPUs tienes', type=int, default=3) parser.add_argument('-nwork', dest='num_workers', help='num processes to use as workers', type=int, default=1) parser.add_argument('-lr', dest='lr', help='learning rate', type=float, default=1e-3) parser.add_argument('-b', dest='batch_size', help='batch size per GPU',type=int, default=2) parser.add_argument('-val_size', dest='val_size', help='val size to use (if 0 we wont use val)', type=int, default=5000) parser.add_argument('-l2', dest='l2', help='weight decay', type=float, default=1e-4) parser.add_argument('-clip', dest='clip', help='gradients will be clipped to have norm less than this', type=float, default=5.0) parser.add_argument('-p', dest='print_interval', help='print during training', type=int, default=100) parser.add_argument('-m', dest='mode', help='mode \in {sgdet, sgcls, predcls}', type=str, default='sgdet') parser.add_argument('-model', dest='model', help='which model to use? (motifnet, stanford). If you want to use the baseline (NoContext) model, then pass in motifnet here, and nl_obj, nl_edge=0', type=str, default='motifnet') parser.add_argument('-old_feats', dest='old_feats', help='Use the original image features for the edges', action='store_true') parser.add_argument('-order', dest='order', help='Linearization order for Rois (confidence -default, size, random)', type=str, default='confidence') parser.add_argument('-cache', dest='cache', help='where should we cache predictions', type=str, default='') parser.add_argument('-gt_box', dest='gt_box', help='use gt boxes during training', action='store_true') parser.add_argument('-adam', dest='adam', help='use adam. Not recommended', action='store_true') parser.add_argument('-test', dest='test', help='test set', action='store_true') parser.add_argument('-multipred', dest='multi_pred', help='Allow multiple predicates per pair of box0, box1.', action='store_true') parser.add_argument('-nepoch', dest='num_epochs', help='Number of epochs to train the model for',type=int, default=25) parser.add_argument('-resnet', dest='use_resnet', help='use resnet instead of VGG', action='store_true') parser.add_argument('-proposals', dest='use_proposals', help='Use Xu et als proposals', action='store_true') parser.add_argument('-nl_obj', dest='nl_obj', help='Num object layers', type=int, default=1) parser.add_argument('-nl_edge', dest='nl_edge', help='Num edge layers', type=int, default=2) parser.add_argument('-hidden_dim', dest='hidden_dim', help='Num edge layers', type=int, default=256) parser.add_argument('-pooling_dim', dest='pooling_dim', help='Dimension of pooling', type=int, default=4096) parser.add_argument('-pass_in_obj_feats_to_decoder', dest='pass_in_obj_feats_to_decoder', action='store_true') parser.add_argument('-pass_in_obj_feats_to_edge', dest='pass_in_obj_feats_to_edge', action='store_true') parser.add_argument('-rec_dropout', dest='rec_dropout', help='recurrent dropout to add', type=float, default=0.1) parser.add_argument('-use_bias', dest='use_bias', action='store_true') parser.add_argument('-use_tanh', dest='use_tanh', action='store_true') parser.add_argument('-limit_vision', dest='limit_vision', action='store_true') return parser ================================================ FILE: data/stanford_filtered/README.md ================================================ # Filtered data Adapted from [Danfei Xu](https://github.com/danfeiX/scene-graph-TF-release/blob/master/data_tools/README.md). Follow the folling steps to get the dataset set up. 1. Download the VG images [part1](https://cs.stanford.edu/people/rak248/VG_100K_2/images.zip) [part2](https://cs.stanford.edu/people/rak248/VG_100K_2/images2.zip). Extract these images to a file and link to them in `config.py` (eg. currently I have `VG_IMAGES=data/visual_genome/VG_100K`). 2. Download the [VG metadata](http://cvgl.stanford.edu/scene-graph/VG/image_data.json). I recommend extracting it to this directory (e.g. `data/stanford_filtered/image_data.json`), or you can edit the path in `config.py`. 3. Download the [scene graphs](http://cvgl.stanford.edu/scene-graph/dataset/VG-SGG.h5) and extract them to `data/stanford_filtered/VG-SGG.h5` 4. Download the [scene graph dataset metadata](http://cvgl.stanford.edu/scene-graph/dataset/VG-SGG-dicts.json) and extract it to `data/stanford_filtered/VG-SGG-dicts.json` ================================================ FILE: dataloaders/__init__.py ================================================ ================================================ FILE: dataloaders/blob.py ================================================ """ Data blob, hopefully to make collating less painful and MGPU training possible """ from lib.fpn.anchor_targets import anchor_target_layer import numpy as np import torch from torch.autograd import Variable class Blob(object): def __init__(self, mode='det', is_train=False, num_gpus=1, primary_gpu=0, batch_size_per_gpu=3): """ Initializes an empty Blob object. :param mode: 'det' for detection and 'rel' for det+relationship :param is_train: True if it's training """ assert mode in ('det', 'rel') assert num_gpus >= 1 self.mode = mode self.is_train = is_train self.num_gpus = num_gpus self.batch_size_per_gpu = batch_size_per_gpu self.primary_gpu = primary_gpu self.imgs = [] # [num_images, 3, IM_SCALE, IM_SCALE] array self.im_sizes = [] # [num_images, 4] array of (h, w, scale, num_valid_anchors) self.all_anchor_inds = [] # [all_anchors, 2] array of (img_ind, anchor_idx). Only has valid # boxes (meaning some are gonna get cut out) self.all_anchors = [] # [num_im, IM_SCALE/4, IM_SCALE/4, num_anchors, 4] shapes. Anchors outside get squashed # to 0 self.gt_boxes = [] # [num_gt, 4] boxes self.gt_classes = [] # [num_gt,2] array of img_ind, class self.gt_rels = [] # [num_rels, 3]. Each row is (gtbox0, gtbox1, rel). self.gt_sents = [] self.gt_nodes = [] self.sent_lengths = [] self.train_anchor_labels = [] # [train_anchors, 5] array of (img_ind, h, w, A, labels) self.train_anchors = [] # [train_anchors, 8] shapes with anchor, target self.train_anchor_inds = None # This will be split into GPUs, just (img_ind, h, w, A). self.batch_size = None self.gt_box_chunks = None self.anchor_chunks = None self.train_chunks = None self.proposal_chunks = None self.proposals = [] @property def is_flickr(self): return self.mode == 'flickr' @property def is_rel(self): return self.mode == 'rel' @property def volatile(self): return not self.is_train def append(self, d): """ Adds a single image to the blob :param datom: :return: """ i = len(self.imgs) self.imgs.append(d['img']) h, w, scale = d['img_size'] # all anchors self.im_sizes.append((h, w, scale)) gt_boxes_ = d['gt_boxes'].astype(np.float32) * d['scale'] self.gt_boxes.append(gt_boxes_) self.gt_classes.append(np.column_stack(( i * np.ones(d['gt_classes'].shape[0], dtype=np.int64), d['gt_classes'], ))) # Add relationship info if self.is_rel: self.gt_rels.append(np.column_stack(( i * np.ones(d['gt_relations'].shape[0], dtype=np.int64), d['gt_relations']))) # Augment with anchor targets if self.is_train: train_anchors_, train_anchor_inds_, train_anchor_targets_, train_anchor_labels_ = \ anchor_target_layer(gt_boxes_, (h, w)) self.train_anchors.append(np.hstack((train_anchors_, train_anchor_targets_))) self.train_anchor_labels.append(np.column_stack(( i * np.ones(train_anchor_inds_.shape[0], dtype=np.int64), train_anchor_inds_, train_anchor_labels_, ))) if 'proposals' in d: self.proposals.append(np.column_stack((i * np.ones(d['proposals'].shape[0], dtype=np.float32), d['scale'] * d['proposals'].astype(np.float32)))) def _chunkize(self, datom, tensor=torch.LongTensor): """ Turn data list into chunks, one per GPU :param datom: List of lists of numpy arrays that will be concatenated. :return: """ chunk_sizes = [0] * self.num_gpus for i in range(self.num_gpus): for j in range(self.batch_size_per_gpu): chunk_sizes[i] += datom[i * self.batch_size_per_gpu + j].shape[0] return Variable(tensor(np.concatenate(datom, 0)), volatile=self.volatile), chunk_sizes def reduce(self): """ Merges all the detections into flat lists + numbers of how many are in each""" if len(self.imgs) != self.batch_size_per_gpu * self.num_gpus: raise ValueError("Wrong batch size? imgs len {} bsize/gpu {} numgpus {}".format( len(self.imgs), self.batch_size_per_gpu, self.num_gpus )) self.imgs = Variable(torch.stack(self.imgs, 0), volatile=self.volatile) self.im_sizes = np.stack(self.im_sizes).reshape( (self.num_gpus, self.batch_size_per_gpu, 3)) if self.is_rel: self.gt_rels, self.gt_rel_chunks = self._chunkize(self.gt_rels) self.gt_boxes, self.gt_box_chunks = self._chunkize(self.gt_boxes, tensor=torch.FloatTensor) self.gt_classes, _ = self._chunkize(self.gt_classes) if self.is_train: self.train_anchor_labels, self.train_chunks = self._chunkize(self.train_anchor_labels) self.train_anchors, _ = self._chunkize(self.train_anchors, tensor=torch.FloatTensor) self.train_anchor_inds = self.train_anchor_labels[:, :-1].contiguous() if len(self.proposals) != 0: self.proposals, self.proposal_chunks = self._chunkize(self.proposals, tensor=torch.FloatTensor) def _scatter(self, x, chunk_sizes, dim=0): """ Helper function""" if self.num_gpus == 1: return x.cuda(self.primary_gpu, async=True) return torch.nn.parallel.scatter_gather.Scatter.apply( list(range(self.num_gpus)), chunk_sizes, dim, x) def scatter(self): """ Assigns everything to the GPUs""" self.imgs = self._scatter(self.imgs, [self.batch_size_per_gpu] * self.num_gpus) self.gt_classes_primary = self.gt_classes.cuda(self.primary_gpu, async=True) self.gt_boxes_primary = self.gt_boxes.cuda(self.primary_gpu, async=True) # Predcls might need these self.gt_classes = self._scatter(self.gt_classes, self.gt_box_chunks) self.gt_boxes = self._scatter(self.gt_boxes, self.gt_box_chunks) if self.is_train: self.train_anchor_inds = self._scatter(self.train_anchor_inds, self.train_chunks) self.train_anchor_labels = self.train_anchor_labels.cuda(self.primary_gpu, async=True) self.train_anchors = self.train_anchors.cuda(self.primary_gpu, async=True) if self.is_rel: self.gt_rels = self._scatter(self.gt_rels, self.gt_rel_chunks) else: if self.is_rel: self.gt_rels = self.gt_rels.cuda(self.primary_gpu, async=True) if self.proposal_chunks is not None: self.proposals = self._scatter(self.proposals, self.proposal_chunks) def __getitem__(self, index): """ Returns a tuple containing data :param index: Which GPU we're on, or 0 if no GPUs :return: If training: (image, im_size, img_start_ind, anchor_inds, anchors, gt_boxes, gt_classes, train_anchor_inds) test: (image, im_size, img_start_ind, anchor_inds, anchors) """ if index not in list(range(self.num_gpus)): raise ValueError("Out of bounds with index {} and {} gpus".format(index, self.num_gpus)) if self.is_rel: rels = self.gt_rels if index > 0 or self.num_gpus != 1: rels_i = rels[index] if self.is_rel else None elif self.is_flickr: rels = (self.gt_sents, self.gt_nodes) if index > 0 or self.num_gpus != 1: rels_i = (self.gt_sents[index], self.gt_nodes[index]) else: rels = None rels_i = None if self.proposal_chunks is None: proposals = None else: proposals = self.proposals if index == 0 and self.num_gpus == 1: image_offset = 0 if self.is_train: return (self.imgs, self.im_sizes[0], image_offset, self.gt_boxes, self.gt_classes, rels, proposals, self.train_anchor_inds) return self.imgs, self.im_sizes[0], image_offset, self.gt_boxes, self.gt_classes, rels, proposals # Otherwise proposals is None assert proposals is None image_offset = self.batch_size_per_gpu * index # TODO: Return a namedtuple if self.is_train: return ( self.imgs[index], self.im_sizes[index], image_offset, self.gt_boxes[index], self.gt_classes[index], rels_i, None, self.train_anchor_inds[index]) return (self.imgs[index], self.im_sizes[index], image_offset, self.gt_boxes[index], self.gt_classes[index], rels_i, None) ================================================ FILE: dataloaders/image_transforms.py ================================================ # Some image transforms from PIL import Image, ImageOps, ImageFilter, ImageEnhance import numpy as np from random import randint # All of these need to be called on PIL imagez class SquarePad(object): def __call__(self, img): w, h = img.size img_padded = ImageOps.expand(img, border=(0, 0, max(h - w, 0), max(w - h, 0)), fill=(int(0.485 * 256), int(0.456 * 256), int(0.406 * 256))) return img_padded class Grayscale(object): """ Converts to grayscale (not always, sometimes). """ def __call__(self, img): factor = np.sqrt(np.sqrt(np.random.rand(1))) # print("gray {}".format(factor)) enhancer = ImageEnhance.Color(img) return enhancer.enhance(factor) class Brightness(object): """ Converts to grayscale (not always, sometimes). """ def __call__(self, img): factor = np.random.randn(1)/6+1 factor = min(max(factor, 0.5), 1.5) # print("brightness {}".format(factor)) enhancer = ImageEnhance.Brightness(img) return enhancer.enhance(factor) class Contrast(object): """ Converts to grayscale (not always, sometimes). """ def __call__(self, img): factor = np.random.randn(1)/8+1.0 factor = min(max(factor, 0.5), 1.5) # print("contrast {}".format(factor)) enhancer = ImageEnhance.Contrast(img) return enhancer.enhance(factor) class Hue(object): """ Converts to grayscale """ def __call__(self, img): # 30 seems good factor = int(np.random.randn(1)*8) factor = min(max(factor, -30), 30) factor = np.array(factor, dtype=np.uint8) hsv = np.array(img.convert('HSV')) hsv[:,:,0] += factor new_img = Image.fromarray(hsv, 'HSV').convert('RGB') return new_img class Sharpness(object): """ Converts to grayscale """ def __call__(self, img): factor = 1.0 + np.random.randn(1)/5 # print("sharpness {}".format(factor)) enhancer = ImageEnhance.Sharpness(img) return enhancer.enhance(factor) def random_crop(img, boxes, box_scale, round_boxes=True, max_crop_fraction=0.1): """ Randomly crops the image :param img: PIL image :param boxes: Ground truth boxes :param box_scale: This is the scale that the boxes are at (e.g. 1024 wide). We'll preserve that ratio :param round_boxes: Set this to true if we're going to round the boxes to ints :return: Cropped image, new boxes """ w, h = img.size max_crop_w = int(w*max_crop_fraction) max_crop_h = int(h*max_crop_fraction) boxes_scaled = boxes * max(w,h) / box_scale max_to_crop_top = min(int(boxes_scaled[:, 1].min()), max_crop_h) max_to_crop_left = min(int(boxes_scaled[:, 0].min()), max_crop_w) max_to_crop_right = min(int(w - boxes_scaled[:, 2].max()), max_crop_w) max_to_crop_bottom = min(int(h - boxes_scaled[:, 3].max()), max_crop_h) crop_top = randint(0, max(max_to_crop_top, 0)) crop_left = randint(0, max(max_to_crop_left, 0)) crop_right = randint(0, max(max_to_crop_right, 0)) crop_bottom = randint(0, max(max_to_crop_bottom, 0)) img_cropped = img.crop((crop_left, crop_top, w - crop_right, h - crop_bottom)) new_boxes = box_scale / max(img_cropped.size) * np.column_stack( (boxes_scaled[:,0]-crop_left, boxes_scaled[:,1]-crop_top, boxes_scaled[:,2]-crop_left, boxes_scaled[:,3]-crop_top)) if round_boxes: new_boxes = np.round(new_boxes).astype(np.int32) return img_cropped, new_boxes class RandomOrder(object): """ Composes several transforms together in random order - or not at all! """ def __init__(self, transforms): self.transforms = transforms def __call__(self, img): if self.transforms is None: return img num_to_pick = np.random.choice(len(self.transforms)) if num_to_pick == 0: return img order = np.random.choice(len(self.transforms), size=num_to_pick, replace=False) for i in order: img = self.transforms[i](img) return img ================================================ FILE: dataloaders/mscoco.py ================================================ from config import COCO_PATH, IM_SCALE, BOX_SCALE import os from torch.utils.data import Dataset from pycocotools.coco import COCO from PIL import Image from lib.fpn.anchor_targets import anchor_target_layer from torchvision.transforms import Resize, Compose, ToTensor, Normalize from dataloaders.image_transforms import SquarePad, Grayscale, Brightness, Sharpness, Contrast, RandomOrder, Hue, random_crop import numpy as np from dataloaders.blob import Blob import torch class CocoDetection(Dataset): """ Adapted from the torchvision code """ def __init__(self, mode): """ :param mode: train2014 or val2014 """ self.mode = mode self.root = os.path.join(COCO_PATH, mode) self.ann_file = os.path.join(COCO_PATH, 'annotations', 'instances_{}.json'.format(mode)) self.coco = COCO(self.ann_file) self.ids = [k for k in self.coco.imgs.keys() if len(self.coco.imgToAnns[k]) > 0] tform = [] if self.is_train: tform.append(RandomOrder([ Grayscale(), Brightness(), Contrast(), Sharpness(), Hue(), ])) tform += [ SquarePad(), Resize(IM_SCALE), ToTensor(), Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ] self.transform_pipeline = Compose(tform) self.ind_to_classes = ['__background__'] + [v['name'] for k, v in self.coco.cats.items()] # COCO inds are weird (84 inds in total but a bunch of numbers are skipped) self.id_to_ind = {coco_id:(ind+1) for ind, coco_id in enumerate(self.coco.cats.keys())} self.id_to_ind[0] = 0 self.ind_to_id = {x:y for y,x in self.id_to_ind.items()} @property def is_train(self): return self.mode.startswith('train') def __getitem__(self, index): """ Args: index (int): Index Returns: entry dict """ img_id = self.ids[index] path = self.coco.loadImgs(img_id)[0]['file_name'] image_unpadded = Image.open(os.path.join(self.root, path)).convert('RGB') ann_ids = self.coco.getAnnIds(imgIds=img_id) anns = self.coco.loadAnns(ann_ids) gt_classes = np.array([self.id_to_ind[x['category_id']] for x in anns], dtype=np.int64) if np.any(gt_classes >= len(self.ind_to_classes)): raise ValueError("OH NO {}".format(index)) if len(anns) == 0: raise ValueError("Annotations should not be empty") # gt_boxes = np.array((0, 4), dtype=np.float32) # else: gt_boxes = np.array([x['bbox'] for x in anns], dtype=np.float32) if np.any(gt_boxes[:, [0,1]] < 0): raise ValueError("GT boxes empty columns") if np.any(gt_boxes[:, [2,3]] < 0): raise ValueError("GT boxes empty h/w") gt_boxes[:, [2, 3]] += gt_boxes[:, [0, 1]] # Rescale so that the boxes are at BOX_SCALE if self.is_train: image_unpadded, gt_boxes = random_crop(image_unpadded, gt_boxes * BOX_SCALE / max(image_unpadded.size), BOX_SCALE, round_boxes=False, ) else: # Seems a bit silly because we won't be using GT boxes then but whatever gt_boxes = gt_boxes * BOX_SCALE / max(image_unpadded.size) w, h = image_unpadded.size box_scale_factor = BOX_SCALE / max(w, h) # Optionally flip the image if we're doing training flipped = self.is_train and np.random.random() > 0.5 if flipped: scaled_w = int(box_scale_factor * float(w)) image_unpadded = image_unpadded.transpose(Image.FLIP_LEFT_RIGHT) gt_boxes[:, [0, 2]] = scaled_w - gt_boxes[:, [2, 0]] img_scale_factor = IM_SCALE / max(w, h) if h > w: im_size = (IM_SCALE, int(w*img_scale_factor), img_scale_factor) elif h < w: im_size = (int(h*img_scale_factor), IM_SCALE, img_scale_factor) else: im_size = (IM_SCALE, IM_SCALE, img_scale_factor) entry = { 'img': self.transform_pipeline(image_unpadded), 'img_size': im_size, 'gt_boxes': gt_boxes, 'gt_classes': gt_classes, 'scale': IM_SCALE / BOX_SCALE, 'index': index, 'image_id': img_id, 'flipped': flipped, 'fn': path, } return entry @classmethod def splits(cls, *args, **kwargs): """ Helper method to generate splits of the dataset""" train = cls('train2014', *args, **kwargs) val = cls('val2014', *args, **kwargs) return train, val def __len__(self): return len(self.ids) def coco_collate(data, num_gpus=3, is_train=False): blob = Blob(mode='det', is_train=is_train, num_gpus=num_gpus, batch_size_per_gpu=len(data) // num_gpus) for d in data: blob.append(d) blob.reduce() return blob class CocoDataLoader(torch.utils.data.DataLoader): """ Iterates through the data, filtering out None, but also loads everything as a (cuda) variable """ # def __iter__(self): # for x in super(CocoDataLoader, self).__iter__(): # if isinstance(x, tuple) or isinstance(x, list): # yield tuple(y.cuda(async=True) if hasattr(y, 'cuda') else y for y in x) # else: # yield x.cuda(async=True) @classmethod def splits(cls, train_data, val_data, batch_size=3, num_workers=1, num_gpus=3, **kwargs): train_load = cls( dataset=train_data, batch_size=batch_size*num_gpus, shuffle=True, num_workers=num_workers, collate_fn=lambda x: coco_collate(x, num_gpus=num_gpus, is_train=True), drop_last=True, # pin_memory=True, **kwargs, ) val_load = cls( dataset=val_data, batch_size=batch_size*num_gpus, shuffle=False, num_workers=num_workers, collate_fn=lambda x: coco_collate(x, num_gpus=num_gpus, is_train=False), drop_last=True, # pin_memory=True, **kwargs, ) return train_load, val_load if __name__ == '__main__': train, val = CocoDetection.splits() gtbox = train[0]['gt_boxes'] img_size = train[0]['img_size'] anchor_strides, labels, bbox_targets = anchor_target_layer(gtbox, img_size) ================================================ FILE: dataloaders/visual_genome.py ================================================ """ File that involves dataloaders for the Visual Genome dataset. """ import json import os import h5py import numpy as np import torch from PIL import Image from torch.utils.data import Dataset from torchvision.transforms import Resize, Compose, ToTensor, Normalize from dataloaders.blob import Blob from lib.fpn.box_intersections_cpu.bbox import bbox_overlaps from config import VG_IMAGES, IM_DATA_FN, VG_SGG_FN, VG_SGG_DICT_FN, BOX_SCALE, IM_SCALE, PROPOSAL_FN from dataloaders.image_transforms import SquarePad, Grayscale, Brightness, Sharpness, Contrast, \ RandomOrder, Hue, random_crop from collections import defaultdict from pycocotools.coco import COCO class VG(Dataset): def __init__(self, mode, roidb_file=VG_SGG_FN, dict_file=VG_SGG_DICT_FN, image_file=IM_DATA_FN, filter_empty_rels=True, num_im=-1, num_val_im=5000, filter_duplicate_rels=True, filter_non_overlap=True, use_proposals=False): """ Torch dataset for VisualGenome :param mode: Must be train, test, or val :param roidb_file: HDF5 containing the GT boxes, classes, and relationships :param dict_file: JSON Contains mapping of classes/relationships to words :param image_file: HDF5 containing image filenames :param filter_empty_rels: True if we filter out images without relationships between boxes. One might want to set this to false if training a detector. :param filter_duplicate_rels: Whenever we see a duplicate relationship we'll sample instead :param num_im: Number of images in the entire dataset. -1 for all images. :param num_val_im: Number of images in the validation set (must be less than num_im unless num_im is -1.) :param proposal_file: If None, we don't provide proposals. Otherwise file for where we get RPN proposals """ if mode not in ('test', 'train', 'val'): raise ValueError("Mode must be in test, train, or val. Supplied {}".format(mode)) self.mode = mode # Initialize self.roidb_file = roidb_file self.dict_file = dict_file self.image_file = image_file self.filter_non_overlap = filter_non_overlap self.filter_duplicate_rels = filter_duplicate_rels and self.mode == 'train' self.split_mask, self.gt_boxes, self.gt_classes, self.relationships = load_graphs( self.roidb_file, self.mode, num_im, num_val_im=num_val_im, filter_empty_rels=filter_empty_rels, filter_non_overlap=self.filter_non_overlap and self.is_train, ) self.filenames = load_image_filenames(image_file) self.filenames = [self.filenames[i] for i in np.where(self.split_mask)[0]] self.ind_to_classes, self.ind_to_predicates = load_info(dict_file) if use_proposals: print("Loading proposals", flush=True) p_h5 = h5py.File(PROPOSAL_FN, 'r') rpn_rois = p_h5['rpn_rois'] rpn_scores = p_h5['rpn_scores'] rpn_im_to_roi_idx = np.array(p_h5['im_to_roi_idx'][self.split_mask]) rpn_num_rois = np.array(p_h5['num_rois'][self.split_mask]) self.rpn_rois = [] for i in range(len(self.filenames)): rpn_i = np.column_stack(( rpn_scores[rpn_im_to_roi_idx[i]:rpn_im_to_roi_idx[i] + rpn_num_rois[i]], rpn_rois[rpn_im_to_roi_idx[i]:rpn_im_to_roi_idx[i] + rpn_num_rois[i]], )) self.rpn_rois.append(rpn_i) else: self.rpn_rois = None # You could add data augmentation here. But we didn't. # tform = [] # if self.is_train: # tform.append(RandomOrder([ # Grayscale(), # Brightness(), # Contrast(), # Sharpness(), # Hue(), # ])) tform = [ SquarePad(), Resize(IM_SCALE), ToTensor(), Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ] self.transform_pipeline = Compose(tform) @property def coco(self): """ :return: a Coco-like object that we can use to evaluate detection! """ anns = [] for i, (cls_array, box_array) in enumerate(zip(self.gt_classes, self.gt_boxes)): for cls, box in zip(cls_array.tolist(), box_array.tolist()): anns.append({ 'area': (box[3] - box[1] + 1) * (box[2] - box[0] + 1), 'bbox': [box[0], box[1], box[2] - box[0] + 1, box[3] - box[1] + 1], 'category_id': cls, 'id': len(anns), 'image_id': i, 'iscrowd': 0, }) fauxcoco = COCO() fauxcoco.dataset = { 'info': {'description': 'ayy lmao'}, 'images': [{'id': i} for i in range(self.__len__())], 'categories': [{'supercategory': 'person', 'id': i, 'name': name} for i, name in enumerate(self.ind_to_classes) if name != '__background__'], 'annotations': anns, } fauxcoco.createIndex() return fauxcoco @property def is_train(self): return self.mode.startswith('train') @classmethod def splits(cls, *args, **kwargs): """ Helper method to generate splits of the dataset""" train = cls('train', *args, **kwargs) val = cls('val', *args, **kwargs) test = cls('test', *args, **kwargs) return train, val, test def __getitem__(self, index): image_unpadded = Image.open(self.filenames[index]).convert('RGB') # Optionally flip the image if we're doing training flipped = self.is_train and np.random.random() > 0.5 gt_boxes = self.gt_boxes[index].copy() # Boxes are already at BOX_SCALE if self.is_train: # crop boxes that are too large. This seems to be only a problem for image heights, but whatevs gt_boxes[:, [1, 3]] = gt_boxes[:, [1, 3]].clip( None, BOX_SCALE / max(image_unpadded.size) * image_unpadded.size[1]) gt_boxes[:, [0, 2]] = gt_boxes[:, [0, 2]].clip( None, BOX_SCALE / max(image_unpadded.size) * image_unpadded.size[0]) # # crop the image for data augmentation # image_unpadded, gt_boxes = random_crop(image_unpadded, gt_boxes, BOX_SCALE, round_boxes=True) w, h = image_unpadded.size box_scale_factor = BOX_SCALE / max(w, h) if flipped: scaled_w = int(box_scale_factor * float(w)) # print("Scaled w is {}".format(scaled_w)) image_unpadded = image_unpadded.transpose(Image.FLIP_LEFT_RIGHT) gt_boxes[:, [0, 2]] = scaled_w - gt_boxes[:, [2, 0]] img_scale_factor = IM_SCALE / max(w, h) if h > w: im_size = (IM_SCALE, int(w * img_scale_factor), img_scale_factor) elif h < w: im_size = (int(h * img_scale_factor), IM_SCALE, img_scale_factor) else: im_size = (IM_SCALE, IM_SCALE, img_scale_factor) gt_rels = self.relationships[index].copy() if self.filter_duplicate_rels: # Filter out dupes! assert self.mode == 'train' old_size = gt_rels.shape[0] all_rel_sets = defaultdict(list) for (o0, o1, r) in gt_rels: all_rel_sets[(o0, o1)].append(r) gt_rels = [(k[0], k[1], np.random.choice(v)) for k,v in all_rel_sets.items()] gt_rels = np.array(gt_rels) entry = { 'img': self.transform_pipeline(image_unpadded), 'img_size': im_size, 'gt_boxes': gt_boxes, 'gt_classes': self.gt_classes[index].copy(), 'gt_relations': gt_rels, 'scale': IM_SCALE / BOX_SCALE, # Multiply the boxes by this. 'index': index, 'flipped': flipped, 'fn': self.filenames[index], } if self.rpn_rois is not None: entry['proposals'] = self.rpn_rois[index] assertion_checks(entry) return entry def __len__(self): return len(self.filenames) @property def num_predicates(self): return len(self.ind_to_predicates) @property def num_classes(self): return len(self.ind_to_classes) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # MISC. HELPER FUNCTIONS ~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def assertion_checks(entry): im_size = tuple(entry['img'].size()) if len(im_size) != 3: raise ValueError("Img must be dim-3") c, h, w = entry['img'].size() if c != 3: raise ValueError("Must have 3 color channels") num_gt = entry['gt_boxes'].shape[0] if entry['gt_classes'].shape[0] != num_gt: raise ValueError("GT classes and GT boxes must have same number of examples") assert (entry['gt_boxes'][:, 2] >= entry['gt_boxes'][:, 0]).all() assert (entry['gt_boxes'] >= -1).all() def load_image_filenames(image_file, image_dir=VG_IMAGES): """ Loads the image filenames from visual genome from the JSON file that contains them. This matches the preprocessing in scene-graph-TF-release/data_tools/vg_to_imdb.py. :param image_file: JSON file. Elements contain the param "image_id". :param image_dir: directory where the VisualGenome images are located :return: List of filenames corresponding to the good images """ with open(image_file, 'r') as f: im_data = json.load(f) corrupted_ims = ['1592.jpg', '1722.jpg', '4616.jpg', '4617.jpg'] fns = [] for i, img in enumerate(im_data): basename = '{}.jpg'.format(img['image_id']) if basename in corrupted_ims: continue filename = os.path.join(image_dir, basename) if os.path.exists(filename): fns.append(filename) assert len(fns) == 108073 return fns def load_graphs(graphs_file, mode='train', num_im=-1, num_val_im=0, filter_empty_rels=True, filter_non_overlap=False): """ Load the file containing the GT boxes and relations, as well as the dataset split :param graphs_file: HDF5 :param mode: (train, val, or test) :param num_im: Number of images we want :param num_val_im: Number of validation images :param filter_empty_rels: (will be filtered otherwise.) :param filter_non_overlap: If training, filter images that dont overlap. :return: image_index: numpy array corresponding to the index of images we're using boxes: List where each element is a [num_gt, 4] array of ground truth boxes (x1, y1, x2, y2) gt_classes: List where each element is a [num_gt] array of classes relationships: List where each element is a [num_r, 3] array of (box_ind_1, box_ind_2, predicate) relationships """ if mode not in ('train', 'val', 'test'): raise ValueError('{} invalid'.format(mode)) roi_h5 = h5py.File(graphs_file, 'r') data_split = roi_h5['split'][:] split = 2 if mode == 'test' else 0 split_mask = data_split == split # Filter out images without bounding boxes split_mask &= roi_h5['img_to_first_box'][:] >= 0 if filter_empty_rels: split_mask &= roi_h5['img_to_first_rel'][:] >= 0 image_index = np.where(split_mask)[0] if num_im > -1: image_index = image_index[:num_im] if num_val_im > 0: if mode == 'val': image_index = image_index[:num_val_im] elif mode == 'train': image_index = image_index[num_val_im:] split_mask = np.zeros_like(data_split).astype(bool) split_mask[image_index] = True # Get box information all_labels = roi_h5['labels'][:, 0] all_boxes = roi_h5['boxes_{}'.format(BOX_SCALE)][:] # will index later assert np.all(all_boxes[:, :2] >= 0) # sanity check assert np.all(all_boxes[:, 2:] > 0) # no empty box # convert from xc, yc, w, h to x1, y1, x2, y2 all_boxes[:, :2] = all_boxes[:, :2] - all_boxes[:, 2:] / 2 all_boxes[:, 2:] = all_boxes[:, :2] + all_boxes[:, 2:] im_to_first_box = roi_h5['img_to_first_box'][split_mask] im_to_last_box = roi_h5['img_to_last_box'][split_mask] im_to_first_rel = roi_h5['img_to_first_rel'][split_mask] im_to_last_rel = roi_h5['img_to_last_rel'][split_mask] # load relation labels _relations = roi_h5['relationships'][:] _relation_predicates = roi_h5['predicates'][:, 0] assert (im_to_first_rel.shape[0] == im_to_last_rel.shape[0]) assert (_relations.shape[0] == _relation_predicates.shape[0]) # sanity check # Get everything by image. boxes = [] gt_classes = [] relationships = [] for i in range(len(image_index)): boxes_i = all_boxes[im_to_first_box[i]:im_to_last_box[i] + 1, :] gt_classes_i = all_labels[im_to_first_box[i]:im_to_last_box[i] + 1] if im_to_first_rel[i] >= 0: predicates = _relation_predicates[im_to_first_rel[i]:im_to_last_rel[i] + 1] obj_idx = _relations[im_to_first_rel[i]:im_to_last_rel[i] + 1] - im_to_first_box[i] assert np.all(obj_idx >= 0) assert np.all(obj_idx < boxes_i.shape[0]) rels = np.column_stack((obj_idx, predicates)) else: assert not filter_empty_rels rels = np.zeros((0, 3), dtype=np.int32) if filter_non_overlap: assert mode == 'train' inters = bbox_overlaps(boxes_i, boxes_i) rel_overs = inters[rels[:, 0], rels[:, 1]] inc = np.where(rel_overs > 0.0)[0] if inc.size > 0: rels = rels[inc] else: split_mask[image_index[i]] = 0 continue boxes.append(boxes_i) gt_classes.append(gt_classes_i) relationships.append(rels) return split_mask, boxes, gt_classes, relationships def load_info(info_file): """ Loads the file containing the visual genome label meanings :param info_file: JSON :return: ind_to_classes: sorted list of classes ind_to_predicates: sorted list of predicates """ info = json.load(open(info_file, 'r')) info['label_to_idx']['__background__'] = 0 info['predicate_to_idx']['__background__'] = 0 class_to_ind = info['label_to_idx'] predicate_to_ind = info['predicate_to_idx'] ind_to_classes = sorted(class_to_ind, key=lambda k: class_to_ind[k]) ind_to_predicates = sorted(predicate_to_ind, key=lambda k: predicate_to_ind[k]) return ind_to_classes, ind_to_predicates def vg_collate(data, num_gpus=3, is_train=False, mode='det'): assert mode in ('det', 'rel') blob = Blob(mode=mode, is_train=is_train, num_gpus=num_gpus, batch_size_per_gpu=len(data) // num_gpus) for d in data: blob.append(d) blob.reduce() return blob class VGDataLoader(torch.utils.data.DataLoader): """ Iterates through the data, filtering out None, but also loads everything as a (cuda) variable """ @classmethod def splits(cls, train_data, val_data, batch_size=3, num_workers=1, num_gpus=3, mode='det', **kwargs): assert mode in ('det', 'rel') train_load = cls( dataset=train_data, batch_size=batch_size * num_gpus, shuffle=True, num_workers=num_workers, collate_fn=lambda x: vg_collate(x, mode=mode, num_gpus=num_gpus, is_train=True), drop_last=True, # pin_memory=True, **kwargs, ) val_load = cls( dataset=val_data, batch_size=batch_size * num_gpus if mode=='det' else num_gpus, shuffle=False, num_workers=num_workers, collate_fn=lambda x: vg_collate(x, mode=mode, num_gpus=num_gpus, is_train=False), drop_last=True, # pin_memory=True, **kwargs, ) return train_load, val_load ================================================ FILE: docs/LICENSE.md ================================================ MIT License Copyright (c) 2017 Heiswayi Nrird Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: docs/_config.yaml ================================================ exclude: [README.md, LICENSE.md] defaults: - values: layout: default ================================================ FILE: docs/_includes/image.html ================================================
{{ include.description }}
================================================ FILE: docs/_layouts/default.html ================================================ {{ page.title }} {{ content }} ================================================ FILE: docs/index.md ================================================ --- permalink: / title: Neural Motifs author: Rowan Zellers description: Scene Graph Parsing with Global Context (CVPR 2018) google_analytics_id: UA-84290243-3 --- # Neural Motifs: Scene Graph Parsing with Global Context (CVPR 2018) ### by [Rowan Zellers](https://rowanzellers.com), [Mark Yatskar](https://homes.cs.washington.edu/~my89/), [Sam Thomson](https://http://samthomson.com/), [Yejin Choi](https://homes.cs.washington.edu/~yejin/) {% include image.html url="teaser.png" description="teaser" %} # Overview * In this work, we investigate the problem of producing structured graph representations of visual scenes. Similar to object detection, we must predict a box around each object. Here, we also need to predict an edge (with one of several labels, possibly `background`) between every ordered pair of boxes, producing a directed graph where the edges hopefully represent the semantics and interactions present in the scene. * We present an analysis of the [Visual Genome Scene Graphs dataset](http://visualgenome.org/). In particular: * Object labels (e.g. person, shirt) are highly predictive of edge labels (e.g. wearing), but **not vice versa**. * Over 90% of the edges in the dataset are non-semantic. * There is a significant amount of structure in the dataset, in the form of graph motifs (regularly appearing substructures). * Motivated by our analysis, we present a simple baseline that outperforms previous approaches. * We introduce Stacked Motif Networks (MotifNet), which is a novel architecture that is designed to capture higher order motifs in scene graphs. In doing so, it achieves a sizeable performance gain over prior state-of-the-art. # Read the paper! The old version of the paper is available at [arxiv link](https://arxiv.org/abs/1711.06640) - camera ready version coming soon! # Bibtex ``` @inproceedings{zellers2018scenegraphs, title={Neural Motifs: Scene Graph Parsing with Global Context}, author={Zellers, Rowan and Yatskar, Mark and Thomson, Sam and Choi, Yejin}, booktitle = "Conference on Computer Vision and Pattern Recognition", year={2018} } ``` # View some examples! Check out [this tool](https://rowanzellers.com/scenegraph2/) I made to visualize the scene graph predictions. Disclaimer: the predictions are from an earlier version of the model, but hopefully they're still helpful! # Code Visit the [`neural-motifs` GitHub repository](https://github.com/rowanz/neural-motifs) for our reference implementation and instructions for running our code. It is released under the MIT license. # Checkpoints available for download * [Pretrained Detector](https://drive.google.com/open?id=11zKRr2OF5oclFL47kjFYBOxScotQzArX) * [Motifnet-SGDet](https://drive.google.com/open?id=1thd_5uSamJQaXAPVGVOUZGAOfGCYZYmb) * [Motifnet-SGCls/PredCls](https://drive.google.com/open?id=12qziGKYjFD3LAnoy4zDT3bcg5QLC0qN6) # questions? Feel free to get in touch! My main website is at [rowanzellers.com](https://rowanzellers.com) ================================================ FILE: docs/upload.sh ================================================ #!/usr/bin/env bash scp -r _site/* USERNAME@SITE:~/rowanzellers.com/neuralmotifs ================================================ FILE: lib/__init__.py ================================================ ================================================ FILE: lib/draw_rectangles/draw_rectangles.c ================================================ /* Generated by Cython 0.25.2 */ /* BEGIN: Cython Metadata { "distutils": { "depends": [] }, "module_name": "draw_rectangles" } END: Cython Metadata */ #define PY_SSIZE_T_CLEAN #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) #error Cython requires Python 2.6+ or Python 3.2+. #else #define CYTHON_ABI "0_25_2" #include #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #ifndef __fastcall #define __fastcall #endif #endif #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #ifndef HAVE_LONG_LONG #if PY_VERSION_HEX >= 0x03030000 || (PY_MAJOR_VERSION == 2 && PY_VERSION_HEX >= 0x02070000) #define HAVE_LONG_LONG #endif #endif #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 0 #undef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 0 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #undef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #undef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 1 #undef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 0 #undef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 0 #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #elif defined(PYSTON_VERSION) #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 1 #define CYTHON_COMPILING_IN_CPYTHON 0 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #if PY_MAJOR_VERSION < 3 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #elif !defined(CYTHON_USE_ASYNC_SLOTS) #define CYTHON_USE_ASYNC_SLOTS 1 #endif #if PY_VERSION_HEX < 0x02070000 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #elif !defined(CYTHON_USE_PYLONG_INTERNALS) #define CYTHON_USE_PYLONG_INTERNALS 1 #endif #ifndef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 1 #endif #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #if PY_VERSION_HEX < 0x030300F0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #elif !defined(CYTHON_USE_UNICODE_WRITER) #define CYTHON_USE_UNICODE_WRITER 1 #endif #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #ifndef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 1 #endif #ifndef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 1 #endif #endif #if !defined(CYTHON_FAST_PYCCALL) #define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) #endif #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #undef SHIFT #undef BASE #undef MASK #endif #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) #define Py_OptimizeFlag 0 #endif #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyType_Type #endif #ifndef Py_TPFLAGS_CHECKTYPES #define Py_TPFLAGS_CHECKTYPES 0 #endif #ifndef Py_TPFLAGS_HAVE_INDEX #define Py_TPFLAGS_HAVE_INDEX 0 #endif #ifndef Py_TPFLAGS_HAVE_NEWBUFFER #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #ifndef Py_TPFLAGS_HAVE_FINALIZE #define Py_TPFLAGS_HAVE_FINALIZE 0 #endif #ifndef METH_FASTCALL #define METH_FASTCALL 0x80 typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames); #else #define __Pyx_PyCFunctionFast _PyCFunctionFast #endif #if CYTHON_FAST_PYCCALL #define __Pyx_PyFastCFunction_Check(func)\ ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST))))) #else #define __Pyx_PyFastCFunction_Check(func) 0 #endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ 0 : _PyUnicode_Ready((PyObject *)(op))) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) #else #define CYTHON_PEP393_ENABLED 0 #define PyUnicode_1BYTE_KIND 1 #define PyUnicode_2BYTE_KIND 2 #define PyUnicode_4BYTE_KIND 4 #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) #endif #if CYTHON_COMPILING_IN_PYPY #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) #else #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) #define PyObject_Malloc(s) PyMem_Malloc(s) #define PyObject_Free(p) PyMem_Free(p) #define PyObject_Realloc(p) PyMem_Realloc(p) #endif #if CYTHON_COMPILING_IN_PYSTON #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) #else #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) #endif #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) #else #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif #if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) #define PyObject_ASCII(o) PyObject_Repr(o) #endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject #define PyString_Type PyUnicode_Type #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) #else #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type #define PyInt_Check(op) PyLong_Check(op) #define PyInt_CheckExact(op) PyLong_CheckExact(op) #define PyInt_FromString PyLong_FromString #define PyInt_FromUnicode PyLong_FromUnicode #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #define PyNumber_Int PyNumber_Long #endif #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif #if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY #ifndef PyUnicode_InternFromString #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) #endif #endif #if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong #else #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #else #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif #if CYTHON_USE_ASYNC_SLOTS #if PY_VERSION_HEX >= 0x030500B1 #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) #else typedef struct { unaryfunc am_await; unaryfunc am_aiter; unaryfunc am_anext; } __Pyx_PyAsyncMethodsStruct; #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) #endif #else #define __Pyx_PyType_AsAsync(obj) NULL #endif #ifndef CYTHON_RESTRICT #if defined(__GNUC__) #define CYTHON_RESTRICT __restrict__ #elif defined(_MSC_VER) && _MSC_VER >= 1400 #define CYTHON_RESTRICT __restrict #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_RESTRICT restrict #else #define CYTHON_RESTRICT #endif #endif #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif # elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif #ifndef CYTHON_MAYBE_UNUSED_VAR # if defined(__cplusplus) template void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } # else # define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) # endif #endif #ifndef CYTHON_NCP_UNUSED # if CYTHON_COMPILING_IN_CPYTHON # define CYTHON_NCP_UNUSED # else # define CYTHON_NCP_UNUSED CYTHON_UNUSED # endif #endif #define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) #ifndef CYTHON_INLINE #if defined(__clang__) #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) #elif defined(__GNUC__) #define CYTHON_INLINE __inline__ #elif defined(_MSC_VER) #define CYTHON_INLINE __inline #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_INLINE inline #else #define CYTHON_INLINE #endif #endif #if defined(WIN32) || defined(MS_WINDOWS) #define _USE_MATH_DEFINES #endif #include #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { float value; memset(&value, 0xFF, sizeof(value)); return value; } #endif #if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) #define __Pyx_truncl trunc #else #define __Pyx_truncl truncl #endif #define __PYX_ERR(f_index, lineno, Ln_error) \ { \ __pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; goto Ln_error; \ } #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #define __PYX_HAVE__draw_rectangles #define __PYX_HAVE_API__draw_rectangles #include #include #include #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" #ifdef _OPENMP #include #endif /* _OPENMP */ #ifdef PYREX_WITHOUT_ASSERTIONS #define CYTHON_WITHOUT_ASSERTIONS #endif typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; #define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 #define __PYX_DEFAULT_STRING_ENCODING "" #define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString #define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #define __Pyx_uchar_cast(c) ((unsigned char)c) #define __Pyx_long_cast(x) ((long)x) #define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ (sizeof(type) < sizeof(Py_ssize_t)) ||\ (sizeof(type) > sizeof(Py_ssize_t) &&\ likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX) &&\ (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ v == (type)PY_SSIZE_T_MIN))) ||\ (sizeof(type) == sizeof(Py_ssize_t) &&\ (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX))) ) #if defined (__cplusplus) && __cplusplus >= 201103L #include #define __Pyx_sst_abs(value) std::abs(value) #elif SIZEOF_INT >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) abs(value) #elif SIZEOF_LONG >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) labs(value) #elif defined (_MSC_VER) && defined (_M_X64) #define __Pyx_sst_abs(value) _abs64(value) #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define __Pyx_sst_abs(value) llabs(value) #elif defined (__GNUC__) #define __Pyx_sst_abs(value) __builtin_llabs(value) #else #define __Pyx_sst_abs(value) ((value<0) ? -value : value) #endif static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); #define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) #define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); #if PY_MAJOR_VERSION < 3 #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #else #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize #endif #define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) #define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) #define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) #define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) #define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) #if PY_MAJOR_VERSION < 3 static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { const Py_UNICODE *u_end = u; while (*u_end++) ; return (size_t)(u_end - u - 1); } #else #define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen #endif #define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) #define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); #if CYTHON_ASSUME_SAFE_MACROS #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) #else #define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) #endif #define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII static int __Pyx_sys_getdefaultencoding_not_ascii; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; PyObject* ascii_chars_u = NULL; PyObject* ascii_chars_b = NULL; const char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; if (strcmp(default_encoding_c, "ascii") == 0) { __Pyx_sys_getdefaultencoding_not_ascii = 0; } else { char ascii_chars[128]; int c; for (c = 0; c < 128; c++) { ascii_chars[c] = c; } __Pyx_sys_getdefaultencoding_not_ascii = 1; ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); if (!ascii_chars_u) goto bad; ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { PyErr_Format( PyExc_ValueError, "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", default_encoding_c); goto bad; } Py_DECREF(ascii_chars_u); Py_DECREF(ascii_chars_b); } Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); Py_XDECREF(ascii_chars_u); Py_XDECREF(ascii_chars_b); return -1; } #endif #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) #else #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT static char* __PYX_DEFAULT_STRING_ENCODING; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); return -1; } #endif #endif /* Test for GCC > 2.95 */ #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ static PyObject *__pyx_m; static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static PyObject *__pyx_empty_unicode; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; /* Header.proto */ #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 #elif defined(_Complex_I) #define CYTHON_CCOMPLEX 1 #else #define CYTHON_CCOMPLEX 0 #endif #endif #if CYTHON_CCOMPLEX #ifdef __cplusplus #include #else #include #endif #endif #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif static const char *__pyx_f[] = { "draw_rectangles.pyx", "__init__.pxd", "type.pxd", }; /* BufferFormatStructs.proto */ #define IS_UNSIGNED(type) (((type) -1) > 0) struct __Pyx_StructField_; #define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) typedef struct { const char* name; struct __Pyx_StructField_* fields; size_t size; size_t arraysize[8]; int ndim; char typegroup; char is_unsigned; int flags; } __Pyx_TypeInfo; typedef struct __Pyx_StructField_ { __Pyx_TypeInfo* type; const char* name; size_t offset; } __Pyx_StructField; typedef struct { __Pyx_StructField* field; size_t parent_offset; } __Pyx_BufFmt_StackElem; typedef struct { __Pyx_StructField root; __Pyx_BufFmt_StackElem* head; size_t fmt_offset; size_t new_count, enc_count; size_t struct_alignment; int is_complex; char enc_type; char new_packmode; char enc_packmode; char is_valid_array; } __Pyx_BufFmt_Context; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":725 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t */ typedef npy_int8 __pyx_t_5numpy_int8_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":726 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t */ typedef npy_int16 __pyx_t_5numpy_int16_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":727 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< * ctypedef npy_int64 int64_t * #ctypedef npy_int96 int96_t */ typedef npy_int32 __pyx_t_5numpy_int32_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":728 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< * #ctypedef npy_int96 int96_t * #ctypedef npy_int128 int128_t */ typedef npy_int64 __pyx_t_5numpy_int64_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":732 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":733 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":734 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< * ctypedef npy_uint64 uint64_t * #ctypedef npy_uint96 uint96_t */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":735 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< * #ctypedef npy_uint96 uint96_t * #ctypedef npy_uint128 uint128_t */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":739 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< * ctypedef npy_float64 float64_t * #ctypedef npy_float80 float80_t */ typedef npy_float32 __pyx_t_5numpy_float32_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":740 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< * #ctypedef npy_float80 float80_t * #ctypedef npy_float128 float128_t */ typedef npy_float64 __pyx_t_5numpy_float64_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":749 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t */ typedef npy_long __pyx_t_5numpy_int_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":750 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< * ctypedef npy_longlong longlong_t * */ typedef npy_longlong __pyx_t_5numpy_long_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":751 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< * * ctypedef npy_ulong uint_t */ typedef npy_longlong __pyx_t_5numpy_longlong_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":753 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t */ typedef npy_ulong __pyx_t_5numpy_uint_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":754 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulonglong_t * */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":755 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< * * ctypedef npy_intp intp_t */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":757 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< * ctypedef npy_uintp uintp_t * */ typedef npy_intp __pyx_t_5numpy_intp_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":758 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< * * ctypedef npy_double float_t */ typedef npy_uintp __pyx_t_5numpy_uintp_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":760 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t */ typedef npy_double __pyx_t_5numpy_float_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":761 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< * ctypedef npy_longdouble longdouble_t * */ typedef npy_double __pyx_t_5numpy_double_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":762 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< * * ctypedef npy_cfloat cfloat_t */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; /* "draw_rectangles.pyx":10 * * DTYPE = np.float32 * ctypedef np.float32_t DTYPE_t # <<<<<<<<<<<<<< * * def draw_union_boxes(bbox_pairs, pooling_size, padding=0): */ typedef __pyx_t_5numpy_float32_t __pyx_t_15draw_rectangles_DTYPE_t; /* Declarations.proto */ #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; #else typedef float _Complex __pyx_t_float_complex; #endif #else typedef struct { float real, imag; } __pyx_t_float_complex; #endif static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); /* Declarations.proto */ #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< double > __pyx_t_double_complex; #else typedef double _Complex __pyx_t_double_complex; #endif #else typedef struct { double real, imag; } __pyx_t_double_complex; #endif static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); /*--- Type declarations ---*/ /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":764 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":765 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< * ctypedef npy_clongdouble clongdouble_t * */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":766 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< * * ctypedef npy_cdouble complex_t */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":768 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew1(a): */ typedef npy_cdouble __pyx_t_5numpy_complex_t; /* --- Runtime support code (head) --- */ /* Refnanny.proto */ #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); void (*DECREF)(void*, PyObject*, int); void (*GOTREF)(void*, PyObject*, int); void (*GIVEREF)(void*, PyObject*, int); void* (*SetupContext)(const char*, int, const char*); void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #ifdef WITH_THREAD #define __Pyx_RefNannySetupContext(name, acquire_gil)\ if (acquire_gil) {\ PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ PyGILState_Release(__pyx_gilstate_save);\ } else {\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ } #else #define __Pyx_RefNannySetupContext(name, acquire_gil)\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) #endif #define __Pyx_RefNannyFinishContext()\ __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) #define __Pyx_GOTREF(r) #define __Pyx_GIVEREF(r) #define __Pyx_XINCREF(r) Py_XINCREF(r) #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif #define __Pyx_XDECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_XDECREF(tmp);\ } while (0) #define __Pyx_DECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_DECREF(tmp);\ } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) /* PyObjectGetAttrStr.proto */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro)) return tp->tp_getattro(obj, attr_name); #if PY_MAJOR_VERSION < 3 if (likely(tp->tp_getattr)) return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); #endif return PyObject_GetAttr(obj, attr_name); } #else #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif /* GetBuiltinName.proto */ static PyObject *__Pyx_GetBuiltinName(PyObject *name); /* RaiseArgTupleInvalid.proto */ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /* RaiseDoubleKeywords.proto */ static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /* ParseKeywords.proto */ static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ const char* function_name); /* PyIntBinop.proto */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_EqObjC(PyObject *op1, PyObject *op2, long intval, int inplace); #else #define __Pyx_PyInt_EqObjC(op1, op2, intval, inplace)\ PyObject_RichCompare(op1, op2, Py_EQ) #endif /* ExtTypeTest.proto */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /* BufferFormatCheck.proto */ static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts); static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type); // PROTO /* GetModuleGlobalName.proto */ static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /* PyObjectCall.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); #else #define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) #endif /* BufferIndexError.proto */ static void __Pyx_RaiseBufferIndexError(int axis); #define __Pyx_BufPtrStrided2d(type, buf, i0, s0, i1, s1) (type)((char*)buf + i0 * s0 + i1 * s1) #define __Pyx_BufPtrStrided4d(type, buf, i0, s0, i1, s1, i2, s2, i3, s3) (type)((char*)buf + i0 * s0 + i1 * s1 + i2 * s2 + i3 * s3) /* PyThreadStateGet.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; #define __Pyx_PyThreadState_assign __pyx_tstate = PyThreadState_GET(); #else #define __Pyx_PyThreadState_declare #define __Pyx_PyThreadState_assign #endif /* PyErrFetchRestore.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) #define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else #define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) #endif /* RaiseException.proto */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /* DictGetItem.proto */ #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { PyObject *value; value = PyDict_GetItemWithError(d, key); if (unlikely(!value)) { if (!PyErr_Occurred()) { PyObject* args = PyTuple_Pack(1, key); if (likely(args)) PyErr_SetObject(PyExc_KeyError, args); Py_XDECREF(args); } return NULL; } Py_INCREF(value); return value; } #else #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) #endif /* RaiseTooManyValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); /* RaiseNeedMoreValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); /* RaiseNoneIterError.proto */ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); /* SaveResetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); #else #define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) #define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) #endif /* PyErrExceptionMatches.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); #else #define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) #endif /* GetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); #endif /* Import.proto */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /* CodeObjectCache.proto */ typedef struct { PyCodeObject* code_object; int code_line; } __Pyx_CodeObjectCacheEntry; struct __Pyx_CodeObjectCache { int count; int max_count; __Pyx_CodeObjectCacheEntry* entries; }; static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); static PyCodeObject *__pyx_find_code_object(int code_line); static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); /* AddTraceback.proto */ static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); /* BufferStructDeclare.proto */ typedef struct { Py_ssize_t shape, strides, suboffsets; } __Pyx_Buf_DimInfo; typedef struct { size_t refcount; Py_buffer pybuffer; } __Pyx_Buffer; typedef struct { __Pyx_Buffer *rcbuffer; char *data; __Pyx_Buf_DimInfo diminfo[8]; } __Pyx_LocalBuf_ND; #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); static void __Pyx_ReleaseBuffer(Py_buffer *view); #else #define __Pyx_GetBuffer PyObject_GetBuffer #define __Pyx_ReleaseBuffer PyBuffer_Release #endif /* None.proto */ static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value); /* RealImag.proto */ #if CYTHON_CCOMPLEX #ifdef __cplusplus #define __Pyx_CREAL(z) ((z).real()) #define __Pyx_CIMAG(z) ((z).imag()) #else #define __Pyx_CREAL(z) (__real__(z)) #define __Pyx_CIMAG(z) (__imag__(z)) #endif #else #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif #if defined(__cplusplus) && CYTHON_CCOMPLEX\ && (defined(_WIN32) || defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 5 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4 )) || __cplusplus >= 201103) #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) #endif /* Arithmetic.proto */ #if CYTHON_CCOMPLEX #define __Pyx_c_eq_float(a, b) ((a)==(b)) #define __Pyx_c_sum_float(a, b) ((a)+(b)) #define __Pyx_c_diff_float(a, b) ((a)-(b)) #define __Pyx_c_prod_float(a, b) ((a)*(b)) #define __Pyx_c_quot_float(a, b) ((a)/(b)) #define __Pyx_c_neg_float(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zero_float(z) ((z)==(float)0) #define __Pyx_c_conj_float(z) (::std::conj(z)) #if 1 #define __Pyx_c_abs_float(z) (::std::abs(z)) #define __Pyx_c_pow_float(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zero_float(z) ((z)==0) #define __Pyx_c_conj_float(z) (conjf(z)) #if 1 #define __Pyx_c_abs_float(z) (cabsf(z)) #define __Pyx_c_pow_float(a, b) (cpowf(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex); static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex); #if 1 static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex, __pyx_t_float_complex); #endif #endif /* Arithmetic.proto */ #if CYTHON_CCOMPLEX #define __Pyx_c_eq_double(a, b) ((a)==(b)) #define __Pyx_c_sum_double(a, b) ((a)+(b)) #define __Pyx_c_diff_double(a, b) ((a)-(b)) #define __Pyx_c_prod_double(a, b) ((a)*(b)) #define __Pyx_c_quot_double(a, b) ((a)/(b)) #define __Pyx_c_neg_double(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zero_double(z) ((z)==(double)0) #define __Pyx_c_conj_double(z) (::std::conj(z)) #if 1 #define __Pyx_c_abs_double(z) (::std::abs(z)) #define __Pyx_c_pow_double(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zero_double(z) ((z)==0) #define __Pyx_c_conj_double(z) (conj(z)) #if 1 #define __Pyx_c_abs_double(z) (cabs(z)) #define __Pyx_c_pow_double(a, b) (cpow(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex); static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex); #if 1 static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex, __pyx_t_double_complex); #endif #endif /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_enum__NPY_TYPES(enum NPY_TYPES value); /* CIntFromPy.proto */ static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); /* CIntFromPy.proto */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); /* CheckBinaryVersion.proto */ static int __Pyx_check_binary_version(void); /* PyIdentifierFromString.proto */ #if !defined(__Pyx_PyIdentifier_FromString) #if PY_MAJOR_VERSION < 3 #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) #else #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) #endif #endif /* ModuleImport.proto */ static PyObject *__Pyx_ImportModule(const char *name); /* TypeImport.proto */ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /* InitStrings.proto */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /* Module declarations from 'cython' */ /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'libc.string' */ /* Module declarations from 'libc.stdio' */ /* Module declarations from '__builtin__' */ /* Module declarations from 'cpython.type' */ static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; /* Module declarations from 'cpython' */ /* Module declarations from 'cpython.object' */ /* Module declarations from 'cpython.ref' */ /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ /* Module declarations from 'numpy' */ static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ /* Module declarations from 'draw_rectangles' */ static __pyx_t_15draw_rectangles_DTYPE_t __pyx_f_15draw_rectangles_minmax(__pyx_t_15draw_rectangles_DTYPE_t); /*proto*/ static PyArrayObject *__pyx_f_15draw_rectangles_draw_union_boxes_c(PyArrayObject *, unsigned int); /*proto*/ static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_15draw_rectangles_DTYPE_t = { "DTYPE_t", NULL, sizeof(__pyx_t_15draw_rectangles_DTYPE_t), { 0 }, 0, 'R', 0, 0 }; #define __Pyx_MODULE_NAME "draw_rectangles" int __pyx_module_is_main_draw_rectangles = 0; /* Implementation of 'draw_rectangles' */ static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_RuntimeError; static PyObject *__pyx_builtin_ImportError; static const char __pyx_k_np[] = "np"; static const char __pyx_k_main[] = "__main__"; static const char __pyx_k_test[] = "__test__"; static const char __pyx_k_DTYPE[] = "DTYPE"; static const char __pyx_k_dtype[] = "dtype"; static const char __pyx_k_numpy[] = "numpy"; static const char __pyx_k_range[] = "range"; static const char __pyx_k_zeros[] = "zeros"; static const char __pyx_k_import[] = "__import__"; static const char __pyx_k_float32[] = "float32"; static const char __pyx_k_padding[] = "padding"; static const char __pyx_k_ValueError[] = "ValueError"; static const char __pyx_k_bbox_pairs[] = "bbox_pairs"; static const char __pyx_k_ImportError[] = "ImportError"; static const char __pyx_k_RuntimeError[] = "RuntimeError"; static const char __pyx_k_pooling_size[] = "pooling_size"; static const char __pyx_k_draw_rectangles[] = "draw_rectangles"; static const char __pyx_k_draw_union_boxes[] = "draw_union_boxes"; static const char __pyx_k_Padding_0_not_supported_yet[] = "Padding>0 not supported yet"; static const char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; static const char __pyx_k_Users_rowanz_code_scene_graph_l[] = "/Users/rowanz/code/scene-graph/lib/draw_rectangles/draw_rectangles.pyx"; static const char __pyx_k_numpy_core_multiarray_failed_to[] = "numpy.core.multiarray failed to import"; static const char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; static const char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; static const char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; static const char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; static const char __pyx_k_numpy_core_umath_failed_to_impor[] = "numpy.core.umath failed to import"; static const char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; static PyObject *__pyx_n_s_DTYPE; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; static PyObject *__pyx_n_s_ImportError; static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; static PyObject *__pyx_kp_s_Padding_0_not_supported_yet; static PyObject *__pyx_n_s_RuntimeError; static PyObject *__pyx_kp_s_Users_rowanz_code_scene_graph_l; static PyObject *__pyx_n_s_ValueError; static PyObject *__pyx_n_s_bbox_pairs; static PyObject *__pyx_n_s_draw_rectangles; static PyObject *__pyx_n_s_draw_union_boxes; static PyObject *__pyx_n_s_dtype; static PyObject *__pyx_n_s_float32; static PyObject *__pyx_n_s_import; static PyObject *__pyx_n_s_main; static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; static PyObject *__pyx_n_s_np; static PyObject *__pyx_n_s_numpy; static PyObject *__pyx_kp_s_numpy_core_multiarray_failed_to; static PyObject *__pyx_kp_s_numpy_core_umath_failed_to_impor; static PyObject *__pyx_n_s_padding; static PyObject *__pyx_n_s_pooling_size; static PyObject *__pyx_n_s_range; static PyObject *__pyx_n_s_test; static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; static PyObject *__pyx_n_s_zeros; static PyObject *__pyx_pf_15draw_rectangles_draw_union_boxes(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_bbox_pairs, PyObject *__pyx_v_pooling_size, PyObject *__pyx_v_padding); /* proto */ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ static PyObject *__pyx_int_0; static PyObject *__pyx_int_2; static PyObject *__pyx_tuple_; static PyObject *__pyx_tuple__2; static PyObject *__pyx_tuple__3; static PyObject *__pyx_tuple__4; static PyObject *__pyx_tuple__5; static PyObject *__pyx_tuple__6; static PyObject *__pyx_tuple__7; static PyObject *__pyx_tuple__8; static PyObject *__pyx_tuple__9; static PyObject *__pyx_tuple__10; static PyObject *__pyx_codeobj__11; /* "draw_rectangles.pyx":12 * ctypedef np.float32_t DTYPE_t * * def draw_union_boxes(bbox_pairs, pooling_size, padding=0): # <<<<<<<<<<<<<< * """ * Draws union boxes for the image. */ /* Python wrapper */ static PyObject *__pyx_pw_15draw_rectangles_1draw_union_boxes(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_15draw_rectangles_draw_union_boxes[] = "\n Draws union boxes for the image.\n :param box_pairs: [num_pairs, 8]\n :param fmap_size: Size of the original feature map\n :param stride: ratio between fmap size and original img (<1)\n :param pooling_size: resize everything to this size\n :return: [num_pairs, 2, pooling_size, pooling_size arr\n "; static PyMethodDef __pyx_mdef_15draw_rectangles_1draw_union_boxes = {"draw_union_boxes", (PyCFunction)__pyx_pw_15draw_rectangles_1draw_union_boxes, METH_VARARGS|METH_KEYWORDS, __pyx_doc_15draw_rectangles_draw_union_boxes}; static PyObject *__pyx_pw_15draw_rectangles_1draw_union_boxes(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_bbox_pairs = 0; PyObject *__pyx_v_pooling_size = 0; PyObject *__pyx_v_padding = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("draw_union_boxes (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_bbox_pairs,&__pyx_n_s_pooling_size,&__pyx_n_s_padding,0}; PyObject* values[3] = {0,0,0}; values[2] = ((PyObject *)__pyx_int_0); if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_bbox_pairs)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_pooling_size)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("draw_union_boxes", 0, 2, 3, 1); __PYX_ERR(0, 12, __pyx_L3_error) } case 2: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_padding); if (value) { values[2] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "draw_union_boxes") < 0)) __PYX_ERR(0, 12, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[0] = PyTuple_GET_ITEM(__pyx_args, 0); break; default: goto __pyx_L5_argtuple_error; } } __pyx_v_bbox_pairs = values[0]; __pyx_v_pooling_size = values[1]; __pyx_v_padding = values[2]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("draw_union_boxes", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 12, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("draw_rectangles.draw_union_boxes", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_15draw_rectangles_draw_union_boxes(__pyx_self, __pyx_v_bbox_pairs, __pyx_v_pooling_size, __pyx_v_padding); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15draw_rectangles_draw_union_boxes(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_bbox_pairs, PyObject *__pyx_v_pooling_size, PyObject *__pyx_v_padding) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; unsigned int __pyx_t_3; __Pyx_RefNannySetupContext("draw_union_boxes", 0); /* "draw_rectangles.pyx":21 * :return: [num_pairs, 2, pooling_size, pooling_size arr * """ * assert padding == 0, "Padding>0 not supported yet" # <<<<<<<<<<<<<< * return draw_union_boxes_c(bbox_pairs, pooling_size) * */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { __pyx_t_1 = __Pyx_PyInt_EqObjC(__pyx_v_padding, __pyx_int_0, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (unlikely(!__pyx_t_2)) { PyErr_SetObject(PyExc_AssertionError, __pyx_kp_s_Padding_0_not_supported_yet); __PYX_ERR(0, 21, __pyx_L1_error) } } #endif /* "draw_rectangles.pyx":22 * """ * assert padding == 0, "Padding>0 not supported yet" * return draw_union_boxes_c(bbox_pairs, pooling_size) # <<<<<<<<<<<<<< * * cdef DTYPE_t minmax(DTYPE_t x): */ __Pyx_XDECREF(__pyx_r); if (!(likely(((__pyx_v_bbox_pairs) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_bbox_pairs, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 22, __pyx_L1_error) __pyx_t_3 = __Pyx_PyInt_As_unsigned_int(__pyx_v_pooling_size); if (unlikely((__pyx_t_3 == (unsigned int)-1) && PyErr_Occurred())) __PYX_ERR(0, 22, __pyx_L1_error) __pyx_t_1 = ((PyObject *)__pyx_f_15draw_rectangles_draw_union_boxes_c(((PyArrayObject *)__pyx_v_bbox_pairs), __pyx_t_3)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 22, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "draw_rectangles.pyx":12 * ctypedef np.float32_t DTYPE_t * * def draw_union_boxes(bbox_pairs, pooling_size, padding=0): # <<<<<<<<<<<<<< * """ * Draws union boxes for the image. */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("draw_rectangles.draw_union_boxes", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "draw_rectangles.pyx":24 * return draw_union_boxes_c(bbox_pairs, pooling_size) * * cdef DTYPE_t minmax(DTYPE_t x): # <<<<<<<<<<<<<< * return min(max(x, 0), 1) * */ static __pyx_t_15draw_rectangles_DTYPE_t __pyx_f_15draw_rectangles_minmax(__pyx_t_15draw_rectangles_DTYPE_t __pyx_v_x) { __pyx_t_15draw_rectangles_DTYPE_t __pyx_r; __Pyx_RefNannyDeclarations long __pyx_t_1; long __pyx_t_2; __pyx_t_15draw_rectangles_DTYPE_t __pyx_t_3; __pyx_t_15draw_rectangles_DTYPE_t __pyx_t_4; __Pyx_RefNannySetupContext("minmax", 0); /* "draw_rectangles.pyx":25 * * cdef DTYPE_t minmax(DTYPE_t x): * return min(max(x, 0), 1) # <<<<<<<<<<<<<< * * cdef np.ndarray[DTYPE_t, ndim=4] draw_union_boxes_c( */ __pyx_t_1 = 1; __pyx_t_2 = 0; __pyx_t_3 = __pyx_v_x; if (((__pyx_t_2 > __pyx_t_3) != 0)) { __pyx_t_4 = __pyx_t_2; } else { __pyx_t_4 = __pyx_t_3; } __pyx_t_3 = __pyx_t_4; if (((__pyx_t_1 < __pyx_t_3) != 0)) { __pyx_t_4 = __pyx_t_1; } else { __pyx_t_4 = __pyx_t_3; } __pyx_r = __pyx_t_4; goto __pyx_L0; /* "draw_rectangles.pyx":24 * return draw_union_boxes_c(bbox_pairs, pooling_size) * * cdef DTYPE_t minmax(DTYPE_t x): # <<<<<<<<<<<<<< * return min(max(x, 0), 1) * */ /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "draw_rectangles.pyx":27 * return min(max(x, 0), 1) * * cdef np.ndarray[DTYPE_t, ndim=4] draw_union_boxes_c( # <<<<<<<<<<<<<< * np.ndarray[DTYPE_t, ndim=2] box_pairs, unsigned int pooling_size): * """ */ static PyArrayObject *__pyx_f_15draw_rectangles_draw_union_boxes_c(PyArrayObject *__pyx_v_box_pairs, unsigned int __pyx_v_pooling_size) { unsigned int __pyx_v_N; PyArrayObject *__pyx_v_uboxes = 0; __pyx_t_15draw_rectangles_DTYPE_t __pyx_v_x1_union; __pyx_t_15draw_rectangles_DTYPE_t __pyx_v_y1_union; __pyx_t_15draw_rectangles_DTYPE_t __pyx_v_x2_union; __pyx_t_15draw_rectangles_DTYPE_t __pyx_v_y2_union; __pyx_t_15draw_rectangles_DTYPE_t __pyx_v_w; __pyx_t_15draw_rectangles_DTYPE_t __pyx_v_h; __pyx_t_15draw_rectangles_DTYPE_t __pyx_v_x1_box; __pyx_t_15draw_rectangles_DTYPE_t __pyx_v_y1_box; __pyx_t_15draw_rectangles_DTYPE_t __pyx_v_x2_box; __pyx_t_15draw_rectangles_DTYPE_t __pyx_v_y2_box; __pyx_t_15draw_rectangles_DTYPE_t __pyx_v_y_contrib; __pyx_t_15draw_rectangles_DTYPE_t __pyx_v_x_contrib; unsigned int __pyx_v_n; unsigned int __pyx_v_i; unsigned int __pyx_v_j; unsigned int __pyx_v_k; __Pyx_LocalBuf_ND __pyx_pybuffernd_box_pairs; __Pyx_Buffer __pyx_pybuffer_box_pairs; __Pyx_LocalBuf_ND __pyx_pybuffernd_uboxes; __Pyx_Buffer __pyx_pybuffer_uboxes; PyArrayObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; unsigned int __pyx_t_7; unsigned int __pyx_t_8; size_t __pyx_t_9; Py_ssize_t __pyx_t_10; int __pyx_t_11; __pyx_t_15draw_rectangles_DTYPE_t __pyx_t_12; size_t __pyx_t_13; Py_ssize_t __pyx_t_14; __pyx_t_15draw_rectangles_DTYPE_t __pyx_t_15; __pyx_t_15draw_rectangles_DTYPE_t __pyx_t_16; size_t __pyx_t_17; Py_ssize_t __pyx_t_18; size_t __pyx_t_19; Py_ssize_t __pyx_t_20; size_t __pyx_t_21; Py_ssize_t __pyx_t_22; size_t __pyx_t_23; Py_ssize_t __pyx_t_24; size_t __pyx_t_25; Py_ssize_t __pyx_t_26; size_t __pyx_t_27; Py_ssize_t __pyx_t_28; unsigned int __pyx_t_29; size_t __pyx_t_30; Py_ssize_t __pyx_t_31; size_t __pyx_t_32; Py_ssize_t __pyx_t_33; size_t __pyx_t_34; Py_ssize_t __pyx_t_35; size_t __pyx_t_36; Py_ssize_t __pyx_t_37; unsigned int __pyx_t_38; unsigned int __pyx_t_39; unsigned int __pyx_t_40; unsigned int __pyx_t_41; size_t __pyx_t_42; size_t __pyx_t_43; size_t __pyx_t_44; size_t __pyx_t_45; __Pyx_RefNannySetupContext("draw_union_boxes_c", 0); __pyx_pybuffer_uboxes.pybuffer.buf = NULL; __pyx_pybuffer_uboxes.refcount = 0; __pyx_pybuffernd_uboxes.data = NULL; __pyx_pybuffernd_uboxes.rcbuffer = &__pyx_pybuffer_uboxes; __pyx_pybuffer_box_pairs.pybuffer.buf = NULL; __pyx_pybuffer_box_pairs.refcount = 0; __pyx_pybuffernd_box_pairs.data = NULL; __pyx_pybuffernd_box_pairs.rcbuffer = &__pyx_pybuffer_box_pairs; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_box_pairs.rcbuffer->pybuffer, (PyObject*)__pyx_v_box_pairs, &__Pyx_TypeInfo_nn___pyx_t_15draw_rectangles_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) __PYX_ERR(0, 27, __pyx_L1_error) } __pyx_pybuffernd_box_pairs.diminfo[0].strides = __pyx_pybuffernd_box_pairs.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_box_pairs.diminfo[0].shape = __pyx_pybuffernd_box_pairs.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_box_pairs.diminfo[1].strides = __pyx_pybuffernd_box_pairs.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_box_pairs.diminfo[1].shape = __pyx_pybuffernd_box_pairs.rcbuffer->pybuffer.shape[1]; /* "draw_rectangles.pyx":38 * overlaps: (N, K) ndarray of overlap between boxes and query_boxes * """ * cdef unsigned int N = box_pairs.shape[0] # <<<<<<<<<<<<<< * * cdef np.ndarray[DTYPE_t, ndim = 4] uboxes = np.zeros( */ __pyx_v_N = (__pyx_v_box_pairs->dimensions[0]); /* "draw_rectangles.pyx":40 * cdef unsigned int N = box_pairs.shape[0] * * cdef np.ndarray[DTYPE_t, ndim = 4] uboxes = np.zeros( # <<<<<<<<<<<<<< * (N, 2, pooling_size, pooling_size), dtype=DTYPE) * cdef DTYPE_t x1_union, y1_union, x2_union, y2_union, w, h, x1_box, y1_box, x2_box, y2_box, y_contrib, x_contrib */ __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 40, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 40, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "draw_rectangles.pyx":41 * * cdef np.ndarray[DTYPE_t, ndim = 4] uboxes = np.zeros( * (N, 2, pooling_size, pooling_size), dtype=DTYPE) # <<<<<<<<<<<<<< * cdef DTYPE_t x1_union, y1_union, x2_union, y2_union, w, h, x1_box, y1_box, x2_box, y2_box, y_contrib, x_contrib * cdef unsigned int n, i, j, k */ __pyx_t_1 = __Pyx_PyInt_From_unsigned_int(__pyx_v_N); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 41, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = __Pyx_PyInt_From_unsigned_int(__pyx_v_pooling_size); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 41, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = __Pyx_PyInt_From_unsigned_int(__pyx_v_pooling_size); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 41, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 41, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1); __Pyx_INCREF(__pyx_int_2); __Pyx_GIVEREF(__pyx_int_2); PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_int_2); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); __pyx_t_1 = 0; __pyx_t_3 = 0; __pyx_t_4 = 0; /* "draw_rectangles.pyx":40 * cdef unsigned int N = box_pairs.shape[0] * * cdef np.ndarray[DTYPE_t, ndim = 4] uboxes = np.zeros( # <<<<<<<<<<<<<< * (N, 2, pooling_size, pooling_size), dtype=DTYPE) * cdef DTYPE_t x1_union, y1_union, x2_union, y2_union, w, h, x1_box, y1_box, x2_box, y2_box, y_contrib, x_contrib */ __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 40, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __pyx_t_5 = 0; /* "draw_rectangles.pyx":41 * * cdef np.ndarray[DTYPE_t, ndim = 4] uboxes = np.zeros( * (N, 2, pooling_size, pooling_size), dtype=DTYPE) # <<<<<<<<<<<<<< * cdef DTYPE_t x1_union, y1_union, x2_union, y2_union, w, h, x1_box, y1_box, x2_box, y2_box, y_contrib, x_contrib * cdef unsigned int n, i, j, k */ __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 41, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 41, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_t_5, __pyx_n_s_dtype, __pyx_t_3) < 0) __PYX_ERR(0, 41, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "draw_rectangles.pyx":40 * cdef unsigned int N = box_pairs.shape[0] * * cdef np.ndarray[DTYPE_t, ndim = 4] uboxes = np.zeros( # <<<<<<<<<<<<<< * (N, 2, pooling_size, pooling_size), dtype=DTYPE) * cdef DTYPE_t x1_union, y1_union, x2_union, y2_union, w, h, x1_box, y1_box, x2_box, y2_box, y_contrib, x_contrib */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 40, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 40, __pyx_L1_error) __pyx_t_6 = ((PyArrayObject *)__pyx_t_3); { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_uboxes.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_15draw_rectangles_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 4, 0, __pyx_stack) == -1)) { __pyx_v_uboxes = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_uboxes.rcbuffer->pybuffer.buf = NULL; __PYX_ERR(0, 40, __pyx_L1_error) } else {__pyx_pybuffernd_uboxes.diminfo[0].strides = __pyx_pybuffernd_uboxes.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_uboxes.diminfo[0].shape = __pyx_pybuffernd_uboxes.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_uboxes.diminfo[1].strides = __pyx_pybuffernd_uboxes.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_uboxes.diminfo[1].shape = __pyx_pybuffernd_uboxes.rcbuffer->pybuffer.shape[1]; __pyx_pybuffernd_uboxes.diminfo[2].strides = __pyx_pybuffernd_uboxes.rcbuffer->pybuffer.strides[2]; __pyx_pybuffernd_uboxes.diminfo[2].shape = __pyx_pybuffernd_uboxes.rcbuffer->pybuffer.shape[2]; __pyx_pybuffernd_uboxes.diminfo[3].strides = __pyx_pybuffernd_uboxes.rcbuffer->pybuffer.strides[3]; __pyx_pybuffernd_uboxes.diminfo[3].shape = __pyx_pybuffernd_uboxes.rcbuffer->pybuffer.shape[3]; } } __pyx_t_6 = 0; __pyx_v_uboxes = ((PyArrayObject *)__pyx_t_3); __pyx_t_3 = 0; /* "draw_rectangles.pyx":45 * cdef unsigned int n, i, j, k * * for n in range(N): # <<<<<<<<<<<<<< * x1_union = min(box_pairs[n, 0], box_pairs[n, 4]) * y1_union = min(box_pairs[n, 1], box_pairs[n, 5]) */ __pyx_t_7 = __pyx_v_N; for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { __pyx_v_n = __pyx_t_8; /* "draw_rectangles.pyx":46 * * for n in range(N): * x1_union = min(box_pairs[n, 0], box_pairs[n, 4]) # <<<<<<<<<<<<<< * y1_union = min(box_pairs[n, 1], box_pairs[n, 5]) * x2_union = max(box_pairs[n, 2], box_pairs[n, 6]) */ __pyx_t_9 = __pyx_v_n; __pyx_t_10 = 4; __pyx_t_11 = -1; if (unlikely(__pyx_t_9 >= (size_t)__pyx_pybuffernd_box_pairs.diminfo[0].shape)) __pyx_t_11 = 0; if (__pyx_t_10 < 0) { __pyx_t_10 += __pyx_pybuffernd_box_pairs.diminfo[1].shape; if (unlikely(__pyx_t_10 < 0)) __pyx_t_11 = 1; } else if (unlikely(__pyx_t_10 >= __pyx_pybuffernd_box_pairs.diminfo[1].shape)) __pyx_t_11 = 1; if (unlikely(__pyx_t_11 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_11); __PYX_ERR(0, 46, __pyx_L1_error) } __pyx_t_12 = (*__Pyx_BufPtrStrided2d(__pyx_t_15draw_rectangles_DTYPE_t *, __pyx_pybuffernd_box_pairs.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_box_pairs.diminfo[0].strides, __pyx_t_10, __pyx_pybuffernd_box_pairs.diminfo[1].strides)); __pyx_t_13 = __pyx_v_n; __pyx_t_14 = 0; __pyx_t_11 = -1; if (unlikely(__pyx_t_13 >= (size_t)__pyx_pybuffernd_box_pairs.diminfo[0].shape)) __pyx_t_11 = 0; if (__pyx_t_14 < 0) { __pyx_t_14 += __pyx_pybuffernd_box_pairs.diminfo[1].shape; if (unlikely(__pyx_t_14 < 0)) __pyx_t_11 = 1; } else if (unlikely(__pyx_t_14 >= __pyx_pybuffernd_box_pairs.diminfo[1].shape)) __pyx_t_11 = 1; if (unlikely(__pyx_t_11 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_11); __PYX_ERR(0, 46, __pyx_L1_error) } __pyx_t_15 = (*__Pyx_BufPtrStrided2d(__pyx_t_15draw_rectangles_DTYPE_t *, __pyx_pybuffernd_box_pairs.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_box_pairs.diminfo[0].strides, __pyx_t_14, __pyx_pybuffernd_box_pairs.diminfo[1].strides)); if (((__pyx_t_12 < __pyx_t_15) != 0)) { __pyx_t_16 = __pyx_t_12; } else { __pyx_t_16 = __pyx_t_15; } __pyx_v_x1_union = __pyx_t_16; /* "draw_rectangles.pyx":47 * for n in range(N): * x1_union = min(box_pairs[n, 0], box_pairs[n, 4]) * y1_union = min(box_pairs[n, 1], box_pairs[n, 5]) # <<<<<<<<<<<<<< * x2_union = max(box_pairs[n, 2], box_pairs[n, 6]) * y2_union = max(box_pairs[n, 3], box_pairs[n, 7]) */ __pyx_t_17 = __pyx_v_n; __pyx_t_18 = 5; __pyx_t_11 = -1; if (unlikely(__pyx_t_17 >= (size_t)__pyx_pybuffernd_box_pairs.diminfo[0].shape)) __pyx_t_11 = 0; if (__pyx_t_18 < 0) { __pyx_t_18 += __pyx_pybuffernd_box_pairs.diminfo[1].shape; if (unlikely(__pyx_t_18 < 0)) __pyx_t_11 = 1; } else if (unlikely(__pyx_t_18 >= __pyx_pybuffernd_box_pairs.diminfo[1].shape)) __pyx_t_11 = 1; if (unlikely(__pyx_t_11 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_11); __PYX_ERR(0, 47, __pyx_L1_error) } __pyx_t_16 = (*__Pyx_BufPtrStrided2d(__pyx_t_15draw_rectangles_DTYPE_t *, __pyx_pybuffernd_box_pairs.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_box_pairs.diminfo[0].strides, __pyx_t_18, __pyx_pybuffernd_box_pairs.diminfo[1].strides)); __pyx_t_19 = __pyx_v_n; __pyx_t_20 = 1; __pyx_t_11 = -1; if (unlikely(__pyx_t_19 >= (size_t)__pyx_pybuffernd_box_pairs.diminfo[0].shape)) __pyx_t_11 = 0; if (__pyx_t_20 < 0) { __pyx_t_20 += __pyx_pybuffernd_box_pairs.diminfo[1].shape; if (unlikely(__pyx_t_20 < 0)) __pyx_t_11 = 1; } else if (unlikely(__pyx_t_20 >= __pyx_pybuffernd_box_pairs.diminfo[1].shape)) __pyx_t_11 = 1; if (unlikely(__pyx_t_11 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_11); __PYX_ERR(0, 47, __pyx_L1_error) } __pyx_t_12 = (*__Pyx_BufPtrStrided2d(__pyx_t_15draw_rectangles_DTYPE_t *, __pyx_pybuffernd_box_pairs.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_box_pairs.diminfo[0].strides, __pyx_t_20, __pyx_pybuffernd_box_pairs.diminfo[1].strides)); if (((__pyx_t_16 < __pyx_t_12) != 0)) { __pyx_t_15 = __pyx_t_16; } else { __pyx_t_15 = __pyx_t_12; } __pyx_v_y1_union = __pyx_t_15; /* "draw_rectangles.pyx":48 * x1_union = min(box_pairs[n, 0], box_pairs[n, 4]) * y1_union = min(box_pairs[n, 1], box_pairs[n, 5]) * x2_union = max(box_pairs[n, 2], box_pairs[n, 6]) # <<<<<<<<<<<<<< * y2_union = max(box_pairs[n, 3], box_pairs[n, 7]) * */ __pyx_t_21 = __pyx_v_n; __pyx_t_22 = 6; __pyx_t_11 = -1; if (unlikely(__pyx_t_21 >= (size_t)__pyx_pybuffernd_box_pairs.diminfo[0].shape)) __pyx_t_11 = 0; if (__pyx_t_22 < 0) { __pyx_t_22 += __pyx_pybuffernd_box_pairs.diminfo[1].shape; if (unlikely(__pyx_t_22 < 0)) __pyx_t_11 = 1; } else if (unlikely(__pyx_t_22 >= __pyx_pybuffernd_box_pairs.diminfo[1].shape)) __pyx_t_11 = 1; if (unlikely(__pyx_t_11 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_11); __PYX_ERR(0, 48, __pyx_L1_error) } __pyx_t_15 = (*__Pyx_BufPtrStrided2d(__pyx_t_15draw_rectangles_DTYPE_t *, __pyx_pybuffernd_box_pairs.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_box_pairs.diminfo[0].strides, __pyx_t_22, __pyx_pybuffernd_box_pairs.diminfo[1].strides)); __pyx_t_23 = __pyx_v_n; __pyx_t_24 = 2; __pyx_t_11 = -1; if (unlikely(__pyx_t_23 >= (size_t)__pyx_pybuffernd_box_pairs.diminfo[0].shape)) __pyx_t_11 = 0; if (__pyx_t_24 < 0) { __pyx_t_24 += __pyx_pybuffernd_box_pairs.diminfo[1].shape; if (unlikely(__pyx_t_24 < 0)) __pyx_t_11 = 1; } else if (unlikely(__pyx_t_24 >= __pyx_pybuffernd_box_pairs.diminfo[1].shape)) __pyx_t_11 = 1; if (unlikely(__pyx_t_11 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_11); __PYX_ERR(0, 48, __pyx_L1_error) } __pyx_t_16 = (*__Pyx_BufPtrStrided2d(__pyx_t_15draw_rectangles_DTYPE_t *, __pyx_pybuffernd_box_pairs.rcbuffer->pybuffer.buf, __pyx_t_23, __pyx_pybuffernd_box_pairs.diminfo[0].strides, __pyx_t_24, __pyx_pybuffernd_box_pairs.diminfo[1].strides)); if (((__pyx_t_15 > __pyx_t_16) != 0)) { __pyx_t_12 = __pyx_t_15; } else { __pyx_t_12 = __pyx_t_16; } __pyx_v_x2_union = __pyx_t_12; /* "draw_rectangles.pyx":49 * y1_union = min(box_pairs[n, 1], box_pairs[n, 5]) * x2_union = max(box_pairs[n, 2], box_pairs[n, 6]) * y2_union = max(box_pairs[n, 3], box_pairs[n, 7]) # <<<<<<<<<<<<<< * * w = x2_union - x1_union */ __pyx_t_25 = __pyx_v_n; __pyx_t_26 = 7; __pyx_t_11 = -1; if (unlikely(__pyx_t_25 >= (size_t)__pyx_pybuffernd_box_pairs.diminfo[0].shape)) __pyx_t_11 = 0; if (__pyx_t_26 < 0) { __pyx_t_26 += __pyx_pybuffernd_box_pairs.diminfo[1].shape; if (unlikely(__pyx_t_26 < 0)) __pyx_t_11 = 1; } else if (unlikely(__pyx_t_26 >= __pyx_pybuffernd_box_pairs.diminfo[1].shape)) __pyx_t_11 = 1; if (unlikely(__pyx_t_11 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_11); __PYX_ERR(0, 49, __pyx_L1_error) } __pyx_t_12 = (*__Pyx_BufPtrStrided2d(__pyx_t_15draw_rectangles_DTYPE_t *, __pyx_pybuffernd_box_pairs.rcbuffer->pybuffer.buf, __pyx_t_25, __pyx_pybuffernd_box_pairs.diminfo[0].strides, __pyx_t_26, __pyx_pybuffernd_box_pairs.diminfo[1].strides)); __pyx_t_27 = __pyx_v_n; __pyx_t_28 = 3; __pyx_t_11 = -1; if (unlikely(__pyx_t_27 >= (size_t)__pyx_pybuffernd_box_pairs.diminfo[0].shape)) __pyx_t_11 = 0; if (__pyx_t_28 < 0) { __pyx_t_28 += __pyx_pybuffernd_box_pairs.diminfo[1].shape; if (unlikely(__pyx_t_28 < 0)) __pyx_t_11 = 1; } else if (unlikely(__pyx_t_28 >= __pyx_pybuffernd_box_pairs.diminfo[1].shape)) __pyx_t_11 = 1; if (unlikely(__pyx_t_11 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_11); __PYX_ERR(0, 49, __pyx_L1_error) } __pyx_t_15 = (*__Pyx_BufPtrStrided2d(__pyx_t_15draw_rectangles_DTYPE_t *, __pyx_pybuffernd_box_pairs.rcbuffer->pybuffer.buf, __pyx_t_27, __pyx_pybuffernd_box_pairs.diminfo[0].strides, __pyx_t_28, __pyx_pybuffernd_box_pairs.diminfo[1].strides)); if (((__pyx_t_12 > __pyx_t_15) != 0)) { __pyx_t_16 = __pyx_t_12; } else { __pyx_t_16 = __pyx_t_15; } __pyx_v_y2_union = __pyx_t_16; /* "draw_rectangles.pyx":51 * y2_union = max(box_pairs[n, 3], box_pairs[n, 7]) * * w = x2_union - x1_union # <<<<<<<<<<<<<< * h = y2_union - y1_union * */ __pyx_v_w = (__pyx_v_x2_union - __pyx_v_x1_union); /* "draw_rectangles.pyx":52 * * w = x2_union - x1_union * h = y2_union - y1_union # <<<<<<<<<<<<<< * * for i in range(2): */ __pyx_v_h = (__pyx_v_y2_union - __pyx_v_y1_union); /* "draw_rectangles.pyx":54 * h = y2_union - y1_union * * for i in range(2): # <<<<<<<<<<<<<< * # Now everything is in the range [0, pooling_size]. * x1_box = (box_pairs[n, 0+4*i] - x1_union)*pooling_size / w */ for (__pyx_t_29 = 0; __pyx_t_29 < 2; __pyx_t_29+=1) { __pyx_v_i = __pyx_t_29; /* "draw_rectangles.pyx":56 * for i in range(2): * # Now everything is in the range [0, pooling_size]. * x1_box = (box_pairs[n, 0+4*i] - x1_union)*pooling_size / w # <<<<<<<<<<<<<< * y1_box = (box_pairs[n, 1+4*i] - y1_union)*pooling_size / h * x2_box = (box_pairs[n, 2+4*i] - x1_union)*pooling_size / w */ __pyx_t_30 = __pyx_v_n; __pyx_t_31 = (0 + (4 * __pyx_v_i)); __pyx_t_11 = -1; if (unlikely(__pyx_t_30 >= (size_t)__pyx_pybuffernd_box_pairs.diminfo[0].shape)) __pyx_t_11 = 0; if (__pyx_t_31 < 0) { __pyx_t_31 += __pyx_pybuffernd_box_pairs.diminfo[1].shape; if (unlikely(__pyx_t_31 < 0)) __pyx_t_11 = 1; } else if (unlikely(__pyx_t_31 >= __pyx_pybuffernd_box_pairs.diminfo[1].shape)) __pyx_t_11 = 1; if (unlikely(__pyx_t_11 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_11); __PYX_ERR(0, 56, __pyx_L1_error) } __pyx_t_16 = (((*__Pyx_BufPtrStrided2d(__pyx_t_15draw_rectangles_DTYPE_t *, __pyx_pybuffernd_box_pairs.rcbuffer->pybuffer.buf, __pyx_t_30, __pyx_pybuffernd_box_pairs.diminfo[0].strides, __pyx_t_31, __pyx_pybuffernd_box_pairs.diminfo[1].strides)) - __pyx_v_x1_union) * __pyx_v_pooling_size); if (unlikely(__pyx_v_w == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "float division"); __PYX_ERR(0, 56, __pyx_L1_error) } __pyx_v_x1_box = (__pyx_t_16 / __pyx_v_w); /* "draw_rectangles.pyx":57 * # Now everything is in the range [0, pooling_size]. * x1_box = (box_pairs[n, 0+4*i] - x1_union)*pooling_size / w * y1_box = (box_pairs[n, 1+4*i] - y1_union)*pooling_size / h # <<<<<<<<<<<<<< * x2_box = (box_pairs[n, 2+4*i] - x1_union)*pooling_size / w * y2_box = (box_pairs[n, 3+4*i] - y1_union)*pooling_size / h */ __pyx_t_32 = __pyx_v_n; __pyx_t_33 = (1 + (4 * __pyx_v_i)); __pyx_t_11 = -1; if (unlikely(__pyx_t_32 >= (size_t)__pyx_pybuffernd_box_pairs.diminfo[0].shape)) __pyx_t_11 = 0; if (__pyx_t_33 < 0) { __pyx_t_33 += __pyx_pybuffernd_box_pairs.diminfo[1].shape; if (unlikely(__pyx_t_33 < 0)) __pyx_t_11 = 1; } else if (unlikely(__pyx_t_33 >= __pyx_pybuffernd_box_pairs.diminfo[1].shape)) __pyx_t_11 = 1; if (unlikely(__pyx_t_11 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_11); __PYX_ERR(0, 57, __pyx_L1_error) } __pyx_t_16 = (((*__Pyx_BufPtrStrided2d(__pyx_t_15draw_rectangles_DTYPE_t *, __pyx_pybuffernd_box_pairs.rcbuffer->pybuffer.buf, __pyx_t_32, __pyx_pybuffernd_box_pairs.diminfo[0].strides, __pyx_t_33, __pyx_pybuffernd_box_pairs.diminfo[1].strides)) - __pyx_v_y1_union) * __pyx_v_pooling_size); if (unlikely(__pyx_v_h == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "float division"); __PYX_ERR(0, 57, __pyx_L1_error) } __pyx_v_y1_box = (__pyx_t_16 / __pyx_v_h); /* "draw_rectangles.pyx":58 * x1_box = (box_pairs[n, 0+4*i] - x1_union)*pooling_size / w * y1_box = (box_pairs[n, 1+4*i] - y1_union)*pooling_size / h * x2_box = (box_pairs[n, 2+4*i] - x1_union)*pooling_size / w # <<<<<<<<<<<<<< * y2_box = (box_pairs[n, 3+4*i] - y1_union)*pooling_size / h * # print("{:.3f}, {:.3f}, {:.3f}, {:.3f}".format(x1_box, y1_box, x2_box, y2_box)) */ __pyx_t_34 = __pyx_v_n; __pyx_t_35 = (2 + (4 * __pyx_v_i)); __pyx_t_11 = -1; if (unlikely(__pyx_t_34 >= (size_t)__pyx_pybuffernd_box_pairs.diminfo[0].shape)) __pyx_t_11 = 0; if (__pyx_t_35 < 0) { __pyx_t_35 += __pyx_pybuffernd_box_pairs.diminfo[1].shape; if (unlikely(__pyx_t_35 < 0)) __pyx_t_11 = 1; } else if (unlikely(__pyx_t_35 >= __pyx_pybuffernd_box_pairs.diminfo[1].shape)) __pyx_t_11 = 1; if (unlikely(__pyx_t_11 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_11); __PYX_ERR(0, 58, __pyx_L1_error) } __pyx_t_16 = (((*__Pyx_BufPtrStrided2d(__pyx_t_15draw_rectangles_DTYPE_t *, __pyx_pybuffernd_box_pairs.rcbuffer->pybuffer.buf, __pyx_t_34, __pyx_pybuffernd_box_pairs.diminfo[0].strides, __pyx_t_35, __pyx_pybuffernd_box_pairs.diminfo[1].strides)) - __pyx_v_x1_union) * __pyx_v_pooling_size); if (unlikely(__pyx_v_w == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "float division"); __PYX_ERR(0, 58, __pyx_L1_error) } __pyx_v_x2_box = (__pyx_t_16 / __pyx_v_w); /* "draw_rectangles.pyx":59 * y1_box = (box_pairs[n, 1+4*i] - y1_union)*pooling_size / h * x2_box = (box_pairs[n, 2+4*i] - x1_union)*pooling_size / w * y2_box = (box_pairs[n, 3+4*i] - y1_union)*pooling_size / h # <<<<<<<<<<<<<< * # print("{:.3f}, {:.3f}, {:.3f}, {:.3f}".format(x1_box, y1_box, x2_box, y2_box)) * for j in range(pooling_size): */ __pyx_t_36 = __pyx_v_n; __pyx_t_37 = (3 + (4 * __pyx_v_i)); __pyx_t_11 = -1; if (unlikely(__pyx_t_36 >= (size_t)__pyx_pybuffernd_box_pairs.diminfo[0].shape)) __pyx_t_11 = 0; if (__pyx_t_37 < 0) { __pyx_t_37 += __pyx_pybuffernd_box_pairs.diminfo[1].shape; if (unlikely(__pyx_t_37 < 0)) __pyx_t_11 = 1; } else if (unlikely(__pyx_t_37 >= __pyx_pybuffernd_box_pairs.diminfo[1].shape)) __pyx_t_11 = 1; if (unlikely(__pyx_t_11 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_11); __PYX_ERR(0, 59, __pyx_L1_error) } __pyx_t_16 = (((*__Pyx_BufPtrStrided2d(__pyx_t_15draw_rectangles_DTYPE_t *, __pyx_pybuffernd_box_pairs.rcbuffer->pybuffer.buf, __pyx_t_36, __pyx_pybuffernd_box_pairs.diminfo[0].strides, __pyx_t_37, __pyx_pybuffernd_box_pairs.diminfo[1].strides)) - __pyx_v_y1_union) * __pyx_v_pooling_size); if (unlikely(__pyx_v_h == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "float division"); __PYX_ERR(0, 59, __pyx_L1_error) } __pyx_v_y2_box = (__pyx_t_16 / __pyx_v_h); /* "draw_rectangles.pyx":61 * y2_box = (box_pairs[n, 3+4*i] - y1_union)*pooling_size / h * # print("{:.3f}, {:.3f}, {:.3f}, {:.3f}".format(x1_box, y1_box, x2_box, y2_box)) * for j in range(pooling_size): # <<<<<<<<<<<<<< * y_contrib = minmax(j+1-y1_box)*minmax(y2_box-j) * for k in range(pooling_size): */ __pyx_t_38 = __pyx_v_pooling_size; for (__pyx_t_39 = 0; __pyx_t_39 < __pyx_t_38; __pyx_t_39+=1) { __pyx_v_j = __pyx_t_39; /* "draw_rectangles.pyx":62 * # print("{:.3f}, {:.3f}, {:.3f}, {:.3f}".format(x1_box, y1_box, x2_box, y2_box)) * for j in range(pooling_size): * y_contrib = minmax(j+1-y1_box)*minmax(y2_box-j) # <<<<<<<<<<<<<< * for k in range(pooling_size): * x_contrib = minmax(k+1-x1_box)*minmax(x2_box-k) */ __pyx_v_y_contrib = (__pyx_f_15draw_rectangles_minmax(((__pyx_v_j + 1) - __pyx_v_y1_box)) * __pyx_f_15draw_rectangles_minmax((__pyx_v_y2_box - __pyx_v_j))); /* "draw_rectangles.pyx":63 * for j in range(pooling_size): * y_contrib = minmax(j+1-y1_box)*minmax(y2_box-j) * for k in range(pooling_size): # <<<<<<<<<<<<<< * x_contrib = minmax(k+1-x1_box)*minmax(x2_box-k) * # print("j {} yc {} k {} xc {}".format(j, y_contrib, k, x_contrib)) */ __pyx_t_40 = __pyx_v_pooling_size; for (__pyx_t_41 = 0; __pyx_t_41 < __pyx_t_40; __pyx_t_41+=1) { __pyx_v_k = __pyx_t_41; /* "draw_rectangles.pyx":64 * y_contrib = minmax(j+1-y1_box)*minmax(y2_box-j) * for k in range(pooling_size): * x_contrib = minmax(k+1-x1_box)*minmax(x2_box-k) # <<<<<<<<<<<<<< * # print("j {} yc {} k {} xc {}".format(j, y_contrib, k, x_contrib)) * uboxes[n,i,j,k] = x_contrib*y_contrib */ __pyx_v_x_contrib = (__pyx_f_15draw_rectangles_minmax(((__pyx_v_k + 1) - __pyx_v_x1_box)) * __pyx_f_15draw_rectangles_minmax((__pyx_v_x2_box - __pyx_v_k))); /* "draw_rectangles.pyx":66 * x_contrib = minmax(k+1-x1_box)*minmax(x2_box-k) * # print("j {} yc {} k {} xc {}".format(j, y_contrib, k, x_contrib)) * uboxes[n,i,j,k] = x_contrib*y_contrib # <<<<<<<<<<<<<< * return uboxes */ __pyx_t_42 = __pyx_v_n; __pyx_t_43 = __pyx_v_i; __pyx_t_44 = __pyx_v_j; __pyx_t_45 = __pyx_v_k; __pyx_t_11 = -1; if (unlikely(__pyx_t_42 >= (size_t)__pyx_pybuffernd_uboxes.diminfo[0].shape)) __pyx_t_11 = 0; if (unlikely(__pyx_t_43 >= (size_t)__pyx_pybuffernd_uboxes.diminfo[1].shape)) __pyx_t_11 = 1; if (unlikely(__pyx_t_44 >= (size_t)__pyx_pybuffernd_uboxes.diminfo[2].shape)) __pyx_t_11 = 2; if (unlikely(__pyx_t_45 >= (size_t)__pyx_pybuffernd_uboxes.diminfo[3].shape)) __pyx_t_11 = 3; if (unlikely(__pyx_t_11 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_11); __PYX_ERR(0, 66, __pyx_L1_error) } *__Pyx_BufPtrStrided4d(__pyx_t_15draw_rectangles_DTYPE_t *, __pyx_pybuffernd_uboxes.rcbuffer->pybuffer.buf, __pyx_t_42, __pyx_pybuffernd_uboxes.diminfo[0].strides, __pyx_t_43, __pyx_pybuffernd_uboxes.diminfo[1].strides, __pyx_t_44, __pyx_pybuffernd_uboxes.diminfo[2].strides, __pyx_t_45, __pyx_pybuffernd_uboxes.diminfo[3].strides) = (__pyx_v_x_contrib * __pyx_v_y_contrib); } } } } /* "draw_rectangles.pyx":67 * # print("j {} yc {} k {} xc {}".format(j, y_contrib, k, x_contrib)) * uboxes[n,i,j,k] = x_contrib*y_contrib * return uboxes # <<<<<<<<<<<<<< */ __Pyx_XDECREF(((PyObject *)__pyx_r)); __Pyx_INCREF(((PyObject *)__pyx_v_uboxes)); __pyx_r = ((PyArrayObject *)__pyx_v_uboxes); goto __pyx_L0; /* "draw_rectangles.pyx":27 * return min(max(x, 0), 1) * * cdef np.ndarray[DTYPE_t, ndim=4] draw_union_boxes_c( # <<<<<<<<<<<<<< * np.ndarray[DTYPE_t, ndim=2] box_pairs, unsigned int pooling_size): * """ */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_box_pairs.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_uboxes.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("draw_rectangles.draw_union_boxes_c", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_box_pairs.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_uboxes.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_uboxes); __Pyx_XGIVEREF((PyObject *)__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":197 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython * # requirements, and does not yet fullfill the PEP. */ /* Python wrapper */ static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_copy_shape; int __pyx_v_i; int __pyx_v_ndim; int __pyx_v_endian_detector; int __pyx_v_little_endian; int __pyx_v_t; char *__pyx_v_f; PyArray_Descr *__pyx_v_descr = 0; int __pyx_v_offset; int __pyx_v_hasfields; int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; int __pyx_t_5; PyObject *__pyx_t_6 = NULL; char *__pyx_t_7; __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":203 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< * * cdef int copy_shape, i, ndim */ __pyx_t_1 = ((__pyx_v_info == NULL) != 0); if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":206 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< * cdef bint little_endian = ((&endian_detector)[0] != 0) * */ __pyx_v_endian_detector = 1; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":207 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< * * ndim = PyArray_NDIM(self) */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":209 * cdef bint little_endian = ((&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":211 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":212 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< * else: * copy_shape = 0 */ __pyx_v_copy_shape = 1; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":211 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ goto __pyx_L4; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":214 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) */ /*else*/ { __pyx_v_copy_shape = 0; } __pyx_L4:; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":216 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ __pyx_t_2 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L6_bool_binop_done; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":217 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L6_bool_binop_done:; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":216 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ if (__pyx_t_1) { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":218 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 218, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 218, __pyx_L1_error) /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":216 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":220 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ __pyx_t_2 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L9_bool_binop_done; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":221 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L9_bool_binop_done:; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":220 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ if (__pyx_t_1) { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":222 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 222, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 222, __pyx_L1_error) /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":220 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":224 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if copy_shape: */ __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":225 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< * if copy_shape: * # Allocate new buffer for strides and shape info. */ __pyx_v_info->ndim = __pyx_v_ndim; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":226 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ __pyx_t_1 = (__pyx_v_copy_shape != 0); if (__pyx_t_1) { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":229 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< * info.shape = info.strides + ndim * for i in range(ndim): */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":230 * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":231 * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] */ __pyx_t_4 = __pyx_v_ndim; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":232 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< * info.shape[i] = PyArray_DIMS(self)[i] * else: */ (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":233 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = PyArray_STRIDES(self) */ (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":226 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ goto __pyx_L11; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":235 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL */ /*else*/ { __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":236 * else: * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); } __pyx_L11:; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":237 * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) */ __pyx_v_info->suboffsets = NULL; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":238 * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) * */ __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":239 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":242 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< * cdef dtype descr = self.descr * cdef int offset */ __pyx_v_f = NULL; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":243 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef int offset * */ __pyx_t_3 = ((PyObject *)__pyx_v_self->descr); __Pyx_INCREF(__pyx_t_3); __pyx_v_descr = ((PyArray_Descr *)__pyx_t_3); __pyx_t_3 = 0; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":246 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< * * if not hasfields and not copy_shape: */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":248 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L15_bool_binop_done; } __pyx_t_2 = ((!(__pyx_v_copy_shape != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L15_bool_binop_done:; if (__pyx_t_1) { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":250 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< * else: * # need to call releasebuffer */ __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":248 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ goto __pyx_L14; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":253 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ /*else*/ { __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } __pyx_L14:; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":255 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or */ __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_1) { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":256 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): */ __pyx_t_4 = __pyx_v_descr->type_num; __pyx_v_t = __pyx_t_4; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":257 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ __pyx_t_2 = ((__pyx_v_descr->byteorder == '>') != 0); if (!__pyx_t_2) { goto __pyx_L20_next_or; } else { } __pyx_t_2 = (__pyx_v_little_endian != 0); if (!__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L19_bool_binop_done; } __pyx_L20_next_or:; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":258 * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ __pyx_t_2 = ((__pyx_v_descr->byteorder == '<') != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L19_bool_binop_done; } __pyx_t_2 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L19_bool_binop_done:; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":257 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ if (__pyx_t_1) { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":259 * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 259, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 259, __pyx_L1_error) /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":257 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":260 * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ switch (__pyx_v_t) { case NPY_BYTE: __pyx_v_f = ((char *)"b"); break; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":261 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ case NPY_UBYTE: __pyx_v_f = ((char *)"B"); break; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":262 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ case NPY_SHORT: __pyx_v_f = ((char *)"h"); break; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":263 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ case NPY_USHORT: __pyx_v_f = ((char *)"H"); break; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":264 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ case NPY_INT: __pyx_v_f = ((char *)"i"); break; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":265 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ case NPY_UINT: __pyx_v_f = ((char *)"I"); break; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":266 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ case NPY_LONG: __pyx_v_f = ((char *)"l"); break; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":267 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ case NPY_ULONG: __pyx_v_f = ((char *)"L"); break; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":268 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ case NPY_LONGLONG: __pyx_v_f = ((char *)"q"); break; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":269 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ case NPY_ULONGLONG: __pyx_v_f = ((char *)"Q"); break; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":270 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ case NPY_FLOAT: __pyx_v_f = ((char *)"f"); break; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":271 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ case NPY_DOUBLE: __pyx_v_f = ((char *)"d"); break; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":272 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ case NPY_LONGDOUBLE: __pyx_v_f = ((char *)"g"); break; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":273 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ case NPY_CFLOAT: __pyx_v_f = ((char *)"Zf"); break; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":274 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ case NPY_CDOUBLE: __pyx_v_f = ((char *)"Zd"); break; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":275 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ case NPY_CLONGDOUBLE: __pyx_v_f = ((char *)"Zg"); break; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":276 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ case NPY_OBJECT: __pyx_v_f = ((char *)"O"); break; default: /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":278 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 278, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_3); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 278, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 278, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 278, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_6, 0, 0, 0); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __PYX_ERR(1, 278, __pyx_L1_error) break; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":279 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< * return * else: */ __pyx_v_info->format = __pyx_v_f; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":280 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< * else: * info.format = stdlib.malloc(_buffer_format_string_len) */ __pyx_r = 0; goto __pyx_L0; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":255 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or */ } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":282 * return * else: * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ /*else*/ { __pyx_v_info->format = ((char *)malloc(0xFF)); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":283 * else: * info.format = stdlib.malloc(_buffer_format_string_len) * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":284 * info.format = stdlib.malloc(_buffer_format_string_len) * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":285 * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< * info.format + _buffer_format_string_len, * &offset) */ __pyx_t_7 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 0xFF), (&__pyx_v_offset)); if (unlikely(__pyx_t_7 == NULL)) __PYX_ERR(1, 285, __pyx_L1_error) __pyx_v_f = __pyx_t_7; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":288 * info.format + _buffer_format_string_len, * &offset) * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ (__pyx_v_f[0]) = '\x00'; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":197 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython * # requirements, and does not yet fullfill the PEP. */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { __Pyx_GOTREF(Py_None); __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; } __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_descr); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":290 * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ /* Python wrapper */ static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__releasebuffer__", 0); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":291 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":292 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) */ free(__pyx_v_info->format); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":291 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":293 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":294 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< * # info.shape was stored after info.strides in the same block * */ free(__pyx_v_info->strides); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":293 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":290 * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":770 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(1, a) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":771 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 771, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":770 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(1, a) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":773 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(2, a, b) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":774 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 774, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":773 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(2, a, b) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":776 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(3, a, b, c) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":777 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 777, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":776 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(3, a, b, c) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":779 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(4, a, b, c, d) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":780 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 780, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":779 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(4, a, b, c, d) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":782 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(5, a, b, c, d, e) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":783 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 783, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":782 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(5, a, b, c, d, e) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":785 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< * # Recursive utility function used in __getbuffer__ to get format * # string. The new location in the format string is returned. */ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { PyArray_Descr *__pyx_v_child = 0; int __pyx_v_endian_detector; int __pyx_v_little_endian; PyObject *__pyx_v_fields = 0; PyObject *__pyx_v_childname = NULL; PyObject *__pyx_v_new_offset = NULL; PyObject *__pyx_v_t = NULL; char *__pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; Py_ssize_t __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; int __pyx_t_5; int __pyx_t_6; int __pyx_t_7; long __pyx_t_8; char *__pyx_t_9; __Pyx_RefNannySetupContext("_util_dtypestring", 0); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":790 * * cdef dtype child * cdef int endian_detector = 1 # <<<<<<<<<<<<<< * cdef bint little_endian = ((&endian_detector)[0] != 0) * cdef tuple fields */ __pyx_v_endian_detector = 1; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":791 * cdef dtype child * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< * cdef tuple fields * */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ if (unlikely(__pyx_v_descr->names == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); __PYX_ERR(1, 794, __pyx_L1_error) } __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(1, 794, __pyx_L1_error) #else __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 794, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); #endif __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); __pyx_t_3 = 0; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ if (unlikely(__pyx_v_descr->fields == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); __PYX_ERR(1, 795, __pyx_L1_error) } __pyx_t_3 = __Pyx_PyDict_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 795, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) __PYX_ERR(1, 795, __pyx_L1_error) __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); __pyx_t_3 = 0; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< * * if (end - f) - (new_offset - offset[0]) < 15: */ if (likely(__pyx_v_fields != Py_None)) { PyObject* sequence = __pyx_v_fields; #if !CYTHON_COMPILING_IN_PYPY Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); #endif if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(1, 796, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); #else __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 796, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 796, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); #endif } else { __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 796, __pyx_L1_error) } if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) __PYX_ERR(1, 796, __pyx_L1_error) __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); __pyx_t_4 = 0; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":798 * child, new_offset = fields * * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 798, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 798, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 798, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); if (__pyx_t_6) { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * * if ((child.byteorder == c'>' and little_endian) or */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 799, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 799, __pyx_L1_error) /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":798 * child, new_offset = fields * * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); if (!__pyx_t_7) { goto __pyx_L8_next_or; } else { } __pyx_t_7 = (__pyx_v_little_endian != 0); if (!__pyx_t_7) { } else { __pyx_t_6 = __pyx_t_7; goto __pyx_L7_bool_binop_done; } __pyx_L8_next_or:; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":802 * * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); if (__pyx_t_7) { } else { __pyx_t_6 = __pyx_t_7; goto __pyx_L7_bool_binop_done; } __pyx_t_7 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_6 = __pyx_t_7; __pyx_L7_bool_binop_done:; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ if (__pyx_t_6) { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":803 * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 803, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 803, __pyx_L1_error) /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":813 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< * f[0] = 120 # "x"; pad byte * f += 1 */ while (1) { __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 813, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 813, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 813, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!__pyx_t_6) break; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< * f += 1 * offset[0] += 1 */ (__pyx_v_f[0]) = 0x78; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< * offset[0] += 1 * */ __pyx_v_f = (__pyx_v_f + 1); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< * * offset[0] += child.itemsize */ __pyx_t_8 = 0; (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + 1); } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(child): */ __pyx_t_8 = 0; (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + __pyx_v_child->elsize); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); if (__pyx_t_6) { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":821 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 821, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); __pyx_t_4 = 0; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); if (__pyx_t_6) { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 823, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __PYX_ERR(1, 823, __pyx_L1_error) /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":826 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_BYTE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 826, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 826, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 826, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 98; goto __pyx_L15; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":827 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_UBYTE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 827, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 827, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 827, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 66; goto __pyx_L15; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":828 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_SHORT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 828, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 828, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 828, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x68; goto __pyx_L15; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":829 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_USHORT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 829, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 829, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 829, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 72; goto __pyx_L15; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":830 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_INT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 830, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 830, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 830, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x69; goto __pyx_L15; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":831 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_UINT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 831, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 831, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 831, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 73; goto __pyx_L15; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":832 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONG); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 832, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 832, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 832, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x6C; goto __pyx_L15; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":833 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_ULONG); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 833, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 833, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 833, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 76; goto __pyx_L15; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":834 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 834, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 834, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 834, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x71; goto __pyx_L15; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":835 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 835, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 835, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 835, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 81; goto __pyx_L15; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":836 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_FLOAT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 836, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 836, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 836, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x66; goto __pyx_L15; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":837 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 837, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 837, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 837, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x64; goto __pyx_L15; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":838 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 838, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 838, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 838, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x67; goto __pyx_L15; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":839 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 839, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 839, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 839, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 0x66; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":840 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 840, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 840, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 840, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 0x64; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":841 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 841, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 841, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 841, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 0x67; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":842 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_OBJECT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 842, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 842, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 842, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 79; goto __pyx_L15; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":844 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ /*else*/ { __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 844, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 844, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 844, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 844, __pyx_L1_error) } __pyx_L15:; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":845 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< * else: * # Cython ignores struct boundary information ("T{...}"), */ __pyx_v_f = (__pyx_v_f + 1); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ goto __pyx_L13; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":849 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ /*else*/ { __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_9 == NULL)) __PYX_ERR(1, 849, __pyx_L1_error) __pyx_v_f = __pyx_t_9; } __pyx_L13:; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_f; goto __pyx_L0; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":785 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< * # Recursive utility function used in __getbuffer__ to get format * # string. The new location in the format string is returned. */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_child); __Pyx_XDECREF(__pyx_v_fields); __Pyx_XDECREF(__pyx_v_childname); __Pyx_XDECREF(__pyx_v_new_offset); __Pyx_XDECREF(__pyx_v_t); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":966 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * cdef PyObject* baseptr * if base is None: */ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; __Pyx_RefNannySetupContext("set_array_base", 0); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":968 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< * baseptr = NULL * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":969 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< * else: * Py_INCREF(base) # important to do this before decref below! */ __pyx_v_baseptr = NULL; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":968 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< * baseptr = NULL * else: */ goto __pyx_L3; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":971 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< * baseptr = base * Py_XDECREF(arr.base) */ /*else*/ { Py_INCREF(__pyx_v_base); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":972 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = base # <<<<<<<<<<<<<< * Py_XDECREF(arr.base) * arr.base = baseptr */ __pyx_v_baseptr = ((PyObject *)__pyx_v_base); } __pyx_L3:; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":973 * Py_INCREF(base) # important to do this before decref below! * baseptr = base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< * arr.base = baseptr * */ Py_XDECREF(__pyx_v_arr->base); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":974 * baseptr = base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< * * cdef inline object get_array_base(ndarray arr): */ __pyx_v_arr->base = __pyx_v_baseptr; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":966 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * cdef PyObject* baseptr * if base is None: */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * if arr.base is NULL: * return None */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("get_array_base", 0); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":977 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); if (__pyx_t_1) { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":978 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< * else: * return arr.base */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":977 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":980 * return None * else: * return arr.base # <<<<<<<<<<<<<< * * */ /*else*/ { __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); __pyx_r = ((PyObject *)__pyx_v_arr->base); goto __pyx_L0; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * if arr.base is NULL: * return None */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":985 * # Versions of the import_* functions which are more suitable for * # Cython code. * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< * try: * _import_array() */ static CYTHON_INLINE int __pyx_f_5numpy_import_array(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; __Pyx_RefNannySetupContext("import_array", 0); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":986 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * _import_array() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":987 * cdef inline int import_array() except -1: * try: * _import_array() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.multiarray failed to import") */ __pyx_t_4 = _import_array(); if (unlikely(__pyx_t_4 == -1)) __PYX_ERR(1, 987, __pyx_L3_error) /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":986 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * _import_array() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L10_try_end; __pyx_L3_error:; __Pyx_PyThreadState_assign /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":988 * try: * _import_array() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.multiarray failed to import") * */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 988, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":989 * _import_array() * except Exception: * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_umath() except -1: */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 989, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(1, 989, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":986 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * _import_array() * except Exception: */ __Pyx_PyThreadState_assign __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L10_try_end:; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":985 * # Versions of the import_* functions which are more suitable for * # Cython code. * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< * try: * _import_array() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":991 * raise ImportError("numpy.core.multiarray failed to import") * * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ static CYTHON_INLINE int __pyx_f_5numpy_import_umath(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; __Pyx_RefNannySetupContext("import_umath", 0); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":992 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":993 * cdef inline int import_umath() except -1: * try: * _import_umath() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.umath failed to import") */ __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == -1)) __PYX_ERR(1, 993, __pyx_L3_error) /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":992 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L10_try_end; __pyx_L3_error:; __Pyx_PyThreadState_assign /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":994 * try: * _import_umath() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.umath failed to import") * */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 994, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":995 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_ufunc() except -1: */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 995, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(1, 995, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":992 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ __Pyx_PyThreadState_assign __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L10_try_end:; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":991 * raise ImportError("numpy.core.multiarray failed to import") * * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":997 * raise ImportError("numpy.core.umath failed to import") * * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ static CYTHON_INLINE int __pyx_f_5numpy_import_ufunc(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; __Pyx_RefNannySetupContext("import_ufunc", 0); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":998 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":999 * cdef inline int import_ufunc() except -1: * try: * _import_umath() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.umath failed to import") */ __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == -1)) __PYX_ERR(1, 999, __pyx_L3_error) /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":998 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L10_try_end; __pyx_L3_error:; __Pyx_PyThreadState_assign /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1000 * try: * _import_umath() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.umath failed to import") */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 1000, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1001 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 1001, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(1, 1001, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":998 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ __Pyx_PyThreadState_assign __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L10_try_end:; } /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":997 * raise ImportError("numpy.core.umath failed to import") * * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { #if PY_VERSION_HEX < 0x03020000 { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, #else PyModuleDef_HEAD_INIT, #endif "draw_rectangles", 0, /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s_DTYPE, __pyx_k_DTYPE, sizeof(__pyx_k_DTYPE), 0, 0, 1, 1}, {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, {&__pyx_n_s_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1}, {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, {&__pyx_kp_s_Padding_0_not_supported_yet, __pyx_k_Padding_0_not_supported_yet, sizeof(__pyx_k_Padding_0_not_supported_yet), 0, 0, 1, 0}, {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, {&__pyx_kp_s_Users_rowanz_code_scene_graph_l, __pyx_k_Users_rowanz_code_scene_graph_l, sizeof(__pyx_k_Users_rowanz_code_scene_graph_l), 0, 0, 1, 0}, {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, {&__pyx_n_s_bbox_pairs, __pyx_k_bbox_pairs, sizeof(__pyx_k_bbox_pairs), 0, 0, 1, 1}, {&__pyx_n_s_draw_rectangles, __pyx_k_draw_rectangles, sizeof(__pyx_k_draw_rectangles), 0, 0, 1, 1}, {&__pyx_n_s_draw_union_boxes, __pyx_k_draw_union_boxes, sizeof(__pyx_k_draw_union_boxes), 0, 0, 1, 1}, {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, {&__pyx_n_s_float32, __pyx_k_float32, sizeof(__pyx_k_float32), 0, 0, 1, 1}, {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, {&__pyx_kp_s_numpy_core_multiarray_failed_to, __pyx_k_numpy_core_multiarray_failed_to, sizeof(__pyx_k_numpy_core_multiarray_failed_to), 0, 0, 1, 0}, {&__pyx_kp_s_numpy_core_umath_failed_to_impor, __pyx_k_numpy_core_umath_failed_to_impor, sizeof(__pyx_k_numpy_core_umath_failed_to_impor), 0, 0, 1, 0}, {&__pyx_n_s_padding, __pyx_k_padding, sizeof(__pyx_k_padding), 0, 0, 1, 1}, {&__pyx_n_s_pooling_size, __pyx_k_pooling_size, sizeof(__pyx_k_pooling_size), 0, 0, 1, 1}, {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 45, __pyx_L1_error) __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(1, 218, __pyx_L1_error) __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) __PYX_ERR(1, 799, __pyx_L1_error) __pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) __PYX_ERR(1, 989, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":218 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple_)) __PYX_ERR(1, 218, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple_); __Pyx_GIVEREF(__pyx_tuple_); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":222 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(1, 222, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__2); __Pyx_GIVEREF(__pyx_tuple__2); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":259 * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(1, 259, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__3); __Pyx_GIVEREF(__pyx_tuple__3); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * * if ((child.byteorder == c'>' and little_endian) or */ __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(1, 799, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__4); __Pyx_GIVEREF(__pyx_tuple__4); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":803 * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(1, 803, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__5); __Pyx_GIVEREF(__pyx_tuple__5); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(1, 823, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__6); __Pyx_GIVEREF(__pyx_tuple__6); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":989 * _import_array() * except Exception: * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_umath() except -1: */ __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_s_numpy_core_multiarray_failed_to); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(1, 989, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__7); __Pyx_GIVEREF(__pyx_tuple__7); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":995 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_ufunc() except -1: */ __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s_numpy_core_umath_failed_to_impor); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(1, 995, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__8); __Pyx_GIVEREF(__pyx_tuple__8); /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1001 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< */ __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_s_numpy_core_umath_failed_to_impor); if (unlikely(!__pyx_tuple__9)) __PYX_ERR(1, 1001, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__9); __Pyx_GIVEREF(__pyx_tuple__9); /* "draw_rectangles.pyx":12 * ctypedef np.float32_t DTYPE_t * * def draw_union_boxes(bbox_pairs, pooling_size, padding=0): # <<<<<<<<<<<<<< * """ * Draws union boxes for the image. */ __pyx_tuple__10 = PyTuple_Pack(3, __pyx_n_s_bbox_pairs, __pyx_n_s_pooling_size, __pyx_n_s_padding); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(0, 12, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__10); __Pyx_GIVEREF(__pyx_tuple__10); __pyx_codeobj__11 = (PyObject*)__Pyx_PyCode_New(3, 0, 3, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__10, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Users_rowanz_code_scene_graph_l, __pyx_n_s_draw_union_boxes, 12, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__11)) __PYX_ERR(0, 12, __pyx_L1_error) __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) __PYX_ERR(0, 1, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } #if PY_MAJOR_VERSION < 3 PyMODINIT_FUNC initdraw_rectangles(void); /*proto*/ PyMODINIT_FUNC initdraw_rectangles(void) #else PyMODINIT_FUNC PyInit_draw_rectangles(void); /*proto*/ PyMODINIT_FUNC PyInit_draw_rectangles(void) #endif { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { PyErr_Clear(); __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); if (!__Pyx_RefNanny) Py_FatalError("failed to import 'refnanny' module"); } #endif __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_draw_rectangles(void)", 0); if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pyx_CyFunction_USED if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_FusedFunction_USED if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Coroutine_USED if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Generator_USED if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_StopAsyncIteration_USED if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS #ifdef WITH_THREAD /* Python build with threading support? */ PyEval_InitThreads(); #endif #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4("draw_rectangles", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_d); __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); #endif if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); /*--- Initialize various global constants etc. ---*/ if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif if (__pyx_module_is_main_draw_rectangles) { if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) } #if PY_MAJOR_VERSION >= 3 { PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) if (!PyDict_GetItemString(modules, "draw_rectangles")) { if (unlikely(PyDict_SetItemString(modules, "draw_rectangles", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) } } #endif /*--- Builtin init code ---*/ if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Constants init code ---*/ if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Global init code ---*/ /*--- Variable export code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ /*--- Type import code ---*/ __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", #if CYTHON_COMPILING_IN_PYPY sizeof(PyTypeObject), #else sizeof(PyHeapTypeObject), #endif 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) __PYX_ERR(2, 9, __pyx_L1_error) __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) __PYX_ERR(1, 155, __pyx_L1_error) __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) __PYX_ERR(1, 168, __pyx_L1_error) __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) __PYX_ERR(1, 172, __pyx_L1_error) __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) __PYX_ERR(1, 181, __pyx_L1_error) __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) __PYX_ERR(1, 861, __pyx_L1_error) /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /* "draw_rectangles.pyx":6 * * cimport cython * import numpy as np # <<<<<<<<<<<<<< * cimport numpy as np * */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 6, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) __PYX_ERR(0, 6, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "draw_rectangles.pyx":9 * cimport numpy as np * * DTYPE = np.float32 # <<<<<<<<<<<<<< * ctypedef np.float32_t DTYPE_t * */ __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 9, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_float32); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 9, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (PyDict_SetItem(__pyx_d, __pyx_n_s_DTYPE, __pyx_t_2) < 0) __PYX_ERR(0, 9, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "draw_rectangles.pyx":12 * ctypedef np.float32_t DTYPE_t * * def draw_union_boxes(bbox_pairs, pooling_size, padding=0): # <<<<<<<<<<<<<< * """ * Draws union boxes for the image. */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_15draw_rectangles_1draw_union_boxes, NULL, __pyx_n_s_draw_rectangles); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 12, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_draw_union_boxes, __pyx_t_2) < 0) __PYX_ERR(0, 12, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "draw_rectangles.pyx":1 * ###### # <<<<<<<<<<<<<< * # Draws rectangles * ###### */ __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":997 * raise ImportError("numpy.core.umath failed to import") * * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ /*--- Wrapped vars code ---*/ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); if (__pyx_m) { if (__pyx_d) { __Pyx_AddTraceback("init draw_rectangles", __pyx_clineno, __pyx_lineno, __pyx_filename); } Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init draw_rectangles"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if PY_MAJOR_VERSION < 3 return; #else return __pyx_m; #endif } /* --- Runtime support code --- */ /* Refnanny */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule((char *)modname); if (!m) goto end; p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif /* GetBuiltinName */ static PyObject *__Pyx_GetBuiltinName(PyObject *name) { PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); if (unlikely(!result)) { PyErr_Format(PyExc_NameError, #if PY_MAJOR_VERSION >= 3 "name '%U' is not defined", name); #else "name '%.200s' is not defined", PyString_AS_STRING(name)); #endif } return result; } /* RaiseArgTupleInvalid */ static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found) { Py_ssize_t num_expected; const char *more_or_less; if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; } else { num_expected = num_max; more_or_less = "at most"; } if (exact) { more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } /* RaiseDoubleKeywords */ static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) { PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION >= 3 "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, PyString_AsString(kw_name)); #endif } /* ParseKeywords */ static int __Pyx_ParseOptionalKeywords( PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name) { PyObject *key = 0, *value = 0; Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; continue; } name = first_kw_arg; #if PY_MAJOR_VERSION < 3 if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { while (*name) { if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) && _PyString_Eq(**name, key)) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { if ((**argname == key) || ( (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) && _PyString_Eq(**argname, key))) { goto arg_passed_twice; } argname++; } } } else #endif if (likely(PyUnicode_Check(key))) { while (*name) { int cmp = (**name == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**name, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { int cmp = (**argname == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**argname, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) goto arg_passed_twice; argname++; } } } else goto invalid_keyword_type; if (kwds2) { if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; } else { goto invalid_keyword; } } return 0; arg_passed_twice: __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", function_name, key); #endif bad: return -1; } /* PyIntBinop */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_EqObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, CYTHON_UNUSED int inplace) { if (op1 == op2) { Py_RETURN_TRUE; } #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(op1))) { const long b = intval; long a = PyInt_AS_LONG(op1); if (a == b) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } #endif #if CYTHON_USE_PYLONG_INTERNALS if (likely(PyLong_CheckExact(op1))) { const long b = intval; long a; const digit* digits = ((PyLongObject*)op1)->ob_digit; const Py_ssize_t size = Py_SIZE(op1); if (likely(__Pyx_sst_abs(size) <= 1)) { a = likely(size) ? digits[0] : 0; if (size == -1) a = -a; } else { switch (size) { case -2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } case 2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } case -3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } case 3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } case -4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } case 4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } #if PyLong_SHIFT < 30 && PyLong_SHIFT != 15 default: return PyLong_Type.tp_richcompare(op1, op2, Py_EQ); #else default: Py_RETURN_FALSE; #endif } } if (a == b) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } #endif if (PyFloat_CheckExact(op1)) { const long b = intval; double a = PyFloat_AS_DOUBLE(op1); if ((double)a == (double)b) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } return PyObject_RichCompare(op1, op2, Py_EQ); } #endif /* ExtTypeTest */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (likely(PyObject_TypeCheck(obj, type))) return 1; PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", Py_TYPE(obj)->tp_name, type->tp_name); return 0; } /* BufferFormatCheck */ static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { unsigned int n = 1; return *(unsigned char*)(&n) != 0; } static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type) { stack[0].field = &ctx->root; stack[0].parent_offset = 0; ctx->root.type = type; ctx->root.name = "buffer dtype"; ctx->root.offset = 0; ctx->head = stack; ctx->head->field = &ctx->root; ctx->fmt_offset = 0; ctx->head->parent_offset = 0; ctx->new_packmode = '@'; ctx->enc_packmode = '@'; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->is_complex = 0; ctx->is_valid_array = 0; ctx->struct_alignment = 0; while (type->typegroup == 'S') { ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = 0; type = type->fields->type; } } static int __Pyx_BufFmt_ParseNumber(const char** ts) { int count; const char* t = *ts; if (*t < '0' || *t > '9') { return -1; } else { count = *t++ - '0'; while (*t >= '0' && *t < '9') { count *= 10; count += *t++ - '0'; } } *ts = t; return count; } static int __Pyx_BufFmt_ExpectNumber(const char **ts) { int number = __Pyx_BufFmt_ParseNumber(ts); if (number == -1) PyErr_Format(PyExc_ValueError,\ "Does not understand character buffer dtype format string ('%c')", **ts); return number; } static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { PyErr_Format(PyExc_ValueError, "Unexpected format string character: '%c'", ch); } static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { case 'c': return "'char'"; case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; case 'i': return "'int'"; case 'I': return "'unsigned int'"; case 'l': return "'long'"; case 'L': return "'unsigned long'"; case 'q': return "'long long'"; case 'Q': return "'unsigned long long'"; case 'f': return (is_complex ? "'complex float'" : "'float'"); case 'd': return (is_complex ? "'complex double'" : "'double'"); case 'g': return (is_complex ? "'complex long double'" : "'long double'"); case 'T': return "a struct"; case 'O': return "Python object"; case 'P': return "a pointer"; case 's': case 'p': return "a string"; case 0: return "end"; default: return "unparseable format string"; } } static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return 2; case 'i': case 'I': case 'l': case 'L': return 4; case 'q': case 'Q': return 8; case 'f': return (is_complex ? 8 : 4); case 'd': return (is_complex ? 16 : 8); case 'g': { PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); return 0; } case 'O': case 'P': return sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { switch (ch) { case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(short); case 'i': case 'I': return sizeof(int); case 'l': case 'L': return sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(float) * (is_complex ? 2 : 1); case 'd': return sizeof(double) * (is_complex ? 2 : 1); case 'g': return sizeof(long double) * (is_complex ? 2 : 1); case 'O': case 'P': return sizeof(void*); default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } typedef struct { char c; short x; } __Pyx_st_short; typedef struct { char c; int x; } __Pyx_st_int; typedef struct { char c; long x; } __Pyx_st_long; typedef struct { char c; float x; } __Pyx_st_float; typedef struct { char c; double x; } __Pyx_st_double; typedef struct { char c; long double x; } __Pyx_st_longdouble; typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_st_float) - sizeof(float); case 'd': return sizeof(__Pyx_st_double) - sizeof(double); case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } /* These are for computing the padding at the end of the struct to align on the first member of the struct. This will probably the same as above, but we don't have any guarantees. */ typedef struct { short x; char c; } __Pyx_pad_short; typedef struct { int x; char c; } __Pyx_pad_int; typedef struct { long x; char c; } __Pyx_pad_long; typedef struct { float x; char c; } __Pyx_pad_float; typedef struct { double x; char c; } __Pyx_pad_double; typedef struct { long double x; char c; } __Pyx_pad_longdouble; typedef struct { void *x; char c; } __Pyx_pad_void_p; #ifdef HAVE_LONG_LONG typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { case 'c': return 'H'; case 'b': case 'h': case 'i': case 'l': case 'q': case 's': case 'p': return 'I'; case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); case 'O': return 'O'; case 'P': return 'P'; default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { if (ctx->head == NULL || ctx->head->field == &ctx->root) { const char* expected; const char* quote; if (ctx->head == NULL) { expected = "end"; quote = ""; } else { expected = ctx->head->field->type->name; quote = "'"; } PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected %s%s%s but got %s", quote, expected, quote, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); } else { __Pyx_StructField* field = ctx->head->field; __Pyx_StructField* parent = (ctx->head - 1)->field; PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), parent->type->name, field->name); } } static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { char group; size_t size, offset, arraysize = 1; if (ctx->enc_type == 0) return 0; if (ctx->head->field->type->arraysize[0]) { int i, ndim = 0; if (ctx->enc_type == 's' || ctx->enc_type == 'p') { ctx->is_valid_array = ctx->head->field->type->ndim == 1; ndim = 1; if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %zu", ctx->head->field->type->arraysize[0], ctx->enc_count); return -1; } } if (!ctx->is_valid_array) { PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", ctx->head->field->type->ndim, ndim); return -1; } for (i = 0; i < ctx->head->field->type->ndim; i++) { arraysize *= ctx->head->field->type->arraysize[i]; } ctx->is_valid_array = 0; ctx->enc_count = 1; } group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); do { __Pyx_StructField* field = ctx->head->field; __Pyx_TypeInfo* type = field->type; if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); } else { size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); } if (ctx->enc_packmode == '@') { size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); size_t align_mod_offset; if (align_at == 0) return -1; align_mod_offset = ctx->fmt_offset % align_at; if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; if (ctx->struct_alignment == 0) ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, ctx->is_complex); } if (type->size != size || type->typegroup != group) { if (type->typegroup == 'C' && type->fields != NULL) { size_t parent_offset = ctx->head->parent_offset + field->offset; ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = parent_offset; continue; } if ((type->typegroup == 'H' || group == 'H') && type->size == size) { } else { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } } offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } ctx->fmt_offset += size; if (arraysize) ctx->fmt_offset += (arraysize - 1) * size; --ctx->enc_count; while (1) { if (field == &ctx->root) { ctx->head = NULL; if (ctx->enc_count != 0) { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } break; } ctx->head->field = ++field; if (field->type == NULL) { --ctx->head; field = ctx->head->field; continue; } else if (field->type->typegroup == 'S') { size_t parent_offset = ctx->head->parent_offset + field->offset; if (field->type->fields->type == NULL) continue; field = field->type->fields; ++ctx->head; ctx->head->field = field; ctx->head->parent_offset = parent_offset; break; } else { break; } } } while (ctx->enc_count); ctx->enc_type = 0; ctx->is_complex = 0; return 0; } static CYTHON_INLINE PyObject * __pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) { const char *ts = *tsp; int i = 0, number; int ndim = ctx->head->field->type->ndim; ; ++ts; if (ctx->new_count != 1) { PyErr_SetString(PyExc_ValueError, "Cannot handle repeated arrays in format string"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; while (*ts && *ts != ')') { switch (*ts) { case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; default: break; } number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) return PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %d", ctx->head->field->type->arraysize[i], number); if (*ts != ',' && *ts != ')') return PyErr_Format(PyExc_ValueError, "Expected a comma in format string, got '%c'", *ts); if (*ts == ',') ts++; i++; } if (i != ndim) return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", ctx->head->field->type->ndim, i); if (!*ts) { PyErr_SetString(PyExc_ValueError, "Unexpected end of format string, expected ')'"); return NULL; } ctx->is_valid_array = 1; ctx->new_count = 1; *tsp = ++ts; return Py_None; } static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { int got_Z = 0; while (1) { switch(*ts) { case 0: if (ctx->enc_type != 0 && ctx->head == NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; if (ctx->head != NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } return ts; case ' ': case '\r': case '\n': ++ts; break; case '<': if (!__Pyx_IsLittleEndian()) { PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '>': case '!': if (__Pyx_IsLittleEndian()) { PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '=': case '@': case '^': ctx->new_packmode = *ts++; break; case 'T': { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; size_t struct_alignment = ctx->struct_alignment; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; ctx->enc_count = 0; ctx->struct_alignment = 0; ++ts; ts_after_sub = ts; for (i = 0; i != struct_count; ++i) { ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); if (!ts_after_sub) return NULL; } ts = ts_after_sub; if (struct_alignment) ctx->struct_alignment = struct_alignment; } break; case '}': { size_t alignment = ctx->struct_alignment; ++ts; if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; if (alignment && ctx->fmt_offset % alignment) { ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); } } return ts; case 'x': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->fmt_offset += ctx->new_count; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->enc_packmode = ctx->new_packmode; ++ts; break; case 'Z': got_Z = 1; ++ts; if (*ts != 'f' && *ts != 'd' && *ts != 'g') { __Pyx_BufFmt_RaiseUnexpectedChar('Z'); return NULL; } case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'g': case 'O': case 'p': if (ctx->enc_type == *ts && got_Z == ctx->is_complex && ctx->enc_packmode == ctx->new_packmode) { ctx->enc_count += ctx->new_count; ctx->new_count = 1; got_Z = 0; ++ts; break; } case 's': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_count = ctx->new_count; ctx->enc_packmode = ctx->new_packmode; ctx->enc_type = *ts; ctx->is_complex = got_Z; ++ts; ctx->new_count = 1; got_Z = 0; break; case ':': ++ts; while(*ts != ':') ++ts; ++ts; break; case '(': if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; break; default: { int number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; ctx->new_count = (size_t)number; } } } } static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; buf->obj = NULL; buf->strides = __Pyx_zeros; buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; } static CYTHON_INLINE int __Pyx_GetBufferAndValidate( Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { if (obj == Py_None || obj == NULL) { __Pyx_ZeroBuffer(buf); return 0; } buf->buf = NULL; if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; if (buf->ndim != nd) { PyErr_Format(PyExc_ValueError, "Buffer has wrong number of dimensions (expected %d, got %d)", nd, buf->ndim); goto fail; } if (!cast) { __Pyx_BufFmt_Context ctx; __Pyx_BufFmt_Init(&ctx, stack, dtype); if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; } if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; return 0; fail:; __Pyx_ZeroBuffer(buf); return -1; } static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { if (info->buf == NULL) return; if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; __Pyx_ReleaseBuffer(info); } /* GetModuleGlobalName */ static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { PyObject *result; #if !CYTHON_AVOID_BORROWED_REFS result = PyDict_GetItem(__pyx_d, name); if (likely(result)) { Py_INCREF(result); } else { #else result = PyObject_GetItem(__pyx_d, name); if (!result) { PyErr_Clear(); #endif result = __Pyx_GetBuiltinName(name); } return result; } /* PyObjectCall */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *result; ternaryfunc call = func->ob_type->tp_call; if (unlikely(!call)) return PyObject_Call(func, arg, kw); if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; result = (*call)(func, arg, kw); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif /* BufferIndexError */ static void __Pyx_RaiseBufferIndexError(int axis) { PyErr_Format(PyExc_IndexError, "Out of bounds on buffer access (axis %d)", axis); } /* PyErrFetchRestore */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; tstate->curexc_type = type; tstate->curexc_value = value; tstate->curexc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; } #endif /* RaiseException */ #if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { __Pyx_PyThreadState_declare Py_XINCREF(type); if (!value || value == Py_None) value = NULL; else Py_INCREF(value); if (!tb || tb == Py_None) tb = NULL; else { Py_INCREF(tb); if (!PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto raise_error; } } if (PyType_Check(type)) { #if CYTHON_COMPILING_IN_PYPY if (!value) { Py_INCREF(Py_None); value = Py_None; } #endif PyErr_NormalizeException(&type, &value, &tb); } else { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } value = type; type = (PyObject*) Py_TYPE(type); Py_INCREF(type); if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto raise_error; } } __Pyx_PyThreadState_assign __Pyx_ErrRestore(type, value, tb); return; raise_error: Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(tb); return; } #else static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto bad; } if (value == Py_None) value = 0; if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto bad; } value = type; type = (PyObject*) Py_TYPE(value); } else if (PyExceptionClass_Check(type)) { PyObject *instance_class = NULL; if (value && PyExceptionInstance_Check(value)) { instance_class = (PyObject*) Py_TYPE(value); if (instance_class != type) { int is_subclass = PyObject_IsSubclass(instance_class, type); if (!is_subclass) { instance_class = NULL; } else if (unlikely(is_subclass == -1)) { goto bad; } else { type = instance_class; } } } if (!instance_class) { PyObject *args; if (!value) args = PyTuple_New(0); else if (PyTuple_Check(value)) { Py_INCREF(value); args = value; } else args = PyTuple_Pack(1, value); if (!args) goto bad; owned_instance = PyObject_Call(type, args, NULL); Py_DECREF(args); if (!owned_instance) goto bad; value = owned_instance; if (!PyExceptionInstance_Check(value)) { PyErr_Format(PyExc_TypeError, "calling %R should have returned an instance of " "BaseException, not %R", type, Py_TYPE(value)); goto bad; } } } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } #if PY_VERSION_HEX >= 0x03030000 if (cause) { #else if (cause && cause != Py_None) { #endif PyObject *fixed_cause; if (cause == Py_None) { fixed_cause = NULL; } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); if (tb) { #if CYTHON_COMPILING_IN_PYPY PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); Py_INCREF(tb); PyErr_Restore(tmp_type, tmp_value, tb); Py_XDECREF(tmp_tb); #else PyThreadState *tstate = PyThreadState_GET(); PyObject* tmp_tb = tstate->curexc_traceback; if (tb != tmp_tb) { Py_INCREF(tb); tstate->curexc_traceback = tb; Py_XDECREF(tmp_tb); } #endif } bad: Py_XDECREF(owned_instance); return; } #endif /* RaiseTooManyValuesToUnpack */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } /* RaiseNeedMoreValuesToUnpack */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", index, (index == 1) ? "" : "s"); } /* RaiseNoneIterError */ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } /* SaveResetException */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { *type = tstate->exc_type; *value = tstate->exc_value; *tb = tstate->exc_traceback; Py_XINCREF(*type); Py_XINCREF(*value); Py_XINCREF(*tb); } static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = type; tstate->exc_value = value; tstate->exc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } #endif /* PyErrExceptionMatches */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err) { PyObject *exc_type = tstate->curexc_type; if (exc_type == err) return 1; if (unlikely(!exc_type)) return 0; return PyErr_GivenExceptionMatches(exc_type, err); } #endif /* GetException */ #if CYTHON_FAST_THREAD_STATE static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { #endif PyObject *local_type, *local_value, *local_tb; #if CYTHON_FAST_THREAD_STATE PyObject *tmp_type, *tmp_value, *tmp_tb; local_type = tstate->curexc_type; local_value = tstate->curexc_value; local_tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; #else PyErr_Fetch(&local_type, &local_value, &local_tb); #endif PyErr_NormalizeException(&local_type, &local_value, &local_tb); #if CYTHON_FAST_THREAD_STATE if (unlikely(tstate->curexc_type)) #else if (unlikely(PyErr_Occurred())) #endif goto bad; #if PY_MAJOR_VERSION >= 3 if (local_tb) { if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) goto bad; } #endif Py_XINCREF(local_tb); Py_XINCREF(local_type); Py_XINCREF(local_value); *type = local_type; *value = local_value; *tb = local_tb; #if CYTHON_FAST_THREAD_STATE tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = local_type; tstate->exc_value = local_value; tstate->exc_traceback = local_tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #else PyErr_SetExcInfo(local_type, local_value, local_tb); #endif return 0; bad: *type = 0; *value = 0; *tb = 0; Py_XDECREF(local_type); Py_XDECREF(local_value); Py_XDECREF(local_tb); return -1; } /* Import */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; #if PY_VERSION_HEX < 0x03030000 PyObject *py_import; py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); if (!py_import) goto bad; #endif if (from_list) list = from_list; else { empty_list = PyList_New(0); if (!empty_list) goto bad; list = empty_list; } global_dict = PyModule_GetDict(__pyx_m); if (!global_dict) goto bad; empty_dict = PyDict_New(); if (!empty_dict) goto bad; { #if PY_MAJOR_VERSION >= 3 if (level == -1) { if (strchr(__Pyx_MODULE_NAME, '.')) { #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(1); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, 1); #endif if (!module) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) goto bad; PyErr_Clear(); } } level = 0; } #endif if (!module) { #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(level); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, level); #endif } } bad: #if PY_VERSION_HEX < 0x03030000 Py_XDECREF(py_import); #endif Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } /* CodeObjectCache */ static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { return count; } while (start < end) { mid = start + (end - start) / 2; if (code_line < entries[mid].code_line) { end = mid; } else if (code_line > entries[mid].code_line) { start = mid + 1; } else { return mid; } } if (code_line <= entries[mid].code_line) { return mid; } else { return mid + 1; } } static PyCodeObject *__pyx_find_code_object(int code_line) { PyCodeObject* code_object; int pos; if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { return NULL; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { return NULL; } code_object = __pyx_code_cache.entries[pos].code_object; Py_INCREF(code_object); return code_object; } static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { int pos, i; __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; if (unlikely(!code_line)) { return; } if (unlikely(!entries)) { entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); if (likely(entries)) { __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = 64; __pyx_code_cache.count = 1; entries[0].code_line = code_line; entries[0].code_object = code_object; Py_INCREF(code_object); } return; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { PyCodeObject* tmp = entries[pos].code_object; entries[pos].code_object = code_object; Py_DECREF(tmp); return; } if (__pyx_code_cache.count == __pyx_code_cache.max_count) { int new_max = __pyx_code_cache.max_count + 64; entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); if (unlikely(!entries)) { return; } __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = new_max; } for (i=__pyx_code_cache.count; i>pos; i--) { entries[i] = entries[i-1]; } entries[pos].code_line = code_line; entries[pos].code_object = code_object; __pyx_code_cache.count++; Py_INCREF(code_object); } /* AddTraceback */ #include "compile.h" #include "frameobject.h" #include "traceback.h" static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; #if PY_MAJOR_VERSION < 3 py_srcfile = PyString_FromString(filename); #else py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; if (c_line) { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromString(funcname); #else py_funcname = PyUnicode_FromString(funcname); #endif } if (!py_funcname) goto bad; py_code = __Pyx_PyCode_New( 0, 0, 0, 0, 0, __pyx_empty_bytes, /*PyObject *code,*/ __pyx_empty_tuple, /*PyObject *consts,*/ __pyx_empty_tuple, /*PyObject *names,*/ __pyx_empty_tuple, /*PyObject *varnames,*/ __pyx_empty_tuple, /*PyObject *freevars,*/ __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ py_line, __pyx_empty_bytes /*PyObject *lnotab*/ ); Py_DECREF(py_srcfile); Py_DECREF(py_funcname); return py_code; bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); return NULL; } static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; py_code = __pyx_find_code_object(c_line ? c_line : py_line); if (!py_code) { py_code = __Pyx_CreateCodeObjectForTraceback( funcname, c_line, py_line, filename); if (!py_code) goto bad; __pyx_insert_code_object(c_line ? c_line : py_line, py_code); } py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ __pyx_d, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; __Pyx_PyFrame_SetLineNumber(py_frame, py_line); PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_code); Py_XDECREF(py_frame); } #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); return -1; } static void __Pyx_ReleaseBuffer(Py_buffer *view) { PyObject *obj = view->obj; if (!obj) return; if (PyObject_CheckBuffer(obj)) { PyBuffer_Release(view); return; } if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } Py_DECREF(obj); view->obj = NULL; } #endif /* CIntFromPyVerify */ #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) #define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) #define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ {\ func_type value = func_value;\ if (sizeof(target_type) < sizeof(func_type)) {\ if (unlikely(value != (func_type) (target_type) value)) {\ func_type zero = 0;\ if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ return (target_type) -1;\ if (is_unsigned && unlikely(value < zero))\ goto raise_neg_overflow;\ else\ goto raise_overflow;\ }\ }\ return (target_type) value;\ } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value) { const unsigned int neg_one = (unsigned int) -1, const_zero = (unsigned int) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(unsigned int) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(unsigned int) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned int) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(unsigned int) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned int) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(unsigned int), little, !is_unsigned); } } /* Declarations */ #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { return ::std::complex< float >(x, y); } #else static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { return x + y*(__pyx_t_float_complex)_Complex_I; } #endif #else static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { __pyx_t_float_complex z; z.real = x; z.imag = y; return z; } #endif /* Arithmetic */ #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { return (a.real == b.real) && (a.imag == b.imag); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real + b.real; z.imag = a.imag + b.imag; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real - b.real; z.imag = a.imag - b.imag; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real * b.real - a.imag * b.imag; z.imag = a.real * b.imag + a.imag * b.real; return z; } #if 1 static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { if (b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); } else if (fabsf(b.real) >= fabsf(b.imag)) { if (b.real == 0 && b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.imag); } else { float r = b.imag / b.real; float s = 1.0 / (b.real + b.imag * r); return __pyx_t_float_complex_from_parts( (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); } } else { float r = b.real / b.imag; float s = 1.0 / (b.imag + b.real * r); return __pyx_t_float_complex_from_parts( (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); } } #else static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { if (b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); } else { float denom = b.real * b.real + b.imag * b.imag; return __pyx_t_float_complex_from_parts( (a.real * b.real + a.imag * b.imag) / denom, (a.imag * b.real - a.real * b.imag) / denom); } } #endif static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex a) { __pyx_t_float_complex z; z.real = -a.real; z.imag = -a.imag; return z; } static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex a) { __pyx_t_float_complex z; z.real = a.real; z.imag = -a.imag; return z; } #if 1 static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex z) { #if !defined(HAVE_HYPOT) || defined(_MSC_VER) return sqrtf(z.real*z.real + z.imag*z.imag); #else return hypotf(z.real, z.imag); #endif } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; float r, lnr, theta, z_r, z_theta; if (b.imag == 0 && b.real == (int)b.real) { if (b.real < 0) { float denom = a.real * a.real + a.imag * a.imag; a.real = a.real / denom; a.imag = -a.imag / denom; b.real = -b.real; } switch ((int)b.real) { case 0: z.real = 1; z.imag = 0; return z; case 1: return a; case 2: z = __Pyx_c_prod_float(a, a); return __Pyx_c_prod_float(a, a); case 3: z = __Pyx_c_prod_float(a, a); return __Pyx_c_prod_float(z, a); case 4: z = __Pyx_c_prod_float(a, a); return __Pyx_c_prod_float(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } else if (b.imag == 0) { z.real = powf(a.real, b.real); z.imag = 0; return z; } else if (a.real > 0) { r = a.real; theta = 0; } else { r = -a.real; theta = atan2f(0, -1); } } else { r = __Pyx_c_abs_float(a); theta = atan2f(a.imag, a.real); } lnr = logf(r); z_r = expf(lnr * b.real - theta * b.imag); z_theta = theta * b.real + lnr * b.imag; z.real = z_r * cosf(z_theta); z.imag = z_r * sinf(z_theta); return z; } #endif #endif /* Declarations */ #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { return ::std::complex< double >(x, y); } #else static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { return x + y*(__pyx_t_double_complex)_Complex_I; } #endif #else static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { __pyx_t_double_complex z; z.real = x; z.imag = y; return z; } #endif /* Arithmetic */ #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { return (a.real == b.real) && (a.imag == b.imag); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real + b.real; z.imag = a.imag + b.imag; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real - b.real; z.imag = a.imag - b.imag; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real * b.real - a.imag * b.imag; z.imag = a.real * b.imag + a.imag * b.real; return z; } #if 1 static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { if (b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); } else if (fabs(b.real) >= fabs(b.imag)) { if (b.real == 0 && b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.imag); } else { double r = b.imag / b.real; double s = 1.0 / (b.real + b.imag * r); return __pyx_t_double_complex_from_parts( (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); } } else { double r = b.real / b.imag; double s = 1.0 / (b.imag + b.real * r); return __pyx_t_double_complex_from_parts( (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); } } #else static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { if (b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); } else { double denom = b.real * b.real + b.imag * b.imag; return __pyx_t_double_complex_from_parts( (a.real * b.real + a.imag * b.imag) / denom, (a.imag * b.real - a.real * b.imag) / denom); } } #endif static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex a) { __pyx_t_double_complex z; z.real = -a.real; z.imag = -a.imag; return z; } static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex a) { __pyx_t_double_complex z; z.real = a.real; z.imag = -a.imag; return z; } #if 1 static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex z) { #if !defined(HAVE_HYPOT) || defined(_MSC_VER) return sqrt(z.real*z.real + z.imag*z.imag); #else return hypot(z.real, z.imag); #endif } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; double r, lnr, theta, z_r, z_theta; if (b.imag == 0 && b.real == (int)b.real) { if (b.real < 0) { double denom = a.real * a.real + a.imag * a.imag; a.real = a.real / denom; a.imag = -a.imag / denom; b.real = -b.real; } switch ((int)b.real) { case 0: z.real = 1; z.imag = 0; return z; case 1: return a; case 2: z = __Pyx_c_prod_double(a, a); return __Pyx_c_prod_double(a, a); case 3: z = __Pyx_c_prod_double(a, a); return __Pyx_c_prod_double(z, a); case 4: z = __Pyx_c_prod_double(a, a); return __Pyx_c_prod_double(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } else if (b.imag == 0) { z.real = pow(a.real, b.real); z.imag = 0; return z; } else if (a.real > 0) { r = a.real; theta = 0; } else { r = -a.real; theta = atan2(0, -1); } } else { r = __Pyx_c_abs_double(a); theta = atan2(a.imag, a.real); } lnr = log(r); z_r = exp(lnr * b.real - theta * b.imag); z_theta = theta * b.real + lnr * b.imag; z.real = z_r * cos(z_theta); z.imag = z_r * sin(z_theta); return z; } #endif #endif /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { const int neg_one = (int) -1, const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(int) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(int) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(int) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(int), little, !is_unsigned); } } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_enum__NPY_TYPES(enum NPY_TYPES value) { const enum NPY_TYPES neg_one = (enum NPY_TYPES) -1, const_zero = (enum NPY_TYPES) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(enum NPY_TYPES) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(enum NPY_TYPES) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(enum NPY_TYPES) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(enum NPY_TYPES) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(enum NPY_TYPES) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(enum NPY_TYPES), little, !is_unsigned); } } /* CIntFromPy */ static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *x) { const unsigned int neg_one = (unsigned int) -1, const_zero = (unsigned int) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(unsigned int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(unsigned int, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (unsigned int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (unsigned int) 0; case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, digits[0]) case 2: if (8 * sizeof(unsigned int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) >= 2 * PyLong_SHIFT) { return (unsigned int) (((((unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])); } } break; case 3: if (8 * sizeof(unsigned int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) >= 3 * PyLong_SHIFT) { return (unsigned int) (((((((unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])); } } break; case 4: if (8 * sizeof(unsigned int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) >= 4 * PyLong_SHIFT) { return (unsigned int) (((((((((unsigned int)digits[3]) << PyLong_SHIFT) | (unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (unsigned int) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(unsigned int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned int, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned int) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (unsigned int) 0; case -1: __PYX_VERIFY_RETURN_INT(unsigned int, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, +digits[0]) case -2: if (8 * sizeof(unsigned int) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 2 * PyLong_SHIFT) { return (unsigned int) (((unsigned int)-1)*(((((unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case 2: if (8 * sizeof(unsigned int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 2 * PyLong_SHIFT) { return (unsigned int) ((((((unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case -3: if (8 * sizeof(unsigned int) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 3 * PyLong_SHIFT) { return (unsigned int) (((unsigned int)-1)*(((((((unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case 3: if (8 * sizeof(unsigned int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 3 * PyLong_SHIFT) { return (unsigned int) ((((((((unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case -4: if (8 * sizeof(unsigned int) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 4 * PyLong_SHIFT) { return (unsigned int) (((unsigned int)-1)*(((((((((unsigned int)digits[3]) << PyLong_SHIFT) | (unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case 4: if (8 * sizeof(unsigned int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 4 * PyLong_SHIFT) { return (unsigned int) ((((((((((unsigned int)digits[3]) << PyLong_SHIFT) | (unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; } #endif if (sizeof(unsigned int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned int, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned int) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned int, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else unsigned int val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (unsigned int) -1; } } else { unsigned int val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (unsigned int) -1; val = __Pyx_PyInt_As_unsigned_int(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to unsigned int"); return (unsigned int) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned int"); return (unsigned int) -1; } /* CIntFromPy */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { const int neg_one = (int) -1, const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (int) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) case -2: if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -3: if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -4: if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; } #endif if (sizeof(int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else int val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (int) -1; } } else { int val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (int) -1; val = __Pyx_PyInt_As_int(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to int"); return (int) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to int"); return (int) -1; } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(long) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(long) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(long), little, !is_unsigned); } } /* CIntFromPy */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(long) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (long) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (long) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(long) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) case -2: if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -3: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -4: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; } #endif if (sizeof(long) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else long val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (long) -1; } } else { long val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (long) -1; val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to long"); return (long) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long) -1; } /* CheckBinaryVersion */ static int __Pyx_check_binary_version(void) { char ctversion[4], rtversion[4]; PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { char message[200]; PyOS_snprintf(message, sizeof(message), "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); return PyErr_WarnEx(NULL, message, 1); } return 0; } /* ModuleImport */ #ifndef __PYX_HAVE_RT_ImportModule #define __PYX_HAVE_RT_ImportModule static PyObject *__Pyx_ImportModule(const char *name) { PyObject *py_name = 0; PyObject *py_module = 0; py_name = __Pyx_PyIdentifier_FromString(name); if (!py_name) goto bad; py_module = PyImport_Import(py_name); Py_DECREF(py_name); return py_module; bad: Py_XDECREF(py_name); return 0; } #endif /* TypeImport */ #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict) { PyObject *py_module = 0; PyObject *result = 0; PyObject *py_name = 0; char warning[200]; Py_ssize_t basicsize; #ifdef Py_LIMITED_API PyObject *py_basicsize; #endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); Py_DECREF(py_name); py_name = 0; Py_DECREF(py_module); py_module = 0; if (!result) goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } #ifndef Py_LIMITED_API basicsize = ((PyTypeObject *)result)->tp_basicsize; #else py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); if (!py_basicsize) goto bad; basicsize = PyLong_AsSsize_t(py_basicsize); Py_DECREF(py_basicsize); py_basicsize = 0; if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) goto bad; #endif if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility. Expected %zd, got %zd", module_name, class_name, basicsize, size); if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; } else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, "%.200s.%.200s has the wrong size, try recompiling. Expected %zd, got %zd", module_name, class_name, basicsize, size); goto bad; } return (PyTypeObject *)result; bad: Py_XDECREF(py_module); Py_XDECREF(result); return NULL; } #endif /* InitStrings */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 if (t->is_unicode) { *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); } else if (t->intern) { *t->p = PyString_InternFromString(t->s); } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } #else if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); } else if (t->encoding) { *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); } else { *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); } } else { *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); } #endif if (!*t->p) return -1; ++t; } return 0; } static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); } static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { #if CYTHON_COMPILING_IN_CPYTHON && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if ( #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII __Pyx_sys_getdefaultencoding_not_ascii && #endif PyUnicode_Check(o)) { #if PY_VERSION_HEX < 0x03030000 char* defenc_c; PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); if (!defenc) return NULL; defenc_c = PyBytes_AS_STRING(defenc); #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII { char* end = defenc_c + PyBytes_GET_SIZE(defenc); char* c; for (c = defenc_c; c < end; c++) { if ((unsigned char) (*c) >= 128) { PyUnicode_AsASCIIString(o); return NULL; } } } #endif *length = PyBytes_GET_SIZE(defenc); return defenc_c; #else if (__Pyx_PyUnicode_READY(o) == -1) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (PyUnicode_IS_ASCII(o)) { *length = PyUnicode_GET_LENGTH(o); return PyUnicode_AsUTF8(o); } else { PyUnicode_AsASCIIString(o); return NULL; } #else return PyUnicode_AsUTF8AndSize(o, length); #endif #endif } else #endif #if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) if (PyByteArray_Check(o)) { *length = PyByteArray_GET_SIZE(o); return PyByteArray_AS_STRING(o); } else #endif { char* result; int r = PyBytes_AsStringAndSize(o, &result, length); if (unlikely(r < 0)) { return NULL; } else { return result; } } } static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { #if CYTHON_USE_TYPE_SLOTS PyNumberMethods *m; #endif const char *name = NULL; PyObject *res = NULL; #if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return __Pyx_NewRef(x); #if CYTHON_USE_TYPE_SLOTS m = Py_TYPE(x)->tp_as_number; #if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); } else if (m && m->nb_long) { name = "long"; res = PyNumber_Long(x); } #else if (m && m->nb_int) { name = "int"; res = PyNumber_Long(x); } #endif #else res = PyNumber_Int(x); #endif if (res) { #if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; } } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "an integer is required"); } return res; } static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject *x; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(b))) { if (sizeof(Py_ssize_t) >= sizeof(long)) return PyInt_AS_LONG(b); else return PyInt_AsSsize_t(x); } #endif if (likely(PyLong_CheckExact(b))) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)b)->ob_digit; const Py_ssize_t size = Py_SIZE(b); if (likely(__Pyx_sst_abs(size) <= 1)) { ival = likely(size) ? digits[0] : 0; if (size == -1) ival = -ival; return ival; } else { switch (size) { case 2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; } } #endif return PyLong_AsSsize_t(b); } x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); } #endif /* Py_PYTHON_H */ ================================================ FILE: lib/draw_rectangles/draw_rectangles.pyx ================================================ ###### # Draws rectangles ###### cimport cython import numpy as np cimport numpy as np DTYPE = np.float32 ctypedef np.float32_t DTYPE_t def draw_union_boxes(bbox_pairs, pooling_size, padding=0): """ Draws union boxes for the image. :param box_pairs: [num_pairs, 8] :param fmap_size: Size of the original feature map :param stride: ratio between fmap size and original img (<1) :param pooling_size: resize everything to this size :return: [num_pairs, 2, pooling_size, pooling_size arr """ assert padding == 0, "Padding>0 not supported yet" return draw_union_boxes_c(bbox_pairs, pooling_size) cdef DTYPE_t minmax(DTYPE_t x): return min(max(x, 0), 1) cdef np.ndarray[DTYPE_t, ndim=4] draw_union_boxes_c( np.ndarray[DTYPE_t, ndim=2] box_pairs, unsigned int pooling_size): """ Parameters ---------- boxes: (N, 4) ndarray of float. everything has arbitrary ratios query_boxes: (K, 4) ndarray of float Returns ------- overlaps: (N, K) ndarray of overlap between boxes and query_boxes """ cdef unsigned int N = box_pairs.shape[0] cdef np.ndarray[DTYPE_t, ndim = 4] uboxes = np.zeros( (N, 2, pooling_size, pooling_size), dtype=DTYPE) cdef DTYPE_t x1_union, y1_union, x2_union, y2_union, w, h, x1_box, y1_box, x2_box, y2_box, y_contrib, x_contrib cdef unsigned int n, i, j, k for n in range(N): x1_union = min(box_pairs[n, 0], box_pairs[n, 4]) y1_union = min(box_pairs[n, 1], box_pairs[n, 5]) x2_union = max(box_pairs[n, 2], box_pairs[n, 6]) y2_union = max(box_pairs[n, 3], box_pairs[n, 7]) w = x2_union - x1_union h = y2_union - y1_union for i in range(2): # Now everything is in the range [0, pooling_size]. x1_box = (box_pairs[n, 0+4*i] - x1_union)*pooling_size / w y1_box = (box_pairs[n, 1+4*i] - y1_union)*pooling_size / h x2_box = (box_pairs[n, 2+4*i] - x1_union)*pooling_size / w y2_box = (box_pairs[n, 3+4*i] - y1_union)*pooling_size / h # print("{:.3f}, {:.3f}, {:.3f}, {:.3f}".format(x1_box, y1_box, x2_box, y2_box)) for j in range(pooling_size): y_contrib = minmax(j+1-y1_box)*minmax(y2_box-j) for k in range(pooling_size): x_contrib = minmax(k+1-x1_box)*minmax(x2_box-k) # print("j {} yc {} k {} xc {}".format(j, y_contrib, k, x_contrib)) uboxes[n,i,j,k] = x_contrib*y_contrib return uboxes ================================================ FILE: lib/draw_rectangles/setup.py ================================================ from distutils.core import setup from Cython.Build import cythonize import numpy setup(name="draw_rectangles_cython", ext_modules=cythonize('draw_rectangles.pyx'), include_dirs=[numpy.get_include()]) ================================================ FILE: lib/evaluation/__init__.py ================================================ ================================================ FILE: lib/evaluation/sg_eval.py ================================================ """ Adapted from Danfei Xu. In particular, slow code was removed """ import numpy as np from functools import reduce from lib.pytorch_misc import intersect_2d, argsort_desc from lib.fpn.box_intersections_cpu.bbox import bbox_overlaps from config import MODES np.set_printoptions(precision=3) class BasicSceneGraphEvaluator: def __init__(self, mode, multiple_preds=False): self.result_dict = {} self.mode = mode self.result_dict[self.mode + '_recall'] = {20: [], 50: [], 100: []} self.multiple_preds = multiple_preds @classmethod def all_modes(cls, **kwargs): evaluators = {m: cls(mode=m, **kwargs) for m in MODES} return evaluators @classmethod def vrd_modes(cls, **kwargs): evaluators = {m: cls(mode=m, multiple_preds=True, **kwargs) for m in ('preddet', 'phrdet')} return evaluators def evaluate_scene_graph_entry(self, gt_entry, pred_scores, viz_dict=None, iou_thresh=0.5): res = evaluate_from_dict(gt_entry, pred_scores, self.mode, self.result_dict, viz_dict=viz_dict, iou_thresh=iou_thresh, multiple_preds=self.multiple_preds) # self.print_stats() return res def save(self, fn): np.save(fn, self.result_dict) def print_stats(self): print('======================' + self.mode + '============================') for k, v in self.result_dict[self.mode + '_recall'].items(): print('R@%i: %f' % (k, np.mean(v))) def evaluate_from_dict(gt_entry, pred_entry, mode, result_dict, multiple_preds=False, viz_dict=None, **kwargs): """ Shortcut to doing evaluate_recall from dict :param gt_entry: Dictionary containing gt_relations, gt_boxes, gt_classes :param pred_entry: Dictionary containing pred_rels, pred_boxes (if detection), pred_classes :param mode: 'det' or 'cls' :param result_dict: :param viz_dict: :param kwargs: :return: """ gt_rels = gt_entry['gt_relations'] gt_boxes = gt_entry['gt_boxes'].astype(float) gt_classes = gt_entry['gt_classes'] pred_rel_inds = pred_entry['pred_rel_inds'] rel_scores = pred_entry['rel_scores'] if mode == 'predcls': pred_boxes = gt_boxes pred_classes = gt_classes obj_scores = np.ones(gt_classes.shape[0]) elif mode == 'sgcls': pred_boxes = gt_boxes pred_classes = pred_entry['pred_classes'] obj_scores = pred_entry['obj_scores'] elif mode == 'sgdet' or mode == 'phrdet': pred_boxes = pred_entry['pred_boxes'].astype(float) pred_classes = pred_entry['pred_classes'] obj_scores = pred_entry['obj_scores'] elif mode == 'preddet': # Only extract the indices that appear in GT prc = intersect_2d(pred_rel_inds, gt_rels[:, :2]) if prc.size == 0: for k in result_dict[mode + '_recall']: result_dict[mode + '_recall'][k].append(0.0) return None, None, None pred_inds_per_gt = prc.argmax(0) pred_rel_inds = pred_rel_inds[pred_inds_per_gt] rel_scores = rel_scores[pred_inds_per_gt] # Now sort the matching ones rel_scores_sorted = argsort_desc(rel_scores[:,1:]) rel_scores_sorted[:,1] += 1 rel_scores_sorted = np.column_stack((pred_rel_inds[rel_scores_sorted[:,0]], rel_scores_sorted[:,1])) matches = intersect_2d(rel_scores_sorted, gt_rels) for k in result_dict[mode + '_recall']: rec_i = float(matches[:k].any(0).sum()) / float(gt_rels.shape[0]) result_dict[mode + '_recall'][k].append(rec_i) return None, None, None else: raise ValueError('invalid mode') if multiple_preds: obj_scores_per_rel = obj_scores[pred_rel_inds].prod(1) overall_scores = obj_scores_per_rel[:,None] * rel_scores[:,1:] score_inds = argsort_desc(overall_scores)[:100] pred_rels = np.column_stack((pred_rel_inds[score_inds[:,0]], score_inds[:,1]+1)) predicate_scores = rel_scores[score_inds[:,0], score_inds[:,1]+1] else: pred_rels = np.column_stack((pred_rel_inds, 1+rel_scores[:,1:].argmax(1))) predicate_scores = rel_scores[:,1:].max(1) pred_to_gt, pred_5ples, rel_scores = evaluate_recall( gt_rels, gt_boxes, gt_classes, pred_rels, pred_boxes, pred_classes, predicate_scores, obj_scores, phrdet= mode=='phrdet', **kwargs) for k in result_dict[mode + '_recall']: match = reduce(np.union1d, pred_to_gt[:k]) rec_i = float(len(match)) / float(gt_rels.shape[0]) result_dict[mode + '_recall'][k].append(rec_i) return pred_to_gt, pred_5ples, rel_scores # print(" ".join(["R@{:2d}: {:.3f}".format(k, v[-1]) for k, v in result_dict[mode + '_recall'].items()])) # Deal with visualization later # # Optionally, log things to a separate dictionary # if viz_dict is not None: # # Caution: pred scores has changed (we took off the 0 class) # gt_rels_scores = pred_scores[ # gt_rels[:, 0], # gt_rels[:, 1], # gt_rels[:, 2] - 1, # ] # # gt_rels_scores_cls = gt_rels_scores * pred_class_scores[ # # gt_rels[:, 0]] * pred_class_scores[gt_rels[:, 1]] # # viz_dict[mode + '_pred_rels'] = pred_5ples.tolist() # viz_dict[mode + '_pred_rels_scores'] = max_pred_scores.tolist() # viz_dict[mode + '_pred_rels_scores_cls'] = max_rel_scores.tolist() # viz_dict[mode + '_gt_rels_scores'] = gt_rels_scores.tolist() # viz_dict[mode + '_gt_rels_scores_cls'] = gt_rels_scores_cls.tolist() # # # Serialize pred2gt matching as a list of lists, where each sublist is of the form # # pred_ind, gt_ind1, gt_ind2, .... # viz_dict[mode + '_pred2gt_rel'] = pred_to_gt ########################### def evaluate_recall(gt_rels, gt_boxes, gt_classes, pred_rels, pred_boxes, pred_classes, rel_scores=None, cls_scores=None, iou_thresh=0.5, phrdet=False): """ Evaluates the recall :param gt_rels: [#gt_rel, 3] array of GT relations :param gt_boxes: [#gt_box, 4] array of GT boxes :param gt_classes: [#gt_box] array of GT classes :param pred_rels: [#pred_rel, 3] array of pred rels. Assumed these are in sorted order and refer to IDs in pred classes / pred boxes (id0, id1, rel) :param pred_boxes: [#pred_box, 4] array of pred boxes :param pred_classes: [#pred_box] array of predicted classes for these boxes :return: pred_to_gt: Matching from predicate to GT pred_5ples: the predicted (id0, id1, cls0, cls1, rel) rel_scores: [cls_0score, cls1_score, relscore] """ if pred_rels.size == 0: return [[]], np.zeros((0,5)), np.zeros(0) num_gt_boxes = gt_boxes.shape[0] num_gt_relations = gt_rels.shape[0] assert num_gt_relations != 0 gt_triplets, gt_triplet_boxes, _ = _triplet(gt_rels[:, 2], gt_rels[:, :2], gt_classes, gt_boxes) num_boxes = pred_boxes.shape[0] assert pred_rels[:,:2].max() < pred_classes.shape[0] # Exclude self rels # assert np.all(pred_rels[:,0] != pred_rels[:,1]) assert np.all(pred_rels[:,2] > 0) pred_triplets, pred_triplet_boxes, relation_scores = \ _triplet(pred_rels[:,2], pred_rels[:,:2], pred_classes, pred_boxes, rel_scores, cls_scores) scores_overall = relation_scores.prod(1) if not np.all(scores_overall[1:] <= scores_overall[:-1] + 1e-5): print("Somehow the relations weren't sorted properly: \n{}".format(scores_overall)) # raise ValueError("Somehow the relations werent sorted properly") # Compute recall. It's most efficient to match once and then do recall after pred_to_gt = _compute_pred_matches( gt_triplets, pred_triplets, gt_triplet_boxes, pred_triplet_boxes, iou_thresh, phrdet=phrdet, ) # Contains some extra stuff for visualization. Not needed. pred_5ples = np.column_stack(( pred_rels[:,:2], pred_triplets[:, [0, 2, 1]], )) return pred_to_gt, pred_5ples, relation_scores def _triplet(predicates, relations, classes, boxes, predicate_scores=None, class_scores=None): """ format predictions into triplets :param predicates: A 1d numpy array of num_boxes*(num_boxes-1) predicates, corresponding to each pair of possibilities :param relations: A (num_boxes*(num_boxes-1), 2) array, where each row represents the boxes in that relation :param classes: A (num_boxes) array of the classes for each thing. :param boxes: A (num_boxes,4) array of the bounding boxes for everything. :param predicate_scores: A (num_boxes*(num_boxes-1)) array of the scores for each predicate :param class_scores: A (num_boxes) array of the likelihood for each object. :return: Triplets: (num_relations, 3) array of class, relation, class Triplet boxes: (num_relation, 8) array of boxes for the parts Triplet scores: num_relation array of the scores overall for the triplets """ assert (predicates.shape[0] == relations.shape[0]) sub_ob_classes = classes[relations[:, :2]] triplets = np.column_stack((sub_ob_classes[:, 0], predicates, sub_ob_classes[:, 1])) triplet_boxes = np.column_stack((boxes[relations[:, 0]], boxes[relations[:, 1]])) triplet_scores = None if predicate_scores is not None and class_scores is not None: triplet_scores = np.column_stack(( class_scores[relations[:, 0]], class_scores[relations[:, 1]], predicate_scores, )) return triplets, triplet_boxes, triplet_scores def _compute_pred_matches(gt_triplets, pred_triplets, gt_boxes, pred_boxes, iou_thresh, phrdet=False): """ Given a set of predicted triplets, return the list of matching GT's for each of the given predictions :param gt_triplets: :param pred_triplets: :param gt_boxes: :param pred_boxes: :param iou_thresh: :return: """ # This performs a matrix multiplication-esque thing between the two arrays # Instead of summing, we want the equality, so we reduce in that way # The rows correspond to GT triplets, columns to pred triplets keeps = intersect_2d(gt_triplets, pred_triplets) gt_has_match = keeps.any(1) pred_to_gt = [[] for x in range(pred_boxes.shape[0])] for gt_ind, gt_box, keep_inds in zip(np.where(gt_has_match)[0], gt_boxes[gt_has_match], keeps[gt_has_match], ): boxes = pred_boxes[keep_inds] if phrdet: # Evaluate where the union box > 0.5 gt_box_union = gt_box.reshape((2, 4)) gt_box_union = np.concatenate((gt_box_union.min(0)[:2], gt_box_union.max(0)[2:]), 0) box_union = boxes.reshape((-1, 2, 4)) box_union = np.concatenate((box_union.min(1)[:,:2], box_union.max(1)[:,2:]), 1) inds = bbox_overlaps(gt_box_union[None], box_union)[0] >= iou_thresh else: sub_iou = bbox_overlaps(gt_box[None,:4], boxes[:, :4])[0] obj_iou = bbox_overlaps(gt_box[None,4:], boxes[:, 4:])[0] inds = (sub_iou >= iou_thresh) & (obj_iou >= iou_thresh) for i in np.where(keep_inds)[0][inds]: pred_to_gt[i].append(int(gt_ind)) return pred_to_gt ================================================ FILE: lib/evaluation/sg_eval_all_rel_cates.py ================================================ """ Adapted from Danfei Xu. In particular, slow code was removed """ import numpy as np from functools import reduce from lib.pytorch_misc import intersect_2d, argsort_desc from lib.fpn.box_intersections_cpu.bbox import bbox_overlaps from config import MODES import sys np.set_printoptions(precision=3) class BasicSceneGraphEvaluator: def __init__(self, mode, multiple_preds=False): self.result_dict = {} self.mode = mode rel_cats = { 0: 'all_rel_cates', 1: "above", 2: "across", 3: "against", 4: "along", 5: "and", 6: "at", 7: "attached to", 8: "behind", 9: "belonging to", 10: "between", 11: "carrying", 12: "covered in", 13: "covering", 14: "eating", 15: "flying in", 16: "for", 17: "from", 18: "growing on", 19: "hanging from", 20: "has", 21: "holding", 22: "in", 23: "in front of", 24: "laying on", 25: "looking at", 26: "lying on", 27: "made of", 28: "mounted on", 29: "near", 30: "of", 31: "on", 32: "on back of", 33: "over", 34: "painted on", 35: "parked on", 36: "part of", 37: "playing", 38: "riding", 39: "says", 40: "sitting on", 41: "standing on", 42: "to", 43: "under", 44: "using", 45: "walking in", 46: "walking on", 47: "watching", 48: "wearing", 49: "wears", 50: "with" } self.rel_cats = rel_cats self.result_dict[self.mode + '_recall'] = {20: {}, 50: {}, 100: []} for key, value in self.result_dict[self.mode + '_recall'].items(): self.result_dict[self.mode + '_recall'][key] = {} for rel_cat_id, rel_cat_name in rel_cats.items(): self.result_dict[self.mode + '_recall'][key][rel_cat_name] = [] self.multiple_preds = multiple_preds @classmethod def all_modes(cls, **kwargs): evaluators = {m: cls(mode=m, **kwargs) for m in MODES} return evaluators @classmethod def vrd_modes(cls, **kwargs): evaluators = {m: cls(mode=m, multiple_preds=True, **kwargs) for m in ('preddet', 'phrdet')} return evaluators def evaluate_scene_graph_entry(self, gt_entry, pred_scores, viz_dict=None, iou_thresh=0.5): res = evaluate_from_dict(gt_entry, pred_scores, self.mode, self.result_dict, viz_dict=viz_dict, iou_thresh=iou_thresh, multiple_preds=self.multiple_preds, rel_cats=self.rel_cats) # self.print_stats() return res def save(self, fn): np.save(fn, self.result_dict) def print_stats(self): print('======================' + self.mode + '============================') for k, v in self.result_dict[self.mode + '_recall'].items(): for rel_cat_id, rel_cat_name in self.rel_cats.items(): print('R@%i: %f' % (k, np.mean(v[rel_cat_name])), rel_cat_name) print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') def evaluate_from_dict(gt_entry, pred_entry, mode, result_dict, multiple_preds=False, viz_dict=None, rel_cats=None, **kwargs): """ Shortcut to doing evaluate_recall from dict :param gt_entry: Dictionary containing gt_relations, gt_boxes, gt_classes :param pred_entry: Dictionary containing pred_rels, pred_boxes (if detection), pred_classes :param mode: 'det' or 'cls' :param result_dict: :param viz_dict: :param kwargs: :return: """ gt_rels = gt_entry['gt_relations'] gt_boxes = gt_entry['gt_boxes'].astype(float) gt_classes = gt_entry['gt_classes'] gt_rels_nums = [0 for x in range(len(rel_cats))] for rel in gt_rels: gt_rels_nums[rel[2]] += 1 gt_rels_nums[0] += 1 pred_rel_inds = pred_entry['pred_rel_inds'] rel_scores = pred_entry['rel_scores'] if mode == 'predcls': pred_boxes = gt_boxes pred_classes = gt_classes obj_scores = np.ones(gt_classes.shape[0]) elif mode == 'sgcls': pred_boxes = gt_boxes pred_classes = pred_entry['pred_classes'] obj_scores = pred_entry['obj_scores'] elif mode == 'sgdet' or mode == 'phrdet': pred_boxes = pred_entry['pred_boxes'].astype(float) pred_classes = pred_entry['pred_classes'] obj_scores = pred_entry['obj_scores'] elif mode == 'preddet': # Only extract the indices that appear in GT prc = intersect_2d(pred_rel_inds, gt_rels[:, :2]) if prc.size == 0: for k in result_dict[mode + '_recall']: result_dict[mode + '_recall'][k].append(0.0) return None, None, None pred_inds_per_gt = prc.argmax(0) pred_rel_inds = pred_rel_inds[pred_inds_per_gt] rel_scores = rel_scores[pred_inds_per_gt] # Now sort the matching ones rel_scores_sorted = argsort_desc(rel_scores[:,1:]) rel_scores_sorted[:,1] += 1 rel_scores_sorted = np.column_stack((pred_rel_inds[rel_scores_sorted[:,0]], rel_scores_sorted[:,1])) matches = intersect_2d(rel_scores_sorted, gt_rels) for k in result_dict[mode + '_recall']: rec_i = float(matches[:k].any(0).sum()) / float(gt_rels.shape[0]) result_dict[mode + '_recall'][k].append(rec_i) return None, None, None else: raise ValueError('invalid mode') if multiple_preds: obj_scores_per_rel = obj_scores[pred_rel_inds].prod(1) overall_scores = obj_scores_per_rel[:,None] * rel_scores[:,1:] score_inds = argsort_desc(overall_scores)[:100] pred_rels = np.column_stack((pred_rel_inds[score_inds[:,0]], score_inds[:,1]+1)) predicate_scores = rel_scores[score_inds[:,0], score_inds[:,1]+1] else: pred_rels = np.column_stack((pred_rel_inds, 1+rel_scores[:,1:].argmax(1))) predicate_scores = rel_scores[:,1:].max(1) pred_to_gt, pred_5ples, rel_scores = evaluate_recall( gt_rels, gt_boxes, gt_classes, pred_rels, pred_boxes, pred_classes, predicate_scores, obj_scores, phrdet= mode=='phrdet',rel_cats=rel_cats, **kwargs) for k in result_dict[mode + '_recall']: for rel_cat_id, rel_cat_name in rel_cats.items(): match = reduce(np.union1d, pred_to_gt[rel_cat_name][:k]) rec_i = float(len(match)) / (float(gt_rels_nums[rel_cat_id]) + sys.float_info.min) #float(gt_rels.shape[0]) result_dict[mode + '_recall'][k][rel_cat_name].append(rec_i) return pred_to_gt, pred_5ples, rel_scores # print(" ".join(["R@{:2d}: {:.3f}".format(k, v[-1]) for k, v in result_dict[mode + '_recall'].items()])) # Deal with visualization later # # Optionally, log things to a separate dictionary # if viz_dict is not None: # # Caution: pred scores has changed (we took off the 0 class) # gt_rels_scores = pred_scores[ # gt_rels[:, 0], # gt_rels[:, 1], # gt_rels[:, 2] - 1, # ] # # gt_rels_scores_cls = gt_rels_scores * pred_class_scores[ # # gt_rels[:, 0]] * pred_class_scores[gt_rels[:, 1]] # # viz_dict[mode + '_pred_rels'] = pred_5ples.tolist() # viz_dict[mode + '_pred_rels_scores'] = max_pred_scores.tolist() # viz_dict[mode + '_pred_rels_scores_cls'] = max_rel_scores.tolist() # viz_dict[mode + '_gt_rels_scores'] = gt_rels_scores.tolist() # viz_dict[mode + '_gt_rels_scores_cls'] = gt_rels_scores_cls.tolist() # # # Serialize pred2gt matching as a list of lists, where each sublist is of the form # # pred_ind, gt_ind1, gt_ind2, .... # viz_dict[mode + '_pred2gt_rel'] = pred_to_gt ########################### def evaluate_recall(gt_rels, gt_boxes, gt_classes, pred_rels, pred_boxes, pred_classes, rel_scores=None, cls_scores=None, iou_thresh=0.5, phrdet=False, rel_cats=None): """ Evaluates the recall :param gt_rels: [#gt_rel, 3] array of GT relations :param gt_boxes: [#gt_box, 4] array of GT boxes :param gt_classes: [#gt_box] array of GT classes :param pred_rels: [#pred_rel, 3] array of pred rels. Assumed these are in sorted order and refer to IDs in pred classes / pred boxes (id0, id1, rel) :param pred_boxes: [#pred_box, 4] array of pred boxes :param pred_classes: [#pred_box] array of predicted classes for these boxes :return: pred_to_gt: Matching from predicate to GT pred_5ples: the predicted (id0, id1, cls0, cls1, rel) rel_scores: [cls_0score, cls1_score, relscore] """ if pred_rels.size == 0: return [[]], np.zeros((0,5)), np.zeros(0) num_gt_boxes = gt_boxes.shape[0] num_gt_relations = gt_rels.shape[0] assert num_gt_relations != 0 gt_triplets, gt_triplet_boxes, _ = _triplet(gt_rels[:, 2], gt_rels[:, :2], gt_classes, gt_boxes) num_boxes = pred_boxes.shape[0] assert pred_rels[:,:2].max() < pred_classes.shape[0] # Exclude self rels # assert np.all(pred_rels[:,0] != pred_rels[:,1]) assert np.all(pred_rels[:,2] > 0) pred_triplets, pred_triplet_boxes, relation_scores = \ _triplet(pred_rels[:,2], pred_rels[:,:2], pred_classes, pred_boxes, rel_scores, cls_scores) scores_overall = relation_scores.prod(1) if not np.all(scores_overall[1:] <= scores_overall[:-1] + 1e-5): print("Somehow the relations weren't sorted properly: \n{}".format(scores_overall)) # raise ValueError("Somehow the relations werent sorted properly") # Compute recall. It's most efficient to match once and then do recall after pred_to_gt = _compute_pred_matches( gt_triplets, pred_triplets, gt_triplet_boxes, pred_triplet_boxes, iou_thresh, phrdet=phrdet, rel_cats=rel_cats, ) # Contains some extra stuff for visualization. Not needed. pred_5ples = np.column_stack(( pred_rels[:,:2], pred_triplets[:, [0, 2, 1]], )) return pred_to_gt, pred_5ples, relation_scores def _triplet(predicates, relations, classes, boxes, predicate_scores=None, class_scores=None): """ format predictions into triplets :param predicates: A 1d numpy array of num_boxes*(num_boxes-1) predicates, corresponding to each pair of possibilities :param relations: A (num_boxes*(num_boxes-1), 2) array, where each row represents the boxes in that relation :param classes: A (num_boxes) array of the classes for each thing. :param boxes: A (num_boxes,4) array of the bounding boxes for everything. :param predicate_scores: A (num_boxes*(num_boxes-1)) array of the scores for each predicate :param class_scores: A (num_boxes) array of the likelihood for each object. :return: Triplets: (num_relations, 3) array of class, relation, class Triplet boxes: (num_relation, 8) array of boxes for the parts Triplet scores: num_relation array of the scores overall for the triplets """ assert (predicates.shape[0] == relations.shape[0]) sub_ob_classes = classes[relations[:, :2]] triplets = np.column_stack((sub_ob_classes[:, 0], predicates, sub_ob_classes[:, 1])) triplet_boxes = np.column_stack((boxes[relations[:, 0]], boxes[relations[:, 1]])) triplet_scores = None if predicate_scores is not None and class_scores is not None: triplet_scores = np.column_stack(( class_scores[relations[:, 0]], class_scores[relations[:, 1]], predicate_scores, )) return triplets, triplet_boxes, triplet_scores def _compute_pred_matches(gt_triplets, pred_triplets, gt_boxes, pred_boxes, iou_thresh, phrdet=False, rel_cats=None): """ Given a set of predicted triplets, return the list of matching GT's for each of the given predictions :param gt_triplets: :param pred_triplets: :param gt_boxes: :param pred_boxes: :param iou_thresh: :return: """ # This performs a matrix multiplication-esque thing between the two arrays # Instead of summing, we want the equality, so we reduce in that way # The rows correspond to GT triplets, columns to pred triplets keeps = intersect_2d(gt_triplets, pred_triplets) gt_has_match = keeps.any(1) pred_to_gt = {} for rel_cat_id, rel_cat_name in rel_cats.items(): pred_to_gt[rel_cat_name] = [[] for x in range(pred_boxes.shape[0])] for gt_ind, gt_box, keep_inds in zip(np.where(gt_has_match)[0], gt_boxes[gt_has_match], keeps[gt_has_match], ): boxes = pred_boxes[keep_inds] if phrdet: # Evaluate where the union box > 0.5 gt_box_union = gt_box.reshape((2, 4)) gt_box_union = np.concatenate((gt_box_union.min(0)[:2], gt_box_union.max(0)[2:]), 0) box_union = boxes.reshape((-1, 2, 4)) box_union = np.concatenate((box_union.min(1)[:,:2], box_union.max(1)[:,2:]), 1) inds = bbox_overlaps(gt_box_union[None], box_union)[0] >= iou_thresh else: sub_iou = bbox_overlaps(gt_box[None,:4], boxes[:, :4])[0] obj_iou = bbox_overlaps(gt_box[None,4:], boxes[:, 4:])[0] inds = (sub_iou >= iou_thresh) & (obj_iou >= iou_thresh) for i in np.where(keep_inds)[0][inds]: pred_to_gt['all_rel_cates'][i].append(int(gt_ind)) pred_to_gt[rel_cats[gt_triplets[int(gt_ind), 1]]][i].append(int(gt_ind)) return pred_to_gt ================================================ FILE: lib/evaluation/sg_eval_slow.py ================================================ # JUST TO CHECK THAT IT IS EXACTLY THE SAME.................................. import numpy as np from config import MODES class BasicSceneGraphEvaluator: def __init__(self, mode): self.result_dict = {} self.mode = {'sgdet':'sg_det', 'sgcls':'sg_cls', 'predcls':'pred_cls'}[mode] self.result_dict = {} self.result_dict[self.mode + '_recall'] = {20:[], 50:[], 100:[]} @classmethod def all_modes(cls): evaluators = {m: cls(mode=m) for m in MODES} return evaluators def evaluate_scene_graph_entry(self, gt_entry, pred_entry, iou_thresh=0.5): roidb_entry = { 'max_overlaps': np.ones(gt_entry['gt_classes'].shape[0], dtype=np.int64), 'boxes': gt_entry['gt_boxes'], 'gt_relations': gt_entry['gt_relations'], 'gt_classes': gt_entry['gt_classes'], } sg_entry = { 'boxes': pred_entry['pred_boxes'], 'relations': pred_entry['pred_rels'], 'obj_scores': pred_entry['obj_scores'], 'rel_scores': pred_entry['rel_scores'], 'pred_classes': pred_entry['pred_classes'], } pred_triplets, triplet_boxes = \ eval_relation_recall(sg_entry, roidb_entry, self.result_dict, self.mode, iou_thresh=iou_thresh) return pred_triplets, triplet_boxes def save(self, fn): np.save(fn, self.result_dict) def print_stats(self): print('======================' + self.mode + '============================') for k, v in self.result_dict[self.mode + '_recall'].items(): print('R@%i: %f' % (k, np.mean(v))) def save(self, fn): np.save(fn, self.result_dict) def print_stats(self): print('======================' + self.mode + '============================') for k, v in self.result_dict[self.mode + '_recall'].items(): print('R@%i: %f' % (k, np.mean(v))) def eval_relation_recall(sg_entry, roidb_entry, result_dict, mode, iou_thresh): # gt gt_inds = np.where(roidb_entry['max_overlaps'] == 1)[0] gt_boxes = roidb_entry['boxes'][gt_inds].copy().astype(float) num_gt_boxes = gt_boxes.shape[0] gt_relations = roidb_entry['gt_relations'].copy() gt_classes = roidb_entry['gt_classes'].copy() num_gt_relations = gt_relations.shape[0] if num_gt_relations == 0: return (None, None) gt_class_scores = np.ones(num_gt_boxes) gt_predicate_scores = np.ones(num_gt_relations) gt_triplets, gt_triplet_boxes, _ = _triplet(gt_relations[:,2], gt_relations[:,:2], gt_classes, gt_boxes, gt_predicate_scores, gt_class_scores) # pred box_preds = sg_entry['boxes'] num_boxes = box_preds.shape[0] relations = sg_entry['relations'] classes = sg_entry['pred_classes'].copy() class_scores = sg_entry['obj_scores'].copy() num_relations = relations.shape[0] if mode =='pred_cls': # if predicate classification task # use ground truth bounding boxes assert(num_boxes == num_gt_boxes) classes = gt_classes class_scores = gt_class_scores boxes = gt_boxes elif mode =='sg_cls': assert(num_boxes == num_gt_boxes) # if scene graph classification task # use gt boxes, but predicted classes # classes = np.argmax(class_preds, 1) # class_scores = class_preds.max(axis=1) boxes = gt_boxes elif mode =='sg_det': # if scene graph detection task # use preicted boxes and predicted classes # classes = np.argmax(class_preds, 1) # class_scores = class_preds.max(axis=1) boxes = box_preds else: raise NotImplementedError('Incorrect Mode! %s' % mode) pred_triplets = np.column_stack(( classes[relations[:, 0]], relations[:,2], classes[relations[:, 1]], )) pred_triplet_boxes = np.column_stack(( boxes[relations[:, 0]], boxes[relations[:, 1]], )) relation_scores = np.column_stack(( class_scores[relations[:, 0]], sg_entry['rel_scores'], class_scores[relations[:, 1]], )).prod(1) sorted_inds = np.argsort(relation_scores)[::-1] # compue recall for k in result_dict[mode + '_recall']: this_k = min(k, num_relations) keep_inds = sorted_inds[:this_k] recall = _relation_recall(gt_triplets, pred_triplets[keep_inds,:], gt_triplet_boxes, pred_triplet_boxes[keep_inds,:], iou_thresh) result_dict[mode + '_recall'][k].append(recall) # for visualization return pred_triplets[sorted_inds, :], pred_triplet_boxes[sorted_inds, :] def _triplet(predicates, relations, classes, boxes, predicate_scores, class_scores): # format predictions into triplets assert(predicates.shape[0] == relations.shape[0]) num_relations = relations.shape[0] triplets = np.zeros([num_relations, 3]).astype(np.int32) triplet_boxes = np.zeros([num_relations, 8]).astype(np.int32) triplet_scores = np.zeros([num_relations]).astype(np.float32) for i in range(num_relations): triplets[i, 1] = predicates[i] sub_i, obj_i = relations[i,:2] triplets[i, 0] = classes[sub_i] triplets[i, 2] = classes[obj_i] triplet_boxes[i, :4] = boxes[sub_i, :] triplet_boxes[i, 4:] = boxes[obj_i, :] # compute triplet score score = class_scores[sub_i] score *= class_scores[obj_i] score *= predicate_scores[i] triplet_scores[i] = score return triplets, triplet_boxes, triplet_scores def _relation_recall(gt_triplets, pred_triplets, gt_boxes, pred_boxes, iou_thresh): # compute the R@K metric for a set of predicted triplets num_gt = gt_triplets.shape[0] num_correct_pred_gt = 0 for gt, gt_box in zip(gt_triplets, gt_boxes): keep = np.zeros(pred_triplets.shape[0]).astype(bool) for i, pred in enumerate(pred_triplets): if gt[0] == pred[0] and gt[1] == pred[1] and gt[2] == pred[2]: keep[i] = True if not np.any(keep): continue boxes = pred_boxes[keep,:] sub_iou = iou(gt_box[:4], boxes[:,:4]) obj_iou = iou(gt_box[4:], boxes[:,4:]) inds = np.intersect1d(np.where(sub_iou >= iou_thresh)[0], np.where(obj_iou >= iou_thresh)[0]) if inds.size > 0: num_correct_pred_gt += 1 return float(num_correct_pred_gt) / float(num_gt) def iou(gt_box, pred_boxes): # computer Intersection-over-Union between two sets of boxes ixmin = np.maximum(gt_box[0], pred_boxes[:,0]) iymin = np.maximum(gt_box[1], pred_boxes[:,1]) ixmax = np.minimum(gt_box[2], pred_boxes[:,2]) iymax = np.minimum(gt_box[3], pred_boxes[:,3]) iw = np.maximum(ixmax - ixmin + 1., 0.) ih = np.maximum(iymax - iymin + 1., 0.) inters = iw * ih # union uni = ((gt_box[2] - gt_box[0] + 1.) * (gt_box[3] - gt_box[1] + 1.) + (pred_boxes[:, 2] - pred_boxes[:, 0] + 1.) * (pred_boxes[:, 3] - pred_boxes[:, 1] + 1.) - inters) overlaps = inters / uni return overlaps ================================================ FILE: lib/evaluation/test_sg_eval.py ================================================ # Just some tests so you can be assured that sg_eval.py works the same as the (original) stanford evaluation import numpy as np from six.moves import xrange from dataloaders.visual_genome import VG from lib.evaluation.sg_eval import evaluate_from_dict from tqdm import trange from lib.fpn.box_utils import center_size, point_form def eval_relation_recall(sg_entry, roidb_entry, result_dict, mode, iou_thresh): # gt gt_inds = np.where(roidb_entry['max_overlaps'] == 1)[0] gt_boxes = roidb_entry['boxes'][gt_inds].copy().astype(float) num_gt_boxes = gt_boxes.shape[0] gt_relations = roidb_entry['gt_relations'].copy() gt_classes = roidb_entry['gt_classes'].copy() num_gt_relations = gt_relations.shape[0] if num_gt_relations == 0: return (None, None) gt_class_scores = np.ones(num_gt_boxes) gt_predicate_scores = np.ones(num_gt_relations) gt_triplets, gt_triplet_boxes, _ = _triplet(gt_relations[:,2], gt_relations[:,:2], gt_classes, gt_boxes, gt_predicate_scores, gt_class_scores) # pred box_preds = sg_entry['boxes'] num_boxes = box_preds.shape[0] predicate_preds = sg_entry['relations'] class_preds = sg_entry['scores'] predicate_preds = predicate_preds.reshape(num_boxes, num_boxes, -1) # no bg predicate_preds = predicate_preds[:, :, 1:] predicates = np.argmax(predicate_preds, 2).ravel() + 1 predicate_scores = predicate_preds.max(axis=2).ravel() relations = [] keep = [] for i in xrange(num_boxes): for j in xrange(num_boxes): if i != j: keep.append(num_boxes*i + j) relations.append([i, j]) # take out self relations predicates = predicates[keep] predicate_scores = predicate_scores[keep] relations = np.array(relations) assert(relations.shape[0] == num_boxes * (num_boxes - 1)) assert(predicates.shape[0] == relations.shape[0]) num_relations = relations.shape[0] if mode =='predcls': # if predicate classification task # use ground truth bounding boxes assert(num_boxes == num_gt_boxes) classes = gt_classes class_scores = gt_class_scores boxes = gt_boxes elif mode =='sgcls': assert(num_boxes == num_gt_boxes) # if scene graph classification task # use gt boxes, but predicted classes classes = np.argmax(class_preds, 1) class_scores = class_preds.max(axis=1) boxes = gt_boxes elif mode =='sgdet': # if scene graph detection task # use preicted boxes and predicted classes classes = np.argmax(class_preds, 1) class_scores = class_preds.max(axis=1) boxes = [] for i, c in enumerate(classes): boxes.append(box_preds[i]) # no bbox regression, c*4:(c+1)*4]) boxes = np.vstack(boxes) else: raise NotImplementedError('Incorrect Mode! %s' % mode) pred_triplets, pred_triplet_boxes, relation_scores = \ _triplet(predicates, relations, classes, boxes, predicate_scores, class_scores) sorted_inds = np.argsort(relation_scores)[::-1] # compue recall for k in result_dict[mode + '_recall']: this_k = min(k, num_relations) keep_inds = sorted_inds[:this_k] recall = _relation_recall(gt_triplets, pred_triplets[keep_inds,:], gt_triplet_boxes, pred_triplet_boxes[keep_inds,:], iou_thresh) result_dict[mode + '_recall'][k].append(recall) # for visualization return pred_triplets[sorted_inds, :], pred_triplet_boxes[sorted_inds, :] def _triplet(predicates, relations, classes, boxes, predicate_scores, class_scores): # format predictions into triplets assert(predicates.shape[0] == relations.shape[0]) num_relations = relations.shape[0] triplets = np.zeros([num_relations, 3]).astype(np.int32) triplet_boxes = np.zeros([num_relations, 8]).astype(np.int32) triplet_scores = np.zeros([num_relations]).astype(np.float32) for i in xrange(num_relations): triplets[i, 1] = predicates[i] sub_i, obj_i = relations[i,:2] triplets[i, 0] = classes[sub_i] triplets[i, 2] = classes[obj_i] triplet_boxes[i, :4] = boxes[sub_i, :] triplet_boxes[i, 4:] = boxes[obj_i, :] # compute triplet score score = class_scores[sub_i] score *= class_scores[obj_i] score *= predicate_scores[i] triplet_scores[i] = score return triplets, triplet_boxes, triplet_scores def _relation_recall(gt_triplets, pred_triplets, gt_boxes, pred_boxes, iou_thresh): # compute the R@K metric for a set of predicted triplets num_gt = gt_triplets.shape[0] num_correct_pred_gt = 0 for gt, gt_box in zip(gt_triplets, gt_boxes): keep = np.zeros(pred_triplets.shape[0]).astype(bool) for i, pred in enumerate(pred_triplets): if gt[0] == pred[0] and gt[1] == pred[1] and gt[2] == pred[2]: keep[i] = True if not np.any(keep): continue boxes = pred_boxes[keep,:] sub_iou = iou(gt_box[:4], boxes[:,:4]) obj_iou = iou(gt_box[4:], boxes[:,4:]) inds = np.intersect1d(np.where(sub_iou >= iou_thresh)[0], np.where(obj_iou >= iou_thresh)[0]) if inds.size > 0: num_correct_pred_gt += 1 return float(num_correct_pred_gt) / float(num_gt) def iou(gt_box, pred_boxes): # computer Intersection-over-Union between two sets of boxes ixmin = np.maximum(gt_box[0], pred_boxes[:,0]) iymin = np.maximum(gt_box[1], pred_boxes[:,1]) ixmax = np.minimum(gt_box[2], pred_boxes[:,2]) iymax = np.minimum(gt_box[3], pred_boxes[:,3]) iw = np.maximum(ixmax - ixmin + 1., 0.) ih = np.maximum(iymax - iymin + 1., 0.) inters = iw * ih # union uni = ((gt_box[2] - gt_box[0] + 1.) * (gt_box[3] - gt_box[1] + 1.) + (pred_boxes[:, 2] - pred_boxes[:, 0] + 1.) * (pred_boxes[:, 3] - pred_boxes[:, 1] + 1.) - inters) overlaps = inters / uni return overlaps train, val, test = VG.splits() result_dict_mine = {'sgdet_recall': {20: [], 50: [], 100: []}} result_dict_theirs = {'sgdet_recall': {20: [], 50: [], 100: []}} for img_i in trange(len(val)): gt_entry = { 'gt_classes': val.gt_classes[img_i].copy(), 'gt_relations': val.relationships[img_i].copy(), 'gt_boxes': val.gt_boxes[img_i].copy(), } # Use shuffled GT boxes gt_indices = np.arange(gt_entry['gt_boxes'].shape[0]) #np.random.choice(gt_entry['gt_boxes'].shape[0], 20) pred_boxes = gt_entry['gt_boxes'][gt_indices] # Jitter the boxes a bit pred_boxes = center_size(pred_boxes) pred_boxes[:,:2] += np.random.rand(pred_boxes.shape[0], 2)*128 pred_boxes[:,2:] *= (1+np.random.randn(pred_boxes.shape[0], 2).clip(-0.1, 0.1)) pred_boxes = point_form(pred_boxes) obj_scores = np.random.rand(pred_boxes.shape[0]) rels_to_use = np.column_stack(np.where(1 - np.diag(np.ones(pred_boxes.shape[0], dtype=np.int32)))) rel_scores = np.random.rand(min(100, rels_to_use.shape[0]), 51) rel_scores = rel_scores / rel_scores.sum(1, keepdims=True) pred_rel_inds = rels_to_use[np.random.choice(rels_to_use.shape[0], rel_scores.shape[0], replace=False)] # We must sort by P(o, o, r) rel_order = np.argsort(-rel_scores[:,1:].max(1) * obj_scores[pred_rel_inds[:,0]] * obj_scores[pred_rel_inds[:,1]]) pred_entry = { 'pred_boxes': pred_boxes, 'pred_classes': gt_entry['gt_classes'][gt_indices], #1+np.random.choice(150, pred_boxes.shape[0], replace=True), 'obj_scores': obj_scores, 'pred_rel_inds': pred_rel_inds[rel_order], 'rel_scores': rel_scores[rel_order], } # def check_whether_they_are_the_same(gt_entry, pred_entry): evaluate_from_dict(gt_entry, pred_entry, 'sgdet', result_dict_mine, multiple_preds=False, viz_dict=None) ######################### predicate_scores_theirs = np.zeros((pred_boxes.shape[0], pred_boxes.shape[0], 51), dtype=np.float64) for (o1, o2), s in zip(pred_entry['pred_rel_inds'], pred_entry['rel_scores']): predicate_scores_theirs[o1, o2] = s obj_scores_theirs = np.zeros((obj_scores.shape[0], 151), dtype=np.float64) obj_scores_theirs[np.arange(obj_scores.shape[0]), pred_entry['pred_classes']] = obj_scores sg_entry_orig_format = { 'boxes': pred_entry['pred_boxes'], # 'gt_classes': gt_entry['gt_classes'], # 'gt_relations': gt_entry['gt_relations'], 'relations': predicate_scores_theirs, 'scores': obj_scores_theirs } roidb_entry = { 'max_overlaps': np.concatenate((np.ones(gt_entry['gt_boxes'].shape[0]), np.zeros(pred_entry['pred_boxes'].shape[0])), 0), 'boxes': np.concatenate((gt_entry['gt_boxes'], pred_entry['pred_boxes']), 0), 'gt_classes': gt_entry['gt_classes'], 'gt_relations': gt_entry['gt_relations'], } eval_relation_recall(sg_entry_orig_format, roidb_entry, result_dict_theirs, 'sgdet', iou_thresh=0.5) my_results = np.array(result_dict_mine['sgdet_recall'][20]) their_results = np.array(result_dict_theirs['sgdet_recall'][20]) assert np.all(my_results == their_results) ================================================ FILE: lib/fpn/anchor_targets.py ================================================ """ Generates anchor targets to train the detector. Does this during the collate step in training as it's much cheaper to do this on a separate thread. Heavily adapted from faster_rcnn/rpn_msr/anchor_target_layer.py. """ import numpy as np import numpy.random as npr from config import IM_SCALE, RPN_NEGATIVE_OVERLAP, RPN_POSITIVE_OVERLAP, \ RPN_BATCHSIZE, RPN_FG_FRACTION, ANCHOR_SIZE, ANCHOR_SCALES, ANCHOR_RATIOS from lib.fpn.box_intersections_cpu.bbox import bbox_overlaps from lib.fpn.generate_anchors import generate_anchors def anchor_target_layer(gt_boxes, im_size, allowed_border=0): """ Assign anchors to ground-truth targets. Produces anchor classification labels and bounding-box regression targets. for each (H, W) location i generate 3 anchor boxes centered on cell i filter out-of-image anchors measure GT overlap :param gt_boxes: [x1, y1, x2, y2] boxes. These are assumed to be at the same scale as the image (IM_SCALE) :param im_size: Size of the image (h, w). This is assumed to be scaled to IM_SCALE """ if max(im_size) != IM_SCALE: raise ValueError("im size is {}".format(im_size)) h, w = im_size # Get the indices of the anchors in the feature map. # h, w, A, 4 ans_np = generate_anchors(base_size=ANCHOR_SIZE, feat_stride=16, anchor_scales=ANCHOR_SCALES, anchor_ratios=ANCHOR_RATIOS, ) ans_np_flat = ans_np.reshape((-1, 4)) inds_inside = np.where( (ans_np_flat[:, 0] >= -allowed_border) & (ans_np_flat[:, 1] >= -allowed_border) & (ans_np_flat[:, 2] < w + allowed_border) & # width (ans_np_flat[:, 3] < h + allowed_border) # height )[0] good_ans_flat = ans_np_flat[inds_inside] if good_ans_flat.size == 0: raise ValueError("There were no good anchors for an image of size {} with boxes {}".format(im_size, gt_boxes)) # overlaps between the anchors and the gt boxes [num_anchors, num_gtboxes] overlaps = bbox_overlaps(good_ans_flat, gt_boxes) anchor_to_gtbox = overlaps.argmax(axis=1) max_overlaps = overlaps[np.arange(anchor_to_gtbox.shape[0]), anchor_to_gtbox] gtbox_to_anchor = overlaps.argmax(axis=0) gt_max_overlaps = overlaps[gtbox_to_anchor, np.arange(overlaps.shape[1])] gt_argmax_overlaps = np.where(overlaps == gt_max_overlaps)[0] # Good anchors are those that match SOMEWHERE within a decent tolerance # label: 1 is positive, 0 is negative, -1 is dont care. # assign bg labels first so that positive labels can clobber them labels = (-1) * np.ones(overlaps.shape[0], dtype=np.int64) labels[max_overlaps < RPN_NEGATIVE_OVERLAP] = 0 labels[gt_argmax_overlaps] = 1 labels[max_overlaps >= RPN_POSITIVE_OVERLAP] = 1 # subsample positive labels if we have too many num_fg = int(RPN_FG_FRACTION * RPN_BATCHSIZE) fg_inds = np.where(labels == 1)[0] if len(fg_inds) > num_fg: labels[npr.choice(fg_inds, size=(len(fg_inds) - num_fg), replace=False)] = -1 # subsample negative labels if we have too many num_bg = RPN_BATCHSIZE - np.sum(labels == 1) bg_inds = np.where(labels == 0)[0] if len(bg_inds) > num_bg: labels[npr.choice(bg_inds, size=(len(bg_inds) - num_bg), replace=False)] = -1 # print("{} fg {} bg ratio{:.3f} inds inside {}".format(RPN_BATCHSIZE-num_bg, num_bg, (RPN_BATCHSIZE-num_bg)/RPN_BATCHSIZE, inds_inside.shape[0])) # Get the labels at the original size labels_unmap = (-1) * np.ones(ans_np_flat.shape[0], dtype=np.int64) labels_unmap[inds_inside] = labels # h, w, A labels_unmap_res = labels_unmap.reshape(ans_np.shape[:-1]) anchor_inds = np.column_stack(np.where(labels_unmap_res >= 0)) # These ought to be in the same order anchor_inds_flat = np.where(labels >= 0)[0] anchors = good_ans_flat[anchor_inds_flat] bbox_targets = gt_boxes[anchor_to_gtbox[anchor_inds_flat]] labels = labels[anchor_inds_flat] assert np.all(labels >= 0) # Anchors: [num_used, 4] # Anchor_inds: [num_used, 3] (h, w, A) # bbox_targets: [num_used, 4] # labels: [num_used] return anchors, anchor_inds, bbox_targets, labels ================================================ FILE: lib/fpn/box_intersections_cpu/bbox.c ================================================ /* Generated by Cython 0.25.2 */ /* BEGIN: Cython Metadata { "distutils": { "depends": [] }, "module_name": "bbox" } END: Cython Metadata */ #define PY_SSIZE_T_CLEAN #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) #error Cython requires Python 2.6+ or Python 3.2+. #else #define CYTHON_ABI "0_25_2" #include #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #ifndef __fastcall #define __fastcall #endif #endif #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #ifndef HAVE_LONG_LONG #if PY_VERSION_HEX >= 0x03030000 || (PY_MAJOR_VERSION == 2 && PY_VERSION_HEX >= 0x02070000) #define HAVE_LONG_LONG #endif #endif #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 0 #undef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 0 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #undef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #undef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 1 #undef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 0 #undef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 0 #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #elif defined(PYSTON_VERSION) #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 1 #define CYTHON_COMPILING_IN_CPYTHON 0 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #if PY_MAJOR_VERSION < 3 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #elif !defined(CYTHON_USE_ASYNC_SLOTS) #define CYTHON_USE_ASYNC_SLOTS 1 #endif #if PY_VERSION_HEX < 0x02070000 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #elif !defined(CYTHON_USE_PYLONG_INTERNALS) #define CYTHON_USE_PYLONG_INTERNALS 1 #endif #ifndef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 1 #endif #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #if PY_VERSION_HEX < 0x030300F0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #elif !defined(CYTHON_USE_UNICODE_WRITER) #define CYTHON_USE_UNICODE_WRITER 1 #endif #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #ifndef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 1 #endif #ifndef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 1 #endif #endif #if !defined(CYTHON_FAST_PYCCALL) #define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) #endif #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #undef SHIFT #undef BASE #undef MASK #endif #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) #define Py_OptimizeFlag 0 #endif #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyType_Type #endif #ifndef Py_TPFLAGS_CHECKTYPES #define Py_TPFLAGS_CHECKTYPES 0 #endif #ifndef Py_TPFLAGS_HAVE_INDEX #define Py_TPFLAGS_HAVE_INDEX 0 #endif #ifndef Py_TPFLAGS_HAVE_NEWBUFFER #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #ifndef Py_TPFLAGS_HAVE_FINALIZE #define Py_TPFLAGS_HAVE_FINALIZE 0 #endif #ifndef METH_FASTCALL #define METH_FASTCALL 0x80 typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames); #else #define __Pyx_PyCFunctionFast _PyCFunctionFast #endif #if CYTHON_FAST_PYCCALL #define __Pyx_PyFastCFunction_Check(func)\ ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST))))) #else #define __Pyx_PyFastCFunction_Check(func) 0 #endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ 0 : _PyUnicode_Ready((PyObject *)(op))) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) #else #define CYTHON_PEP393_ENABLED 0 #define PyUnicode_1BYTE_KIND 1 #define PyUnicode_2BYTE_KIND 2 #define PyUnicode_4BYTE_KIND 4 #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) #endif #if CYTHON_COMPILING_IN_PYPY #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) #else #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) #define PyObject_Malloc(s) PyMem_Malloc(s) #define PyObject_Free(p) PyMem_Free(p) #define PyObject_Realloc(p) PyMem_Realloc(p) #endif #if CYTHON_COMPILING_IN_PYSTON #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) #else #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) #endif #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) #else #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif #if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) #define PyObject_ASCII(o) PyObject_Repr(o) #endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject #define PyString_Type PyUnicode_Type #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) #else #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type #define PyInt_Check(op) PyLong_Check(op) #define PyInt_CheckExact(op) PyLong_CheckExact(op) #define PyInt_FromString PyLong_FromString #define PyInt_FromUnicode PyLong_FromUnicode #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #define PyNumber_Int PyNumber_Long #endif #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif #if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY #ifndef PyUnicode_InternFromString #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) #endif #endif #if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong #else #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #else #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif #if CYTHON_USE_ASYNC_SLOTS #if PY_VERSION_HEX >= 0x030500B1 #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) #else typedef struct { unaryfunc am_await; unaryfunc am_aiter; unaryfunc am_anext; } __Pyx_PyAsyncMethodsStruct; #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) #endif #else #define __Pyx_PyType_AsAsync(obj) NULL #endif #ifndef CYTHON_RESTRICT #if defined(__GNUC__) #define CYTHON_RESTRICT __restrict__ #elif defined(_MSC_VER) && _MSC_VER >= 1400 #define CYTHON_RESTRICT __restrict #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_RESTRICT restrict #else #define CYTHON_RESTRICT #endif #endif #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif # elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif #ifndef CYTHON_MAYBE_UNUSED_VAR # if defined(__cplusplus) template void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } # else # define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) # endif #endif #ifndef CYTHON_NCP_UNUSED # if CYTHON_COMPILING_IN_CPYTHON # define CYTHON_NCP_UNUSED # else # define CYTHON_NCP_UNUSED CYTHON_UNUSED # endif #endif #define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) #ifndef CYTHON_INLINE #if defined(__clang__) #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) #elif defined(__GNUC__) #define CYTHON_INLINE __inline__ #elif defined(_MSC_VER) #define CYTHON_INLINE __inline #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_INLINE inline #else #define CYTHON_INLINE #endif #endif #if defined(WIN32) || defined(MS_WINDOWS) #define _USE_MATH_DEFINES #endif #include #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { float value; memset(&value, 0xFF, sizeof(value)); return value; } #endif #if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) #define __Pyx_truncl trunc #else #define __Pyx_truncl truncl #endif #define __PYX_ERR(f_index, lineno, Ln_error) \ { \ __pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; goto Ln_error; \ } #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #define __PYX_HAVE__bbox #define __PYX_HAVE_API__bbox #include #include #include #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" #ifdef _OPENMP #include #endif /* _OPENMP */ #ifdef PYREX_WITHOUT_ASSERTIONS #define CYTHON_WITHOUT_ASSERTIONS #endif typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; #define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 #define __PYX_DEFAULT_STRING_ENCODING "" #define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString #define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #define __Pyx_uchar_cast(c) ((unsigned char)c) #define __Pyx_long_cast(x) ((long)x) #define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ (sizeof(type) < sizeof(Py_ssize_t)) ||\ (sizeof(type) > sizeof(Py_ssize_t) &&\ likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX) &&\ (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ v == (type)PY_SSIZE_T_MIN))) ||\ (sizeof(type) == sizeof(Py_ssize_t) &&\ (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX))) ) #if defined (__cplusplus) && __cplusplus >= 201103L #include #define __Pyx_sst_abs(value) std::abs(value) #elif SIZEOF_INT >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) abs(value) #elif SIZEOF_LONG >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) labs(value) #elif defined (_MSC_VER) && defined (_M_X64) #define __Pyx_sst_abs(value) _abs64(value) #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define __Pyx_sst_abs(value) llabs(value) #elif defined (__GNUC__) #define __Pyx_sst_abs(value) __builtin_llabs(value) #else #define __Pyx_sst_abs(value) ((value<0) ? -value : value) #endif static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); #define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) #define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); #if PY_MAJOR_VERSION < 3 #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #else #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize #endif #define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) #define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) #define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) #define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) #define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) #if PY_MAJOR_VERSION < 3 static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { const Py_UNICODE *u_end = u; while (*u_end++) ; return (size_t)(u_end - u - 1); } #else #define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen #endif #define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) #define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); #if CYTHON_ASSUME_SAFE_MACROS #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) #else #define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) #endif #define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII static int __Pyx_sys_getdefaultencoding_not_ascii; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; PyObject* ascii_chars_u = NULL; PyObject* ascii_chars_b = NULL; const char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; if (strcmp(default_encoding_c, "ascii") == 0) { __Pyx_sys_getdefaultencoding_not_ascii = 0; } else { char ascii_chars[128]; int c; for (c = 0; c < 128; c++) { ascii_chars[c] = c; } __Pyx_sys_getdefaultencoding_not_ascii = 1; ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); if (!ascii_chars_u) goto bad; ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { PyErr_Format( PyExc_ValueError, "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", default_encoding_c); goto bad; } Py_DECREF(ascii_chars_u); Py_DECREF(ascii_chars_b); } Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); Py_XDECREF(ascii_chars_u); Py_XDECREF(ascii_chars_b); return -1; } #endif #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) #else #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT static char* __PYX_DEFAULT_STRING_ENCODING; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); return -1; } #endif #endif /* Test for GCC > 2.95 */ #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ static PyObject *__pyx_m; static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static PyObject *__pyx_empty_unicode; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; /* Header.proto */ #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 #elif defined(_Complex_I) #define CYTHON_CCOMPLEX 1 #else #define CYTHON_CCOMPLEX 0 #endif #endif #if CYTHON_CCOMPLEX #ifdef __cplusplus #include #else #include #endif #endif #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif static const char *__pyx_f[] = { "bbox.pyx", "__init__.pxd", "type.pxd", }; /* BufferFormatStructs.proto */ #define IS_UNSIGNED(type) (((type) -1) > 0) struct __Pyx_StructField_; #define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) typedef struct { const char* name; struct __Pyx_StructField_* fields; size_t size; size_t arraysize[8]; int ndim; char typegroup; char is_unsigned; int flags; } __Pyx_TypeInfo; typedef struct __Pyx_StructField_ { __Pyx_TypeInfo* type; const char* name; size_t offset; } __Pyx_StructField; typedef struct { __Pyx_StructField* field; size_t parent_offset; } __Pyx_BufFmt_StackElem; typedef struct { __Pyx_StructField root; __Pyx_BufFmt_StackElem* head; size_t fmt_offset; size_t new_count, enc_count; size_t struct_alignment; int is_complex; char enc_type; char new_packmode; char enc_packmode; char is_valid_array; } __Pyx_BufFmt_Context; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":725 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t */ typedef npy_int8 __pyx_t_5numpy_int8_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":726 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t */ typedef npy_int16 __pyx_t_5numpy_int16_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":727 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< * ctypedef npy_int64 int64_t * #ctypedef npy_int96 int96_t */ typedef npy_int32 __pyx_t_5numpy_int32_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":728 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< * #ctypedef npy_int96 int96_t * #ctypedef npy_int128 int128_t */ typedef npy_int64 __pyx_t_5numpy_int64_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":732 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":733 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":734 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< * ctypedef npy_uint64 uint64_t * #ctypedef npy_uint96 uint96_t */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":735 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< * #ctypedef npy_uint96 uint96_t * #ctypedef npy_uint128 uint128_t */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":739 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< * ctypedef npy_float64 float64_t * #ctypedef npy_float80 float80_t */ typedef npy_float32 __pyx_t_5numpy_float32_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":740 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< * #ctypedef npy_float80 float80_t * #ctypedef npy_float128 float128_t */ typedef npy_float64 __pyx_t_5numpy_float64_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":749 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t */ typedef npy_long __pyx_t_5numpy_int_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":750 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< * ctypedef npy_longlong longlong_t * */ typedef npy_longlong __pyx_t_5numpy_long_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":751 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< * * ctypedef npy_ulong uint_t */ typedef npy_longlong __pyx_t_5numpy_longlong_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":753 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t */ typedef npy_ulong __pyx_t_5numpy_uint_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":754 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulonglong_t * */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":755 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< * * ctypedef npy_intp intp_t */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":757 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< * ctypedef npy_uintp uintp_t * */ typedef npy_intp __pyx_t_5numpy_intp_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":758 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< * * ctypedef npy_double float_t */ typedef npy_uintp __pyx_t_5numpy_uintp_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":760 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t */ typedef npy_double __pyx_t_5numpy_float_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":761 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< * ctypedef npy_longdouble longdouble_t * */ typedef npy_double __pyx_t_5numpy_double_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":762 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< * * ctypedef npy_cfloat cfloat_t */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; /* "bbox.pyx":13 * * DTYPE = np.float * ctypedef np.float_t DTYPE_t # <<<<<<<<<<<<<< * * def bbox_overlaps(boxes, query_boxes): */ typedef __pyx_t_5numpy_float_t __pyx_t_4bbox_DTYPE_t; /* Declarations.proto */ #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; #else typedef float _Complex __pyx_t_float_complex; #endif #else typedef struct { float real, imag; } __pyx_t_float_complex; #endif static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); /* Declarations.proto */ #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< double > __pyx_t_double_complex; #else typedef double _Complex __pyx_t_double_complex; #endif #else typedef struct { double real, imag; } __pyx_t_double_complex; #endif static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); /*--- Type declarations ---*/ /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":764 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":765 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< * ctypedef npy_clongdouble clongdouble_t * */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":766 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< * * ctypedef npy_cdouble complex_t */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":768 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew1(a): */ typedef npy_cdouble __pyx_t_5numpy_complex_t; /* --- Runtime support code (head) --- */ /* Refnanny.proto */ #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); void (*DECREF)(void*, PyObject*, int); void (*GOTREF)(void*, PyObject*, int); void (*GIVEREF)(void*, PyObject*, int); void* (*SetupContext)(const char*, int, const char*); void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #ifdef WITH_THREAD #define __Pyx_RefNannySetupContext(name, acquire_gil)\ if (acquire_gil) {\ PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ PyGILState_Release(__pyx_gilstate_save);\ } else {\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ } #else #define __Pyx_RefNannySetupContext(name, acquire_gil)\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) #endif #define __Pyx_RefNannyFinishContext()\ __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) #define __Pyx_GOTREF(r) #define __Pyx_GIVEREF(r) #define __Pyx_XINCREF(r) Py_XINCREF(r) #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif #define __Pyx_XDECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_XDECREF(tmp);\ } while (0) #define __Pyx_DECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_DECREF(tmp);\ } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) /* PyObjectGetAttrStr.proto */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro)) return tp->tp_getattro(obj, attr_name); #if PY_MAJOR_VERSION < 3 if (likely(tp->tp_getattr)) return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); #endif return PyObject_GetAttr(obj, attr_name); } #else #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif /* GetBuiltinName.proto */ static PyObject *__Pyx_GetBuiltinName(PyObject *name); /* RaiseArgTupleInvalid.proto */ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /* RaiseDoubleKeywords.proto */ static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /* ParseKeywords.proto */ static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ const char* function_name); /* GetModuleGlobalName.proto */ static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /* PyObjectCall.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); #else #define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) #endif /* ExtTypeTest.proto */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /* BufferFormatCheck.proto */ static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts); static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type); // PROTO /* PyThreadStateGet.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; #define __Pyx_PyThreadState_assign __pyx_tstate = PyThreadState_GET(); #else #define __Pyx_PyThreadState_declare #define __Pyx_PyThreadState_assign #endif /* PyErrFetchRestore.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) #define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else #define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) #endif /* BufferIndexError.proto */ static void __Pyx_RaiseBufferIndexError(int axis); #define __Pyx_BufPtrStrided2d(type, buf, i0, s0, i1, s1) (type)((char*)buf + i0 * s0 + i1 * s1) /* RaiseException.proto */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /* DictGetItem.proto */ #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { PyObject *value; value = PyDict_GetItemWithError(d, key); if (unlikely(!value)) { if (!PyErr_Occurred()) { PyObject* args = PyTuple_Pack(1, key); if (likely(args)) PyErr_SetObject(PyExc_KeyError, args); Py_XDECREF(args); } return NULL; } Py_INCREF(value); return value; } #else #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) #endif /* RaiseTooManyValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); /* RaiseNeedMoreValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); /* RaiseNoneIterError.proto */ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); /* SaveResetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); #else #define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) #define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) #endif /* PyErrExceptionMatches.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); #else #define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) #endif /* GetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); #endif /* Import.proto */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /* CodeObjectCache.proto */ typedef struct { PyCodeObject* code_object; int code_line; } __Pyx_CodeObjectCacheEntry; struct __Pyx_CodeObjectCache { int count; int max_count; __Pyx_CodeObjectCacheEntry* entries; }; static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); static PyCodeObject *__pyx_find_code_object(int code_line); static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); /* AddTraceback.proto */ static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); /* BufferStructDeclare.proto */ typedef struct { Py_ssize_t shape, strides, suboffsets; } __Pyx_Buf_DimInfo; typedef struct { size_t refcount; Py_buffer pybuffer; } __Pyx_Buffer; typedef struct { __Pyx_Buffer *rcbuffer; char *data; __Pyx_Buf_DimInfo diminfo[8]; } __Pyx_LocalBuf_ND; #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); static void __Pyx_ReleaseBuffer(Py_buffer *view); #else #define __Pyx_GetBuffer PyObject_GetBuffer #define __Pyx_ReleaseBuffer PyBuffer_Release #endif /* None.proto */ static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value); /* RealImag.proto */ #if CYTHON_CCOMPLEX #ifdef __cplusplus #define __Pyx_CREAL(z) ((z).real()) #define __Pyx_CIMAG(z) ((z).imag()) #else #define __Pyx_CREAL(z) (__real__(z)) #define __Pyx_CIMAG(z) (__imag__(z)) #endif #else #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif #if defined(__cplusplus) && CYTHON_CCOMPLEX\ && (defined(_WIN32) || defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 5 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4 )) || __cplusplus >= 201103) #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) #endif /* Arithmetic.proto */ #if CYTHON_CCOMPLEX #define __Pyx_c_eq_float(a, b) ((a)==(b)) #define __Pyx_c_sum_float(a, b) ((a)+(b)) #define __Pyx_c_diff_float(a, b) ((a)-(b)) #define __Pyx_c_prod_float(a, b) ((a)*(b)) #define __Pyx_c_quot_float(a, b) ((a)/(b)) #define __Pyx_c_neg_float(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zero_float(z) ((z)==(float)0) #define __Pyx_c_conj_float(z) (::std::conj(z)) #if 1 #define __Pyx_c_abs_float(z) (::std::abs(z)) #define __Pyx_c_pow_float(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zero_float(z) ((z)==0) #define __Pyx_c_conj_float(z) (conjf(z)) #if 1 #define __Pyx_c_abs_float(z) (cabsf(z)) #define __Pyx_c_pow_float(a, b) (cpowf(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex); static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex); #if 1 static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex, __pyx_t_float_complex); #endif #endif /* Arithmetic.proto */ #if CYTHON_CCOMPLEX #define __Pyx_c_eq_double(a, b) ((a)==(b)) #define __Pyx_c_sum_double(a, b) ((a)+(b)) #define __Pyx_c_diff_double(a, b) ((a)-(b)) #define __Pyx_c_prod_double(a, b) ((a)*(b)) #define __Pyx_c_quot_double(a, b) ((a)/(b)) #define __Pyx_c_neg_double(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zero_double(z) ((z)==(double)0) #define __Pyx_c_conj_double(z) (::std::conj(z)) #if 1 #define __Pyx_c_abs_double(z) (::std::abs(z)) #define __Pyx_c_pow_double(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zero_double(z) ((z)==0) #define __Pyx_c_conj_double(z) (conj(z)) #if 1 #define __Pyx_c_abs_double(z) (cabs(z)) #define __Pyx_c_pow_double(a, b) (cpow(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex); static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex); #if 1 static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex, __pyx_t_double_complex); #endif #endif /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_enum__NPY_TYPES(enum NPY_TYPES value); /* CIntFromPy.proto */ static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); /* CIntFromPy.proto */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); /* CheckBinaryVersion.proto */ static int __Pyx_check_binary_version(void); /* PyIdentifierFromString.proto */ #if !defined(__Pyx_PyIdentifier_FromString) #if PY_MAJOR_VERSION < 3 #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) #else #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) #endif #endif /* ModuleImport.proto */ static PyObject *__Pyx_ImportModule(const char *name); /* TypeImport.proto */ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /* InitStrings.proto */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /* Module declarations from 'cython' */ /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'libc.string' */ /* Module declarations from 'libc.stdio' */ /* Module declarations from '__builtin__' */ /* Module declarations from 'cpython.type' */ static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; /* Module declarations from 'cpython' */ /* Module declarations from 'cpython.object' */ /* Module declarations from 'cpython.ref' */ /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ /* Module declarations from 'numpy' */ static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ /* Module declarations from 'bbox' */ static PyArrayObject *__pyx_f_4bbox_bbox_overlaps_c(PyArrayObject *, PyArrayObject *); /*proto*/ static PyArrayObject *__pyx_f_4bbox_bbox_intersections_c(PyArrayObject *, PyArrayObject *); /*proto*/ static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_4bbox_DTYPE_t = { "DTYPE_t", NULL, sizeof(__pyx_t_4bbox_DTYPE_t), { 0 }, 0, 'R', 0, 0 }; #define __Pyx_MODULE_NAME "bbox" int __pyx_module_is_main_bbox = 0; /* Implementation of 'bbox' */ static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_RuntimeError; static PyObject *__pyx_builtin_ImportError; static const char __pyx_k_np[] = "np"; static const char __pyx_k_bbox[] = "bbox"; static const char __pyx_k_main[] = "__main__"; static const char __pyx_k_test[] = "__test__"; static const char __pyx_k_DTYPE[] = "DTYPE"; static const char __pyx_k_boxes[] = "boxes"; static const char __pyx_k_dtype[] = "dtype"; static const char __pyx_k_float[] = "float"; static const char __pyx_k_numpy[] = "numpy"; static const char __pyx_k_range[] = "range"; static const char __pyx_k_zeros[] = "zeros"; static const char __pyx_k_import[] = "__import__"; static const char __pyx_k_ValueError[] = "ValueError"; static const char __pyx_k_ImportError[] = "ImportError"; static const char __pyx_k_query_boxes[] = "query_boxes"; static const char __pyx_k_RuntimeError[] = "RuntimeError"; static const char __pyx_k_boxes_contig[] = "boxes_contig"; static const char __pyx_k_query_contig[] = "query_contig"; static const char __pyx_k_bbox_overlaps[] = "bbox_overlaps"; static const char __pyx_k_ascontiguousarray[] = "ascontiguousarray"; static const char __pyx_k_bbox_intersections[] = "bbox_intersections"; static const char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; static const char __pyx_k_Users_rowanz_code_scene_graph_l[] = "/Users/rowanz/code/scene-graph/lib/fpn/box_intersections_cpu/bbox.pyx"; static const char __pyx_k_numpy_core_multiarray_failed_to[] = "numpy.core.multiarray failed to import"; static const char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; static const char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; static const char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; static const char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; static const char __pyx_k_numpy_core_umath_failed_to_impor[] = "numpy.core.umath failed to import"; static const char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; static PyObject *__pyx_n_s_DTYPE; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; static PyObject *__pyx_n_s_ImportError; static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; static PyObject *__pyx_n_s_RuntimeError; static PyObject *__pyx_kp_s_Users_rowanz_code_scene_graph_l; static PyObject *__pyx_n_s_ValueError; static PyObject *__pyx_n_s_ascontiguousarray; static PyObject *__pyx_n_s_bbox; static PyObject *__pyx_n_s_bbox_intersections; static PyObject *__pyx_n_s_bbox_overlaps; static PyObject *__pyx_n_s_boxes; static PyObject *__pyx_n_s_boxes_contig; static PyObject *__pyx_n_s_dtype; static PyObject *__pyx_n_s_float; static PyObject *__pyx_n_s_import; static PyObject *__pyx_n_s_main; static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; static PyObject *__pyx_n_s_np; static PyObject *__pyx_n_s_numpy; static PyObject *__pyx_kp_s_numpy_core_multiarray_failed_to; static PyObject *__pyx_kp_s_numpy_core_umath_failed_to_impor; static PyObject *__pyx_n_s_query_boxes; static PyObject *__pyx_n_s_query_contig; static PyObject *__pyx_n_s_range; static PyObject *__pyx_n_s_test; static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; static PyObject *__pyx_n_s_zeros; static PyObject *__pyx_pf_4bbox_bbox_overlaps(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_boxes, PyObject *__pyx_v_query_boxes); /* proto */ static PyObject *__pyx_pf_4bbox_2bbox_intersections(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_boxes, PyObject *__pyx_v_query_boxes); /* proto */ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ static PyObject *__pyx_tuple_; static PyObject *__pyx_tuple__2; static PyObject *__pyx_tuple__3; static PyObject *__pyx_tuple__4; static PyObject *__pyx_tuple__5; static PyObject *__pyx_tuple__6; static PyObject *__pyx_tuple__7; static PyObject *__pyx_tuple__8; static PyObject *__pyx_tuple__9; static PyObject *__pyx_tuple__10; static PyObject *__pyx_tuple__12; static PyObject *__pyx_codeobj__11; static PyObject *__pyx_codeobj__13; /* "bbox.pyx":15 * ctypedef np.float_t DTYPE_t * * def bbox_overlaps(boxes, query_boxes): # <<<<<<<<<<<<<< * cdef np.ndarray[DTYPE_t, ndim=2] boxes_contig = np.ascontiguousarray(boxes, dtype=DTYPE) * cdef np.ndarray[DTYPE_t, ndim=2] query_contig = np.ascontiguousarray(query_boxes, dtype=DTYPE) */ /* Python wrapper */ static PyObject *__pyx_pw_4bbox_1bbox_overlaps(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyMethodDef __pyx_mdef_4bbox_1bbox_overlaps = {"bbox_overlaps", (PyCFunction)__pyx_pw_4bbox_1bbox_overlaps, METH_VARARGS|METH_KEYWORDS, 0}; static PyObject *__pyx_pw_4bbox_1bbox_overlaps(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_boxes = 0; PyObject *__pyx_v_query_boxes = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("bbox_overlaps (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_boxes,&__pyx_n_s_query_boxes,0}; PyObject* values[2] = {0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_boxes)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_query_boxes)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bbox_overlaps", 1, 2, 2, 1); __PYX_ERR(0, 15, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "bbox_overlaps") < 0)) __PYX_ERR(0, 15, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } __pyx_v_boxes = values[0]; __pyx_v_query_boxes = values[1]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("bbox_overlaps", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 15, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("bbox.bbox_overlaps", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_4bbox_bbox_overlaps(__pyx_self, __pyx_v_boxes, __pyx_v_query_boxes); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_4bbox_bbox_overlaps(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_boxes, PyObject *__pyx_v_query_boxes) { PyArrayObject *__pyx_v_boxes_contig = 0; PyArrayObject *__pyx_v_query_contig = 0; __Pyx_LocalBuf_ND __pyx_pybuffernd_boxes_contig; __Pyx_Buffer __pyx_pybuffer_boxes_contig; __Pyx_LocalBuf_ND __pyx_pybuffernd_query_contig; __Pyx_Buffer __pyx_pybuffer_query_contig; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyArrayObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; __Pyx_RefNannySetupContext("bbox_overlaps", 0); __pyx_pybuffer_boxes_contig.pybuffer.buf = NULL; __pyx_pybuffer_boxes_contig.refcount = 0; __pyx_pybuffernd_boxes_contig.data = NULL; __pyx_pybuffernd_boxes_contig.rcbuffer = &__pyx_pybuffer_boxes_contig; __pyx_pybuffer_query_contig.pybuffer.buf = NULL; __pyx_pybuffer_query_contig.refcount = 0; __pyx_pybuffernd_query_contig.data = NULL; __pyx_pybuffernd_query_contig.rcbuffer = &__pyx_pybuffer_query_contig; /* "bbox.pyx":16 * * def bbox_overlaps(boxes, query_boxes): * cdef np.ndarray[DTYPE_t, ndim=2] boxes_contig = np.ascontiguousarray(boxes, dtype=DTYPE) # <<<<<<<<<<<<<< * cdef np.ndarray[DTYPE_t, ndim=2] query_contig = np.ascontiguousarray(query_boxes, dtype=DTYPE) * */ __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 16, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ascontiguousarray); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 16, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 16, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(__pyx_v_boxes); __Pyx_GIVEREF(__pyx_v_boxes); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_boxes); __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 16, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 16, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_4) < 0) __PYX_ERR(0, 16, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 16, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 16, __pyx_L1_error) __pyx_t_5 = ((PyArrayObject *)__pyx_t_4); { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_boxes_contig.rcbuffer->pybuffer, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_nn___pyx_t_4bbox_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) { __pyx_v_boxes_contig = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_boxes_contig.rcbuffer->pybuffer.buf = NULL; __PYX_ERR(0, 16, __pyx_L1_error) } else {__pyx_pybuffernd_boxes_contig.diminfo[0].strides = __pyx_pybuffernd_boxes_contig.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_boxes_contig.diminfo[0].shape = __pyx_pybuffernd_boxes_contig.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_boxes_contig.diminfo[1].strides = __pyx_pybuffernd_boxes_contig.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_boxes_contig.diminfo[1].shape = __pyx_pybuffernd_boxes_contig.rcbuffer->pybuffer.shape[1]; } } __pyx_t_5 = 0; __pyx_v_boxes_contig = ((PyArrayObject *)__pyx_t_4); __pyx_t_4 = 0; /* "bbox.pyx":17 * def bbox_overlaps(boxes, query_boxes): * cdef np.ndarray[DTYPE_t, ndim=2] boxes_contig = np.ascontiguousarray(boxes, dtype=DTYPE) * cdef np.ndarray[DTYPE_t, ndim=2] query_contig = np.ascontiguousarray(query_boxes, dtype=DTYPE) # <<<<<<<<<<<<<< * * return bbox_overlaps_c(boxes_contig, query_contig) */ __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 17, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_ascontiguousarray); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 17, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 17, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_INCREF(__pyx_v_query_boxes); __Pyx_GIVEREF(__pyx_v_query_boxes); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_query_boxes); __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 17, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 17, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_2) < 0) __PYX_ERR(0, 17, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 17, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 17, __pyx_L1_error) __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_query_contig.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_4bbox_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) { __pyx_v_query_contig = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_query_contig.rcbuffer->pybuffer.buf = NULL; __PYX_ERR(0, 17, __pyx_L1_error) } else {__pyx_pybuffernd_query_contig.diminfo[0].strides = __pyx_pybuffernd_query_contig.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_query_contig.diminfo[0].shape = __pyx_pybuffernd_query_contig.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_query_contig.diminfo[1].strides = __pyx_pybuffernd_query_contig.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_query_contig.diminfo[1].shape = __pyx_pybuffernd_query_contig.rcbuffer->pybuffer.shape[1]; } } __pyx_t_6 = 0; __pyx_v_query_contig = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "bbox.pyx":19 * cdef np.ndarray[DTYPE_t, ndim=2] query_contig = np.ascontiguousarray(query_boxes, dtype=DTYPE) * * return bbox_overlaps_c(boxes_contig, query_contig) # <<<<<<<<<<<<<< * * cdef np.ndarray[DTYPE_t, ndim=2] bbox_overlaps_c( */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = ((PyObject *)__pyx_f_4bbox_bbox_overlaps_c(((PyArrayObject *)__pyx_v_boxes_contig), ((PyArrayObject *)__pyx_v_query_contig))); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 19, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "bbox.pyx":15 * ctypedef np.float_t DTYPE_t * * def bbox_overlaps(boxes, query_boxes): # <<<<<<<<<<<<<< * cdef np.ndarray[DTYPE_t, ndim=2] boxes_contig = np.ascontiguousarray(boxes, dtype=DTYPE) * cdef np.ndarray[DTYPE_t, ndim=2] query_contig = np.ascontiguousarray(query_boxes, dtype=DTYPE) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_boxes_contig.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_query_contig.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("bbox.bbox_overlaps", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_boxes_contig.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_query_contig.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_boxes_contig); __Pyx_XDECREF((PyObject *)__pyx_v_query_contig); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "bbox.pyx":21 * return bbox_overlaps_c(boxes_contig, query_contig) * * cdef np.ndarray[DTYPE_t, ndim=2] bbox_overlaps_c( # <<<<<<<<<<<<<< * np.ndarray[DTYPE_t, ndim=2] boxes, * np.ndarray[DTYPE_t, ndim=2] query_boxes): */ static PyArrayObject *__pyx_f_4bbox_bbox_overlaps_c(PyArrayObject *__pyx_v_boxes, PyArrayObject *__pyx_v_query_boxes) { unsigned int __pyx_v_N; unsigned int __pyx_v_K; PyArrayObject *__pyx_v_overlaps = 0; __pyx_t_4bbox_DTYPE_t __pyx_v_iw; __pyx_t_4bbox_DTYPE_t __pyx_v_ih; __pyx_t_4bbox_DTYPE_t __pyx_v_box_area; __pyx_t_4bbox_DTYPE_t __pyx_v_ua; unsigned int __pyx_v_k; unsigned int __pyx_v_n; __Pyx_LocalBuf_ND __pyx_pybuffernd_boxes; __Pyx_Buffer __pyx_pybuffer_boxes; __Pyx_LocalBuf_ND __pyx_pybuffernd_overlaps; __Pyx_Buffer __pyx_pybuffer_overlaps; __Pyx_LocalBuf_ND __pyx_pybuffernd_query_boxes; __Pyx_Buffer __pyx_pybuffer_query_boxes; PyArrayObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyArrayObject *__pyx_t_5 = NULL; unsigned int __pyx_t_6; unsigned int __pyx_t_7; size_t __pyx_t_8; Py_ssize_t __pyx_t_9; int __pyx_t_10; size_t __pyx_t_11; Py_ssize_t __pyx_t_12; size_t __pyx_t_13; Py_ssize_t __pyx_t_14; size_t __pyx_t_15; Py_ssize_t __pyx_t_16; unsigned int __pyx_t_17; unsigned int __pyx_t_18; size_t __pyx_t_19; Py_ssize_t __pyx_t_20; __pyx_t_4bbox_DTYPE_t __pyx_t_21; size_t __pyx_t_22; Py_ssize_t __pyx_t_23; __pyx_t_4bbox_DTYPE_t __pyx_t_24; __pyx_t_4bbox_DTYPE_t __pyx_t_25; size_t __pyx_t_26; Py_ssize_t __pyx_t_27; size_t __pyx_t_28; Py_ssize_t __pyx_t_29; __pyx_t_4bbox_DTYPE_t __pyx_t_30; int __pyx_t_31; size_t __pyx_t_32; Py_ssize_t __pyx_t_33; size_t __pyx_t_34; Py_ssize_t __pyx_t_35; size_t __pyx_t_36; Py_ssize_t __pyx_t_37; size_t __pyx_t_38; Py_ssize_t __pyx_t_39; size_t __pyx_t_40; Py_ssize_t __pyx_t_41; size_t __pyx_t_42; Py_ssize_t __pyx_t_43; size_t __pyx_t_44; Py_ssize_t __pyx_t_45; size_t __pyx_t_46; Py_ssize_t __pyx_t_47; size_t __pyx_t_48; size_t __pyx_t_49; __Pyx_RefNannySetupContext("bbox_overlaps_c", 0); __pyx_pybuffer_overlaps.pybuffer.buf = NULL; __pyx_pybuffer_overlaps.refcount = 0; __pyx_pybuffernd_overlaps.data = NULL; __pyx_pybuffernd_overlaps.rcbuffer = &__pyx_pybuffer_overlaps; __pyx_pybuffer_boxes.pybuffer.buf = NULL; __pyx_pybuffer_boxes.refcount = 0; __pyx_pybuffernd_boxes.data = NULL; __pyx_pybuffernd_boxes.rcbuffer = &__pyx_pybuffer_boxes; __pyx_pybuffer_query_boxes.pybuffer.buf = NULL; __pyx_pybuffer_query_boxes.refcount = 0; __pyx_pybuffernd_query_boxes.data = NULL; __pyx_pybuffernd_query_boxes.rcbuffer = &__pyx_pybuffer_query_boxes; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_boxes.rcbuffer->pybuffer, (PyObject*)__pyx_v_boxes, &__Pyx_TypeInfo_nn___pyx_t_4bbox_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) __PYX_ERR(0, 21, __pyx_L1_error) } __pyx_pybuffernd_boxes.diminfo[0].strides = __pyx_pybuffernd_boxes.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_boxes.diminfo[0].shape = __pyx_pybuffernd_boxes.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_boxes.diminfo[1].strides = __pyx_pybuffernd_boxes.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_boxes.diminfo[1].shape = __pyx_pybuffernd_boxes.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_query_boxes.rcbuffer->pybuffer, (PyObject*)__pyx_v_query_boxes, &__Pyx_TypeInfo_nn___pyx_t_4bbox_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) __PYX_ERR(0, 21, __pyx_L1_error) } __pyx_pybuffernd_query_boxes.diminfo[0].strides = __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_query_boxes.diminfo[0].shape = __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_query_boxes.diminfo[1].strides = __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_query_boxes.diminfo[1].shape = __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.shape[1]; /* "bbox.pyx":33 * overlaps: (N, K) ndarray of overlap between boxes and query_boxes * """ * cdef unsigned int N = boxes.shape[0] # <<<<<<<<<<<<<< * cdef unsigned int K = query_boxes.shape[0] * cdef np.ndarray[DTYPE_t, ndim=2] overlaps = np.zeros((N, K), dtype=DTYPE) */ __pyx_v_N = (__pyx_v_boxes->dimensions[0]); /* "bbox.pyx":34 * """ * cdef unsigned int N = boxes.shape[0] * cdef unsigned int K = query_boxes.shape[0] # <<<<<<<<<<<<<< * cdef np.ndarray[DTYPE_t, ndim=2] overlaps = np.zeros((N, K), dtype=DTYPE) * cdef DTYPE_t iw, ih, box_area */ __pyx_v_K = (__pyx_v_query_boxes->dimensions[0]); /* "bbox.pyx":35 * cdef unsigned int N = boxes.shape[0] * cdef unsigned int K = query_boxes.shape[0] * cdef np.ndarray[DTYPE_t, ndim=2] overlaps = np.zeros((N, K), dtype=DTYPE) # <<<<<<<<<<<<<< * cdef DTYPE_t iw, ih, box_area * cdef DTYPE_t ua */ __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 35, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 35, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyInt_From_unsigned_int(__pyx_v_N); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 35, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = __Pyx_PyInt_From_unsigned_int(__pyx_v_K); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 35, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 35, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); __pyx_t_1 = 0; __pyx_t_3 = 0; __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 35, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 35, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 35, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_1) < 0) __PYX_ERR(0, 35, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 35, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 35, __pyx_L1_error) __pyx_t_5 = ((PyArrayObject *)__pyx_t_1); { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_overlaps.rcbuffer->pybuffer, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_nn___pyx_t_4bbox_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) { __pyx_v_overlaps = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_overlaps.rcbuffer->pybuffer.buf = NULL; __PYX_ERR(0, 35, __pyx_L1_error) } else {__pyx_pybuffernd_overlaps.diminfo[0].strides = __pyx_pybuffernd_overlaps.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_overlaps.diminfo[0].shape = __pyx_pybuffernd_overlaps.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_overlaps.diminfo[1].strides = __pyx_pybuffernd_overlaps.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_overlaps.diminfo[1].shape = __pyx_pybuffernd_overlaps.rcbuffer->pybuffer.shape[1]; } } __pyx_t_5 = 0; __pyx_v_overlaps = ((PyArrayObject *)__pyx_t_1); __pyx_t_1 = 0; /* "bbox.pyx":39 * cdef DTYPE_t ua * cdef unsigned int k, n * for k in range(K): # <<<<<<<<<<<<<< * box_area = ( * (query_boxes[k, 2] - query_boxes[k, 0] + 1) * */ __pyx_t_6 = __pyx_v_K; for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { __pyx_v_k = __pyx_t_7; /* "bbox.pyx":41 * for k in range(K): * box_area = ( * (query_boxes[k, 2] - query_boxes[k, 0] + 1) * # <<<<<<<<<<<<<< * (query_boxes[k, 3] - query_boxes[k, 1] + 1) * ) */ __pyx_t_8 = __pyx_v_k; __pyx_t_9 = 2; __pyx_t_10 = -1; if (unlikely(__pyx_t_8 >= (size_t)__pyx_pybuffernd_query_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_9 < 0) { __pyx_t_9 += __pyx_pybuffernd_query_boxes.diminfo[1].shape; if (unlikely(__pyx_t_9 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_9 >= __pyx_pybuffernd_query_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 41, __pyx_L1_error) } __pyx_t_11 = __pyx_v_k; __pyx_t_12 = 0; __pyx_t_10 = -1; if (unlikely(__pyx_t_11 >= (size_t)__pyx_pybuffernd_query_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_12 < 0) { __pyx_t_12 += __pyx_pybuffernd_query_boxes.diminfo[1].shape; if (unlikely(__pyx_t_12 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_12 >= __pyx_pybuffernd_query_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 41, __pyx_L1_error) } /* "bbox.pyx":42 * box_area = ( * (query_boxes[k, 2] - query_boxes[k, 0] + 1) * * (query_boxes[k, 3] - query_boxes[k, 1] + 1) # <<<<<<<<<<<<<< * ) * for n in range(N): */ __pyx_t_13 = __pyx_v_k; __pyx_t_14 = 3; __pyx_t_10 = -1; if (unlikely(__pyx_t_13 >= (size_t)__pyx_pybuffernd_query_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_14 < 0) { __pyx_t_14 += __pyx_pybuffernd_query_boxes.diminfo[1].shape; if (unlikely(__pyx_t_14 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_14 >= __pyx_pybuffernd_query_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 42, __pyx_L1_error) } __pyx_t_15 = __pyx_v_k; __pyx_t_16 = 1; __pyx_t_10 = -1; if (unlikely(__pyx_t_15 >= (size_t)__pyx_pybuffernd_query_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_16 < 0) { __pyx_t_16 += __pyx_pybuffernd_query_boxes.diminfo[1].shape; if (unlikely(__pyx_t_16 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_16 >= __pyx_pybuffernd_query_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 42, __pyx_L1_error) } /* "bbox.pyx":41 * for k in range(K): * box_area = ( * (query_boxes[k, 2] - query_boxes[k, 0] + 1) * # <<<<<<<<<<<<<< * (query_boxes[k, 3] - query_boxes[k, 1] + 1) * ) */ __pyx_v_box_area = ((((*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_query_boxes.diminfo[0].strides, __pyx_t_9, __pyx_pybuffernd_query_boxes.diminfo[1].strides)) - (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_query_boxes.diminfo[0].strides, __pyx_t_12, __pyx_pybuffernd_query_boxes.diminfo[1].strides))) + 1.0) * (((*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_query_boxes.diminfo[0].strides, __pyx_t_14, __pyx_pybuffernd_query_boxes.diminfo[1].strides)) - (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_query_boxes.diminfo[0].strides, __pyx_t_16, __pyx_pybuffernd_query_boxes.diminfo[1].strides))) + 1.0)); /* "bbox.pyx":44 * (query_boxes[k, 3] - query_boxes[k, 1] + 1) * ) * for n in range(N): # <<<<<<<<<<<<<< * iw = ( * min(boxes[n, 2], query_boxes[k, 2]) - */ __pyx_t_17 = __pyx_v_N; for (__pyx_t_18 = 0; __pyx_t_18 < __pyx_t_17; __pyx_t_18+=1) { __pyx_v_n = __pyx_t_18; /* "bbox.pyx":46 * for n in range(N): * iw = ( * min(boxes[n, 2], query_boxes[k, 2]) - # <<<<<<<<<<<<<< * max(boxes[n, 0], query_boxes[k, 0]) + 1 * ) */ __pyx_t_19 = __pyx_v_k; __pyx_t_20 = 2; __pyx_t_10 = -1; if (unlikely(__pyx_t_19 >= (size_t)__pyx_pybuffernd_query_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_20 < 0) { __pyx_t_20 += __pyx_pybuffernd_query_boxes.diminfo[1].shape; if (unlikely(__pyx_t_20 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_20 >= __pyx_pybuffernd_query_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 46, __pyx_L1_error) } __pyx_t_21 = (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_query_boxes.diminfo[0].strides, __pyx_t_20, __pyx_pybuffernd_query_boxes.diminfo[1].strides)); __pyx_t_22 = __pyx_v_n; __pyx_t_23 = 2; __pyx_t_10 = -1; if (unlikely(__pyx_t_22 >= (size_t)__pyx_pybuffernd_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_23 < 0) { __pyx_t_23 += __pyx_pybuffernd_boxes.diminfo[1].shape; if (unlikely(__pyx_t_23 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_23 >= __pyx_pybuffernd_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 46, __pyx_L1_error) } __pyx_t_24 = (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_boxes.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_boxes.diminfo[0].strides, __pyx_t_23, __pyx_pybuffernd_boxes.diminfo[1].strides)); if (((__pyx_t_21 < __pyx_t_24) != 0)) { __pyx_t_25 = __pyx_t_21; } else { __pyx_t_25 = __pyx_t_24; } /* "bbox.pyx":47 * iw = ( * min(boxes[n, 2], query_boxes[k, 2]) - * max(boxes[n, 0], query_boxes[k, 0]) + 1 # <<<<<<<<<<<<<< * ) * if iw > 0: */ __pyx_t_26 = __pyx_v_k; __pyx_t_27 = 0; __pyx_t_10 = -1; if (unlikely(__pyx_t_26 >= (size_t)__pyx_pybuffernd_query_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_27 < 0) { __pyx_t_27 += __pyx_pybuffernd_query_boxes.diminfo[1].shape; if (unlikely(__pyx_t_27 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_27 >= __pyx_pybuffernd_query_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 47, __pyx_L1_error) } __pyx_t_21 = (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.buf, __pyx_t_26, __pyx_pybuffernd_query_boxes.diminfo[0].strides, __pyx_t_27, __pyx_pybuffernd_query_boxes.diminfo[1].strides)); __pyx_t_28 = __pyx_v_n; __pyx_t_29 = 0; __pyx_t_10 = -1; if (unlikely(__pyx_t_28 >= (size_t)__pyx_pybuffernd_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_29 < 0) { __pyx_t_29 += __pyx_pybuffernd_boxes.diminfo[1].shape; if (unlikely(__pyx_t_29 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_29 >= __pyx_pybuffernd_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 47, __pyx_L1_error) } __pyx_t_24 = (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_boxes.rcbuffer->pybuffer.buf, __pyx_t_28, __pyx_pybuffernd_boxes.diminfo[0].strides, __pyx_t_29, __pyx_pybuffernd_boxes.diminfo[1].strides)); if (((__pyx_t_21 > __pyx_t_24) != 0)) { __pyx_t_30 = __pyx_t_21; } else { __pyx_t_30 = __pyx_t_24; } /* "bbox.pyx":46 * for n in range(N): * iw = ( * min(boxes[n, 2], query_boxes[k, 2]) - # <<<<<<<<<<<<<< * max(boxes[n, 0], query_boxes[k, 0]) + 1 * ) */ __pyx_v_iw = ((__pyx_t_25 - __pyx_t_30) + 1.0); /* "bbox.pyx":49 * max(boxes[n, 0], query_boxes[k, 0]) + 1 * ) * if iw > 0: # <<<<<<<<<<<<<< * ih = ( * min(boxes[n, 3], query_boxes[k, 3]) - */ __pyx_t_31 = ((__pyx_v_iw > 0.0) != 0); if (__pyx_t_31) { /* "bbox.pyx":51 * if iw > 0: * ih = ( * min(boxes[n, 3], query_boxes[k, 3]) - # <<<<<<<<<<<<<< * max(boxes[n, 1], query_boxes[k, 1]) + 1 * ) */ __pyx_t_32 = __pyx_v_k; __pyx_t_33 = 3; __pyx_t_10 = -1; if (unlikely(__pyx_t_32 >= (size_t)__pyx_pybuffernd_query_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_33 < 0) { __pyx_t_33 += __pyx_pybuffernd_query_boxes.diminfo[1].shape; if (unlikely(__pyx_t_33 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_33 >= __pyx_pybuffernd_query_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 51, __pyx_L1_error) } __pyx_t_30 = (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.buf, __pyx_t_32, __pyx_pybuffernd_query_boxes.diminfo[0].strides, __pyx_t_33, __pyx_pybuffernd_query_boxes.diminfo[1].strides)); __pyx_t_34 = __pyx_v_n; __pyx_t_35 = 3; __pyx_t_10 = -1; if (unlikely(__pyx_t_34 >= (size_t)__pyx_pybuffernd_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_35 < 0) { __pyx_t_35 += __pyx_pybuffernd_boxes.diminfo[1].shape; if (unlikely(__pyx_t_35 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_35 >= __pyx_pybuffernd_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 51, __pyx_L1_error) } __pyx_t_25 = (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_boxes.rcbuffer->pybuffer.buf, __pyx_t_34, __pyx_pybuffernd_boxes.diminfo[0].strides, __pyx_t_35, __pyx_pybuffernd_boxes.diminfo[1].strides)); if (((__pyx_t_30 < __pyx_t_25) != 0)) { __pyx_t_21 = __pyx_t_30; } else { __pyx_t_21 = __pyx_t_25; } /* "bbox.pyx":52 * ih = ( * min(boxes[n, 3], query_boxes[k, 3]) - * max(boxes[n, 1], query_boxes[k, 1]) + 1 # <<<<<<<<<<<<<< * ) * if ih > 0: */ __pyx_t_36 = __pyx_v_k; __pyx_t_37 = 1; __pyx_t_10 = -1; if (unlikely(__pyx_t_36 >= (size_t)__pyx_pybuffernd_query_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_37 < 0) { __pyx_t_37 += __pyx_pybuffernd_query_boxes.diminfo[1].shape; if (unlikely(__pyx_t_37 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_37 >= __pyx_pybuffernd_query_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 52, __pyx_L1_error) } __pyx_t_30 = (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.buf, __pyx_t_36, __pyx_pybuffernd_query_boxes.diminfo[0].strides, __pyx_t_37, __pyx_pybuffernd_query_boxes.diminfo[1].strides)); __pyx_t_38 = __pyx_v_n; __pyx_t_39 = 1; __pyx_t_10 = -1; if (unlikely(__pyx_t_38 >= (size_t)__pyx_pybuffernd_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_39 < 0) { __pyx_t_39 += __pyx_pybuffernd_boxes.diminfo[1].shape; if (unlikely(__pyx_t_39 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_39 >= __pyx_pybuffernd_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 52, __pyx_L1_error) } __pyx_t_25 = (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_boxes.rcbuffer->pybuffer.buf, __pyx_t_38, __pyx_pybuffernd_boxes.diminfo[0].strides, __pyx_t_39, __pyx_pybuffernd_boxes.diminfo[1].strides)); if (((__pyx_t_30 > __pyx_t_25) != 0)) { __pyx_t_24 = __pyx_t_30; } else { __pyx_t_24 = __pyx_t_25; } /* "bbox.pyx":51 * if iw > 0: * ih = ( * min(boxes[n, 3], query_boxes[k, 3]) - # <<<<<<<<<<<<<< * max(boxes[n, 1], query_boxes[k, 1]) + 1 * ) */ __pyx_v_ih = ((__pyx_t_21 - __pyx_t_24) + 1.0); /* "bbox.pyx":54 * max(boxes[n, 1], query_boxes[k, 1]) + 1 * ) * if ih > 0: # <<<<<<<<<<<<<< * ua = float( * (boxes[n, 2] - boxes[n, 0] + 1) * */ __pyx_t_31 = ((__pyx_v_ih > 0.0) != 0); if (__pyx_t_31) { /* "bbox.pyx":56 * if ih > 0: * ua = float( * (boxes[n, 2] - boxes[n, 0] + 1) * # <<<<<<<<<<<<<< * (boxes[n, 3] - boxes[n, 1] + 1) + * box_area - iw * ih */ __pyx_t_40 = __pyx_v_n; __pyx_t_41 = 2; __pyx_t_10 = -1; if (unlikely(__pyx_t_40 >= (size_t)__pyx_pybuffernd_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_41 < 0) { __pyx_t_41 += __pyx_pybuffernd_boxes.diminfo[1].shape; if (unlikely(__pyx_t_41 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_41 >= __pyx_pybuffernd_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 56, __pyx_L1_error) } __pyx_t_42 = __pyx_v_n; __pyx_t_43 = 0; __pyx_t_10 = -1; if (unlikely(__pyx_t_42 >= (size_t)__pyx_pybuffernd_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_43 < 0) { __pyx_t_43 += __pyx_pybuffernd_boxes.diminfo[1].shape; if (unlikely(__pyx_t_43 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_43 >= __pyx_pybuffernd_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 56, __pyx_L1_error) } /* "bbox.pyx":57 * ua = float( * (boxes[n, 2] - boxes[n, 0] + 1) * * (boxes[n, 3] - boxes[n, 1] + 1) + # <<<<<<<<<<<<<< * box_area - iw * ih * ) */ __pyx_t_44 = __pyx_v_n; __pyx_t_45 = 3; __pyx_t_10 = -1; if (unlikely(__pyx_t_44 >= (size_t)__pyx_pybuffernd_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_45 < 0) { __pyx_t_45 += __pyx_pybuffernd_boxes.diminfo[1].shape; if (unlikely(__pyx_t_45 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_45 >= __pyx_pybuffernd_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 57, __pyx_L1_error) } __pyx_t_46 = __pyx_v_n; __pyx_t_47 = 1; __pyx_t_10 = -1; if (unlikely(__pyx_t_46 >= (size_t)__pyx_pybuffernd_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_47 < 0) { __pyx_t_47 += __pyx_pybuffernd_boxes.diminfo[1].shape; if (unlikely(__pyx_t_47 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_47 >= __pyx_pybuffernd_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 57, __pyx_L1_error) } /* "bbox.pyx":55 * ) * if ih > 0: * ua = float( # <<<<<<<<<<<<<< * (boxes[n, 2] - boxes[n, 0] + 1) * * (boxes[n, 3] - boxes[n, 1] + 1) + */ __pyx_v_ua = ((double)((((((*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_boxes.rcbuffer->pybuffer.buf, __pyx_t_40, __pyx_pybuffernd_boxes.diminfo[0].strides, __pyx_t_41, __pyx_pybuffernd_boxes.diminfo[1].strides)) - (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_boxes.rcbuffer->pybuffer.buf, __pyx_t_42, __pyx_pybuffernd_boxes.diminfo[0].strides, __pyx_t_43, __pyx_pybuffernd_boxes.diminfo[1].strides))) + 1.0) * (((*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_boxes.rcbuffer->pybuffer.buf, __pyx_t_44, __pyx_pybuffernd_boxes.diminfo[0].strides, __pyx_t_45, __pyx_pybuffernd_boxes.diminfo[1].strides)) - (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_boxes.rcbuffer->pybuffer.buf, __pyx_t_46, __pyx_pybuffernd_boxes.diminfo[0].strides, __pyx_t_47, __pyx_pybuffernd_boxes.diminfo[1].strides))) + 1.0)) + __pyx_v_box_area) - (__pyx_v_iw * __pyx_v_ih))); /* "bbox.pyx":60 * box_area - iw * ih * ) * overlaps[n, k] = iw * ih / ua # <<<<<<<<<<<<<< * return overlaps * */ __pyx_t_24 = (__pyx_v_iw * __pyx_v_ih); if (unlikely(__pyx_v_ua == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "float division"); __PYX_ERR(0, 60, __pyx_L1_error) } __pyx_t_48 = __pyx_v_n; __pyx_t_49 = __pyx_v_k; __pyx_t_10 = -1; if (unlikely(__pyx_t_48 >= (size_t)__pyx_pybuffernd_overlaps.diminfo[0].shape)) __pyx_t_10 = 0; if (unlikely(__pyx_t_49 >= (size_t)__pyx_pybuffernd_overlaps.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 60, __pyx_L1_error) } *__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_overlaps.rcbuffer->pybuffer.buf, __pyx_t_48, __pyx_pybuffernd_overlaps.diminfo[0].strides, __pyx_t_49, __pyx_pybuffernd_overlaps.diminfo[1].strides) = (__pyx_t_24 / __pyx_v_ua); /* "bbox.pyx":54 * max(boxes[n, 1], query_boxes[k, 1]) + 1 * ) * if ih > 0: # <<<<<<<<<<<<<< * ua = float( * (boxes[n, 2] - boxes[n, 0] + 1) * */ } /* "bbox.pyx":49 * max(boxes[n, 0], query_boxes[k, 0]) + 1 * ) * if iw > 0: # <<<<<<<<<<<<<< * ih = ( * min(boxes[n, 3], query_boxes[k, 3]) - */ } } } /* "bbox.pyx":61 * ) * overlaps[n, k] = iw * ih / ua * return overlaps # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(((PyObject *)__pyx_r)); __Pyx_INCREF(((PyObject *)__pyx_v_overlaps)); __pyx_r = ((PyArrayObject *)__pyx_v_overlaps); goto __pyx_L0; /* "bbox.pyx":21 * return bbox_overlaps_c(boxes_contig, query_contig) * * cdef np.ndarray[DTYPE_t, ndim=2] bbox_overlaps_c( # <<<<<<<<<<<<<< * np.ndarray[DTYPE_t, ndim=2] boxes, * np.ndarray[DTYPE_t, ndim=2] query_boxes): */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_boxes.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_overlaps.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_query_boxes.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("bbox.bbox_overlaps_c", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_boxes.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_overlaps.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_query_boxes.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_overlaps); __Pyx_XGIVEREF((PyObject *)__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "bbox.pyx":64 * * * def bbox_intersections(boxes, query_boxes): # <<<<<<<<<<<<<< * cdef np.ndarray[DTYPE_t, ndim=2] boxes_contig = np.ascontiguousarray(boxes, dtype=DTYPE) * cdef np.ndarray[DTYPE_t, ndim=2] query_contig = np.ascontiguousarray(query_boxes, dtype=DTYPE) */ /* Python wrapper */ static PyObject *__pyx_pw_4bbox_3bbox_intersections(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyMethodDef __pyx_mdef_4bbox_3bbox_intersections = {"bbox_intersections", (PyCFunction)__pyx_pw_4bbox_3bbox_intersections, METH_VARARGS|METH_KEYWORDS, 0}; static PyObject *__pyx_pw_4bbox_3bbox_intersections(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_boxes = 0; PyObject *__pyx_v_query_boxes = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("bbox_intersections (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_boxes,&__pyx_n_s_query_boxes,0}; PyObject* values[2] = {0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_boxes)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_query_boxes)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("bbox_intersections", 1, 2, 2, 1); __PYX_ERR(0, 64, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "bbox_intersections") < 0)) __PYX_ERR(0, 64, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } __pyx_v_boxes = values[0]; __pyx_v_query_boxes = values[1]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("bbox_intersections", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 64, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("bbox.bbox_intersections", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_4bbox_2bbox_intersections(__pyx_self, __pyx_v_boxes, __pyx_v_query_boxes); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_4bbox_2bbox_intersections(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_boxes, PyObject *__pyx_v_query_boxes) { PyArrayObject *__pyx_v_boxes_contig = 0; PyArrayObject *__pyx_v_query_contig = 0; __Pyx_LocalBuf_ND __pyx_pybuffernd_boxes_contig; __Pyx_Buffer __pyx_pybuffer_boxes_contig; __Pyx_LocalBuf_ND __pyx_pybuffernd_query_contig; __Pyx_Buffer __pyx_pybuffer_query_contig; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyArrayObject *__pyx_t_5 = NULL; PyArrayObject *__pyx_t_6 = NULL; __Pyx_RefNannySetupContext("bbox_intersections", 0); __pyx_pybuffer_boxes_contig.pybuffer.buf = NULL; __pyx_pybuffer_boxes_contig.refcount = 0; __pyx_pybuffernd_boxes_contig.data = NULL; __pyx_pybuffernd_boxes_contig.rcbuffer = &__pyx_pybuffer_boxes_contig; __pyx_pybuffer_query_contig.pybuffer.buf = NULL; __pyx_pybuffer_query_contig.refcount = 0; __pyx_pybuffernd_query_contig.data = NULL; __pyx_pybuffernd_query_contig.rcbuffer = &__pyx_pybuffer_query_contig; /* "bbox.pyx":65 * * def bbox_intersections(boxes, query_boxes): * cdef np.ndarray[DTYPE_t, ndim=2] boxes_contig = np.ascontiguousarray(boxes, dtype=DTYPE) # <<<<<<<<<<<<<< * cdef np.ndarray[DTYPE_t, ndim=2] query_contig = np.ascontiguousarray(query_boxes, dtype=DTYPE) * */ __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 65, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ascontiguousarray); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 65, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 65, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(__pyx_v_boxes); __Pyx_GIVEREF(__pyx_v_boxes); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_boxes); __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 65, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 65, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_dtype, __pyx_t_4) < 0) __PYX_ERR(0, 65, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 65, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_4) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_4, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 65, __pyx_L1_error) __pyx_t_5 = ((PyArrayObject *)__pyx_t_4); { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_boxes_contig.rcbuffer->pybuffer, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_nn___pyx_t_4bbox_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) { __pyx_v_boxes_contig = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_boxes_contig.rcbuffer->pybuffer.buf = NULL; __PYX_ERR(0, 65, __pyx_L1_error) } else {__pyx_pybuffernd_boxes_contig.diminfo[0].strides = __pyx_pybuffernd_boxes_contig.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_boxes_contig.diminfo[0].shape = __pyx_pybuffernd_boxes_contig.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_boxes_contig.diminfo[1].strides = __pyx_pybuffernd_boxes_contig.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_boxes_contig.diminfo[1].shape = __pyx_pybuffernd_boxes_contig.rcbuffer->pybuffer.shape[1]; } } __pyx_t_5 = 0; __pyx_v_boxes_contig = ((PyArrayObject *)__pyx_t_4); __pyx_t_4 = 0; /* "bbox.pyx":66 * def bbox_intersections(boxes, query_boxes): * cdef np.ndarray[DTYPE_t, ndim=2] boxes_contig = np.ascontiguousarray(boxes, dtype=DTYPE) * cdef np.ndarray[DTYPE_t, ndim=2] query_contig = np.ascontiguousarray(query_boxes, dtype=DTYPE) # <<<<<<<<<<<<<< * * return bbox_intersections_c(boxes_contig, query_contig) */ __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 66, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_ascontiguousarray); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 66, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 66, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_INCREF(__pyx_v_query_boxes); __Pyx_GIVEREF(__pyx_v_query_boxes); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_query_boxes); __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 66, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 66, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_dtype, __pyx_t_2) < 0) __PYX_ERR(0, 66, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 66, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (!(likely(((__pyx_t_2) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_2, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 66, __pyx_L1_error) __pyx_t_6 = ((PyArrayObject *)__pyx_t_2); { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_query_contig.rcbuffer->pybuffer, (PyObject*)__pyx_t_6, &__Pyx_TypeInfo_nn___pyx_t_4bbox_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) { __pyx_v_query_contig = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_query_contig.rcbuffer->pybuffer.buf = NULL; __PYX_ERR(0, 66, __pyx_L1_error) } else {__pyx_pybuffernd_query_contig.diminfo[0].strides = __pyx_pybuffernd_query_contig.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_query_contig.diminfo[0].shape = __pyx_pybuffernd_query_contig.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_query_contig.diminfo[1].strides = __pyx_pybuffernd_query_contig.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_query_contig.diminfo[1].shape = __pyx_pybuffernd_query_contig.rcbuffer->pybuffer.shape[1]; } } __pyx_t_6 = 0; __pyx_v_query_contig = ((PyArrayObject *)__pyx_t_2); __pyx_t_2 = 0; /* "bbox.pyx":68 * cdef np.ndarray[DTYPE_t, ndim=2] query_contig = np.ascontiguousarray(query_boxes, dtype=DTYPE) * * return bbox_intersections_c(boxes_contig, query_contig) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = ((PyObject *)__pyx_f_4bbox_bbox_intersections_c(((PyArrayObject *)__pyx_v_boxes_contig), ((PyArrayObject *)__pyx_v_query_contig))); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 68, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "bbox.pyx":64 * * * def bbox_intersections(boxes, query_boxes): # <<<<<<<<<<<<<< * cdef np.ndarray[DTYPE_t, ndim=2] boxes_contig = np.ascontiguousarray(boxes, dtype=DTYPE) * cdef np.ndarray[DTYPE_t, ndim=2] query_contig = np.ascontiguousarray(query_boxes, dtype=DTYPE) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_boxes_contig.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_query_contig.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("bbox.bbox_intersections", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_boxes_contig.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_query_contig.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_boxes_contig); __Pyx_XDECREF((PyObject *)__pyx_v_query_contig); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "bbox.pyx":71 * * * cdef np.ndarray[DTYPE_t, ndim=2] bbox_intersections_c( # <<<<<<<<<<<<<< * np.ndarray[DTYPE_t, ndim=2] boxes, * np.ndarray[DTYPE_t, ndim=2] query_boxes): */ static PyArrayObject *__pyx_f_4bbox_bbox_intersections_c(PyArrayObject *__pyx_v_boxes, PyArrayObject *__pyx_v_query_boxes) { unsigned int __pyx_v_N; unsigned int __pyx_v_K; PyArrayObject *__pyx_v_intersec = 0; __pyx_t_4bbox_DTYPE_t __pyx_v_iw; __pyx_t_4bbox_DTYPE_t __pyx_v_ih; __pyx_t_4bbox_DTYPE_t __pyx_v_box_area; unsigned int __pyx_v_k; unsigned int __pyx_v_n; __Pyx_LocalBuf_ND __pyx_pybuffernd_boxes; __Pyx_Buffer __pyx_pybuffer_boxes; __Pyx_LocalBuf_ND __pyx_pybuffernd_intersec; __Pyx_Buffer __pyx_pybuffer_intersec; __Pyx_LocalBuf_ND __pyx_pybuffernd_query_boxes; __Pyx_Buffer __pyx_pybuffer_query_boxes; PyArrayObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyArrayObject *__pyx_t_5 = NULL; unsigned int __pyx_t_6; unsigned int __pyx_t_7; size_t __pyx_t_8; Py_ssize_t __pyx_t_9; int __pyx_t_10; size_t __pyx_t_11; Py_ssize_t __pyx_t_12; size_t __pyx_t_13; Py_ssize_t __pyx_t_14; size_t __pyx_t_15; Py_ssize_t __pyx_t_16; unsigned int __pyx_t_17; unsigned int __pyx_t_18; size_t __pyx_t_19; Py_ssize_t __pyx_t_20; __pyx_t_4bbox_DTYPE_t __pyx_t_21; size_t __pyx_t_22; Py_ssize_t __pyx_t_23; __pyx_t_4bbox_DTYPE_t __pyx_t_24; __pyx_t_4bbox_DTYPE_t __pyx_t_25; size_t __pyx_t_26; Py_ssize_t __pyx_t_27; size_t __pyx_t_28; Py_ssize_t __pyx_t_29; __pyx_t_4bbox_DTYPE_t __pyx_t_30; int __pyx_t_31; size_t __pyx_t_32; Py_ssize_t __pyx_t_33; size_t __pyx_t_34; Py_ssize_t __pyx_t_35; size_t __pyx_t_36; Py_ssize_t __pyx_t_37; size_t __pyx_t_38; Py_ssize_t __pyx_t_39; size_t __pyx_t_40; size_t __pyx_t_41; __Pyx_RefNannySetupContext("bbox_intersections_c", 0); __pyx_pybuffer_intersec.pybuffer.buf = NULL; __pyx_pybuffer_intersec.refcount = 0; __pyx_pybuffernd_intersec.data = NULL; __pyx_pybuffernd_intersec.rcbuffer = &__pyx_pybuffer_intersec; __pyx_pybuffer_boxes.pybuffer.buf = NULL; __pyx_pybuffer_boxes.refcount = 0; __pyx_pybuffernd_boxes.data = NULL; __pyx_pybuffernd_boxes.rcbuffer = &__pyx_pybuffer_boxes; __pyx_pybuffer_query_boxes.pybuffer.buf = NULL; __pyx_pybuffer_query_boxes.refcount = 0; __pyx_pybuffernd_query_boxes.data = NULL; __pyx_pybuffernd_query_boxes.rcbuffer = &__pyx_pybuffer_query_boxes; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_boxes.rcbuffer->pybuffer, (PyObject*)__pyx_v_boxes, &__Pyx_TypeInfo_nn___pyx_t_4bbox_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) __PYX_ERR(0, 71, __pyx_L1_error) } __pyx_pybuffernd_boxes.diminfo[0].strides = __pyx_pybuffernd_boxes.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_boxes.diminfo[0].shape = __pyx_pybuffernd_boxes.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_boxes.diminfo[1].strides = __pyx_pybuffernd_boxes.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_boxes.diminfo[1].shape = __pyx_pybuffernd_boxes.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_query_boxes.rcbuffer->pybuffer, (PyObject*)__pyx_v_query_boxes, &__Pyx_TypeInfo_nn___pyx_t_4bbox_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES, 2, 0, __pyx_stack) == -1)) __PYX_ERR(0, 71, __pyx_L1_error) } __pyx_pybuffernd_query_boxes.diminfo[0].strides = __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_query_boxes.diminfo[0].shape = __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_query_boxes.diminfo[1].strides = __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_query_boxes.diminfo[1].shape = __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.shape[1]; /* "bbox.pyx":85 * overlaps: (N, K) ndarray of intersec between boxes and query_boxes * """ * cdef unsigned int N = boxes.shape[0] # <<<<<<<<<<<<<< * cdef unsigned int K = query_boxes.shape[0] * cdef np.ndarray[DTYPE_t, ndim=2] intersec = np.zeros((N, K), dtype=DTYPE) */ __pyx_v_N = (__pyx_v_boxes->dimensions[0]); /* "bbox.pyx":86 * """ * cdef unsigned int N = boxes.shape[0] * cdef unsigned int K = query_boxes.shape[0] # <<<<<<<<<<<<<< * cdef np.ndarray[DTYPE_t, ndim=2] intersec = np.zeros((N, K), dtype=DTYPE) * cdef DTYPE_t iw, ih, box_area */ __pyx_v_K = (__pyx_v_query_boxes->dimensions[0]); /* "bbox.pyx":87 * cdef unsigned int N = boxes.shape[0] * cdef unsigned int K = query_boxes.shape[0] * cdef np.ndarray[DTYPE_t, ndim=2] intersec = np.zeros((N, K), dtype=DTYPE) # <<<<<<<<<<<<<< * cdef DTYPE_t iw, ih, box_area * cdef DTYPE_t ua */ __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 87, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_zeros); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 87, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyInt_From_unsigned_int(__pyx_v_N); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 87, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = __Pyx_PyInt_From_unsigned_int(__pyx_v_K); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 87, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 87, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_3); __pyx_t_1 = 0; __pyx_t_3 = 0; __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 87, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = PyDict_New(); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 87, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_DTYPE); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 87, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_1) < 0) __PYX_ERR(0, 87, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 87, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 87, __pyx_L1_error) __pyx_t_5 = ((PyArrayObject *)__pyx_t_1); { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_intersec.rcbuffer->pybuffer, (PyObject*)__pyx_t_5, &__Pyx_TypeInfo_nn___pyx_t_4bbox_DTYPE_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 2, 0, __pyx_stack) == -1)) { __pyx_v_intersec = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_intersec.rcbuffer->pybuffer.buf = NULL; __PYX_ERR(0, 87, __pyx_L1_error) } else {__pyx_pybuffernd_intersec.diminfo[0].strides = __pyx_pybuffernd_intersec.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_intersec.diminfo[0].shape = __pyx_pybuffernd_intersec.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_intersec.diminfo[1].strides = __pyx_pybuffernd_intersec.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_intersec.diminfo[1].shape = __pyx_pybuffernd_intersec.rcbuffer->pybuffer.shape[1]; } } __pyx_t_5 = 0; __pyx_v_intersec = ((PyArrayObject *)__pyx_t_1); __pyx_t_1 = 0; /* "bbox.pyx":91 * cdef DTYPE_t ua * cdef unsigned int k, n * for k in range(K): # <<<<<<<<<<<<<< * box_area = ( * (query_boxes[k, 2] - query_boxes[k, 0] + 1) * */ __pyx_t_6 = __pyx_v_K; for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { __pyx_v_k = __pyx_t_7; /* "bbox.pyx":93 * for k in range(K): * box_area = ( * (query_boxes[k, 2] - query_boxes[k, 0] + 1) * # <<<<<<<<<<<<<< * (query_boxes[k, 3] - query_boxes[k, 1] + 1) * ) */ __pyx_t_8 = __pyx_v_k; __pyx_t_9 = 2; __pyx_t_10 = -1; if (unlikely(__pyx_t_8 >= (size_t)__pyx_pybuffernd_query_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_9 < 0) { __pyx_t_9 += __pyx_pybuffernd_query_boxes.diminfo[1].shape; if (unlikely(__pyx_t_9 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_9 >= __pyx_pybuffernd_query_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 93, __pyx_L1_error) } __pyx_t_11 = __pyx_v_k; __pyx_t_12 = 0; __pyx_t_10 = -1; if (unlikely(__pyx_t_11 >= (size_t)__pyx_pybuffernd_query_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_12 < 0) { __pyx_t_12 += __pyx_pybuffernd_query_boxes.diminfo[1].shape; if (unlikely(__pyx_t_12 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_12 >= __pyx_pybuffernd_query_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 93, __pyx_L1_error) } /* "bbox.pyx":94 * box_area = ( * (query_boxes[k, 2] - query_boxes[k, 0] + 1) * * (query_boxes[k, 3] - query_boxes[k, 1] + 1) # <<<<<<<<<<<<<< * ) * for n in range(N): */ __pyx_t_13 = __pyx_v_k; __pyx_t_14 = 3; __pyx_t_10 = -1; if (unlikely(__pyx_t_13 >= (size_t)__pyx_pybuffernd_query_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_14 < 0) { __pyx_t_14 += __pyx_pybuffernd_query_boxes.diminfo[1].shape; if (unlikely(__pyx_t_14 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_14 >= __pyx_pybuffernd_query_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 94, __pyx_L1_error) } __pyx_t_15 = __pyx_v_k; __pyx_t_16 = 1; __pyx_t_10 = -1; if (unlikely(__pyx_t_15 >= (size_t)__pyx_pybuffernd_query_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_16 < 0) { __pyx_t_16 += __pyx_pybuffernd_query_boxes.diminfo[1].shape; if (unlikely(__pyx_t_16 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_16 >= __pyx_pybuffernd_query_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 94, __pyx_L1_error) } /* "bbox.pyx":93 * for k in range(K): * box_area = ( * (query_boxes[k, 2] - query_boxes[k, 0] + 1) * # <<<<<<<<<<<<<< * (query_boxes[k, 3] - query_boxes[k, 1] + 1) * ) */ __pyx_v_box_area = ((((*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_query_boxes.diminfo[0].strides, __pyx_t_9, __pyx_pybuffernd_query_boxes.diminfo[1].strides)) - (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_query_boxes.diminfo[0].strides, __pyx_t_12, __pyx_pybuffernd_query_boxes.diminfo[1].strides))) + 1.0) * (((*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_query_boxes.diminfo[0].strides, __pyx_t_14, __pyx_pybuffernd_query_boxes.diminfo[1].strides)) - (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.buf, __pyx_t_15, __pyx_pybuffernd_query_boxes.diminfo[0].strides, __pyx_t_16, __pyx_pybuffernd_query_boxes.diminfo[1].strides))) + 1.0)); /* "bbox.pyx":96 * (query_boxes[k, 3] - query_boxes[k, 1] + 1) * ) * for n in range(N): # <<<<<<<<<<<<<< * iw = ( * min(boxes[n, 2], query_boxes[k, 2]) - */ __pyx_t_17 = __pyx_v_N; for (__pyx_t_18 = 0; __pyx_t_18 < __pyx_t_17; __pyx_t_18+=1) { __pyx_v_n = __pyx_t_18; /* "bbox.pyx":98 * for n in range(N): * iw = ( * min(boxes[n, 2], query_boxes[k, 2]) - # <<<<<<<<<<<<<< * max(boxes[n, 0], query_boxes[k, 0]) + 1 * ) */ __pyx_t_19 = __pyx_v_k; __pyx_t_20 = 2; __pyx_t_10 = -1; if (unlikely(__pyx_t_19 >= (size_t)__pyx_pybuffernd_query_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_20 < 0) { __pyx_t_20 += __pyx_pybuffernd_query_boxes.diminfo[1].shape; if (unlikely(__pyx_t_20 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_20 >= __pyx_pybuffernd_query_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 98, __pyx_L1_error) } __pyx_t_21 = (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_query_boxes.diminfo[0].strides, __pyx_t_20, __pyx_pybuffernd_query_boxes.diminfo[1].strides)); __pyx_t_22 = __pyx_v_n; __pyx_t_23 = 2; __pyx_t_10 = -1; if (unlikely(__pyx_t_22 >= (size_t)__pyx_pybuffernd_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_23 < 0) { __pyx_t_23 += __pyx_pybuffernd_boxes.diminfo[1].shape; if (unlikely(__pyx_t_23 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_23 >= __pyx_pybuffernd_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 98, __pyx_L1_error) } __pyx_t_24 = (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_boxes.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_boxes.diminfo[0].strides, __pyx_t_23, __pyx_pybuffernd_boxes.diminfo[1].strides)); if (((__pyx_t_21 < __pyx_t_24) != 0)) { __pyx_t_25 = __pyx_t_21; } else { __pyx_t_25 = __pyx_t_24; } /* "bbox.pyx":99 * iw = ( * min(boxes[n, 2], query_boxes[k, 2]) - * max(boxes[n, 0], query_boxes[k, 0]) + 1 # <<<<<<<<<<<<<< * ) * if iw > 0: */ __pyx_t_26 = __pyx_v_k; __pyx_t_27 = 0; __pyx_t_10 = -1; if (unlikely(__pyx_t_26 >= (size_t)__pyx_pybuffernd_query_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_27 < 0) { __pyx_t_27 += __pyx_pybuffernd_query_boxes.diminfo[1].shape; if (unlikely(__pyx_t_27 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_27 >= __pyx_pybuffernd_query_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 99, __pyx_L1_error) } __pyx_t_21 = (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.buf, __pyx_t_26, __pyx_pybuffernd_query_boxes.diminfo[0].strides, __pyx_t_27, __pyx_pybuffernd_query_boxes.diminfo[1].strides)); __pyx_t_28 = __pyx_v_n; __pyx_t_29 = 0; __pyx_t_10 = -1; if (unlikely(__pyx_t_28 >= (size_t)__pyx_pybuffernd_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_29 < 0) { __pyx_t_29 += __pyx_pybuffernd_boxes.diminfo[1].shape; if (unlikely(__pyx_t_29 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_29 >= __pyx_pybuffernd_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 99, __pyx_L1_error) } __pyx_t_24 = (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_boxes.rcbuffer->pybuffer.buf, __pyx_t_28, __pyx_pybuffernd_boxes.diminfo[0].strides, __pyx_t_29, __pyx_pybuffernd_boxes.diminfo[1].strides)); if (((__pyx_t_21 > __pyx_t_24) != 0)) { __pyx_t_30 = __pyx_t_21; } else { __pyx_t_30 = __pyx_t_24; } /* "bbox.pyx":98 * for n in range(N): * iw = ( * min(boxes[n, 2], query_boxes[k, 2]) - # <<<<<<<<<<<<<< * max(boxes[n, 0], query_boxes[k, 0]) + 1 * ) */ __pyx_v_iw = ((__pyx_t_25 - __pyx_t_30) + 1.0); /* "bbox.pyx":101 * max(boxes[n, 0], query_boxes[k, 0]) + 1 * ) * if iw > 0: # <<<<<<<<<<<<<< * ih = ( * min(boxes[n, 3], query_boxes[k, 3]) - */ __pyx_t_31 = ((__pyx_v_iw > 0.0) != 0); if (__pyx_t_31) { /* "bbox.pyx":103 * if iw > 0: * ih = ( * min(boxes[n, 3], query_boxes[k, 3]) - # <<<<<<<<<<<<<< * max(boxes[n, 1], query_boxes[k, 1]) + 1 * ) */ __pyx_t_32 = __pyx_v_k; __pyx_t_33 = 3; __pyx_t_10 = -1; if (unlikely(__pyx_t_32 >= (size_t)__pyx_pybuffernd_query_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_33 < 0) { __pyx_t_33 += __pyx_pybuffernd_query_boxes.diminfo[1].shape; if (unlikely(__pyx_t_33 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_33 >= __pyx_pybuffernd_query_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 103, __pyx_L1_error) } __pyx_t_30 = (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.buf, __pyx_t_32, __pyx_pybuffernd_query_boxes.diminfo[0].strides, __pyx_t_33, __pyx_pybuffernd_query_boxes.diminfo[1].strides)); __pyx_t_34 = __pyx_v_n; __pyx_t_35 = 3; __pyx_t_10 = -1; if (unlikely(__pyx_t_34 >= (size_t)__pyx_pybuffernd_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_35 < 0) { __pyx_t_35 += __pyx_pybuffernd_boxes.diminfo[1].shape; if (unlikely(__pyx_t_35 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_35 >= __pyx_pybuffernd_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 103, __pyx_L1_error) } __pyx_t_25 = (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_boxes.rcbuffer->pybuffer.buf, __pyx_t_34, __pyx_pybuffernd_boxes.diminfo[0].strides, __pyx_t_35, __pyx_pybuffernd_boxes.diminfo[1].strides)); if (((__pyx_t_30 < __pyx_t_25) != 0)) { __pyx_t_21 = __pyx_t_30; } else { __pyx_t_21 = __pyx_t_25; } /* "bbox.pyx":104 * ih = ( * min(boxes[n, 3], query_boxes[k, 3]) - * max(boxes[n, 1], query_boxes[k, 1]) + 1 # <<<<<<<<<<<<<< * ) * if ih > 0: */ __pyx_t_36 = __pyx_v_k; __pyx_t_37 = 1; __pyx_t_10 = -1; if (unlikely(__pyx_t_36 >= (size_t)__pyx_pybuffernd_query_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_37 < 0) { __pyx_t_37 += __pyx_pybuffernd_query_boxes.diminfo[1].shape; if (unlikely(__pyx_t_37 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_37 >= __pyx_pybuffernd_query_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 104, __pyx_L1_error) } __pyx_t_30 = (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_query_boxes.rcbuffer->pybuffer.buf, __pyx_t_36, __pyx_pybuffernd_query_boxes.diminfo[0].strides, __pyx_t_37, __pyx_pybuffernd_query_boxes.diminfo[1].strides)); __pyx_t_38 = __pyx_v_n; __pyx_t_39 = 1; __pyx_t_10 = -1; if (unlikely(__pyx_t_38 >= (size_t)__pyx_pybuffernd_boxes.diminfo[0].shape)) __pyx_t_10 = 0; if (__pyx_t_39 < 0) { __pyx_t_39 += __pyx_pybuffernd_boxes.diminfo[1].shape; if (unlikely(__pyx_t_39 < 0)) __pyx_t_10 = 1; } else if (unlikely(__pyx_t_39 >= __pyx_pybuffernd_boxes.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 104, __pyx_L1_error) } __pyx_t_25 = (*__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_boxes.rcbuffer->pybuffer.buf, __pyx_t_38, __pyx_pybuffernd_boxes.diminfo[0].strides, __pyx_t_39, __pyx_pybuffernd_boxes.diminfo[1].strides)); if (((__pyx_t_30 > __pyx_t_25) != 0)) { __pyx_t_24 = __pyx_t_30; } else { __pyx_t_24 = __pyx_t_25; } /* "bbox.pyx":103 * if iw > 0: * ih = ( * min(boxes[n, 3], query_boxes[k, 3]) - # <<<<<<<<<<<<<< * max(boxes[n, 1], query_boxes[k, 1]) + 1 * ) */ __pyx_v_ih = ((__pyx_t_21 - __pyx_t_24) + 1.0); /* "bbox.pyx":106 * max(boxes[n, 1], query_boxes[k, 1]) + 1 * ) * if ih > 0: # <<<<<<<<<<<<<< * intersec[n, k] = iw * ih / box_area * return intersec */ __pyx_t_31 = ((__pyx_v_ih > 0.0) != 0); if (__pyx_t_31) { /* "bbox.pyx":107 * ) * if ih > 0: * intersec[n, k] = iw * ih / box_area # <<<<<<<<<<<<<< * return intersec */ __pyx_t_24 = (__pyx_v_iw * __pyx_v_ih); if (unlikely(__pyx_v_box_area == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "float division"); __PYX_ERR(0, 107, __pyx_L1_error) } __pyx_t_40 = __pyx_v_n; __pyx_t_41 = __pyx_v_k; __pyx_t_10 = -1; if (unlikely(__pyx_t_40 >= (size_t)__pyx_pybuffernd_intersec.diminfo[0].shape)) __pyx_t_10 = 0; if (unlikely(__pyx_t_41 >= (size_t)__pyx_pybuffernd_intersec.diminfo[1].shape)) __pyx_t_10 = 1; if (unlikely(__pyx_t_10 != -1)) { __Pyx_RaiseBufferIndexError(__pyx_t_10); __PYX_ERR(0, 107, __pyx_L1_error) } *__Pyx_BufPtrStrided2d(__pyx_t_4bbox_DTYPE_t *, __pyx_pybuffernd_intersec.rcbuffer->pybuffer.buf, __pyx_t_40, __pyx_pybuffernd_intersec.diminfo[0].strides, __pyx_t_41, __pyx_pybuffernd_intersec.diminfo[1].strides) = (__pyx_t_24 / __pyx_v_box_area); /* "bbox.pyx":106 * max(boxes[n, 1], query_boxes[k, 1]) + 1 * ) * if ih > 0: # <<<<<<<<<<<<<< * intersec[n, k] = iw * ih / box_area * return intersec */ } /* "bbox.pyx":101 * max(boxes[n, 0], query_boxes[k, 0]) + 1 * ) * if iw > 0: # <<<<<<<<<<<<<< * ih = ( * min(boxes[n, 3], query_boxes[k, 3]) - */ } } } /* "bbox.pyx":108 * if ih > 0: * intersec[n, k] = iw * ih / box_area * return intersec # <<<<<<<<<<<<<< */ __Pyx_XDECREF(((PyObject *)__pyx_r)); __Pyx_INCREF(((PyObject *)__pyx_v_intersec)); __pyx_r = ((PyArrayObject *)__pyx_v_intersec); goto __pyx_L0; /* "bbox.pyx":71 * * * cdef np.ndarray[DTYPE_t, ndim=2] bbox_intersections_c( # <<<<<<<<<<<<<< * np.ndarray[DTYPE_t, ndim=2] boxes, * np.ndarray[DTYPE_t, ndim=2] query_boxes): */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_boxes.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_intersec.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_query_boxes.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("bbox.bbox_intersections_c", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_boxes.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_intersec.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_query_boxes.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_intersec); __Pyx_XGIVEREF((PyObject *)__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":197 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython * # requirements, and does not yet fullfill the PEP. */ /* Python wrapper */ static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_copy_shape; int __pyx_v_i; int __pyx_v_ndim; int __pyx_v_endian_detector; int __pyx_v_little_endian; int __pyx_v_t; char *__pyx_v_f; PyArray_Descr *__pyx_v_descr = 0; int __pyx_v_offset; int __pyx_v_hasfields; int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; int __pyx_t_5; PyObject *__pyx_t_6 = NULL; char *__pyx_t_7; __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":203 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< * * cdef int copy_shape, i, ndim */ __pyx_t_1 = ((__pyx_v_info == NULL) != 0); if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":206 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< * cdef bint little_endian = ((&endian_detector)[0] != 0) * */ __pyx_v_endian_detector = 1; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":207 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< * * ndim = PyArray_NDIM(self) */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":209 * cdef bint little_endian = ((&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":211 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":212 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< * else: * copy_shape = 0 */ __pyx_v_copy_shape = 1; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":211 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ goto __pyx_L4; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":214 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) */ /*else*/ { __pyx_v_copy_shape = 0; } __pyx_L4:; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":216 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ __pyx_t_2 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L6_bool_binop_done; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":217 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L6_bool_binop_done:; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":216 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ if (__pyx_t_1) { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":218 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 218, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 218, __pyx_L1_error) /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":216 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":220 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ __pyx_t_2 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L9_bool_binop_done; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":221 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L9_bool_binop_done:; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":220 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ if (__pyx_t_1) { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":222 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 222, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 222, __pyx_L1_error) /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":220 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":224 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if copy_shape: */ __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":225 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< * if copy_shape: * # Allocate new buffer for strides and shape info. */ __pyx_v_info->ndim = __pyx_v_ndim; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":226 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ __pyx_t_1 = (__pyx_v_copy_shape != 0); if (__pyx_t_1) { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":229 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) # <<<<<<<<<<<<<< * info.shape = info.strides + ndim * for i in range(ndim): */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":230 * # This is allocated as one block, strides first. * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":231 * info.strides = stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] */ __pyx_t_4 = __pyx_v_ndim; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":232 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< * info.shape[i] = PyArray_DIMS(self)[i] * else: */ (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":233 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = PyArray_STRIDES(self) */ (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":226 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ goto __pyx_L11; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":235 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL */ /*else*/ { __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":236 * else: * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); } __pyx_L11:; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":237 * info.strides = PyArray_STRIDES(self) * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) */ __pyx_v_info->suboffsets = NULL; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":238 * info.shape = PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) * */ __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":239 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":242 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< * cdef dtype descr = self.descr * cdef int offset */ __pyx_v_f = NULL; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":243 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef int offset * */ __pyx_t_3 = ((PyObject *)__pyx_v_self->descr); __Pyx_INCREF(__pyx_t_3); __pyx_v_descr = ((PyArray_Descr *)__pyx_t_3); __pyx_t_3 = 0; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":246 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< * * if not hasfields and not copy_shape: */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":248 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L15_bool_binop_done; } __pyx_t_2 = ((!(__pyx_v_copy_shape != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L15_bool_binop_done:; if (__pyx_t_1) { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":250 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< * else: * # need to call releasebuffer */ __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":248 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ goto __pyx_L14; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":253 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ /*else*/ { __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } __pyx_L14:; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":255 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or */ __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_1) { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":256 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): */ __pyx_t_4 = __pyx_v_descr->type_num; __pyx_v_t = __pyx_t_4; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":257 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ __pyx_t_2 = ((__pyx_v_descr->byteorder == '>') != 0); if (!__pyx_t_2) { goto __pyx_L20_next_or; } else { } __pyx_t_2 = (__pyx_v_little_endian != 0); if (!__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L19_bool_binop_done; } __pyx_L20_next_or:; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":258 * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ __pyx_t_2 = ((__pyx_v_descr->byteorder == '<') != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L19_bool_binop_done; } __pyx_t_2 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L19_bool_binop_done:; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":257 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ if (__pyx_t_1) { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":259 * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 259, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 259, __pyx_L1_error) /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":257 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":260 * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ switch (__pyx_v_t) { case NPY_BYTE: __pyx_v_f = ((char *)"b"); break; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":261 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ case NPY_UBYTE: __pyx_v_f = ((char *)"B"); break; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":262 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ case NPY_SHORT: __pyx_v_f = ((char *)"h"); break; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":263 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ case NPY_USHORT: __pyx_v_f = ((char *)"H"); break; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":264 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ case NPY_INT: __pyx_v_f = ((char *)"i"); break; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":265 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ case NPY_UINT: __pyx_v_f = ((char *)"I"); break; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":266 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ case NPY_LONG: __pyx_v_f = ((char *)"l"); break; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":267 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ case NPY_ULONG: __pyx_v_f = ((char *)"L"); break; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":268 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ case NPY_LONGLONG: __pyx_v_f = ((char *)"q"); break; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":269 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ case NPY_ULONGLONG: __pyx_v_f = ((char *)"Q"); break; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":270 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ case NPY_FLOAT: __pyx_v_f = ((char *)"f"); break; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":271 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ case NPY_DOUBLE: __pyx_v_f = ((char *)"d"); break; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":272 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ case NPY_LONGDOUBLE: __pyx_v_f = ((char *)"g"); break; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":273 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ case NPY_CFLOAT: __pyx_v_f = ((char *)"Zf"); break; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":274 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ case NPY_CDOUBLE: __pyx_v_f = ((char *)"Zd"); break; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":275 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ case NPY_CLONGDOUBLE: __pyx_v_f = ((char *)"Zg"); break; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":276 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ case NPY_OBJECT: __pyx_v_f = ((char *)"O"); break; default: /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":278 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 278, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_3); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 278, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 278, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 278, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_6, 0, 0, 0); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __PYX_ERR(1, 278, __pyx_L1_error) break; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":279 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< * return * else: */ __pyx_v_info->format = __pyx_v_f; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":280 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< * else: * info.format = stdlib.malloc(_buffer_format_string_len) */ __pyx_r = 0; goto __pyx_L0; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":255 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or */ } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":282 * return * else: * info.format = stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ /*else*/ { __pyx_v_info->format = ((char *)malloc(0xFF)); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":283 * else: * info.format = stdlib.malloc(_buffer_format_string_len) * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":284 * info.format = stdlib.malloc(_buffer_format_string_len) * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":285 * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< * info.format + _buffer_format_string_len, * &offset) */ __pyx_t_7 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 0xFF), (&__pyx_v_offset)); if (unlikely(__pyx_t_7 == NULL)) __PYX_ERR(1, 285, __pyx_L1_error) __pyx_v_f = __pyx_t_7; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":288 * info.format + _buffer_format_string_len, * &offset) * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ (__pyx_v_f[0]) = '\x00'; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":197 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython * # requirements, and does not yet fullfill the PEP. */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { __Pyx_GOTREF(Py_None); __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; } __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_descr); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":290 * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ /* Python wrapper */ static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__releasebuffer__", 0); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":291 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":292 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) */ free(__pyx_v_info->format); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":291 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":293 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":294 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< * # info.shape was stored after info.strides in the same block * */ free(__pyx_v_info->strides); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":293 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":290 * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":770 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(1, a) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":771 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 771, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":770 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(1, a) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":773 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(2, a, b) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":774 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 774, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":773 * return PyArray_MultiIterNew(1, a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(2, a, b) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":776 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(3, a, b, c) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":777 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 777, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":776 * return PyArray_MultiIterNew(2, a, b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(3, a, b, c) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":779 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(4, a, b, c, d) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":780 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 780, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":779 * return PyArray_MultiIterNew(3, a, b, c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(4, a, b, c, d) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":782 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(5, a, b, c, d, e) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":783 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 783, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":782 * return PyArray_MultiIterNew(4, a, b, c, d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(5, a, b, c, d, e) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":785 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< * # Recursive utility function used in __getbuffer__ to get format * # string. The new location in the format string is returned. */ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { PyArray_Descr *__pyx_v_child = 0; int __pyx_v_endian_detector; int __pyx_v_little_endian; PyObject *__pyx_v_fields = 0; PyObject *__pyx_v_childname = NULL; PyObject *__pyx_v_new_offset = NULL; PyObject *__pyx_v_t = NULL; char *__pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; Py_ssize_t __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; int __pyx_t_5; int __pyx_t_6; int __pyx_t_7; long __pyx_t_8; char *__pyx_t_9; __Pyx_RefNannySetupContext("_util_dtypestring", 0); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":790 * * cdef dtype child * cdef int endian_detector = 1 # <<<<<<<<<<<<<< * cdef bint little_endian = ((&endian_detector)[0] != 0) * cdef tuple fields */ __pyx_v_endian_detector = 1; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":791 * cdef dtype child * cdef int endian_detector = 1 * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< * cdef tuple fields * */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ if (unlikely(__pyx_v_descr->names == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); __PYX_ERR(1, 794, __pyx_L1_error) } __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(1, 794, __pyx_L1_error) #else __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 794, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); #endif __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); __pyx_t_3 = 0; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ if (unlikely(__pyx_v_descr->fields == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); __PYX_ERR(1, 795, __pyx_L1_error) } __pyx_t_3 = __Pyx_PyDict_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 795, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) __PYX_ERR(1, 795, __pyx_L1_error) __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); __pyx_t_3 = 0; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< * * if (end - f) - (new_offset - offset[0]) < 15: */ if (likely(__pyx_v_fields != Py_None)) { PyObject* sequence = __pyx_v_fields; #if !CYTHON_COMPILING_IN_PYPY Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); #endif if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(1, 796, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); #else __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 796, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 796, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); #endif } else { __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 796, __pyx_L1_error) } if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) __PYX_ERR(1, 796, __pyx_L1_error) __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); __pyx_t_4 = 0; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":798 * child, new_offset = fields * * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 798, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 798, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 798, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); if (__pyx_t_6) { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * * if ((child.byteorder == c'>' and little_endian) or */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 799, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 799, __pyx_L1_error) /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":798 * child, new_offset = fields * * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); if (!__pyx_t_7) { goto __pyx_L8_next_or; } else { } __pyx_t_7 = (__pyx_v_little_endian != 0); if (!__pyx_t_7) { } else { __pyx_t_6 = __pyx_t_7; goto __pyx_L7_bool_binop_done; } __pyx_L8_next_or:; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":802 * * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); if (__pyx_t_7) { } else { __pyx_t_6 = __pyx_t_7; goto __pyx_L7_bool_binop_done; } __pyx_t_7 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_6 = __pyx_t_7; __pyx_L7_bool_binop_done:; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ if (__pyx_t_6) { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":803 * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 803, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 803, __pyx_L1_error) /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":813 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< * f[0] = 120 # "x"; pad byte * f += 1 */ while (1) { __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 813, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 813, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 813, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!__pyx_t_6) break; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< * f += 1 * offset[0] += 1 */ (__pyx_v_f[0]) = 0x78; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< * offset[0] += 1 * */ __pyx_v_f = (__pyx_v_f + 1); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< * * offset[0] += child.itemsize */ __pyx_t_8 = 0; (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + 1); } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(child): */ __pyx_t_8 = 0; (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + __pyx_v_child->elsize); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); if (__pyx_t_6) { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":821 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 821, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); __pyx_t_4 = 0; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); if (__pyx_t_6) { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 823, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __PYX_ERR(1, 823, __pyx_L1_error) /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":826 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_BYTE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 826, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 826, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 826, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 98; goto __pyx_L15; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":827 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_UBYTE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 827, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 827, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 827, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 66; goto __pyx_L15; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":828 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_SHORT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 828, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 828, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 828, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x68; goto __pyx_L15; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":829 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_USHORT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 829, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 829, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 829, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 72; goto __pyx_L15; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":830 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_INT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 830, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 830, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 830, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x69; goto __pyx_L15; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":831 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_UINT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 831, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 831, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 831, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 73; goto __pyx_L15; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":832 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONG); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 832, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 832, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 832, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x6C; goto __pyx_L15; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":833 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_ULONG); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 833, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 833, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 833, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 76; goto __pyx_L15; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":834 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 834, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 834, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 834, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x71; goto __pyx_L15; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":835 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 835, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 835, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 835, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 81; goto __pyx_L15; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":836 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_FLOAT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 836, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 836, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 836, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x66; goto __pyx_L15; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":837 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 837, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 837, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 837, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x64; goto __pyx_L15; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":838 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 838, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 838, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 838, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x67; goto __pyx_L15; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":839 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 839, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 839, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 839, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 0x66; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":840 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 840, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 840, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 840, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 0x64; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":841 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 841, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 841, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 841, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 0x67; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":842 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_OBJECT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 842, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 842, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 842, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 79; goto __pyx_L15; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":844 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ /*else*/ { __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 844, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 844, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 844, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 844, __pyx_L1_error) } __pyx_L15:; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":845 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< * else: * # Cython ignores struct boundary information ("T{...}"), */ __pyx_v_f = (__pyx_v_f + 1); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ goto __pyx_L13; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":849 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ /*else*/ { __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_9 == NULL)) __PYX_ERR(1, 849, __pyx_L1_error) __pyx_v_f = __pyx_t_9; } __pyx_L13:; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_f; goto __pyx_L0; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":785 * return PyArray_MultiIterNew(5, a, b, c, d, e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< * # Recursive utility function used in __getbuffer__ to get format * # string. The new location in the format string is returned. */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_child); __Pyx_XDECREF(__pyx_v_fields); __Pyx_XDECREF(__pyx_v_childname); __Pyx_XDECREF(__pyx_v_new_offset); __Pyx_XDECREF(__pyx_v_t); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":966 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * cdef PyObject* baseptr * if base is None: */ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; __Pyx_RefNannySetupContext("set_array_base", 0); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":968 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< * baseptr = NULL * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":969 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< * else: * Py_INCREF(base) # important to do this before decref below! */ __pyx_v_baseptr = NULL; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":968 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< * baseptr = NULL * else: */ goto __pyx_L3; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":971 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< * baseptr = base * Py_XDECREF(arr.base) */ /*else*/ { Py_INCREF(__pyx_v_base); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":972 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = base # <<<<<<<<<<<<<< * Py_XDECREF(arr.base) * arr.base = baseptr */ __pyx_v_baseptr = ((PyObject *)__pyx_v_base); } __pyx_L3:; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":973 * Py_INCREF(base) # important to do this before decref below! * baseptr = base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< * arr.base = baseptr * */ Py_XDECREF(__pyx_v_arr->base); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":974 * baseptr = base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< * * cdef inline object get_array_base(ndarray arr): */ __pyx_v_arr->base = __pyx_v_baseptr; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":966 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * cdef PyObject* baseptr * if base is None: */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * if arr.base is NULL: * return None */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("get_array_base", 0); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":977 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); if (__pyx_t_1) { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":978 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< * else: * return arr.base */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":977 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":980 * return None * else: * return arr.base # <<<<<<<<<<<<<< * * */ /*else*/ { __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); __pyx_r = ((PyObject *)__pyx_v_arr->base); goto __pyx_L0; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * if arr.base is NULL: * return None */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":985 * # Versions of the import_* functions which are more suitable for * # Cython code. * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< * try: * _import_array() */ static CYTHON_INLINE int __pyx_f_5numpy_import_array(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; __Pyx_RefNannySetupContext("import_array", 0); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":986 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * _import_array() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":987 * cdef inline int import_array() except -1: * try: * _import_array() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.multiarray failed to import") */ __pyx_t_4 = _import_array(); if (unlikely(__pyx_t_4 == -1)) __PYX_ERR(1, 987, __pyx_L3_error) /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":986 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * _import_array() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L10_try_end; __pyx_L3_error:; __Pyx_PyThreadState_assign /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":988 * try: * _import_array() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.multiarray failed to import") * */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 988, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":989 * _import_array() * except Exception: * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_umath() except -1: */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 989, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(1, 989, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":986 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * _import_array() * except Exception: */ __Pyx_PyThreadState_assign __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L10_try_end:; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":985 * # Versions of the import_* functions which are more suitable for * # Cython code. * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< * try: * _import_array() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":991 * raise ImportError("numpy.core.multiarray failed to import") * * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ static CYTHON_INLINE int __pyx_f_5numpy_import_umath(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; __Pyx_RefNannySetupContext("import_umath", 0); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":992 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":993 * cdef inline int import_umath() except -1: * try: * _import_umath() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.umath failed to import") */ __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == -1)) __PYX_ERR(1, 993, __pyx_L3_error) /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":992 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L10_try_end; __pyx_L3_error:; __Pyx_PyThreadState_assign /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":994 * try: * _import_umath() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.umath failed to import") * */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 994, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":995 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_ufunc() except -1: */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 995, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(1, 995, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":992 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ __Pyx_PyThreadState_assign __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L10_try_end:; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":991 * raise ImportError("numpy.core.multiarray failed to import") * * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":997 * raise ImportError("numpy.core.umath failed to import") * * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ static CYTHON_INLINE int __pyx_f_5numpy_import_ufunc(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; __Pyx_RefNannySetupContext("import_ufunc", 0); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":998 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":999 * cdef inline int import_ufunc() except -1: * try: * _import_umath() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.umath failed to import") */ __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == -1)) __PYX_ERR(1, 999, __pyx_L3_error) /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":998 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L10_try_end; __pyx_L3_error:; __Pyx_PyThreadState_assign /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1000 * try: * _import_umath() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.umath failed to import") */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 1000, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1001 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 1001, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(1, 1001, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":998 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ __Pyx_PyThreadState_assign __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L10_try_end:; } /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":997 * raise ImportError("numpy.core.umath failed to import") * * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { #if PY_VERSION_HEX < 0x03020000 { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, #else PyModuleDef_HEAD_INIT, #endif "bbox", 0, /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s_DTYPE, __pyx_k_DTYPE, sizeof(__pyx_k_DTYPE), 0, 0, 1, 1}, {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, {&__pyx_n_s_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1}, {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, {&__pyx_kp_s_Users_rowanz_code_scene_graph_l, __pyx_k_Users_rowanz_code_scene_graph_l, sizeof(__pyx_k_Users_rowanz_code_scene_graph_l), 0, 0, 1, 0}, {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, {&__pyx_n_s_ascontiguousarray, __pyx_k_ascontiguousarray, sizeof(__pyx_k_ascontiguousarray), 0, 0, 1, 1}, {&__pyx_n_s_bbox, __pyx_k_bbox, sizeof(__pyx_k_bbox), 0, 0, 1, 1}, {&__pyx_n_s_bbox_intersections, __pyx_k_bbox_intersections, sizeof(__pyx_k_bbox_intersections), 0, 0, 1, 1}, {&__pyx_n_s_bbox_overlaps, __pyx_k_bbox_overlaps, sizeof(__pyx_k_bbox_overlaps), 0, 0, 1, 1}, {&__pyx_n_s_boxes, __pyx_k_boxes, sizeof(__pyx_k_boxes), 0, 0, 1, 1}, {&__pyx_n_s_boxes_contig, __pyx_k_boxes_contig, sizeof(__pyx_k_boxes_contig), 0, 0, 1, 1}, {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, {&__pyx_n_s_float, __pyx_k_float, sizeof(__pyx_k_float), 0, 0, 1, 1}, {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, {&__pyx_kp_s_numpy_core_multiarray_failed_to, __pyx_k_numpy_core_multiarray_failed_to, sizeof(__pyx_k_numpy_core_multiarray_failed_to), 0, 0, 1, 0}, {&__pyx_kp_s_numpy_core_umath_failed_to_impor, __pyx_k_numpy_core_umath_failed_to_impor, sizeof(__pyx_k_numpy_core_umath_failed_to_impor), 0, 0, 1, 0}, {&__pyx_n_s_query_boxes, __pyx_k_query_boxes, sizeof(__pyx_k_query_boxes), 0, 0, 1, 1}, {&__pyx_n_s_query_contig, __pyx_k_query_contig, sizeof(__pyx_k_query_contig), 0, 0, 1, 1}, {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 39, __pyx_L1_error) __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(1, 218, __pyx_L1_error) __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) __PYX_ERR(1, 799, __pyx_L1_error) __pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) __PYX_ERR(1, 989, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":218 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple_)) __PYX_ERR(1, 218, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple_); __Pyx_GIVEREF(__pyx_tuple_); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":222 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(1, 222, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__2); __Pyx_GIVEREF(__pyx_tuple__2); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":259 * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(1, 259, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__3); __Pyx_GIVEREF(__pyx_tuple__3); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":799 * * if (end - f) - (new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * * if ((child.byteorder == c'>' and little_endian) or */ __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(1, 799, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__4); __Pyx_GIVEREF(__pyx_tuple__4); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":803 * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(1, 803, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__5); __Pyx_GIVEREF(__pyx_tuple__5); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(1, 823, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__6); __Pyx_GIVEREF(__pyx_tuple__6); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":989 * _import_array() * except Exception: * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_umath() except -1: */ __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_s_numpy_core_multiarray_failed_to); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(1, 989, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__7); __Pyx_GIVEREF(__pyx_tuple__7); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":995 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_ufunc() except -1: */ __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s_numpy_core_umath_failed_to_impor); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(1, 995, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__8); __Pyx_GIVEREF(__pyx_tuple__8); /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1001 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< */ __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_s_numpy_core_umath_failed_to_impor); if (unlikely(!__pyx_tuple__9)) __PYX_ERR(1, 1001, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__9); __Pyx_GIVEREF(__pyx_tuple__9); /* "bbox.pyx":15 * ctypedef np.float_t DTYPE_t * * def bbox_overlaps(boxes, query_boxes): # <<<<<<<<<<<<<< * cdef np.ndarray[DTYPE_t, ndim=2] boxes_contig = np.ascontiguousarray(boxes, dtype=DTYPE) * cdef np.ndarray[DTYPE_t, ndim=2] query_contig = np.ascontiguousarray(query_boxes, dtype=DTYPE) */ __pyx_tuple__10 = PyTuple_Pack(4, __pyx_n_s_boxes, __pyx_n_s_query_boxes, __pyx_n_s_boxes_contig, __pyx_n_s_query_contig); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(0, 15, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__10); __Pyx_GIVEREF(__pyx_tuple__10); __pyx_codeobj__11 = (PyObject*)__Pyx_PyCode_New(2, 0, 4, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__10, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Users_rowanz_code_scene_graph_l, __pyx_n_s_bbox_overlaps, 15, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__11)) __PYX_ERR(0, 15, __pyx_L1_error) /* "bbox.pyx":64 * * * def bbox_intersections(boxes, query_boxes): # <<<<<<<<<<<<<< * cdef np.ndarray[DTYPE_t, ndim=2] boxes_contig = np.ascontiguousarray(boxes, dtype=DTYPE) * cdef np.ndarray[DTYPE_t, ndim=2] query_contig = np.ascontiguousarray(query_boxes, dtype=DTYPE) */ __pyx_tuple__12 = PyTuple_Pack(4, __pyx_n_s_boxes, __pyx_n_s_query_boxes, __pyx_n_s_boxes_contig, __pyx_n_s_query_contig); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(0, 64, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__12); __Pyx_GIVEREF(__pyx_tuple__12); __pyx_codeobj__13 = (PyObject*)__Pyx_PyCode_New(2, 0, 4, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__12, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_Users_rowanz_code_scene_graph_l, __pyx_n_s_bbox_intersections, 64, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__13)) __PYX_ERR(0, 64, __pyx_L1_error) __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); return 0; __pyx_L1_error:; return -1; } #if PY_MAJOR_VERSION < 3 PyMODINIT_FUNC initbbox(void); /*proto*/ PyMODINIT_FUNC initbbox(void) #else PyMODINIT_FUNC PyInit_bbox(void); /*proto*/ PyMODINIT_FUNC PyInit_bbox(void) #endif { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { PyErr_Clear(); __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); if (!__Pyx_RefNanny) Py_FatalError("failed to import 'refnanny' module"); } #endif __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_bbox(void)", 0); if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pyx_CyFunction_USED if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_FusedFunction_USED if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Coroutine_USED if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Generator_USED if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_StopAsyncIteration_USED if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS #ifdef WITH_THREAD /* Python build with threading support? */ PyEval_InitThreads(); #endif #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4("bbox", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_d); __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); #endif if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); /*--- Initialize various global constants etc. ---*/ if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif if (__pyx_module_is_main_bbox) { if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) } #if PY_MAJOR_VERSION >= 3 { PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) if (!PyDict_GetItemString(modules, "bbox")) { if (unlikely(PyDict_SetItemString(modules, "bbox", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) } } #endif /*--- Builtin init code ---*/ if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Constants init code ---*/ if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Global init code ---*/ /*--- Variable export code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ /*--- Type import code ---*/ __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", #if CYTHON_COMPILING_IN_PYPY sizeof(PyTypeObject), #else sizeof(PyHeapTypeObject), #endif 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) __PYX_ERR(2, 9, __pyx_L1_error) __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) __PYX_ERR(1, 155, __pyx_L1_error) __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) __PYX_ERR(1, 168, __pyx_L1_error) __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) __PYX_ERR(1, 172, __pyx_L1_error) __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) __PYX_ERR(1, 181, __pyx_L1_error) __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) __PYX_ERR(1, 861, __pyx_L1_error) /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /* "bbox.pyx":9 * * cimport cython * import numpy as np # <<<<<<<<<<<<<< * cimport numpy as np * */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 9, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) __PYX_ERR(0, 9, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "bbox.pyx":12 * cimport numpy as np * * DTYPE = np.float # <<<<<<<<<<<<<< * ctypedef np.float_t DTYPE_t * */ __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 12, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_float); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 12, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (PyDict_SetItem(__pyx_d, __pyx_n_s_DTYPE, __pyx_t_2) < 0) __PYX_ERR(0, 12, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "bbox.pyx":15 * ctypedef np.float_t DTYPE_t * * def bbox_overlaps(boxes, query_boxes): # <<<<<<<<<<<<<< * cdef np.ndarray[DTYPE_t, ndim=2] boxes_contig = np.ascontiguousarray(boxes, dtype=DTYPE) * cdef np.ndarray[DTYPE_t, ndim=2] query_contig = np.ascontiguousarray(query_boxes, dtype=DTYPE) */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_4bbox_1bbox_overlaps, NULL, __pyx_n_s_bbox); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 15, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_bbox_overlaps, __pyx_t_2) < 0) __PYX_ERR(0, 15, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "bbox.pyx":64 * * * def bbox_intersections(boxes, query_boxes): # <<<<<<<<<<<<<< * cdef np.ndarray[DTYPE_t, ndim=2] boxes_contig = np.ascontiguousarray(boxes, dtype=DTYPE) * cdef np.ndarray[DTYPE_t, ndim=2] query_contig = np.ascontiguousarray(query_boxes, dtype=DTYPE) */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_4bbox_3bbox_intersections, NULL, __pyx_n_s_bbox); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 64, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_bbox_intersections, __pyx_t_2) < 0) __PYX_ERR(0, 64, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "bbox.pyx":1 * # -------------------------------------------------------- # <<<<<<<<<<<<<< * # Fast R-CNN * # Copyright (c) 2015 Microsoft */ __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "../../../../../anaconda/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":997 * raise ImportError("numpy.core.umath failed to import") * * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ /*--- Wrapped vars code ---*/ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); if (__pyx_m) { if (__pyx_d) { __Pyx_AddTraceback("init bbox", __pyx_clineno, __pyx_lineno, __pyx_filename); } Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init bbox"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if PY_MAJOR_VERSION < 3 return; #else return __pyx_m; #endif } /* --- Runtime support code --- */ /* Refnanny */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule((char *)modname); if (!m) goto end; p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif /* GetBuiltinName */ static PyObject *__Pyx_GetBuiltinName(PyObject *name) { PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); if (unlikely(!result)) { PyErr_Format(PyExc_NameError, #if PY_MAJOR_VERSION >= 3 "name '%U' is not defined", name); #else "name '%.200s' is not defined", PyString_AS_STRING(name)); #endif } return result; } /* RaiseArgTupleInvalid */ static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found) { Py_ssize_t num_expected; const char *more_or_less; if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; } else { num_expected = num_max; more_or_less = "at most"; } if (exact) { more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } /* RaiseDoubleKeywords */ static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) { PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION >= 3 "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, PyString_AsString(kw_name)); #endif } /* ParseKeywords */ static int __Pyx_ParseOptionalKeywords( PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name) { PyObject *key = 0, *value = 0; Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; continue; } name = first_kw_arg; #if PY_MAJOR_VERSION < 3 if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { while (*name) { if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) && _PyString_Eq(**name, key)) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { if ((**argname == key) || ( (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) && _PyString_Eq(**argname, key))) { goto arg_passed_twice; } argname++; } } } else #endif if (likely(PyUnicode_Check(key))) { while (*name) { int cmp = (**name == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**name, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { int cmp = (**argname == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**argname, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) goto arg_passed_twice; argname++; } } } else goto invalid_keyword_type; if (kwds2) { if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; } else { goto invalid_keyword; } } return 0; arg_passed_twice: __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", function_name, key); #endif bad: return -1; } /* GetModuleGlobalName */ static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { PyObject *result; #if !CYTHON_AVOID_BORROWED_REFS result = PyDict_GetItem(__pyx_d, name); if (likely(result)) { Py_INCREF(result); } else { #else result = PyObject_GetItem(__pyx_d, name); if (!result) { PyErr_Clear(); #endif result = __Pyx_GetBuiltinName(name); } return result; } /* PyObjectCall */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *result; ternaryfunc call = func->ob_type->tp_call; if (unlikely(!call)) return PyObject_Call(func, arg, kw); if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; result = (*call)(func, arg, kw); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif /* ExtTypeTest */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (likely(PyObject_TypeCheck(obj, type))) return 1; PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", Py_TYPE(obj)->tp_name, type->tp_name); return 0; } /* BufferFormatCheck */ static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { unsigned int n = 1; return *(unsigned char*)(&n) != 0; } static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type) { stack[0].field = &ctx->root; stack[0].parent_offset = 0; ctx->root.type = type; ctx->root.name = "buffer dtype"; ctx->root.offset = 0; ctx->head = stack; ctx->head->field = &ctx->root; ctx->fmt_offset = 0; ctx->head->parent_offset = 0; ctx->new_packmode = '@'; ctx->enc_packmode = '@'; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->is_complex = 0; ctx->is_valid_array = 0; ctx->struct_alignment = 0; while (type->typegroup == 'S') { ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = 0; type = type->fields->type; } } static int __Pyx_BufFmt_ParseNumber(const char** ts) { int count; const char* t = *ts; if (*t < '0' || *t > '9') { return -1; } else { count = *t++ - '0'; while (*t >= '0' && *t < '9') { count *= 10; count += *t++ - '0'; } } *ts = t; return count; } static int __Pyx_BufFmt_ExpectNumber(const char **ts) { int number = __Pyx_BufFmt_ParseNumber(ts); if (number == -1) PyErr_Format(PyExc_ValueError,\ "Does not understand character buffer dtype format string ('%c')", **ts); return number; } static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { PyErr_Format(PyExc_ValueError, "Unexpected format string character: '%c'", ch); } static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { case 'c': return "'char'"; case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; case 'i': return "'int'"; case 'I': return "'unsigned int'"; case 'l': return "'long'"; case 'L': return "'unsigned long'"; case 'q': return "'long long'"; case 'Q': return "'unsigned long long'"; case 'f': return (is_complex ? "'complex float'" : "'float'"); case 'd': return (is_complex ? "'complex double'" : "'double'"); case 'g': return (is_complex ? "'complex long double'" : "'long double'"); case 'T': return "a struct"; case 'O': return "Python object"; case 'P': return "a pointer"; case 's': case 'p': return "a string"; case 0: return "end"; default: return "unparseable format string"; } } static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return 2; case 'i': case 'I': case 'l': case 'L': return 4; case 'q': case 'Q': return 8; case 'f': return (is_complex ? 8 : 4); case 'd': return (is_complex ? 16 : 8); case 'g': { PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); return 0; } case 'O': case 'P': return sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { switch (ch) { case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(short); case 'i': case 'I': return sizeof(int); case 'l': case 'L': return sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(float) * (is_complex ? 2 : 1); case 'd': return sizeof(double) * (is_complex ? 2 : 1); case 'g': return sizeof(long double) * (is_complex ? 2 : 1); case 'O': case 'P': return sizeof(void*); default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } typedef struct { char c; short x; } __Pyx_st_short; typedef struct { char c; int x; } __Pyx_st_int; typedef struct { char c; long x; } __Pyx_st_long; typedef struct { char c; float x; } __Pyx_st_float; typedef struct { char c; double x; } __Pyx_st_double; typedef struct { char c; long double x; } __Pyx_st_longdouble; typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_st_float) - sizeof(float); case 'd': return sizeof(__Pyx_st_double) - sizeof(double); case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } /* These are for computing the padding at the end of the struct to align on the first member of the struct. This will probably the same as above, but we don't have any guarantees. */ typedef struct { short x; char c; } __Pyx_pad_short; typedef struct { int x; char c; } __Pyx_pad_int; typedef struct { long x; char c; } __Pyx_pad_long; typedef struct { float x; char c; } __Pyx_pad_float; typedef struct { double x; char c; } __Pyx_pad_double; typedef struct { long double x; char c; } __Pyx_pad_longdouble; typedef struct { void *x; char c; } __Pyx_pad_void_p; #ifdef HAVE_LONG_LONG typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { case 'c': return 'H'; case 'b': case 'h': case 'i': case 'l': case 'q': case 's': case 'p': return 'I'; case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); case 'O': return 'O'; case 'P': return 'P'; default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { if (ctx->head == NULL || ctx->head->field == &ctx->root) { const char* expected; const char* quote; if (ctx->head == NULL) { expected = "end"; quote = ""; } else { expected = ctx->head->field->type->name; quote = "'"; } PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected %s%s%s but got %s", quote, expected, quote, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); } else { __Pyx_StructField* field = ctx->head->field; __Pyx_StructField* parent = (ctx->head - 1)->field; PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), parent->type->name, field->name); } } static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { char group; size_t size, offset, arraysize = 1; if (ctx->enc_type == 0) return 0; if (ctx->head->field->type->arraysize[0]) { int i, ndim = 0; if (ctx->enc_type == 's' || ctx->enc_type == 'p') { ctx->is_valid_array = ctx->head->field->type->ndim == 1; ndim = 1; if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %zu", ctx->head->field->type->arraysize[0], ctx->enc_count); return -1; } } if (!ctx->is_valid_array) { PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", ctx->head->field->type->ndim, ndim); return -1; } for (i = 0; i < ctx->head->field->type->ndim; i++) { arraysize *= ctx->head->field->type->arraysize[i]; } ctx->is_valid_array = 0; ctx->enc_count = 1; } group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); do { __Pyx_StructField* field = ctx->head->field; __Pyx_TypeInfo* type = field->type; if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); } else { size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); } if (ctx->enc_packmode == '@') { size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); size_t align_mod_offset; if (align_at == 0) return -1; align_mod_offset = ctx->fmt_offset % align_at; if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; if (ctx->struct_alignment == 0) ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, ctx->is_complex); } if (type->size != size || type->typegroup != group) { if (type->typegroup == 'C' && type->fields != NULL) { size_t parent_offset = ctx->head->parent_offset + field->offset; ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = parent_offset; continue; } if ((type->typegroup == 'H' || group == 'H') && type->size == size) { } else { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } } offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } ctx->fmt_offset += size; if (arraysize) ctx->fmt_offset += (arraysize - 1) * size; --ctx->enc_count; while (1) { if (field == &ctx->root) { ctx->head = NULL; if (ctx->enc_count != 0) { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } break; } ctx->head->field = ++field; if (field->type == NULL) { --ctx->head; field = ctx->head->field; continue; } else if (field->type->typegroup == 'S') { size_t parent_offset = ctx->head->parent_offset + field->offset; if (field->type->fields->type == NULL) continue; field = field->type->fields; ++ctx->head; ctx->head->field = field; ctx->head->parent_offset = parent_offset; break; } else { break; } } } while (ctx->enc_count); ctx->enc_type = 0; ctx->is_complex = 0; return 0; } static CYTHON_INLINE PyObject * __pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) { const char *ts = *tsp; int i = 0, number; int ndim = ctx->head->field->type->ndim; ; ++ts; if (ctx->new_count != 1) { PyErr_SetString(PyExc_ValueError, "Cannot handle repeated arrays in format string"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; while (*ts && *ts != ')') { switch (*ts) { case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; default: break; } number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) return PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %d", ctx->head->field->type->arraysize[i], number); if (*ts != ',' && *ts != ')') return PyErr_Format(PyExc_ValueError, "Expected a comma in format string, got '%c'", *ts); if (*ts == ',') ts++; i++; } if (i != ndim) return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", ctx->head->field->type->ndim, i); if (!*ts) { PyErr_SetString(PyExc_ValueError, "Unexpected end of format string, expected ')'"); return NULL; } ctx->is_valid_array = 1; ctx->new_count = 1; *tsp = ++ts; return Py_None; } static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { int got_Z = 0; while (1) { switch(*ts) { case 0: if (ctx->enc_type != 0 && ctx->head == NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; if (ctx->head != NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } return ts; case ' ': case '\r': case '\n': ++ts; break; case '<': if (!__Pyx_IsLittleEndian()) { PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '>': case '!': if (__Pyx_IsLittleEndian()) { PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '=': case '@': case '^': ctx->new_packmode = *ts++; break; case 'T': { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; size_t struct_alignment = ctx->struct_alignment; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; ctx->enc_count = 0; ctx->struct_alignment = 0; ++ts; ts_after_sub = ts; for (i = 0; i != struct_count; ++i) { ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); if (!ts_after_sub) return NULL; } ts = ts_after_sub; if (struct_alignment) ctx->struct_alignment = struct_alignment; } break; case '}': { size_t alignment = ctx->struct_alignment; ++ts; if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; if (alignment && ctx->fmt_offset % alignment) { ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); } } return ts; case 'x': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->fmt_offset += ctx->new_count; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->enc_packmode = ctx->new_packmode; ++ts; break; case 'Z': got_Z = 1; ++ts; if (*ts != 'f' && *ts != 'd' && *ts != 'g') { __Pyx_BufFmt_RaiseUnexpectedChar('Z'); return NULL; } case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'g': case 'O': case 'p': if (ctx->enc_type == *ts && got_Z == ctx->is_complex && ctx->enc_packmode == ctx->new_packmode) { ctx->enc_count += ctx->new_count; ctx->new_count = 1; got_Z = 0; ++ts; break; } case 's': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_count = ctx->new_count; ctx->enc_packmode = ctx->new_packmode; ctx->enc_type = *ts; ctx->is_complex = got_Z; ++ts; ctx->new_count = 1; got_Z = 0; break; case ':': ++ts; while(*ts != ':') ++ts; ++ts; break; case '(': if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; break; default: { int number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; ctx->new_count = (size_t)number; } } } } static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; buf->obj = NULL; buf->strides = __Pyx_zeros; buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; } static CYTHON_INLINE int __Pyx_GetBufferAndValidate( Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { if (obj == Py_None || obj == NULL) { __Pyx_ZeroBuffer(buf); return 0; } buf->buf = NULL; if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; if (buf->ndim != nd) { PyErr_Format(PyExc_ValueError, "Buffer has wrong number of dimensions (expected %d, got %d)", nd, buf->ndim); goto fail; } if (!cast) { __Pyx_BufFmt_Context ctx; __Pyx_BufFmt_Init(&ctx, stack, dtype); if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; } if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; return 0; fail:; __Pyx_ZeroBuffer(buf); return -1; } static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { if (info->buf == NULL) return; if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; __Pyx_ReleaseBuffer(info); } /* PyErrFetchRestore */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; tstate->curexc_type = type; tstate->curexc_value = value; tstate->curexc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; } #endif /* BufferIndexError */ static void __Pyx_RaiseBufferIndexError(int axis) { PyErr_Format(PyExc_IndexError, "Out of bounds on buffer access (axis %d)", axis); } /* RaiseException */ #if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { __Pyx_PyThreadState_declare Py_XINCREF(type); if (!value || value == Py_None) value = NULL; else Py_INCREF(value); if (!tb || tb == Py_None) tb = NULL; else { Py_INCREF(tb); if (!PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto raise_error; } } if (PyType_Check(type)) { #if CYTHON_COMPILING_IN_PYPY if (!value) { Py_INCREF(Py_None); value = Py_None; } #endif PyErr_NormalizeException(&type, &value, &tb); } else { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } value = type; type = (PyObject*) Py_TYPE(type); Py_INCREF(type); if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto raise_error; } } __Pyx_PyThreadState_assign __Pyx_ErrRestore(type, value, tb); return; raise_error: Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(tb); return; } #else static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto bad; } if (value == Py_None) value = 0; if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto bad; } value = type; type = (PyObject*) Py_TYPE(value); } else if (PyExceptionClass_Check(type)) { PyObject *instance_class = NULL; if (value && PyExceptionInstance_Check(value)) { instance_class = (PyObject*) Py_TYPE(value); if (instance_class != type) { int is_subclass = PyObject_IsSubclass(instance_class, type); if (!is_subclass) { instance_class = NULL; } else if (unlikely(is_subclass == -1)) { goto bad; } else { type = instance_class; } } } if (!instance_class) { PyObject *args; if (!value) args = PyTuple_New(0); else if (PyTuple_Check(value)) { Py_INCREF(value); args = value; } else args = PyTuple_Pack(1, value); if (!args) goto bad; owned_instance = PyObject_Call(type, args, NULL); Py_DECREF(args); if (!owned_instance) goto bad; value = owned_instance; if (!PyExceptionInstance_Check(value)) { PyErr_Format(PyExc_TypeError, "calling %R should have returned an instance of " "BaseException, not %R", type, Py_TYPE(value)); goto bad; } } } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } #if PY_VERSION_HEX >= 0x03030000 if (cause) { #else if (cause && cause != Py_None) { #endif PyObject *fixed_cause; if (cause == Py_None) { fixed_cause = NULL; } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); if (tb) { #if CYTHON_COMPILING_IN_PYPY PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); Py_INCREF(tb); PyErr_Restore(tmp_type, tmp_value, tb); Py_XDECREF(tmp_tb); #else PyThreadState *tstate = PyThreadState_GET(); PyObject* tmp_tb = tstate->curexc_traceback; if (tb != tmp_tb) { Py_INCREF(tb); tstate->curexc_traceback = tb; Py_XDECREF(tmp_tb); } #endif } bad: Py_XDECREF(owned_instance); return; } #endif /* RaiseTooManyValuesToUnpack */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } /* RaiseNeedMoreValuesToUnpack */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", index, (index == 1) ? "" : "s"); } /* RaiseNoneIterError */ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } /* SaveResetException */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { *type = tstate->exc_type; *value = tstate->exc_value; *tb = tstate->exc_traceback; Py_XINCREF(*type); Py_XINCREF(*value); Py_XINCREF(*tb); } static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = type; tstate->exc_value = value; tstate->exc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } #endif /* PyErrExceptionMatches */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err) { PyObject *exc_type = tstate->curexc_type; if (exc_type == err) return 1; if (unlikely(!exc_type)) return 0; return PyErr_GivenExceptionMatches(exc_type, err); } #endif /* GetException */ #if CYTHON_FAST_THREAD_STATE static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { #endif PyObject *local_type, *local_value, *local_tb; #if CYTHON_FAST_THREAD_STATE PyObject *tmp_type, *tmp_value, *tmp_tb; local_type = tstate->curexc_type; local_value = tstate->curexc_value; local_tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; #else PyErr_Fetch(&local_type, &local_value, &local_tb); #endif PyErr_NormalizeException(&local_type, &local_value, &local_tb); #if CYTHON_FAST_THREAD_STATE if (unlikely(tstate->curexc_type)) #else if (unlikely(PyErr_Occurred())) #endif goto bad; #if PY_MAJOR_VERSION >= 3 if (local_tb) { if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) goto bad; } #endif Py_XINCREF(local_tb); Py_XINCREF(local_type); Py_XINCREF(local_value); *type = local_type; *value = local_value; *tb = local_tb; #if CYTHON_FAST_THREAD_STATE tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = local_type; tstate->exc_value = local_value; tstate->exc_traceback = local_tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #else PyErr_SetExcInfo(local_type, local_value, local_tb); #endif return 0; bad: *type = 0; *value = 0; *tb = 0; Py_XDECREF(local_type); Py_XDECREF(local_value); Py_XDECREF(local_tb); return -1; } /* Import */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; #if PY_VERSION_HEX < 0x03030000 PyObject *py_import; py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); if (!py_import) goto bad; #endif if (from_list) list = from_list; else { empty_list = PyList_New(0); if (!empty_list) goto bad; list = empty_list; } global_dict = PyModule_GetDict(__pyx_m); if (!global_dict) goto bad; empty_dict = PyDict_New(); if (!empty_dict) goto bad; { #if PY_MAJOR_VERSION >= 3 if (level == -1) { if (strchr(__Pyx_MODULE_NAME, '.')) { #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(1); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, 1); #endif if (!module) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) goto bad; PyErr_Clear(); } } level = 0; } #endif if (!module) { #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(level); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, level); #endif } } bad: #if PY_VERSION_HEX < 0x03030000 Py_XDECREF(py_import); #endif Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } /* CodeObjectCache */ static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { return count; } while (start < end) { mid = start + (end - start) / 2; if (code_line < entries[mid].code_line) { end = mid; } else if (code_line > entries[mid].code_line) { start = mid + 1; } else { return mid; } } if (code_line <= entries[mid].code_line) { return mid; } else { return mid + 1; } } static PyCodeObject *__pyx_find_code_object(int code_line) { PyCodeObject* code_object; int pos; if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { return NULL; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { return NULL; } code_object = __pyx_code_cache.entries[pos].code_object; Py_INCREF(code_object); return code_object; } static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { int pos, i; __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; if (unlikely(!code_line)) { return; } if (unlikely(!entries)) { entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); if (likely(entries)) { __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = 64; __pyx_code_cache.count = 1; entries[0].code_line = code_line; entries[0].code_object = code_object; Py_INCREF(code_object); } return; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { PyCodeObject* tmp = entries[pos].code_object; entries[pos].code_object = code_object; Py_DECREF(tmp); return; } if (__pyx_code_cache.count == __pyx_code_cache.max_count) { int new_max = __pyx_code_cache.max_count + 64; entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); if (unlikely(!entries)) { return; } __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = new_max; } for (i=__pyx_code_cache.count; i>pos; i--) { entries[i] = entries[i-1]; } entries[pos].code_line = code_line; entries[pos].code_object = code_object; __pyx_code_cache.count++; Py_INCREF(code_object); } /* AddTraceback */ #include "compile.h" #include "frameobject.h" #include "traceback.h" static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; #if PY_MAJOR_VERSION < 3 py_srcfile = PyString_FromString(filename); #else py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; if (c_line) { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromString(funcname); #else py_funcname = PyUnicode_FromString(funcname); #endif } if (!py_funcname) goto bad; py_code = __Pyx_PyCode_New( 0, 0, 0, 0, 0, __pyx_empty_bytes, /*PyObject *code,*/ __pyx_empty_tuple, /*PyObject *consts,*/ __pyx_empty_tuple, /*PyObject *names,*/ __pyx_empty_tuple, /*PyObject *varnames,*/ __pyx_empty_tuple, /*PyObject *freevars,*/ __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ py_line, __pyx_empty_bytes /*PyObject *lnotab*/ ); Py_DECREF(py_srcfile); Py_DECREF(py_funcname); return py_code; bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); return NULL; } static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; py_code = __pyx_find_code_object(c_line ? c_line : py_line); if (!py_code) { py_code = __Pyx_CreateCodeObjectForTraceback( funcname, c_line, py_line, filename); if (!py_code) goto bad; __pyx_insert_code_object(c_line ? c_line : py_line, py_code); } py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ __pyx_d, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; __Pyx_PyFrame_SetLineNumber(py_frame, py_line); PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_code); Py_XDECREF(py_frame); } #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); return -1; } static void __Pyx_ReleaseBuffer(Py_buffer *view) { PyObject *obj = view->obj; if (!obj) return; if (PyObject_CheckBuffer(obj)) { PyBuffer_Release(view); return; } if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } Py_DECREF(obj); view->obj = NULL; } #endif /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value) { const unsigned int neg_one = (unsigned int) -1, const_zero = (unsigned int) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(unsigned int) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(unsigned int) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned int) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(unsigned int) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned int) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(unsigned int), little, !is_unsigned); } } /* CIntFromPyVerify */ #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) #define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) #define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ {\ func_type value = func_value;\ if (sizeof(target_type) < sizeof(func_type)) {\ if (unlikely(value != (func_type) (target_type) value)) {\ func_type zero = 0;\ if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ return (target_type) -1;\ if (is_unsigned && unlikely(value < zero))\ goto raise_neg_overflow;\ else\ goto raise_overflow;\ }\ }\ return (target_type) value;\ } /* Declarations */ #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { return ::std::complex< float >(x, y); } #else static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { return x + y*(__pyx_t_float_complex)_Complex_I; } #endif #else static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { __pyx_t_float_complex z; z.real = x; z.imag = y; return z; } #endif /* Arithmetic */ #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { return (a.real == b.real) && (a.imag == b.imag); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real + b.real; z.imag = a.imag + b.imag; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real - b.real; z.imag = a.imag - b.imag; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real * b.real - a.imag * b.imag; z.imag = a.real * b.imag + a.imag * b.real; return z; } #if 1 static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { if (b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); } else if (fabsf(b.real) >= fabsf(b.imag)) { if (b.real == 0 && b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.imag); } else { float r = b.imag / b.real; float s = 1.0 / (b.real + b.imag * r); return __pyx_t_float_complex_from_parts( (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); } } else { float r = b.real / b.imag; float s = 1.0 / (b.imag + b.real * r); return __pyx_t_float_complex_from_parts( (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); } } #else static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { if (b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); } else { float denom = b.real * b.real + b.imag * b.imag; return __pyx_t_float_complex_from_parts( (a.real * b.real + a.imag * b.imag) / denom, (a.imag * b.real - a.real * b.imag) / denom); } } #endif static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex a) { __pyx_t_float_complex z; z.real = -a.real; z.imag = -a.imag; return z; } static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex a) { __pyx_t_float_complex z; z.real = a.real; z.imag = -a.imag; return z; } #if 1 static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex z) { #if !defined(HAVE_HYPOT) || defined(_MSC_VER) return sqrtf(z.real*z.real + z.imag*z.imag); #else return hypotf(z.real, z.imag); #endif } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; float r, lnr, theta, z_r, z_theta; if (b.imag == 0 && b.real == (int)b.real) { if (b.real < 0) { float denom = a.real * a.real + a.imag * a.imag; a.real = a.real / denom; a.imag = -a.imag / denom; b.real = -b.real; } switch ((int)b.real) { case 0: z.real = 1; z.imag = 0; return z; case 1: return a; case 2: z = __Pyx_c_prod_float(a, a); return __Pyx_c_prod_float(a, a); case 3: z = __Pyx_c_prod_float(a, a); return __Pyx_c_prod_float(z, a); case 4: z = __Pyx_c_prod_float(a, a); return __Pyx_c_prod_float(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } else if (b.imag == 0) { z.real = powf(a.real, b.real); z.imag = 0; return z; } else if (a.real > 0) { r = a.real; theta = 0; } else { r = -a.real; theta = atan2f(0, -1); } } else { r = __Pyx_c_abs_float(a); theta = atan2f(a.imag, a.real); } lnr = logf(r); z_r = expf(lnr * b.real - theta * b.imag); z_theta = theta * b.real + lnr * b.imag; z.real = z_r * cosf(z_theta); z.imag = z_r * sinf(z_theta); return z; } #endif #endif /* Declarations */ #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { return ::std::complex< double >(x, y); } #else static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { return x + y*(__pyx_t_double_complex)_Complex_I; } #endif #else static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { __pyx_t_double_complex z; z.real = x; z.imag = y; return z; } #endif /* Arithmetic */ #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { return (a.real == b.real) && (a.imag == b.imag); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real + b.real; z.imag = a.imag + b.imag; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real - b.real; z.imag = a.imag - b.imag; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real * b.real - a.imag * b.imag; z.imag = a.real * b.imag + a.imag * b.real; return z; } #if 1 static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { if (b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); } else if (fabs(b.real) >= fabs(b.imag)) { if (b.real == 0 && b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.imag); } else { double r = b.imag / b.real; double s = 1.0 / (b.real + b.imag * r); return __pyx_t_double_complex_from_parts( (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); } } else { double r = b.real / b.imag; double s = 1.0 / (b.imag + b.real * r); return __pyx_t_double_complex_from_parts( (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); } } #else static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { if (b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); } else { double denom = b.real * b.real + b.imag * b.imag; return __pyx_t_double_complex_from_parts( (a.real * b.real + a.imag * b.imag) / denom, (a.imag * b.real - a.real * b.imag) / denom); } } #endif static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex a) { __pyx_t_double_complex z; z.real = -a.real; z.imag = -a.imag; return z; } static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex a) { __pyx_t_double_complex z; z.real = a.real; z.imag = -a.imag; return z; } #if 1 static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex z) { #if !defined(HAVE_HYPOT) || defined(_MSC_VER) return sqrt(z.real*z.real + z.imag*z.imag); #else return hypot(z.real, z.imag); #endif } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; double r, lnr, theta, z_r, z_theta; if (b.imag == 0 && b.real == (int)b.real) { if (b.real < 0) { double denom = a.real * a.real + a.imag * a.imag; a.real = a.real / denom; a.imag = -a.imag / denom; b.real = -b.real; } switch ((int)b.real) { case 0: z.real = 1; z.imag = 0; return z; case 1: return a; case 2: z = __Pyx_c_prod_double(a, a); return __Pyx_c_prod_double(a, a); case 3: z = __Pyx_c_prod_double(a, a); return __Pyx_c_prod_double(z, a); case 4: z = __Pyx_c_prod_double(a, a); return __Pyx_c_prod_double(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } else if (b.imag == 0) { z.real = pow(a.real, b.real); z.imag = 0; return z; } else if (a.real > 0) { r = a.real; theta = 0; } else { r = -a.real; theta = atan2(0, -1); } } else { r = __Pyx_c_abs_double(a); theta = atan2(a.imag, a.real); } lnr = log(r); z_r = exp(lnr * b.real - theta * b.imag); z_theta = theta * b.real + lnr * b.imag; z.real = z_r * cos(z_theta); z.imag = z_r * sin(z_theta); return z; } #endif #endif /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { const int neg_one = (int) -1, const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(int) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(int) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(int) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(int), little, !is_unsigned); } } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_enum__NPY_TYPES(enum NPY_TYPES value) { const enum NPY_TYPES neg_one = (enum NPY_TYPES) -1, const_zero = (enum NPY_TYPES) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(enum NPY_TYPES) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(enum NPY_TYPES) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(enum NPY_TYPES) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(enum NPY_TYPES) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(enum NPY_TYPES) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(enum NPY_TYPES), little, !is_unsigned); } } /* CIntFromPy */ static CYTHON_INLINE unsigned int __Pyx_PyInt_As_unsigned_int(PyObject *x) { const unsigned int neg_one = (unsigned int) -1, const_zero = (unsigned int) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(unsigned int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(unsigned int, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (unsigned int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (unsigned int) 0; case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, digits[0]) case 2: if (8 * sizeof(unsigned int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) >= 2 * PyLong_SHIFT) { return (unsigned int) (((((unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])); } } break; case 3: if (8 * sizeof(unsigned int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) >= 3 * PyLong_SHIFT) { return (unsigned int) (((((((unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])); } } break; case 4: if (8 * sizeof(unsigned int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) >= 4 * PyLong_SHIFT) { return (unsigned int) (((((((((unsigned int)digits[3]) << PyLong_SHIFT) | (unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (unsigned int) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(unsigned int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned int, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned int) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (unsigned int) 0; case -1: __PYX_VERIFY_RETURN_INT(unsigned int, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(unsigned int, digit, +digits[0]) case -2: if (8 * sizeof(unsigned int) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 2 * PyLong_SHIFT) { return (unsigned int) (((unsigned int)-1)*(((((unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case 2: if (8 * sizeof(unsigned int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 2 * PyLong_SHIFT) { return (unsigned int) ((((((unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case -3: if (8 * sizeof(unsigned int) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 3 * PyLong_SHIFT) { return (unsigned int) (((unsigned int)-1)*(((((((unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case 3: if (8 * sizeof(unsigned int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 3 * PyLong_SHIFT) { return (unsigned int) ((((((((unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case -4: if (8 * sizeof(unsigned int) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 4 * PyLong_SHIFT) { return (unsigned int) (((unsigned int)-1)*(((((((((unsigned int)digits[3]) << PyLong_SHIFT) | (unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; case 4: if (8 * sizeof(unsigned int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(unsigned int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(unsigned int) - 1 > 4 * PyLong_SHIFT) { return (unsigned int) ((((((((((unsigned int)digits[3]) << PyLong_SHIFT) | (unsigned int)digits[2]) << PyLong_SHIFT) | (unsigned int)digits[1]) << PyLong_SHIFT) | (unsigned int)digits[0]))); } } break; } #endif if (sizeof(unsigned int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned int, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(unsigned int) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(unsigned int, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else unsigned int val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (unsigned int) -1; } } else { unsigned int val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (unsigned int) -1; val = __Pyx_PyInt_As_unsigned_int(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to unsigned int"); return (unsigned int) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned int"); return (unsigned int) -1; } /* CIntFromPy */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { const int neg_one = (int) -1, const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (int) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) case -2: if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -3: if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -4: if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; } #endif if (sizeof(int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else int val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (int) -1; } } else { int val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (int) -1; val = __Pyx_PyInt_As_int(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to int"); return (int) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to int"); return (int) -1; } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(long) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(long) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(long), little, !is_unsigned); } } /* CIntFromPy */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(long) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (long) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (long) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(long) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) case -2: if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -3: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -4: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; } #endif if (sizeof(long) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else long val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (long) -1; } } else { long val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (long) -1; val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to long"); return (long) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long) -1; } /* CheckBinaryVersion */ static int __Pyx_check_binary_version(void) { char ctversion[4], rtversion[4]; PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { char message[200]; PyOS_snprintf(message, sizeof(message), "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); return PyErr_WarnEx(NULL, message, 1); } return 0; } /* ModuleImport */ #ifndef __PYX_HAVE_RT_ImportModule #define __PYX_HAVE_RT_ImportModule static PyObject *__Pyx_ImportModule(const char *name) { PyObject *py_name = 0; PyObject *py_module = 0; py_name = __Pyx_PyIdentifier_FromString(name); if (!py_name) goto bad; py_module = PyImport_Import(py_name); Py_DECREF(py_name); return py_module; bad: Py_XDECREF(py_name); return 0; } #endif /* TypeImport */ #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict) { PyObject *py_module = 0; PyObject *result = 0; PyObject *py_name = 0; char warning[200]; Py_ssize_t basicsize; #ifdef Py_LIMITED_API PyObject *py_basicsize; #endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); Py_DECREF(py_name); py_name = 0; Py_DECREF(py_module); py_module = 0; if (!result) goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } #ifndef Py_LIMITED_API basicsize = ((PyTypeObject *)result)->tp_basicsize; #else py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); if (!py_basicsize) goto bad; basicsize = PyLong_AsSsize_t(py_basicsize); Py_DECREF(py_basicsize); py_basicsize = 0; if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) goto bad; #endif if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility. Expected %zd, got %zd", module_name, class_name, basicsize, size); if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; } else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, "%.200s.%.200s has the wrong size, try recompiling. Expected %zd, got %zd", module_name, class_name, basicsize, size); goto bad; } return (PyTypeObject *)result; bad: Py_XDECREF(py_module); Py_XDECREF(result); return NULL; } #endif /* InitStrings */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 if (t->is_unicode) { *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); } else if (t->intern) { *t->p = PyString_InternFromString(t->s); } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } #else if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); } else if (t->encoding) { *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); } else { *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); } } else { *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); } #endif if (!*t->p) return -1; ++t; } return 0; } static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); } static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { #if CYTHON_COMPILING_IN_CPYTHON && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if ( #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII __Pyx_sys_getdefaultencoding_not_ascii && #endif PyUnicode_Check(o)) { #if PY_VERSION_HEX < 0x03030000 char* defenc_c; PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); if (!defenc) return NULL; defenc_c = PyBytes_AS_STRING(defenc); #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII { char* end = defenc_c + PyBytes_GET_SIZE(defenc); char* c; for (c = defenc_c; c < end; c++) { if ((unsigned char) (*c) >= 128) { PyUnicode_AsASCIIString(o); return NULL; } } } #endif *length = PyBytes_GET_SIZE(defenc); return defenc_c; #else if (__Pyx_PyUnicode_READY(o) == -1) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (PyUnicode_IS_ASCII(o)) { *length = PyUnicode_GET_LENGTH(o); return PyUnicode_AsUTF8(o); } else { PyUnicode_AsASCIIString(o); return NULL; } #else return PyUnicode_AsUTF8AndSize(o, length); #endif #endif } else #endif #if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) if (PyByteArray_Check(o)) { *length = PyByteArray_GET_SIZE(o); return PyByteArray_AS_STRING(o); } else #endif { char* result; int r = PyBytes_AsStringAndSize(o, &result, length); if (unlikely(r < 0)) { return NULL; } else { return result; } } } static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { #if CYTHON_USE_TYPE_SLOTS PyNumberMethods *m; #endif const char *name = NULL; PyObject *res = NULL; #if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return __Pyx_NewRef(x); #if CYTHON_USE_TYPE_SLOTS m = Py_TYPE(x)->tp_as_number; #if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); } else if (m && m->nb_long) { name = "long"; res = PyNumber_Long(x); } #else if (m && m->nb_int) { name = "int"; res = PyNumber_Long(x); } #endif #else res = PyNumber_Int(x); #endif if (res) { #if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; } } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "an integer is required"); } return res; } static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject *x; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(b))) { if (sizeof(Py_ssize_t) >= sizeof(long)) return PyInt_AS_LONG(b); else return PyInt_AsSsize_t(x); } #endif if (likely(PyLong_CheckExact(b))) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)b)->ob_digit; const Py_ssize_t size = Py_SIZE(b); if (likely(__Pyx_sst_abs(size) <= 1)) { ival = likely(size) ? digits[0] : 0; if (size == -1) ival = -ival; return ival; } else { switch (size) { case 2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; } } #endif return PyLong_AsSsize_t(b); } x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); } #endif /* Py_PYTHON_H */ ================================================ FILE: lib/fpn/box_intersections_cpu/bbox.pyx ================================================ # -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Sergey Karayev # -------------------------------------------------------- cimport cython import numpy as np cimport numpy as np DTYPE = np.float ctypedef np.float_t DTYPE_t def bbox_overlaps(boxes, query_boxes): cdef np.ndarray[DTYPE_t, ndim=2] boxes_contig = np.ascontiguousarray(boxes, dtype=DTYPE) cdef np.ndarray[DTYPE_t, ndim=2] query_contig = np.ascontiguousarray(query_boxes, dtype=DTYPE) return bbox_overlaps_c(boxes_contig, query_contig) cdef np.ndarray[DTYPE_t, ndim=2] bbox_overlaps_c( np.ndarray[DTYPE_t, ndim=2] boxes, np.ndarray[DTYPE_t, ndim=2] query_boxes): """ Parameters ---------- boxes: (N, 4) ndarray of float query_boxes: (K, 4) ndarray of float Returns ------- overlaps: (N, K) ndarray of overlap between boxes and query_boxes """ cdef unsigned int N = boxes.shape[0] cdef unsigned int K = query_boxes.shape[0] cdef np.ndarray[DTYPE_t, ndim=2] overlaps = np.zeros((N, K), dtype=DTYPE) cdef DTYPE_t iw, ih, box_area cdef DTYPE_t ua cdef unsigned int k, n for k in range(K): box_area = ( (query_boxes[k, 2] - query_boxes[k, 0] + 1) * (query_boxes[k, 3] - query_boxes[k, 1] + 1) ) for n in range(N): iw = ( min(boxes[n, 2], query_boxes[k, 2]) - max(boxes[n, 0], query_boxes[k, 0]) + 1 ) if iw > 0: ih = ( min(boxes[n, 3], query_boxes[k, 3]) - max(boxes[n, 1], query_boxes[k, 1]) + 1 ) if ih > 0: ua = float( (boxes[n, 2] - boxes[n, 0] + 1) * (boxes[n, 3] - boxes[n, 1] + 1) + box_area - iw * ih ) overlaps[n, k] = iw * ih / ua return overlaps def bbox_intersections(boxes, query_boxes): cdef np.ndarray[DTYPE_t, ndim=2] boxes_contig = np.ascontiguousarray(boxes, dtype=DTYPE) cdef np.ndarray[DTYPE_t, ndim=2] query_contig = np.ascontiguousarray(query_boxes, dtype=DTYPE) return bbox_intersections_c(boxes_contig, query_contig) cdef np.ndarray[DTYPE_t, ndim=2] bbox_intersections_c( np.ndarray[DTYPE_t, ndim=2] boxes, np.ndarray[DTYPE_t, ndim=2] query_boxes): """ For each query box compute the intersection ratio covered by boxes ---------- Parameters ---------- boxes: (N, 4) ndarray of float query_boxes: (K, 4) ndarray of float Returns ------- overlaps: (N, K) ndarray of intersec between boxes and query_boxes """ cdef unsigned int N = boxes.shape[0] cdef unsigned int K = query_boxes.shape[0] cdef np.ndarray[DTYPE_t, ndim=2] intersec = np.zeros((N, K), dtype=DTYPE) cdef DTYPE_t iw, ih, box_area cdef DTYPE_t ua cdef unsigned int k, n for k in range(K): box_area = ( (query_boxes[k, 2] - query_boxes[k, 0] + 1) * (query_boxes[k, 3] - query_boxes[k, 1] + 1) ) for n in range(N): iw = ( min(boxes[n, 2], query_boxes[k, 2]) - max(boxes[n, 0], query_boxes[k, 0]) + 1 ) if iw > 0: ih = ( min(boxes[n, 3], query_boxes[k, 3]) - max(boxes[n, 1], query_boxes[k, 1]) + 1 ) if ih > 0: intersec[n, k] = iw * ih / box_area return intersec ================================================ FILE: lib/fpn/box_intersections_cpu/setup.py ================================================ from distutils.core import setup from Cython.Build import cythonize import numpy setup(name="bbox_cython", ext_modules=cythonize('bbox.pyx'), include_dirs=[numpy.get_include()]) ================================================ FILE: lib/fpn/box_utils.py ================================================ import torch import numpy as np from torch.nn import functional as F from lib.fpn.box_intersections_cpu.bbox import bbox_overlaps as bbox_overlaps_np from lib.fpn.box_intersections_cpu.bbox import bbox_intersections as bbox_intersections_np def bbox_loss(prior_boxes, deltas, gt_boxes, eps=1e-4, scale_before=1): """ Computes the loss for predicting the GT boxes from prior boxes :param prior_boxes: [num_boxes, 4] (x1, y1, x2, y2) :param deltas: [num_boxes, 4] (tx, ty, th, tw) :param gt_boxes: [num_boxes, 4] (x1, y1, x2, y2) :return: """ prior_centers = center_size(prior_boxes) #(cx, cy, w, h) gt_centers = center_size(gt_boxes) #(cx, cy, w, h) center_targets = (gt_centers[:, :2] - prior_centers[:, :2]) / prior_centers[:, 2:] size_targets = torch.log(gt_centers[:, 2:]) - torch.log(prior_centers[:, 2:]) all_targets = torch.cat((center_targets, size_targets), 1) loss = F.smooth_l1_loss(deltas, all_targets, size_average=False)/(eps + prior_centers.size(0)) return loss def bbox_preds(boxes, deltas): """ Converts "deltas" (predicted by the network) along with prior boxes into (x1, y1, x2, y2) representation. :param boxes: Prior boxes, represented as (x1, y1, x2, y2) :param deltas: Offsets (tx, ty, tw, th) :param box_strides [num_boxes,] distance apart between boxes. anchor box can't go more than \pm box_strides/2 from its current position. If None then we'll use the widths and heights :return: Transformed boxes """ if boxes.size(0) == 0: return boxes prior_centers = center_size(boxes) xys = prior_centers[:, :2] + prior_centers[:, 2:] * deltas[:, :2] whs = torch.exp(deltas[:, 2:]) * prior_centers[:, 2:] return point_form(torch.cat((xys, whs), 1)) def center_size(boxes): """ Convert prior_boxes to (cx, cy, w, h) representation for comparison to center-size form ground truth data. Args: boxes: (tensor) point_form boxes Return: boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes. """ wh = boxes[:, 2:] - boxes[:, :2] + 1.0 if isinstance(boxes, np.ndarray): return np.column_stack((boxes[:, :2] + 0.5 * wh, wh)) return torch.cat((boxes[:, :2] + 0.5 * wh, wh), 1) def point_form(boxes): """ Convert prior_boxes to (xmin, ymin, xmax, ymax) representation for comparison to point form ground truth data. Args: boxes: (tensor) center-size default boxes from priorbox layers. Return: boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes. """ if isinstance(boxes, np.ndarray): return np.column_stack((boxes[:, :2] - 0.5 * boxes[:, 2:], boxes[:, :2] + 0.5 * (boxes[:, 2:] - 2.0))) return torch.cat((boxes[:, :2] - 0.5 * boxes[:, 2:], boxes[:, :2] + 0.5 * (boxes[:, 2:] - 2.0)), 1) # xmax, ymax ########################################################################### ### Torch Utils, creds to Max de Groot ########################################################################### def bbox_intersections(box_a, box_b): """ We resize both tensors to [A,B,2] without new malloc: [A,2] -> [A,1,2] -> [A,B,2] [B,2] -> [1,B,2] -> [A,B,2] Then we compute the area of intersect between box_a and box_b. Args: box_a: (tensor) bounding boxes, Shape: [A,4]. box_b: (tensor) bounding boxes, Shape: [B,4]. Return: (tensor) intersection area, Shape: [A,B]. """ if isinstance(box_a, np.ndarray): assert isinstance(box_b, np.ndarray) return bbox_intersections_np(box_a, box_b) A = box_a.size(0) B = box_b.size(0) max_xy = torch.min(box_a[:, 2:].unsqueeze(1).expand(A, B, 2), box_b[:, 2:].unsqueeze(0).expand(A, B, 2)) min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2), box_b[:, :2].unsqueeze(0).expand(A, B, 2)) inter = torch.clamp((max_xy - min_xy + 1.0), min=0) return inter[:, :, 0] * inter[:, :, 1] def bbox_overlaps(box_a, box_b): """Compute the jaccard overlap of two sets of boxes. The jaccard overlap is simply the intersection over union of two boxes. Here we operate on ground truth boxes and default boxes. E.g.: A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B) Args: box_a: (tensor) Ground truth bounding boxes, Shape: [num_objects,4] box_b: (tensor) Prior boxes from priorbox layers, Shape: [num_priors,4] Return: jaccard overlap: (tensor) Shape: [box_a.size(0), box_b.size(0)] """ if isinstance(box_a, np.ndarray): assert isinstance(box_b, np.ndarray) return bbox_overlaps_np(box_a, box_b) inter = bbox_intersections(box_a, box_b) area_a = ((box_a[:, 2] - box_a[:, 0] + 1.0) * (box_a[:, 3] - box_a[:, 1] + 1.0)).unsqueeze(1).expand_as(inter) # [A,B] area_b = ((box_b[:, 2] - box_b[:, 0] + 1.0) * (box_b[:, 3] - box_b[:, 1] + 1.0)).unsqueeze(0).expand_as(inter) # [A,B] union = area_a + area_b - inter return inter / union # [A,B] def nms_overlaps(boxes): """ get overlaps for each channel""" assert boxes.dim() == 3 N = boxes.size(0) nc = boxes.size(1) max_xy = torch.min(boxes[:, None, :, 2:].expand(N, N, nc, 2), boxes[None, :, :, 2:].expand(N, N, nc, 2)) min_xy = torch.max(boxes[:, None, :, :2].expand(N, N, nc, 2), boxes[None, :, :, :2].expand(N, N, nc, 2)) inter = torch.clamp((max_xy - min_xy + 1.0), min=0) # n, n, 151 inters = inter[:,:,:,0]*inter[:,:,:,1] boxes_flat = boxes.view(-1, 4) areas_flat = (boxes_flat[:,2]- boxes_flat[:,0]+1.0)*( boxes_flat[:,3]- boxes_flat[:,1]+1.0) areas = areas_flat.view(boxes.size(0), boxes.size(1)) union = -inters + areas[None] + areas[:, None] return inters / union ================================================ FILE: lib/fpn/generate_anchors.py ================================================ # -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Sean Bell # -------------------------------------------------------- from config import IM_SCALE import numpy as np # Verify that we compute the same anchors as Shaoqing's matlab implementation: # # >> load output/rpn_cachedir/faster_rcnn_VOC2007_ZF_stage1_rpn/anchors.mat # >> anchors # # anchors = # # -83 -39 100 56 # -175 -87 192 104 # -359 -183 376 200 # -55 -55 72 72 # -119 -119 136 136 # -247 -247 264 264 # -35 -79 52 96 # -79 -167 96 184 # -167 -343 184 360 # array([[ -83., -39., 100., 56.], # [-175., -87., 192., 104.], # [-359., -183., 376., 200.], # [ -55., -55., 72., 72.], # [-119., -119., 136., 136.], # [-247., -247., 264., 264.], # [ -35., -79., 52., 96.], # [ -79., -167., 96., 184.], # [-167., -343., 184., 360.]]) def generate_anchors(base_size=16, feat_stride=16, anchor_scales=(8,16,32), anchor_ratios=(0.5,1,2)): """ A wrapper function to generate anchors given different scales Also return the number of anchors in variable 'length' """ anchors = generate_base_anchors(base_size=base_size, ratios=np.array(anchor_ratios), scales=np.array(anchor_scales)) A = anchors.shape[0] shift_x = np.arange(0, IM_SCALE // feat_stride) * feat_stride # Same as shift_x shift_x, shift_y = np.meshgrid(shift_x, shift_x) shifts = np.stack([shift_x, shift_y, shift_x, shift_y], -1) # h, w, 4 all_anchors = shifts[:, :, None] + anchors[None, None] #h, w, A, 4 return all_anchors # shifts = np.vstack((shift_x.ravel(), shift_y.ravel(), shift_x.ravel(), shift_y.ravel())).transpose() # K = shifts.shape[0] # # width changes faster, so here it is H, W, C # anchors = anchors.reshape((1, A, 4)) + shifts.reshape((1, K, 4)).transpose((1, 0, 2)) # anchors = anchors.reshape((K * A, 4)).astype(np.float32, copy=False) # length = np.int32(anchors.shape[0]) def generate_base_anchors(base_size=16, ratios=[0.5, 1, 2], scales=2 ** np.arange(3, 6)): """ Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, 15, 15) window. """ base_anchor = np.array([1, 1, base_size, base_size]) - 1 ratio_anchors = _ratio_enum(base_anchor, ratios) anchors = np.vstack([_scale_enum(ratio_anchors[i, :], scales) for i in range(ratio_anchors.shape[0])]) return anchors def _whctrs(anchor): """ Return width, height, x center, and y center for an anchor (window). """ w = anchor[2] - anchor[0] + 1 h = anchor[3] - anchor[1] + 1 x_ctr = anchor[0] + 0.5 * (w - 1) y_ctr = anchor[1] + 0.5 * (h - 1) return w, h, x_ctr, y_ctr def _mkanchors(ws, hs, x_ctr, y_ctr): """ Given a vector of widths (ws) and heights (hs) around a center (x_ctr, y_ctr), output a set of anchors (windows). """ ws = ws[:, np.newaxis] hs = hs[:, np.newaxis] anchors = np.hstack((x_ctr - 0.5 * (ws - 1), y_ctr - 0.5 * (hs - 1), x_ctr + 0.5 * (ws - 1), y_ctr + 0.5 * (hs - 1))) return anchors def _ratio_enum(anchor, ratios): """ Enumerate a set of anchors for each aspect ratio wrt an anchor. """ w, h, x_ctr, y_ctr = _whctrs(anchor) size = w * h size_ratios = size / ratios # NOTE: CHANGED TO NOT HAVE ROUNDING ws = np.sqrt(size_ratios) hs = ws * ratios anchors = _mkanchors(ws, hs, x_ctr, y_ctr) return anchors def _scale_enum(anchor, scales): """ Enumerate a set of anchors for each scale wrt an anchor. """ w, h, x_ctr, y_ctr = _whctrs(anchor) ws = w * scales hs = h * scales anchors = _mkanchors(ws, hs, x_ctr, y_ctr) return anchors ================================================ FILE: lib/fpn/make.sh ================================================ #!/usr/bin/env bash cd anchors python setup.py build_ext --inplace cd .. cd box_intersections_cpu python setup.py build_ext --inplace cd .. cd cpu_nms python build.py cd .. cd roi_align python build.py -C src/cuda clean python build.py -C src/cuda clean cd .. echo "Done compiling hopefully" ================================================ FILE: lib/fpn/nms/Makefile ================================================ all: src/cuda/nms.cu.o python build.py src/cuda/nms.cu.o: src/cuda/nms_kernel.cu $(MAKE) -C src/cuda clean: $(MAKE) -C src/cuda clean ================================================ FILE: lib/fpn/nms/build.py ================================================ import os import torch from torch.utils.ffi import create_extension # Might have to export PATH=/usr/local/cuda-8.0/bin${PATH:+:${PATH}} sources = [] headers = [] defines = [] with_cuda = False if torch.cuda.is_available(): print('Including CUDA code.') sources += ['src/nms_cuda.c'] headers += ['src/nms_cuda.h'] defines += [('WITH_CUDA', None)] with_cuda = True this_file = os.path.dirname(os.path.realpath(__file__)) print(this_file) extra_objects = ['src/cuda/nms.cu.o'] extra_objects = [os.path.join(this_file, fname) for fname in extra_objects] ffi = create_extension( '_ext.nms', headers=headers, sources=sources, define_macros=defines, relative_to=__file__, with_cuda=with_cuda, extra_objects=extra_objects ) if __name__ == '__main__': ffi.build() ================================================ FILE: lib/fpn/nms/functions/nms.py ================================================ # Le code for doing NMS import torch import numpy as np from .._ext import nms def apply_nms(scores, boxes, pre_nms_topn=12000, post_nms_topn=2000, boxes_per_im=None, nms_thresh=0.7): """ Note - this function is non-differentiable so everything is assumed to be a tensor, not a variable. """ just_inds = boxes_per_im is None if boxes_per_im is None: boxes_per_im = [boxes.size(0)] s = 0 keep = [] im_per = [] for bpi in boxes_per_im: e = s + int(bpi) keep_im = _nms_single_im(scores[s:e], boxes[s:e], pre_nms_topn, post_nms_topn, nms_thresh) keep.append(keep_im + s) im_per.append(keep_im.size(0)) s = e inds = torch.cat(keep, 0) if just_inds: return inds return inds, im_per def _nms_single_im(scores, boxes, pre_nms_topn=12000, post_nms_topn=2000, nms_thresh=0.7): keep = torch.IntTensor(scores.size(0)) vs, idx = torch.sort(scores, dim=0, descending=True) if idx.size(0) > pre_nms_topn: idx = idx[:pre_nms_topn] boxes_sorted = boxes[idx].contiguous() num_out = nms.nms_apply(keep, boxes_sorted, nms_thresh) num_out = min(num_out, post_nms_topn) keep = keep[:num_out].long() keep = idx[keep.cuda(scores.get_device())] return keep ================================================ FILE: lib/fpn/nms/src/cuda/Makefile ================================================ all: nms_kernel.cu nms_kernel.h /usr/local/cuda/bin/nvcc -c -o nms.cu.o nms_kernel.cu --compiler-options -fPIC -gencode arch=compute_61,code=sm_61 clean: rm nms.cu.o ================================================ FILE: lib/fpn/nms/src/cuda/nms_kernel.cu ================================================ // ------------------------------------------------------------------ // Faster R-CNN // Copyright (c) 2015 Microsoft // Licensed under The MIT License [see fast-rcnn/LICENSE for details] // Written by Shaoqing Ren // ------------------------------------------------------------------ #include #include #define CUDA_CHECK(condition) \ /* Code block avoids redefinition of cudaError_t error */ \ do { \ cudaError_t error = condition; \ if (error != cudaSuccess) { \ std::cout << cudaGetErrorString(error) << std::endl; \ } \ } while (0) #define DIVUP(m,n) ((m) / (n) + ((m) % (n) > 0)) int const threadsPerBlock = sizeof(unsigned long long) * 8; __device__ inline float devIoU(float const * const a, float const * const b) { float left = max(a[0], b[0]), right = min(a[2], b[2]); float top = max(a[1], b[1]), bottom = min(a[3], b[3]); float width = max(right - left + 1, 0.f), height = max(bottom - top + 1, 0.f); float interS = width * height; float Sa = (a[2] - a[0] + 1) * (a[3] - a[1] + 1); float Sb = (b[2] - b[0] + 1) * (b[3] - b[1] + 1); return interS / (Sa + Sb - interS); } __global__ void nms_kernel(const int n_boxes, const float nms_overlap_thresh, const float *dev_boxes, unsigned long long *dev_mask) { const int row_start = blockIdx.y; const int col_start = blockIdx.x; // if (row_start > col_start) return; const int row_size = min(n_boxes - row_start * threadsPerBlock, threadsPerBlock); const int col_size = min(n_boxes - col_start * threadsPerBlock, threadsPerBlock); __shared__ float block_boxes[threadsPerBlock * 5]; if (threadIdx.x < col_size) { block_boxes[threadIdx.x * 4 + 0] = dev_boxes[(threadsPerBlock * col_start + threadIdx.x) * 4 + 0]; block_boxes[threadIdx.x * 4 + 1] = dev_boxes[(threadsPerBlock * col_start + threadIdx.x) * 4 + 1]; block_boxes[threadIdx.x * 4 + 2] = dev_boxes[(threadsPerBlock * col_start + threadIdx.x) * 4 + 2]; block_boxes[threadIdx.x * 4 + 3] = dev_boxes[(threadsPerBlock * col_start + threadIdx.x) * 4 + 3]; } __syncthreads(); if (threadIdx.x < row_size) { const int cur_box_idx = threadsPerBlock * row_start + threadIdx.x; const float *cur_box = dev_boxes + cur_box_idx * 4; int i = 0; unsigned long long t = 0; int start = 0; if (row_start == col_start) { start = threadIdx.x + 1; } for (i = start; i < col_size; i++) { if (devIoU(cur_box, block_boxes + i * 4) > nms_overlap_thresh) { t |= 1ULL << i; } } const int col_blocks = DIVUP(n_boxes, threadsPerBlock); dev_mask[cur_box_idx * col_blocks + col_start] = t; } } void _set_device(int device_id) { int current_device; CUDA_CHECK(cudaGetDevice(¤t_device)); if (current_device == device_id) { return; } // The call to cudaSetDevice must come before any calls to Get, which // may perform initialization using the GPU. CUDA_CHECK(cudaSetDevice(device_id)); } extern "C" int ApplyNMSGPU(int* keep_out, const float* boxes_dev, const int boxes_num, float nms_overlap_thresh, int device_id) { _set_device(device_id); unsigned long long* mask_dev = NULL; const int col_blocks = DIVUP(boxes_num, threadsPerBlock); CUDA_CHECK(cudaMalloc(&mask_dev, boxes_num * col_blocks * sizeof(unsigned long long))); dim3 blocks(DIVUP(boxes_num, threadsPerBlock), DIVUP(boxes_num, threadsPerBlock)); dim3 threads(threadsPerBlock); nms_kernel<<>>(boxes_num, nms_overlap_thresh, boxes_dev, mask_dev); std::vector mask_host(boxes_num * col_blocks); CUDA_CHECK(cudaMemcpy(&mask_host[0], mask_dev, sizeof(unsigned long long) * boxes_num * col_blocks, cudaMemcpyDeviceToHost)); std::vector remv(col_blocks); memset(&remv[0], 0, sizeof(unsigned long long) * col_blocks); int num_to_keep = 0; for (int i = 0; i < boxes_num; i++) { int nblock = i / threadsPerBlock; int inblock = i % threadsPerBlock; if (!(remv[nblock] & (1ULL << inblock))) { keep_out[num_to_keep++] = i; unsigned long long *p = &mask_host[0] + i * col_blocks; for (int j = nblock; j < col_blocks; j++) { remv[j] |= p[j]; } } } CUDA_CHECK(cudaFree(mask_dev)); return num_to_keep; } ================================================ FILE: lib/fpn/nms/src/cuda/nms_kernel.h ================================================ int ApplyNMSGPU(int* keep_out, const float* boxes_dev, const int boxes_num, float nms_overlap_thresh, int device_id); ================================================ FILE: lib/fpn/nms/src/nms_cuda.c ================================================ #include #include #include "cuda/nms_kernel.h" extern THCState *state; int nms_apply(THIntTensor* keep, THCudaTensor* boxes_sorted, const float nms_thresh) { int* keep_data = THIntTensor_data(keep); const float* boxes_sorted_data = THCudaTensor_data(state, boxes_sorted); const int boxes_num = THCudaTensor_size(state, boxes_sorted, 0); const int devId = THCudaTensor_getDevice(state, boxes_sorted); int numTotalKeep = ApplyNMSGPU(keep_data, boxes_sorted_data, boxes_num, nms_thresh, devId); return numTotalKeep; } ================================================ FILE: lib/fpn/nms/src/nms_cuda.h ================================================ int nms_apply(THIntTensor* keep, THCudaTensor* boxes_sorted, const float nms_thresh); ================================================ FILE: lib/fpn/proposal_assignments/proposal_assignments_det.py ================================================ import numpy as np import numpy.random as npr from config import BG_THRESH_HI, BG_THRESH_LO, FG_FRACTION, ROIS_PER_IMG from lib.fpn.box_utils import bbox_overlaps from lib.pytorch_misc import to_variable import torch ############################################################# # The following is only for object detection @to_variable def proposal_assignments_det(rpn_rois, gt_boxes, gt_classes, image_offset, fg_thresh=0.5): """ Assign object detection proposals to ground-truth targets. Produces proposal classification labels and bounding-box regression targets. :param rpn_rois: [img_ind, x1, y1, x2, y2] :param gt_boxes: [num_boxes, 4] array of x0, y0, x1, y1 :param gt_classes: [num_boxes, 2] array of [img_ind, class] :param Overlap threshold for a ROI to be considered foreground (if >= FG_THRESH) :return: rois: [num_rois, 5] labels: [num_rois] array of labels bbox_targets [num_rois, 4] array of targets for the labels. """ fg_rois_per_image = int(np.round(ROIS_PER_IMG * FG_FRACTION)) gt_img_inds = gt_classes[:, 0] - image_offset all_boxes = torch.cat([rpn_rois[:, 1:], gt_boxes], 0) ims_per_box = torch.cat([rpn_rois[:, 0].long(), gt_img_inds], 0) im_sorted, idx = torch.sort(ims_per_box, 0) all_boxes = all_boxes[idx] # Assume that the GT boxes are already sorted in terms of image id num_images = int(im_sorted[-1]) + 1 labels = [] rois = [] bbox_targets = [] for im_ind in range(num_images): g_inds = (gt_img_inds == im_ind).nonzero() if g_inds.dim() == 0: continue g_inds = g_inds.squeeze(1) g_start = g_inds[0] g_end = g_inds[-1] + 1 t_inds = (im_sorted == im_ind).nonzero().squeeze(1) t_start = t_inds[0] t_end = t_inds[-1] + 1 # Max overlaps: for each predicted box, get the max ROI # Get the indices into the GT boxes too (must offset by the box start) ious = bbox_overlaps(all_boxes[t_start:t_end], gt_boxes[g_start:g_end]) max_overlaps, gt_assignment = ious.max(1) max_overlaps = max_overlaps.cpu().numpy() # print("Best overlap is {}".format(max_overlaps.max())) # print("\ngt assignment is {} while g_start is {} \n ---".format(gt_assignment, g_start)) gt_assignment += g_start keep_inds_np, num_fg = _sel_inds(max_overlaps, fg_thresh, fg_rois_per_image, ROIS_PER_IMG) if keep_inds_np.size == 0: continue keep_inds = torch.LongTensor(keep_inds_np).cuda(rpn_rois.get_device()) labels_ = gt_classes[:, 1][gt_assignment[keep_inds]] bbox_target_ = gt_boxes[gt_assignment[keep_inds]] # Clamp labels_ for the background RoIs to 0 if num_fg < labels_.size(0): labels_[num_fg:] = 0 rois_ = torch.cat(( im_sorted[t_start:t_end, None][keep_inds].float(), all_boxes[t_start:t_end][keep_inds], ), 1) labels.append(labels_) rois.append(rois_) bbox_targets.append(bbox_target_) rois = torch.cat(rois, 0) labels = torch.cat(labels, 0) bbox_targets = torch.cat(bbox_targets, 0) return rois, labels, bbox_targets def _sel_inds(max_overlaps, fg_thresh=0.5, fg_rois_per_image=128, rois_per_image=256): # Select foreground RoIs as those with >= FG_THRESH overlap fg_inds = np.where(max_overlaps >= fg_thresh)[0] # Guard against the case when an image has fewer than fg_rois_per_image # foreground RoIs fg_rois_per_this_image = min(fg_rois_per_image, fg_inds.shape[0]) # Sample foreground regions without replacement if fg_inds.size > 0: fg_inds = npr.choice(fg_inds, size=fg_rois_per_this_image, replace=False) # Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI) bg_inds = np.where((max_overlaps < BG_THRESH_HI) & (max_overlaps >= BG_THRESH_LO))[0] # Compute number of background RoIs to take from this image (guarding # against there being fewer than desired) bg_rois_per_this_image = rois_per_image - fg_rois_per_this_image bg_rois_per_this_image = min(bg_rois_per_this_image, bg_inds.size) # Sample background regions without replacement if bg_inds.size > 0: bg_inds = npr.choice(bg_inds, size=bg_rois_per_this_image, replace=False) return np.append(fg_inds, bg_inds), fg_rois_per_this_image ================================================ FILE: lib/fpn/proposal_assignments/proposal_assignments_gtbox.py ================================================ from lib.pytorch_misc import enumerate_by_image, gather_nd, random_choose from lib.fpn.box_utils import bbox_preds, center_size, bbox_overlaps import torch from lib.pytorch_misc import diagonal_inds, to_variable from config import RELS_PER_IMG, REL_FG_FRACTION @to_variable def proposal_assignments_gtbox(rois, gt_boxes, gt_classes, gt_rels, image_offset, fg_thresh=0.5): """ Assign object detection proposals to ground-truth targets. Produces proposal classification labels and bounding-box regression targets. :param rpn_rois: [img_ind, x1, y1, x2, y2] :param gt_boxes: [num_boxes, 4] array of x0, y0, x1, y1]. Not needed it seems :param gt_classes: [num_boxes, 2] array of [img_ind, class] Note, the img_inds here start at image_offset :param gt_rels [num_boxes, 4] array of [img_ind, box_0, box_1, rel type]. Note, the img_inds here start at image_offset :param Overlap threshold for a ROI to be considered foreground (if >= FG_THRESH) :return: rois: [num_rois, 5] labels: [num_rois] array of labels bbox_targets [num_rois, 4] array of targets for the labels. rel_labels: [num_rels, 4] (img ind, box0 ind, box1ind, rel type) """ im_inds = rois[:,0].long() num_im = im_inds[-1] + 1 # Offset the image indices in fg_rels to refer to absolute indices (not just within img i) fg_rels = gt_rels.clone() fg_rels[:,0] -= image_offset offset = {} for i, s, e in enumerate_by_image(im_inds): offset[i] = s for i, s, e in enumerate_by_image(fg_rels[:, 0]): fg_rels[s:e, 1:3] += offset[i] # Try ALL things, not just intersections. is_cand = (im_inds[:, None] == im_inds[None]) is_cand.view(-1)[diagonal_inds(is_cand)] = 0 # # Compute salience # gt_inds = fg_rels[:, 1:3].contiguous().view(-1) # labels_arange = labels.data.new(labels.size(0)) # torch.arange(0, labels.size(0), out=labels_arange) # salience_labels = ((gt_inds[:, None] == labels_arange[None]).long().sum(0) > 0).long() # labels = torch.stack((labels, salience_labels), 1) # Add in some BG labels # NOW WE HAVE TO EXCLUDE THE FGs. # TODO: check if this causes an error if many duplicate GTs havent been filtered out is_cand.view(-1)[fg_rels[:,1]*im_inds.size(0) + fg_rels[:,2]] = 0 is_bgcand = is_cand.nonzero() # TODO: make this sample on a per image case # If too many then sample num_fg = min(fg_rels.size(0), int(RELS_PER_IMG * REL_FG_FRACTION * num_im)) if num_fg < fg_rels.size(0): fg_rels = random_choose(fg_rels, num_fg) # If too many then sample num_bg = min(is_bgcand.size(0) if is_bgcand.dim() > 0 else 0, int(RELS_PER_IMG * num_im) - num_fg) if num_bg > 0: bg_rels = torch.cat(( im_inds[is_bgcand[:, 0]][:, None], is_bgcand, (is_bgcand[:, 0, None] < -10).long(), ), 1) if num_bg < is_bgcand.size(0): bg_rels = random_choose(bg_rels, num_bg) rel_labels = torch.cat((fg_rels, bg_rels), 0) else: rel_labels = fg_rels # last sort by rel. _, perm = torch.sort(rel_labels[:, 0]*(gt_boxes.size(0)**2) + rel_labels[:,1]*gt_boxes.size(0) + rel_labels[:,2]) rel_labels = rel_labels[perm].contiguous() labels = gt_classes[:,1].contiguous() return rois, labels, rel_labels ================================================ FILE: lib/fpn/proposal_assignments/proposal_assignments_postnms.py ================================================ # -------------------------------------------------------- # Goal: assign ROIs to targets # -------------------------------------------------------- import numpy as np import numpy.random as npr from .proposal_assignments_rel import _sel_rels from lib.fpn.box_utils import bbox_overlaps from lib.pytorch_misc import to_variable import torch @to_variable def proposal_assignments_postnms( rois, gt_boxes, gt_classes, gt_rels, nms_inds, image_offset, fg_thresh=0.5, max_objs=100, max_rels=100, rand_val=0.01): """ Assign object detection proposals to ground-truth targets. Produces proposal classification labels and bounding-box regression targets. :param rpn_rois: [img_ind, x1, y1, x2, y2] :param gt_boxes: [num_boxes, 4] array of x0, y0, x1, y1] :param gt_classes: [num_boxes, 2] array of [img_ind, class] :param gt_rels [num_boxes, 4] array of [img_ind, box_0, box_1, rel type] :param Overlap threshold for a ROI to be considered foreground (if >= FG_THRESH) :return: rois: [num_rois, 5] labels: [num_rois] array of labels rel_labels: [num_rels, 4] (img ind, box0 ind, box1ind, rel type) """ pred_inds_np = rois[:, 0].cpu().numpy().astype(np.int64) pred_boxes_np = rois[:, 1:].cpu().numpy() nms_inds_np = nms_inds.cpu().numpy() sup_inds_np = np.setdiff1d(np.arange(pred_boxes_np.shape[0]), nms_inds_np) # split into chosen and suppressed chosen_inds_np = pred_inds_np[nms_inds_np] chosen_boxes_np = pred_boxes_np[nms_inds_np] suppre_inds_np = pred_inds_np[sup_inds_np] suppre_boxes_np = pred_boxes_np[sup_inds_np] gt_boxes_np = gt_boxes.cpu().numpy() gt_classes_np = gt_classes.cpu().numpy() gt_rels_np = gt_rels.cpu().numpy() gt_classes_np[:, 0] -= image_offset gt_rels_np[:, 0] -= image_offset num_im = gt_classes_np[:, 0].max()+1 rois = [] obj_labels = [] rel_labels = [] num_box_seen = 0 for im_ind in range(num_im): chosen_ind = np.where(chosen_inds_np == im_ind)[0] suppre_ind = np.where(suppre_inds_np == im_ind)[0] gt_ind = np.where(gt_classes_np[:, 0] == im_ind)[0] gt_boxes_i = gt_boxes_np[gt_ind] gt_classes_i = gt_classes_np[gt_ind, 1] gt_rels_i = gt_rels_np[gt_rels_np[:, 0] == im_ind, 1:] # Get IOUs between chosen and GT boxes and if needed we'll add more in chosen_boxes_i = chosen_boxes_np[chosen_ind] suppre_boxes_i = suppre_boxes_np[suppre_ind] n_chosen = chosen_boxes_i.shape[0] n_suppre = suppre_boxes_i.shape[0] n_gt_box = gt_boxes_i.shape[0] # add a teensy bit of random noise because some GT boxes might be duplicated, etc. pred_boxes_i = np.concatenate((chosen_boxes_i, suppre_boxes_i, gt_boxes_i), 0) ious = bbox_overlaps(pred_boxes_i, gt_boxes_i) + rand_val*( np.random.rand(pred_boxes_i.shape[0], gt_boxes_i.shape[0])-0.5) # Let's say that a box can only be assigned ONCE for now because we've already done # the NMS and stuff. is_hit = ious > fg_thresh obj_assignments_i = is_hit.argmax(1) obj_assignments_i[~is_hit.any(1)] = -1 vals, first_occurance_ind = np.unique(obj_assignments_i, return_index=True) obj_assignments_i[np.setdiff1d( np.arange(obj_assignments_i.shape[0]), first_occurance_ind)] = -1 extra_to_add = np.where(obj_assignments_i[n_chosen:] != -1)[0] + n_chosen # Add them in somewhere at random num_inds_to_have = min(max_objs, n_chosen + extra_to_add.shape[0]) boxes_i = np.zeros((num_inds_to_have, 4), dtype=np.float32) labels_i = np.zeros(num_inds_to_have, dtype=np.int64) inds_from_nms = np.sort(np.random.choice(num_inds_to_have, size=n_chosen, replace=False)) inds_from_elsewhere = np.setdiff1d(np.arange(num_inds_to_have), inds_from_nms) boxes_i[inds_from_nms] = chosen_boxes_i labels_i[inds_from_nms] = gt_classes_i[obj_assignments_i[:n_chosen]] boxes_i[inds_from_elsewhere] = pred_boxes_i[extra_to_add] labels_i[inds_from_elsewhere] = gt_classes_i[obj_assignments_i[extra_to_add]] # Now, we do the relationships. same as for rle all_rels_i = _sel_rels(bbox_overlaps(boxes_i, gt_boxes_i), boxes_i, labels_i, gt_classes_i, gt_rels_i, fg_thresh=fg_thresh, fg_rels_per_image=100) all_rels_i[:,0:2] += num_box_seen rois.append(np.column_stack(( im_ind * np.ones(boxes_i.shape[0], dtype=np.float32), boxes_i, ))) obj_labels.append(labels_i) rel_labels.append(np.column_stack(( im_ind*np.ones(all_rels_i.shape[0], dtype=np.int64), all_rels_i, ))) num_box_seen += boxes_i.size rois = torch.FloatTensor(np.concatenate(rois, 0)).cuda(gt_boxes.get_device(), async=True) labels = torch.LongTensor(np.concatenate(obj_labels, 0)).cuda(gt_boxes.get_device(), async=True) rel_labels = torch.LongTensor(np.concatenate(rel_labels, 0)).cuda(gt_boxes.get_device(), async=True) return rois, labels, rel_labels ================================================ FILE: lib/fpn/proposal_assignments/proposal_assignments_rel.py ================================================ # -------------------------------------------------------- # Goal: assign ROIs to targets # -------------------------------------------------------- import numpy as np import numpy.random as npr from config import BG_THRESH_HI, BG_THRESH_LO, FG_FRACTION_REL, ROIS_PER_IMG_REL, REL_FG_FRACTION, \ RELS_PER_IMG from lib.fpn.box_utils import bbox_overlaps from lib.pytorch_misc import to_variable, nonintersecting_2d_inds from collections import defaultdict import torch @to_variable def proposal_assignments_rel(rpn_rois, gt_boxes, gt_classes, gt_rels, image_offset, fg_thresh=0.5): """ Assign object detection proposals to ground-truth targets. Produces proposal classification labels and bounding-box regression targets. :param rpn_rois: [img_ind, x1, y1, x2, y2] :param gt_boxes: [num_boxes, 4] array of x0, y0, x1, y1] :param gt_classes: [num_boxes, 2] array of [img_ind, class] :param gt_rels [num_boxes, 4] array of [img_ind, box_0, box_1, rel type] :param Overlap threshold for a ROI to be considered foreground (if >= FG_THRESH) :return: rois: [num_rois, 5] labels: [num_rois] array of labels bbox_targets [num_rois, 4] array of targets for the labels. rel_labels: [num_rels, 4] (img ind, box0 ind, box1ind, rel type) """ fg_rois_per_image = int(np.round(ROIS_PER_IMG_REL * FG_FRACTION_REL)) fg_rels_per_image = int(np.round(REL_FG_FRACTION * RELS_PER_IMG)) pred_inds_np = rpn_rois[:, 0].cpu().numpy().astype(np.int64) pred_boxes_np = rpn_rois[:, 1:].cpu().numpy() gt_boxes_np = gt_boxes.cpu().numpy() gt_classes_np = gt_classes.cpu().numpy() gt_rels_np = gt_rels.cpu().numpy() gt_classes_np[:, 0] -= image_offset gt_rels_np[:, 0] -= image_offset num_im = gt_classes_np[:, 0].max()+1 rois = [] obj_labels = [] rel_labels = [] bbox_targets = [] num_box_seen = 0 for im_ind in range(num_im): pred_ind = np.where(pred_inds_np == im_ind)[0] gt_ind = np.where(gt_classes_np[:, 0] == im_ind)[0] gt_boxes_i = gt_boxes_np[gt_ind] gt_classes_i = gt_classes_np[gt_ind, 1] gt_rels_i = gt_rels_np[gt_rels_np[:, 0] == im_ind, 1:] pred_boxes_i = np.concatenate((pred_boxes_np[pred_ind], gt_boxes_i), 0) ious = bbox_overlaps(pred_boxes_i, gt_boxes_i) obj_inds_i, obj_labels_i, obj_assignments_i = _sel_inds(ious, gt_classes_i, fg_thresh, fg_rois_per_image, ROIS_PER_IMG_REL) all_rels_i = _sel_rels(ious[obj_inds_i], pred_boxes_i[obj_inds_i], obj_labels_i, gt_classes_i, gt_rels_i, fg_thresh=fg_thresh, fg_rels_per_image=fg_rels_per_image) all_rels_i[:,0:2] += num_box_seen rois.append(np.column_stack(( im_ind * np.ones(obj_inds_i.shape[0], dtype=np.float32), pred_boxes_i[obj_inds_i], ))) obj_labels.append(obj_labels_i) rel_labels.append(np.column_stack(( im_ind*np.ones(all_rels_i.shape[0], dtype=np.int64), all_rels_i, ))) # print("Gtboxes i {} obj assignments i {}".format(gt_boxes_i, obj_assignments_i)) bbox_targets.append(gt_boxes_i[obj_assignments_i]) num_box_seen += obj_inds_i.size rois = torch.FloatTensor(np.concatenate(rois, 0)).cuda(rpn_rois.get_device(), async=True) labels = torch.LongTensor(np.concatenate(obj_labels, 0)).cuda(rpn_rois.get_device(), async=True) bbox_targets = torch.FloatTensor(np.concatenate(bbox_targets, 0)).cuda(rpn_rois.get_device(), async=True) rel_labels = torch.LongTensor(np.concatenate(rel_labels, 0)).cuda(rpn_rois.get_device(), async=True) return rois, labels, bbox_targets, rel_labels def _sel_rels(ious, pred_boxes, pred_labels, gt_classes, gt_rels, fg_thresh=0.5, fg_rels_per_image=128, num_sample_per_gt=1, filter_non_overlap=True): """ Selects the relations needed :param ious: [num_pred', num_gt] :param pred_boxes: [num_pred', num_gt] :param pred_labels: [num_pred'] :param gt_classes: [num_gt] :param gt_rels: [num_gtrel, 3] :param fg_thresh: :param fg_rels_per_image: :return: new rels, [num_predrel, 3] where each is (pred_ind1, pred_ind2, predicate) """ is_match = (ious >= fg_thresh) & (pred_labels[:, None] == gt_classes[None, :]) pbi_iou = bbox_overlaps(pred_boxes, pred_boxes) # Limit ourselves to only IOUs that overlap, but are not the exact same box # since we duplicated stuff earlier. if filter_non_overlap: rel_possibilities = (pbi_iou < 1) & (pbi_iou > 0) rels_intersect = rel_possibilities else: rel_possibilities = np.ones((pred_labels.shape[0], pred_labels.shape[0]), dtype=np.int64) - np.eye(pred_labels.shape[0], dtype=np.int64) rels_intersect = (pbi_iou < 1) & (pbi_iou > 0) # ONLY select relations between ground truth because otherwise we get useless data rel_possibilities[pred_labels == 0] = 0 rel_possibilities[:,pred_labels == 0] = 0 # For each GT relationship, sample exactly 1 relationship. fg_rels = [] p_size = [] for i, (from_gtind, to_gtind, rel_id) in enumerate(gt_rels): fg_rels_i = [] fg_scores_i = [] for from_ind in np.where(is_match[:,from_gtind])[0]: for to_ind in np.where(is_match[:,to_gtind])[0]: if from_ind != to_ind: fg_rels_i.append((from_ind, to_ind, rel_id)) fg_scores_i.append((ious[from_ind, from_gtind]*ious[to_ind, to_gtind])) rel_possibilities[from_ind, to_ind] = 0 if len(fg_rels_i) == 0: continue p = np.array(fg_scores_i) p = p/p.sum() p_size.append(p.shape[0]) num_to_add = min(p.shape[0], num_sample_per_gt) for rel_to_add in npr.choice(p.shape[0], p=p, size=num_to_add, replace=False): fg_rels.append(fg_rels_i[rel_to_add]) bg_rels = np.column_stack(np.where(rel_possibilities)) bg_rels = np.column_stack((bg_rels, np.zeros(bg_rels.shape[0], dtype=np.int64))) fg_rels = np.array(fg_rels, dtype=np.int64) if fg_rels.size > 0 and fg_rels.shape[0] > fg_rels_per_image: fg_rels = fg_rels[npr.choice(fg_rels.shape[0], size=fg_rels_per_image, replace=False)] # print("{} scores for {} GT. max={} min={} BG rels {}".format( # fg_rels_scores.shape[0], gt_rels.shape[0], fg_rels_scores.max(), fg_rels_scores.min(), # bg_rels.shape)) elif fg_rels.size == 0: fg_rels = np.zeros((0,3), dtype=np.int64) num_bg_rel = min(RELS_PER_IMG - fg_rels.shape[0], bg_rels.shape[0]) if bg_rels.size > 0: # Sample 4x as many intersecting relationships as non-intersecting. bg_rels_intersect = rels_intersect[bg_rels[:,0], bg_rels[:,1]] p = bg_rels_intersect.astype(np.float32) p[bg_rels_intersect == 0] = 0.2 p[bg_rels_intersect == 1] = 0.8 p /= p.sum() bg_rels = bg_rels[np.random.choice(bg_rels.shape[0], p=p, size=num_bg_rel, replace=False)] else: bg_rels = np.zeros((0,3), dtype=np.int64) #print("GTR {} -> AR {} vs {}".format(gt_rels.shape, fg_rels.shape, bg_rels.shape)) all_rels = np.concatenate((fg_rels, bg_rels), 0) # Sort by 2nd ind and then 1st ind all_rels = all_rels[np.lexsort((all_rels[:, 1], all_rels[:, 0]))] return all_rels def _sel_inds(ious, gt_classes_i, fg_thresh=0.5, fg_rois_per_image=128, rois_per_image=256, n_sample_per=1): #gt_assignment = ious.argmax(1) #max_overlaps = ious[np.arange(ious.shape[0]), gt_assignment] #fg_inds = np.where(max_overlaps >= fg_thresh)[0] fg_ious = ious.T >= fg_thresh #[num_gt, num_pred] #is_bg = ~fg_ious.any(0) # Sample K inds per GT image. fg_inds = [] for i, (ious_i, cls_i) in enumerate(zip(fg_ious, gt_classes_i)): n_sample_this_roi = min(n_sample_per, ious_i.sum()) if n_sample_this_roi > 0: p = ious_i.astype(np.float64) / ious_i.sum() for ind in npr.choice(ious_i.shape[0], p=p, size=n_sample_this_roi, replace=False): fg_inds.append((ind, i)) fg_inds = np.array(fg_inds, dtype=np.int64) if fg_inds.size == 0: fg_inds = np.zeros((0, 2), dtype=np.int64) elif fg_inds.shape[0] > fg_rois_per_image: #print("sample FG") fg_inds = fg_inds[npr.choice(fg_inds.shape[0], size=fg_rois_per_image, replace=False)] # Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI) max_overlaps = ious.max(1) bg_inds = np.where((max_overlaps < BG_THRESH_HI) & (max_overlaps >= BG_THRESH_LO))[0] # Compute number of background RoIs to take from this image (guarding # against there being fewer than desired) bg_rois_per_this_image = min(rois_per_image-fg_inds.shape[0], bg_inds.size) # Sample background regions without replacement if bg_inds.size > 0: bg_inds = npr.choice(bg_inds, size=bg_rois_per_this_image, replace=False) # FIx for format issues obj_inds = np.concatenate((fg_inds[:,0], bg_inds), 0) obj_assignments_i = np.concatenate((fg_inds[:,1], np.zeros(bg_inds.shape[0], dtype=np.int64))) obj_labels_i = gt_classes_i[obj_assignments_i] obj_labels_i[fg_inds.shape[0]:] = 0 #print("{} FG and {} BG".format(fg_inds.shape[0], bg_inds.shape[0])) return obj_inds, obj_labels_i, obj_assignments_i ================================================ FILE: lib/fpn/proposal_assignments/rel_assignments.py ================================================ # -------------------------------------------------------- # Goal: assign ROIs to targets # -------------------------------------------------------- import numpy as np import numpy.random as npr from config import BG_THRESH_HI, BG_THRESH_LO, REL_FG_FRACTION, RELS_PER_IMG_REFINE from lib.fpn.box_utils import bbox_overlaps from lib.pytorch_misc import to_variable, nonintersecting_2d_inds from collections import defaultdict import torch @to_variable def rel_assignments(im_inds, rpn_rois, roi_gtlabels, gt_boxes, gt_classes, gt_rels, image_offset, fg_thresh=0.5, num_sample_per_gt=4, filter_non_overlap=True): """ Assign object detection proposals to ground-truth targets. Produces proposal classification labels and bounding-box regression targets. :param rpn_rois: [img_ind, x1, y1, x2, y2] :param gt_boxes: [num_boxes, 4] array of x0, y0, x1, y1] :param gt_classes: [num_boxes, 2] array of [img_ind, class] :param gt_rels [num_boxes, 4] array of [img_ind, box_0, box_1, rel type] :param Overlap threshold for a ROI to be considered foreground (if >= FG_THRESH) :return: rois: [num_rois, 5] labels: [num_rois] array of labels bbox_targets [num_rois, 4] array of targets for the labels. rel_labels: [num_rels, 4] (img ind, box0 ind, box1ind, rel type) """ fg_rels_per_image = int(np.round(REL_FG_FRACTION * 64)) pred_inds_np = im_inds.cpu().numpy() pred_boxes_np = rpn_rois.cpu().numpy() pred_boxlabels_np = roi_gtlabels.cpu().numpy() gt_boxes_np = gt_boxes.cpu().numpy() gt_classes_np = gt_classes.cpu().numpy() gt_rels_np = gt_rels.cpu().numpy() gt_classes_np[:, 0] -= image_offset gt_rels_np[:, 0] -= image_offset num_im = gt_classes_np[:, 0].max()+1 # print("Pred inds {} pred boxes {} pred box labels {} gt classes {} gt rels {}".format( # pred_inds_np, pred_boxes_np, pred_boxlabels_np, gt_classes_np, gt_rels_np # )) rel_labels = [] num_box_seen = 0 for im_ind in range(num_im): pred_ind = np.where(pred_inds_np == im_ind)[0] gt_ind = np.where(gt_classes_np[:, 0] == im_ind)[0] gt_boxes_i = gt_boxes_np[gt_ind] gt_classes_i = gt_classes_np[gt_ind, 1] gt_rels_i = gt_rels_np[gt_rels_np[:, 0] == im_ind, 1:] # [num_pred, num_gt] pred_boxes_i = pred_boxes_np[pred_ind] pred_boxlabels_i = pred_boxlabels_np[pred_ind] ious = bbox_overlaps(pred_boxes_i, gt_boxes_i) is_match = (pred_boxlabels_i[:,None] == gt_classes_i[None]) & (ious >= fg_thresh) # FOR BG. Limit ourselves to only IOUs that overlap, but are not the exact same box pbi_iou = bbox_overlaps(pred_boxes_i, pred_boxes_i) if filter_non_overlap: rel_possibilities = (pbi_iou < 1) & (pbi_iou > 0) rels_intersect = rel_possibilities else: rel_possibilities = np.ones((pred_boxes_i.shape[0], pred_boxes_i.shape[0]), dtype=np.int64) - np.eye(pred_boxes_i.shape[0], dtype=np.int64) rels_intersect = (pbi_iou < 1) & (pbi_iou > 0) # ONLY select relations between ground truth because otherwise we get useless data rel_possibilities[pred_boxlabels_i == 0] = 0 rel_possibilities[:, pred_boxlabels_i == 0] = 0 # Sample the GT relationships. fg_rels = [] p_size = [] for i, (from_gtind, to_gtind, rel_id) in enumerate(gt_rels_i): fg_rels_i = [] fg_scores_i = [] for from_ind in np.where(is_match[:, from_gtind])[0]: for to_ind in np.where(is_match[:, to_gtind])[0]: if from_ind != to_ind: fg_rels_i.append((from_ind, to_ind, rel_id)) fg_scores_i.append((ious[from_ind, from_gtind] * ious[to_ind, to_gtind])) rel_possibilities[from_ind, to_ind] = 0 if len(fg_rels_i) == 0: continue p = np.array(fg_scores_i) p = p / p.sum() p_size.append(p.shape[0]) num_to_add = min(p.shape[0], num_sample_per_gt) for rel_to_add in npr.choice(p.shape[0], p=p, size=num_to_add, replace=False): fg_rels.append(fg_rels_i[rel_to_add]) fg_rels = np.array(fg_rels, dtype=np.int64) if fg_rels.size > 0 and fg_rels.shape[0] > fg_rels_per_image: fg_rels = fg_rels[npr.choice(fg_rels.shape[0], size=fg_rels_per_image, replace=False)] elif fg_rels.size == 0: fg_rels = np.zeros((0, 3), dtype=np.int64) bg_rels = np.column_stack(np.where(rel_possibilities)) bg_rels = np.column_stack((bg_rels, np.zeros(bg_rels.shape[0], dtype=np.int64))) num_bg_rel = min(64 - fg_rels.shape[0], bg_rels.shape[0]) if bg_rels.size > 0: # Sample 4x as many intersecting relationships as non-intersecting. # bg_rels_intersect = rels_intersect[bg_rels[:, 0], bg_rels[:, 1]] # p = bg_rels_intersect.astype(np.float32) # p[bg_rels_intersect == 0] = 0.2 # p[bg_rels_intersect == 1] = 0.8 # p /= p.sum() bg_rels = bg_rels[ np.random.choice(bg_rels.shape[0], #p=p, size=num_bg_rel, replace=False)] else: bg_rels = np.zeros((0, 3), dtype=np.int64) if fg_rels.size == 0 and bg_rels.size == 0: # Just put something here bg_rels = np.array([[0, 0, 0]], dtype=np.int64) # print("GTR {} -> AR {} vs {}".format(gt_rels.shape, fg_rels.shape, bg_rels.shape)) all_rels_i = np.concatenate((fg_rels, bg_rels), 0) all_rels_i[:,0:2] += num_box_seen all_rels_i = all_rels_i[np.lexsort((all_rels_i[:,1], all_rels_i[:,0]))] rel_labels.append(np.column_stack(( im_ind*np.ones(all_rels_i.shape[0], dtype=np.int64), all_rels_i, ))) num_box_seen += pred_boxes_i.shape[0] rel_labels = torch.LongTensor(np.concatenate(rel_labels, 0)).cuda(rpn_rois.get_device(), async=True) return rel_labels ================================================ FILE: lib/fpn/roi_align/Makefile ================================================ all: src/cuda/roi_align.cu.o python build.py src/cuda/roi_align.cu.o: src/cuda/roi_align_kernel.cu $(MAKE) -C src/cuda clean: $(MAKE) -C src/cuda clean ================================================ FILE: lib/fpn/roi_align/__init__.py ================================================ ================================================ FILE: lib/fpn/roi_align/_ext/__init__.py ================================================ ================================================ FILE: lib/fpn/roi_align/_ext/roi_align/__init__.py ================================================ from torch.utils.ffi import _wrap_function from ._roi_align import lib as _lib, ffi as _ffi __all__ = [] def _import_symbols(locals): for symbol in dir(_lib): fn = getattr(_lib, symbol) locals[symbol] = _wrap_function(fn, _ffi) __all__.append(symbol) _import_symbols(locals()) ================================================ FILE: lib/fpn/roi_align/build.py ================================================ import os import torch from torch.utils.ffi import create_extension # Might have to export PATH=/usr/local/cuda-8.0/bin${PATH:+:${PATH}} # sources = ['src/roi_align.c'] # headers = ['src/roi_align.h'] sources = [] headers = [] defines = [] with_cuda = False if torch.cuda.is_available(): print('Including CUDA code.') sources += ['src/roi_align_cuda.c'] headers += ['src/roi_align_cuda.h'] defines += [('WITH_CUDA', None)] with_cuda = True this_file = os.path.dirname(os.path.realpath(__file__)) print(this_file) extra_objects = ['src/cuda/roi_align.cu.o'] extra_objects = [os.path.join(this_file, fname) for fname in extra_objects] ffi = create_extension( '_ext.roi_align', headers=headers, sources=sources, define_macros=defines, relative_to=__file__, with_cuda=with_cuda, extra_objects=extra_objects ) if __name__ == '__main__': ffi.build() ================================================ FILE: lib/fpn/roi_align/functions/__init__.py ================================================ ================================================ FILE: lib/fpn/roi_align/functions/roi_align.py ================================================ """ performs ROI aligning """ import torch from torch.autograd import Function from .._ext import roi_align class RoIAlignFunction(Function): def __init__(self, aligned_height, aligned_width, spatial_scale): self.aligned_width = int(aligned_width) self.aligned_height = int(aligned_height) self.spatial_scale = float(spatial_scale) self.feature_size = None def forward(self, features, rois): self.save_for_backward(rois) rois_normalized = rois.clone() self.feature_size = features.size() batch_size, num_channels, data_height, data_width = self.feature_size height = (data_height -1) / self.spatial_scale width = (data_width - 1) / self.spatial_scale rois_normalized[:,1] /= width rois_normalized[:,2] /= height rois_normalized[:,3] /= width rois_normalized[:,4] /= height num_rois = rois.size(0) output = features.new(num_rois, num_channels, self.aligned_height, self.aligned_width).zero_() if features.is_cuda: res = roi_align.roi_align_forward_cuda(self.aligned_height, self.aligned_width, self.spatial_scale, features, rois_normalized, output) assert res == 1 else: raise ValueError return output def backward(self, grad_output): assert(self.feature_size is not None and grad_output.is_cuda) rois = self.saved_tensors[0] rois_normalized = rois.clone() batch_size, num_channels, data_height, data_width = self.feature_size height = (data_height -1) / self.spatial_scale width = (data_width - 1) / self.spatial_scale rois_normalized[:,1] /= width rois_normalized[:,2] /= height rois_normalized[:,3] /= width rois_normalized[:,4] /= height grad_input = rois_normalized.new(batch_size, num_channels, data_height, data_width).zero_() res = roi_align.roi_align_backward_cuda(self.aligned_height, self.aligned_width, self.spatial_scale, grad_output, rois_normalized, grad_input) assert res == 1 return grad_input, None ================================================ FILE: lib/fpn/roi_align/modules/__init__.py ================================================ ================================================ FILE: lib/fpn/roi_align/modules/roi_align.py ================================================ from torch.nn.modules.module import Module from torch.nn.functional import avg_pool2d, max_pool2d from ..functions.roi_align import RoIAlignFunction class RoIAlign(Module): def __init__(self, aligned_height, aligned_width, spatial_scale): super(RoIAlign, self).__init__() self.aligned_width = int(aligned_width) self.aligned_height = int(aligned_height) self.spatial_scale = float(spatial_scale) def forward(self, features, rois): return RoIAlignFunction(self.aligned_height, self.aligned_width, self.spatial_scale)(features, rois) class RoIAlignAvg(Module): def __init__(self, aligned_height, aligned_width, spatial_scale): super(RoIAlignAvg, self).__init__() self.aligned_width = int(aligned_width) self.aligned_height = int(aligned_height) self.spatial_scale = float(spatial_scale) def forward(self, features, rois): x = RoIAlignFunction(self.aligned_height+1, self.aligned_width+1, self.spatial_scale)(features, rois) return avg_pool2d(x, kernel_size=2, stride=1) class RoIAlignMax(Module): def __init__(self, aligned_height, aligned_width, spatial_scale): super(RoIAlignMax, self).__init__() self.aligned_width = int(aligned_width) self.aligned_height = int(aligned_height) self.spatial_scale = float(spatial_scale) def forward(self, features, rois): x = RoIAlignFunction(self.aligned_height+1, self.aligned_width+1, self.spatial_scale)(features, rois) return max_pool2d(x, kernel_size=2, stride=1) ================================================ FILE: lib/fpn/roi_align/src/cuda/Makefile ================================================ all: roi_align_kernel.cu roi_align_kernel.h /usr/local/cuda/bin/nvcc -c -o roi_align.cu.o roi_align_kernel.cu --compiler-options -fPIC -gencode arch=compute_61,code=sm_61 clean: rm roi_align.cu.o ================================================ FILE: lib/fpn/roi_align/src/cuda/roi_align_kernel.cu ================================================ #ifdef __cplusplus extern "C" { #endif #include #include #include #include "roi_align_kernel.h" #define CUDA_1D_KERNEL_LOOP(i, n) \ for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; \ i += blockDim.x * gridDim.x) __global__ void ROIAlignForward(const int nthreads, const float* image_ptr, const float* boxes_ptr, int num_boxes, int batch, int image_height, int image_width, int crop_height, int crop_width, int depth, float extrapolation_value, float* crops_ptr) { CUDA_1D_KERNEL_LOOP(out_idx, nthreads) { // (n, c, ph, pw) is an element in the aligned output int idx = out_idx; const int x = idx % crop_width; idx /= crop_width; const int y = idx % crop_height; idx /= crop_height; const int d = idx % depth; const int b = idx / depth; const int b_in = int(boxes_ptr[b*5]); const float x1 = boxes_ptr[b * 5 + 1]; const float y1 = boxes_ptr[b * 5 + 2]; const float x2 = boxes_ptr[b * 5 + 3]; const float y2 = boxes_ptr[b * 5 + 4]; if (b_in < 0 || b_in >= batch) { continue; } const float height_scale = (crop_height > 1) ? (y2 - y1) * (image_height - 1) / (crop_height - 1) : 0; const float width_scale = (crop_width > 1) ? (x2 - x1) * (image_width - 1) / (crop_width - 1) : 0; const float in_y = (crop_height > 1) ? y1 * (image_height - 1) + y * height_scale : 0.5 * (y1 + y2) * (image_height - 1); if (in_y < 0 || in_y > image_height - 1) { crops_ptr[out_idx] = extrapolation_value; continue; } const float in_x = (crop_width > 1) ? x1 * (image_width - 1) + x * width_scale : 0.5 * (x1 + x2) * (image_width - 1); if (in_x < 0 || in_x > image_width - 1) { crops_ptr[out_idx] = extrapolation_value; continue; } const int top_y_index = floorf(in_y); const int bottom_y_index = ceilf(in_y); const float y_lerp = in_y - top_y_index; const int left_x_index = floorf(in_x); const int right_x_index = ceilf(in_x); const float x_lerp = in_x - left_x_index; const float top_left = image_ptr[((b_in*depth + d) * image_height + top_y_index) * image_width + left_x_index]; const float top_right = image_ptr[((b_in*depth + d) * image_height + top_y_index) * image_width + right_x_index]; const float bottom_left = image_ptr[((b_in*depth + d) * image_height + bottom_y_index) * image_width + left_x_index]; const float bottom_right = image_ptr[((b_in*depth + d) * image_height + bottom_y_index) * image_width + right_x_index]; const float top = top_left + (top_right - top_left) * x_lerp; const float bottom = bottom_left + (bottom_right - bottom_left) * x_lerp; crops_ptr[out_idx] = top + (bottom - top) * y_lerp; } } int ROIAlignForwardLaucher(const float* image_ptr, const float* boxes_ptr, int num_boxes, int batch, int image_height, int image_width, int crop_height, int crop_width, int depth, float extrapolation_value, float* crops_ptr, cudaStream_t stream) { const int kThreadsPerBlock = 1024; const int output_size = num_boxes * crop_height * crop_width * depth; cudaError_t err; ROIAlignForward<<<(output_size + kThreadsPerBlock - 1) / kThreadsPerBlock, kThreadsPerBlock, 0, stream>>> (output_size, image_ptr, boxes_ptr, num_boxes, batch, image_height, image_width, crop_height, crop_width, depth, extrapolation_value, crops_ptr); err = cudaGetLastError(); if(cudaSuccess != err) { fprintf( stderr, "cudaCheckError() failed : %s\n", cudaGetErrorString( err ) ); exit( -1 ); } return 1; } __global__ void ROIAlignBackward( const int nthreads, const float* grads_ptr, const float* boxes_ptr, int num_boxes, int batch, int image_height, int image_width, int crop_height, int crop_width, int depth, float* grads_image_ptr) { CUDA_1D_KERNEL_LOOP(out_idx, nthreads) { // out_idx = d + depth * (w + crop_width * (h + crop_height * b)) int idx = out_idx; const int x = idx % crop_width; idx /= crop_width; const int y = idx % crop_height; idx /= crop_height; const int d = idx % depth; const int b = idx / depth; const int b_in = boxes_ptr[b * 5]; const float x1 = boxes_ptr[b * 5 + 1]; const float y1 = boxes_ptr[b * 5 + 2]; const float x2 = boxes_ptr[b * 5 + 3]; const float y2 = boxes_ptr[b * 5 + 4]; if (b_in < 0 || b_in >= batch) { continue; } const float height_scale = (crop_height > 1) ? (y2 - y1) * (image_height - 1) / (crop_height - 1) : 0; const float width_scale = (crop_width > 1) ? (x2 - x1) * (image_width - 1) / (crop_width - 1) : 0; const float in_y = (crop_height > 1) ? y1 * (image_height - 1) + y * height_scale : 0.5 * (y1 + y2) * (image_height - 1); if (in_y < 0 || in_y > image_height - 1) { continue; } const float in_x = (crop_width > 1) ? x1 * (image_width - 1) + x * width_scale : 0.5 * (x1 + x2) * (image_width - 1); if (in_x < 0 || in_x > image_width - 1) { continue; } const int top_y_index = floorf(in_y); const int bottom_y_index = ceilf(in_y); const float y_lerp = in_y - top_y_index; const int left_x_index = floorf(in_x); const int right_x_index = ceilf(in_x); const float x_lerp = in_x - left_x_index; const float dtop = (1 - y_lerp) * grads_ptr[out_idx]; atomicAdd( grads_image_ptr + ((b_in*depth + d)*image_height + top_y_index) * image_width + left_x_index, (1 - x_lerp) * dtop); atomicAdd(grads_image_ptr + ((b_in * depth + d)*image_height+top_y_index)*image_width + right_x_index, x_lerp * dtop); const float dbottom = y_lerp * grads_ptr[out_idx]; atomicAdd(grads_image_ptr + ((b_in*depth+d)*image_height+bottom_y_index)*image_width+left_x_index, (1 - x_lerp) * dbottom); atomicAdd(grads_image_ptr + ((b_in*depth+d)*image_height+bottom_y_index)*image_width+right_x_index, x_lerp * dbottom); } } int ROIAlignBackwardLaucher(const float* grads_ptr, const float* boxes_ptr, int num_boxes, int batch, int image_height, int image_width, int crop_height, int crop_width, int depth, float* grads_image_ptr, cudaStream_t stream) { const int kThreadsPerBlock = 1024; const int output_size = num_boxes * crop_height * crop_width * depth; cudaError_t err; ROIAlignBackward<<<(output_size + kThreadsPerBlock - 1) / kThreadsPerBlock, kThreadsPerBlock, 0, stream>>> (output_size, grads_ptr, boxes_ptr, num_boxes, batch, image_height, image_width, crop_height, crop_width, depth, grads_image_ptr); err = cudaGetLastError(); if(cudaSuccess != err) { fprintf( stderr, "cudaCheckError() failed : %s\n", cudaGetErrorString( err ) ); exit( -1 ); } return 1; } #ifdef __cplusplus } #endif ================================================ FILE: lib/fpn/roi_align/src/cuda/roi_align_kernel.h ================================================ #ifndef _ROI_ALIGN_KERNEL #define _ROI_ALIGN_KERNEL #ifdef __cplusplus extern "C" { #endif __global__ void ROIAlignForward(const int nthreads, const float* image_ptr, const float* boxes_ptr, int num_boxes, int batch, int image_height, int image_width, int crop_height, int crop_width, int depth, float extrapolation_value, float* crops_ptr); int ROIAlignForwardLaucher( const float* image_ptr, const float* boxes_ptr, int num_boxes, int batch, int image_height, int image_width, int crop_height, int crop_width, int depth, float extrapolation_value, float* crops_ptr, cudaStream_t stream); __global__ void ROIAlignBackward(const int nthreads, const float* grads_ptr, const float* boxes_ptr, int num_boxes, int batch, int image_height, int image_width, int crop_height, int crop_width, int depth, float* grads_image_ptr); int ROIAlignBackwardLaucher(const float* grads_ptr, const float* boxes_ptr, int num_boxes, int batch, int image_height, int image_width, int crop_height, int crop_width, int depth, float* grads_image_ptr, cudaStream_t stream); #ifdef __cplusplus } #endif #endif ================================================ FILE: lib/fpn/roi_align/src/roi_align_cuda.c ================================================ #include #include #include "cuda/roi_align_kernel.h" extern THCState *state; int roi_align_forward_cuda(int crop_height, int crop_width, float spatial_scale, THCudaTensor * features, THCudaTensor * rois, THCudaTensor * output) { // Grab the input tensor float * image_ptr = THCudaTensor_data(state, features); float * boxes_ptr = THCudaTensor_data(state, rois); float * crops_ptr = THCudaTensor_data(state, output); // Number of ROIs int num_boxes = THCudaTensor_size(state, rois, 0); int size_rois = THCudaTensor_size(state, rois, 1); if (size_rois != 5) { return 0; } // batch size int batch = THCudaTensor_size(state, features, 0); // data height int image_height = THCudaTensor_size(state, features, 2); // data width int image_width = THCudaTensor_size(state, features, 3); // Number of channels int depth = THCudaTensor_size(state, features, 1); cudaStream_t stream = THCState_getCurrentStream(state); float extrapolation_value = 0.0; ROIAlignForwardLaucher( image_ptr, boxes_ptr, num_boxes, batch, image_height, image_width, crop_height, crop_width, depth, extrapolation_value, crops_ptr, stream); return 1; } int roi_align_backward_cuda(int crop_height, int crop_width, float spatial_scale, THCudaTensor * top_grad, THCudaTensor * rois, THCudaTensor * bottom_grad) { // Grab the input tensor float * grads_ptr = THCudaTensor_data(state, top_grad); float * boxes_ptr = THCudaTensor_data(state, rois); float * grads_image_ptr = THCudaTensor_data(state, bottom_grad); // Number of ROIs int num_boxes = THCudaTensor_size(state, rois, 0); int size_rois = THCudaTensor_size(state, rois, 1); if (size_rois != 5) { return 0; } // batch size int batch = THCudaTensor_size(state, bottom_grad, 0); // data height int image_height = THCudaTensor_size(state, bottom_grad, 2); // data width int image_width = THCudaTensor_size(state, bottom_grad, 3); // Number of channels int depth = THCudaTensor_size(state, bottom_grad, 1); cudaStream_t stream = THCState_getCurrentStream(state); ROIAlignBackwardLaucher( grads_ptr, boxes_ptr, num_boxes, batch, image_height, image_width, crop_height, crop_width, depth, grads_image_ptr, stream); return 1; } ================================================ FILE: lib/fpn/roi_align/src/roi_align_cuda.h ================================================ int roi_align_forward_cuda(int crop_height, int crop_width, float spatial_scale, THCudaTensor * features, THCudaTensor * rois, THCudaTensor * output); int roi_align_backward_cuda(int crop_height, int crop_width, float spatial_scale, THCudaTensor * top_grad, THCudaTensor * rois, THCudaTensor * bottom_grad); ================================================ FILE: lib/get_dataset_counts.py ================================================ """ Get counts of all of the examples in the dataset. Used for creating the baseline dictionary model """ import numpy as np from dataloaders.visual_genome import VG from lib.fpn.box_intersections_cpu.bbox import bbox_overlaps from lib.pytorch_misc import nonintersecting_2d_inds def get_counts(train_data=VG(mode='train', filter_duplicate_rels=False, num_val_im=5000), must_overlap=True): """ Get counts of all of the relations. Used for modeling directly P(rel | o1, o2) :param train_data: :param must_overlap: :return: """ fg_matrix = np.zeros(( train_data.num_classes, train_data.num_classes, train_data.num_predicates, ), dtype=np.int64) bg_matrix = np.zeros(( train_data.num_classes, train_data.num_classes, ), dtype=np.int64) for ex_ind in range(len(train_data)): gt_classes = train_data.gt_classes[ex_ind].copy() gt_relations = train_data.relationships[ex_ind].copy() gt_boxes = train_data.gt_boxes[ex_ind].copy() # For the foreground, we'll just look at everything o1o2 = gt_classes[gt_relations[:, :2]] for (o1, o2), gtr in zip(o1o2, gt_relations[:,2]): fg_matrix[o1, o2, gtr] += 1 # For the background, get all of the things that overlap. o1o2_total = gt_classes[np.array( box_filter(gt_boxes, must_overlap=must_overlap), dtype=int)] for (o1, o2) in o1o2_total: bg_matrix[o1, o2] += 1 return fg_matrix, bg_matrix def box_filter(boxes, must_overlap=False): """ Only include boxes that overlap as possible relations. If no overlapping boxes, use all of them.""" n_cands = boxes.shape[0] overlaps = bbox_overlaps(boxes.astype(np.float), boxes.astype(np.float)) > 0 np.fill_diagonal(overlaps, 0) all_possib = np.ones_like(overlaps, dtype=np.bool) np.fill_diagonal(all_possib, 0) if must_overlap: possible_boxes = np.column_stack(np.where(overlaps)) if possible_boxes.size == 0: possible_boxes = np.column_stack(np.where(all_possib)) else: possible_boxes = np.column_stack(np.where(all_possib)) return possible_boxes if __name__ == '__main__': fg, bg = get_counts(must_overlap=False) ================================================ FILE: lib/get_union_boxes.py ================================================ """ credits to https://github.com/ruotianluo/pytorch-faster-rcnn/blob/master/lib/nets/network.py#L91 """ import torch from torch.autograd import Variable from torch.nn import functional as F from lib.fpn.roi_align.functions.roi_align import RoIAlignFunction from lib.draw_rectangles.draw_rectangles import draw_union_boxes import numpy as np from torch.nn.modules.module import Module from torch import nn from config import BATCHNORM_MOMENTUM class UnionBoxesAndFeats(Module): def __init__(self, pooling_size=7, stride=16, dim=256, concat=False, use_feats=True): """ :param pooling_size: Pool the union boxes to this dimension :param stride: pixel spacing in the entire image :param dim: Dimension of the feats :param concat: Whether to concat (yes) or add (False) the representations """ super(UnionBoxesAndFeats, self).__init__() self.pooling_size = pooling_size self.stride = stride self.dim = dim self.use_feats = use_feats self.conv = nn.Sequential( nn.Conv2d(2, dim //2, kernel_size=7, stride=2, padding=3, bias=True), nn.ReLU(inplace=True), nn.BatchNorm2d(dim//2, momentum=BATCHNORM_MOMENTUM), nn.MaxPool2d(kernel_size=3, stride=2, padding=1), nn.Conv2d(dim // 2, dim, kernel_size=3, stride=1, padding=1, bias=True), nn.ReLU(inplace=True), nn.BatchNorm2d(dim, momentum=BATCHNORM_MOMENTUM), ) self.concat = concat def forward(self, fmap, rois, union_inds): union_pools = union_boxes(fmap, rois, union_inds, pooling_size=self.pooling_size, stride=self.stride) if not self.use_feats: return union_pools.detach() pair_rois = torch.cat((rois[:, 1:][union_inds[:, 0]], rois[:, 1:][union_inds[:, 1]]),1).data.cpu().numpy() # rects_np = get_rect_features(pair_rois, self.pooling_size*2-1) - 0.5 rects_np = draw_union_boxes(pair_rois, self.pooling_size*4-1) - 0.5 rects = Variable(torch.FloatTensor(rects_np).cuda(fmap.get_device()), volatile=fmap.volatile) if self.concat: return torch.cat((union_pools, self.conv(rects)), 1) return union_pools + self.conv(rects) # def get_rect_features(roi_pairs, pooling_size): # rects_np = draw_union_boxes(roi_pairs, pooling_size) # # add union + intersection # stuff_to_cat = [ # rects_np.max(1), # rects_np.min(1), # np.minimum(1-rects_np[:,0], rects_np[:,1]), # np.maximum(1-rects_np[:,0], rects_np[:,1]), # np.minimum(rects_np[:,0], 1-rects_np[:,1]), # np.maximum(rects_np[:,0], 1-rects_np[:,1]), # np.minimum(1-rects_np[:,0], 1-rects_np[:,1]), # np.maximum(1-rects_np[:,0], 1-rects_np[:,1]), # ] # rects_np = np.concatenate([rects_np] + [x[:,None] for x in stuff_to_cat], 1) # return rects_np def union_boxes(fmap, rois, union_inds, pooling_size=14, stride=16): """ :param fmap: (batch_size, d, IM_SIZE/stride, IM_SIZE/stride) :param rois: (num_rois, 5) with [im_ind, x1, y1, x2, y2] :param union_inds: (num_urois, 2) with [roi_ind1, roi_ind2] :param pooling_size: we'll resize to this :param stride: :return: """ assert union_inds.size(1) == 2 im_inds = rois[:,0][union_inds[:,0]] assert (im_inds.data == rois.data[:,0][union_inds[:,1]]).sum() == union_inds.size(0) union_rois = torch.cat(( im_inds[:,None], torch.min(rois[:, 1:3][union_inds[:, 0]], rois[:, 1:3][union_inds[:, 1]]), torch.max(rois[:, 3:5][union_inds[:, 0]], rois[:, 3:5][union_inds[:, 1]]), ),1) # (num_rois, d, pooling_size, pooling_size) union_pools = RoIAlignFunction(pooling_size, pooling_size, spatial_scale=1/stride)(fmap, union_rois) return union_pools ================================================ FILE: lib/lstm/__init__.py ================================================ ================================================ FILE: lib/lstm/decoder_rnn.py ================================================ import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.nn.utils.rnn import PackedSequence from typing import Optional, Tuple from lib.fpn.box_utils import nms_overlaps from lib.word_vectors import obj_edge_vectors from .highway_lstm_cuda.alternating_highway_lstm import block_orthogonal import numpy as np def get_dropout_mask(dropout_probability: float, tensor_for_masking: torch.autograd.Variable): """ Computes and returns an element-wise dropout mask for a given tensor, where each element in the mask is dropped out with probability dropout_probability. Note that the mask is NOT applied to the tensor - the tensor is passed to retain the correct CUDA tensor type for the mask. Parameters ---------- dropout_probability : float, required. Probability of dropping a dimension of the input. tensor_for_masking : torch.Variable, required. Returns ------- A torch.FloatTensor consisting of the binary mask scaled by 1/ (1 - dropout_probability). This scaling ensures expected values and variances of the output of applying this mask and the original tensor are the same. """ binary_mask = tensor_for_masking.clone() binary_mask.data.copy_(torch.rand(tensor_for_masking.size()) > dropout_probability) # Scale mask by 1/keep_prob to preserve output statistics. dropout_mask = binary_mask.float().div(1.0 - dropout_probability) return dropout_mask class DecoderRNN(torch.nn.Module): def __init__(self, classes, embed_dim, inputs_dim, hidden_dim, recurrent_dropout_probability=0.2, use_highway=True, use_input_projection_bias=True): """ Initializes the RNN :param embed_dim: Dimension of the embeddings :param encoder_hidden_dim: Hidden dim of the encoder, for attention purposes :param hidden_dim: Hidden dim of the decoder :param vocab_size: Number of words in the vocab :param bos_token: To use during decoding (non teacher forcing mode)) :param bos: beginning of sentence token :param unk: unknown token (not used) """ super(DecoderRNN, self).__init__() self.classes = classes embed_vecs = obj_edge_vectors(['start'] + self.classes, wv_dim=100) self.obj_embed = nn.Embedding(len(self.classes), embed_dim) self.obj_embed.weight.data = embed_vecs self.hidden_size = hidden_dim self.inputs_dim = inputs_dim self.nms_thresh = 0.3 self.recurrent_dropout_probability=recurrent_dropout_probability self.use_highway=use_highway # We do the projections for all the gates all at once, so if we are # using highway layers, we need some extra projections, which is # why the sizes of the Linear layers change here depending on this flag. if use_highway: self.input_linearity = torch.nn.Linear(self.input_size, 6 * self.hidden_size, bias=use_input_projection_bias) self.state_linearity = torch.nn.Linear(self.hidden_size, 5 * self.hidden_size, bias=True) else: self.input_linearity = torch.nn.Linear(self.input_size, 4 * self.hidden_size, bias=use_input_projection_bias) self.state_linearity = torch.nn.Linear(self.hidden_size, 4 * self.hidden_size, bias=True) self.out = nn.Linear(self.hidden_size, len(self.classes)) self.reset_parameters() @property def input_size(self): return self.inputs_dim + self.obj_embed.weight.size(1) def reset_parameters(self): # Use sensible default initializations for parameters. block_orthogonal(self.input_linearity.weight.data, [self.hidden_size, self.input_size]) block_orthogonal(self.state_linearity.weight.data, [self.hidden_size, self.hidden_size]) self.state_linearity.bias.data.fill_(0.0) # Initialize forget gate biases to 1.0 as per An Empirical # Exploration of Recurrent Network Architectures, (Jozefowicz, 2015). self.state_linearity.bias.data[self.hidden_size:2 * self.hidden_size].fill_(1.0) def lstm_equations(self, timestep_input, previous_state, previous_memory, dropout_mask=None): """ Does the hairy LSTM math :param timestep_input: :param previous_state: :param previous_memory: :param dropout_mask: :return: """ # Do the projections for all the gates all at once. projected_input = self.input_linearity(timestep_input) projected_state = self.state_linearity(previous_state) # Main LSTM equations using relevant chunks of the big linear # projections of the hidden state and inputs. input_gate = torch.sigmoid(projected_input[:, 0 * self.hidden_size:1 * self.hidden_size] + projected_state[:, 0 * self.hidden_size:1 * self.hidden_size]) forget_gate = torch.sigmoid(projected_input[:, 1 * self.hidden_size:2 * self.hidden_size] + projected_state[:, 1 * self.hidden_size:2 * self.hidden_size]) memory_init = torch.tanh(projected_input[:, 2 * self.hidden_size:3 * self.hidden_size] + projected_state[:, 2 * self.hidden_size:3 * self.hidden_size]) output_gate = torch.sigmoid(projected_input[:, 3 * self.hidden_size:4 * self.hidden_size] + projected_state[:, 3 * self.hidden_size:4 * self.hidden_size]) memory = input_gate * memory_init + forget_gate * previous_memory timestep_output = output_gate * torch.tanh(memory) if self.use_highway: highway_gate = torch.sigmoid(projected_input[:, 4 * self.hidden_size:5 * self.hidden_size] + projected_state[:, 4 * self.hidden_size:5 * self.hidden_size]) highway_input_projection = projected_input[:, 5 * self.hidden_size:6 * self.hidden_size] timestep_output = highway_gate * timestep_output + (1 - highway_gate) * highway_input_projection # Only do dropout if the dropout prob is > 0.0 and we are in training mode. if dropout_mask is not None and self.training: timestep_output = timestep_output * dropout_mask return timestep_output, memory def forward(self, # pylint: disable=arguments-differ inputs: PackedSequence, initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, labels=None, boxes_for_nms=None): """ Parameters ---------- inputs : PackedSequence, required. A tensor of shape (batch_size, num_timesteps, input_size) to apply the LSTM over. initial_state : Tuple[torch.Tensor, torch.Tensor], optional, (default = None) A tuple (state, memory) representing the initial hidden state and memory of the LSTM. Each tensor has shape (1, batch_size, output_dimension). Returns ------- A PackedSequence containing a torch.FloatTensor of shape (batch_size, num_timesteps, output_dimension) representing the outputs of the LSTM per timestep and a tuple containing the LSTM state, with shape (1, batch_size, hidden_size) to match the Pytorch API. """ if not isinstance(inputs, PackedSequence): raise ValueError('inputs must be PackedSequence but got %s' % (type(inputs))) assert isinstance(inputs, PackedSequence) sequence_tensor, batch_lengths = inputs batch_size = batch_lengths[0] # We're just doing an LSTM decoder here so ignore states, etc if initial_state is None: previous_memory = Variable(sequence_tensor.data.new() .resize_(batch_size, self.hidden_size).fill_(0)) previous_state = Variable(sequence_tensor.data.new() .resize_(batch_size, self.hidden_size).fill_(0)) else: assert len(initial_state) == 2 previous_state = initial_state[0].squeeze(0) previous_memory = initial_state[1].squeeze(0) previous_embed = self.obj_embed.weight[0, None].expand(batch_size, 100) if self.recurrent_dropout_probability > 0.0: dropout_mask = get_dropout_mask(self.recurrent_dropout_probability, previous_memory) else: dropout_mask = None # Only accumulating label predictions here, discarding everything else out_dists = [] out_commitments = [] end_ind = 0 for i, l_batch in enumerate(batch_lengths): start_ind = end_ind end_ind = end_ind + l_batch if previous_memory.size(0) != l_batch: previous_memory = previous_memory[:l_batch] previous_state = previous_state[:l_batch] previous_embed = previous_embed[:l_batch] if dropout_mask is not None: dropout_mask = dropout_mask[:l_batch] timestep_input = torch.cat((sequence_tensor[start_ind:end_ind], previous_embed), 1) previous_state, previous_memory = self.lstm_equations(timestep_input, previous_state, previous_memory, dropout_mask=dropout_mask) pred_dist = self.out(previous_state) out_dists.append(pred_dist) if self.training: labels_to_embed = labels[start_ind:end_ind].clone() # Whenever labels are 0 set input to be our max prediction nonzero_pred = pred_dist[:, 1:].max(1)[1] + 1 is_bg = (labels_to_embed.data == 0).nonzero() if is_bg.dim() > 0: labels_to_embed[is_bg.squeeze(1)] = nonzero_pred[is_bg.squeeze(1)] out_commitments.append(labels_to_embed) previous_embed = self.obj_embed(labels_to_embed+1) else: assert l_batch == 1 out_dist_sample = F.softmax(pred_dist, dim=1) # if boxes_for_nms is not None: # out_dist_sample[domains_allowed[i] == 0] = 0.0 # Greedily take the max here amongst non-bgs best_ind = out_dist_sample[:, 1:].max(1)[1] + 1 # if boxes_for_nms is not None and i < boxes_for_nms.size(0): # best_int = int(best_ind.data[0]) # domains_allowed[i:, best_int] *= (1 - is_overlap[i, i:, best_int]) out_commitments.append(best_ind) previous_embed = self.obj_embed(best_ind+1) # Do NMS here as a post-processing step if boxes_for_nms is not None and not self.training: is_overlap = nms_overlaps(boxes_for_nms.data).view( boxes_for_nms.size(0), boxes_for_nms.size(0), boxes_for_nms.size(1) ).cpu().numpy() >= self.nms_thresh # is_overlap[np.arange(boxes_for_nms.size(0)), np.arange(boxes_for_nms.size(0))] = False out_dists_sampled = F.softmax(torch.cat(out_dists,0), 1).data.cpu().numpy() out_dists_sampled[:,0] = 0 out_commitments = out_commitments[0].data.new(len(out_commitments)).fill_(0) for i in range(out_commitments.size(0)): box_ind, cls_ind = np.unravel_index(out_dists_sampled.argmax(), out_dists_sampled.shape) out_commitments[int(box_ind)] = int(cls_ind) out_dists_sampled[is_overlap[box_ind,:,cls_ind], cls_ind] = 0.0 out_dists_sampled[box_ind] = -1.0 # This way we won't re-sample out_commitments = Variable(out_commitments) else: out_commitments = torch.cat(out_commitments, 0) return torch.cat(out_dists, 0), out_commitments ================================================ FILE: lib/lstm/highway_lstm_cuda/__init__.py ================================================ ================================================ FILE: lib/lstm/highway_lstm_cuda/_ext/__init__.py ================================================ ================================================ FILE: lib/lstm/highway_lstm_cuda/_ext/highway_lstm_layer/__init__.py ================================================ from torch.utils.ffi import _wrap_function from ._highway_lstm_layer import lib as _lib, ffi as _ffi __all__ = [] def _import_symbols(locals): for symbol in dir(_lib): fn = getattr(_lib, symbol) locals[symbol] = _wrap_function(fn, _ffi) __all__.append(symbol) _import_symbols(locals()) ================================================ FILE: lib/lstm/highway_lstm_cuda/alternating_highway_lstm.py ================================================ from typing import Tuple from overrides import overrides import torch from torch.autograd import Function, Variable from torch.nn import Parameter from torch.nn.utils.rnn import PackedSequence, pad_packed_sequence, pack_padded_sequence import itertools from ._ext import highway_lstm_layer def block_orthogonal(tensor, split_sizes, gain=1.0): """ An initializer which allows initializing model parameters in "blocks". This is helpful in the case of recurrent models which use multiple gates applied to linear projections, which can be computed efficiently if they are concatenated together. However, they are separate parameters which should be initialized independently. Parameters ---------- tensor : ``torch.Tensor``, required. A tensor to initialize. split_sizes : List[int], required. A list of length ``tensor.ndim()`` specifying the size of the blocks along that particular dimension. E.g. ``[10, 20]`` would result in the tensor being split into chunks of size 10 along the first dimension and 20 along the second. gain : float, optional (default = 1.0) The gain (scaling) applied to the orthogonal initialization. """ if isinstance(tensor, Variable): block_orthogonal(tensor.data, split_sizes, gain) return tensor sizes = list(tensor.size()) if any([a % b != 0 for a, b in zip(sizes, split_sizes)]): raise ValueError("tensor dimensions must be divisible by their respective " "split_sizes. Found size: {} and split_sizes: {}".format(sizes, split_sizes)) indexes = [list(range(0, max_size, split)) for max_size, split in zip(sizes, split_sizes)] # Iterate over all possible blocks within the tensor. for block_start_indices in itertools.product(*indexes): # A list of tuples containing the index to start at for this block # and the appropriate step size (i.e split_size[i] for dimension i). index_and_step_tuples = zip(block_start_indices, split_sizes) # This is a tuple of slices corresponding to: # tensor[index: index + step_size, ...]. This is # required because we could have an arbitrary number # of dimensions. The actual slices we need are the # start_index: start_index + step for each dimension in the tensor. block_slice = tuple([slice(start_index, start_index + step) for start_index, step in index_and_step_tuples]) # let's not initialize empty things to 0s because THAT SOUNDS REALLY BAD assert len(block_slice) == 2 sizes = [x.stop - x.start for x in block_slice] tensor_copy = tensor.new(max(sizes), max(sizes)) torch.nn.init.orthogonal(tensor_copy, gain=gain) tensor[block_slice] = tensor_copy[0:sizes[0], 0:sizes[1]] class _AlternatingHighwayLSTMFunction(Function): def __init__(self, input_size: int, hidden_size: int, num_layers: int, train: bool) -> None: super(_AlternatingHighwayLSTMFunction, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.num_layers = num_layers self.train = train @overrides def forward(self, # pylint: disable=arguments-differ inputs: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor, state_accumulator: torch.Tensor, memory_accumulator: torch.Tensor, dropout_mask: torch.Tensor, lengths: torch.Tensor, gates: torch.Tensor) -> Tuple[torch.Tensor, None]: sequence_length, batch_size, input_size = inputs.size() tmp_i = inputs.new(batch_size, 6 * self.hidden_size) tmp_h = inputs.new(batch_size, 5 * self.hidden_size) is_training = 1 if self.train else 0 highway_lstm_layer.highway_lstm_forward_cuda(input_size, # type: ignore # pylint: disable=no-member self.hidden_size, batch_size, self.num_layers, sequence_length, inputs, lengths, state_accumulator, memory_accumulator, tmp_i, tmp_h, weight, bias, dropout_mask, gates, is_training) self.save_for_backward(inputs, lengths, weight, bias, state_accumulator, memory_accumulator, dropout_mask, gates) # The state_accumulator has shape: (num_layers, sequence_length + 1, batch_size, hidden_size) # so for the output, we want the last layer and all but the first timestep, which was the # initial state. output = state_accumulator[-1, 1:, :, :] return output, state_accumulator[:, 1:, :, :] @overrides def backward(self, grad_output, grad_hy): # pylint: disable=arguments-differ (inputs, lengths, weight, bias, state_accumulator, # pylint: disable=unpacking-non-sequence memory_accumulator, dropout_mask, gates) = self.saved_tensors inputs = inputs.contiguous() sequence_length, batch_size, input_size = inputs.size() parameters_need_grad = 1 if self.needs_input_grad[1] else 0 # pylint: disable=unsubscriptable-object grad_input = inputs.new().resize_as_(inputs).zero_() grad_state_accumulator = inputs.new().resize_as_(state_accumulator).zero_() grad_memory_accumulator = inputs.new().resize_as_(memory_accumulator).zero_() grad_weight = inputs.new() grad_bias = inputs.new() grad_dropout = None grad_lengths = None grad_gates = None if parameters_need_grad: grad_weight.resize_as_(weight).zero_() grad_bias.resize_as_(bias).zero_() tmp_i_gates_grad = inputs.new().resize_(batch_size, 6 * self.hidden_size).zero_() tmp_h_gates_grad = inputs.new().resize_(batch_size, 5 * self.hidden_size).zero_() is_training = 1 if self.train else 0 highway_lstm_layer.highway_lstm_backward_cuda(input_size, # pylint: disable=no-member self.hidden_size, batch_size, self.num_layers, sequence_length, grad_output, lengths, grad_state_accumulator, grad_memory_accumulator, inputs, state_accumulator, memory_accumulator, weight, gates, dropout_mask, tmp_h_gates_grad, tmp_i_gates_grad, grad_hy, grad_input, grad_weight, grad_bias, is_training, parameters_need_grad) return (grad_input, grad_weight, grad_bias, grad_state_accumulator, grad_memory_accumulator, grad_dropout, grad_lengths, grad_gates) class AlternatingHighwayLSTM(torch.nn.Module): """ A stacked LSTM with LSTM layers which alternate between going forwards over the sequence and going backwards, with highway connections between each of the alternating layers. This implementation is based on the description in `Deep Semantic Role Labelling - What works and what's next `_ . Parameters ---------- input_size : int, required The dimension of the inputs to the LSTM. hidden_size : int, required The dimension of the outputs of the LSTM. num_layers : int, required The number of stacked LSTMs to use. recurrent_dropout_probability: float, optional (default = 0.0) The dropout probability to be used in a dropout scheme as stated in `A Theoretically Grounded Application of Dropout in Recurrent Neural Networks `_ . Returns ------- output : PackedSequence The outputs of the interleaved LSTMs per timestep. A tensor of shape (batch_size, max_timesteps, hidden_size) where for a given batch element, all outputs past the sequence length for that batch are zero tensors. """ def __init__(self, input_size: int, hidden_size: int, num_layers: int = 1, recurrent_dropout_probability: float = 0) -> None: super(AlternatingHighwayLSTM, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.num_layers = num_layers self.recurrent_dropout_probability = recurrent_dropout_probability self.training = True # Input dimensions consider the fact that we do # all of the LSTM projections (and highway parts) # in a single matrix multiplication. input_projection_size = 6 * hidden_size state_projection_size = 5 * hidden_size bias_size = 5 * hidden_size # Here we are creating a single weight and bias with the # parameters for all layers unfolded into it. This is necessary # because unpacking and re-packing the weights inside the # kernel would be slow, as it would happen every time it is called. total_weight_size = 0 total_bias_size = 0 for layer in range(num_layers): layer_input_size = input_size if layer == 0 else hidden_size input_weights = input_projection_size * layer_input_size state_weights = state_projection_size * hidden_size total_weight_size += input_weights + state_weights total_bias_size += bias_size self.weight = Parameter(torch.FloatTensor(total_weight_size)) self.bias = Parameter(torch.FloatTensor(total_bias_size)) self.reset_parameters() def reset_parameters(self) -> None: self.bias.data.zero_() weight_index = 0 bias_index = 0 for i in range(self.num_layers): input_size = self.input_size if i == 0 else self.hidden_size # Create a tensor of the right size and initialize it. init_tensor = self.weight.data.new(input_size, self.hidden_size * 6).zero_() block_orthogonal(init_tensor, [input_size, self.hidden_size]) # Copy it into the flat weight. self.weight.data[weight_index: weight_index + init_tensor.nelement()] \ .view_as(init_tensor).copy_(init_tensor) weight_index += init_tensor.nelement() # Same for the recurrent connection weight. init_tensor = self.weight.data.new(self.hidden_size, self.hidden_size * 5).zero_() block_orthogonal(init_tensor, [self.hidden_size, self.hidden_size]) self.weight.data[weight_index: weight_index + init_tensor.nelement()] \ .view_as(init_tensor).copy_(init_tensor) weight_index += init_tensor.nelement() # Set the forget bias to 1. self.bias.data[bias_index + self.hidden_size:bias_index + 2 * self.hidden_size].fill_(1) bias_index += 5 * self.hidden_size def forward(self, inputs, initial_state=None) -> Tuple[PackedSequence, torch.Tensor]: """ Parameters ---------- inputs : ``PackedSequence``, required. A batch first ``PackedSequence`` to run the stacked LSTM over. initial_state : Tuple[torch.Tensor, torch.Tensor], optional, (default = None) Currently, this is ignored. Returns ------- output_sequence : ``PackedSequence`` The encoded sequence of shape (batch_size, sequence_length, hidden_size) final_states: ``torch.Tensor`` The per-layer final (state, memory) states of the LSTM, each with shape (num_layers, batch_size, hidden_size). """ inputs, lengths = pad_packed_sequence(inputs, batch_first=False) sequence_length, batch_size, _ = inputs.size() accumulator_shape = [self.num_layers, sequence_length + 1, batch_size, self.hidden_size] state_accumulator = Variable(inputs.data.new(*accumulator_shape).zero_(), requires_grad=False) memory_accumulator = Variable(inputs.data.new(*accumulator_shape).zero_(), requires_grad=False) dropout_weights = inputs.data.new().resize_(self.num_layers, batch_size, self.hidden_size).fill_(1.0) if self.training: # Normalize by 1 - dropout_prob to preserve the output statistics of the layer. dropout_weights.bernoulli_(1 - self.recurrent_dropout_probability) \ .div_((1 - self.recurrent_dropout_probability)) dropout_weights = Variable(dropout_weights, requires_grad=False) gates = Variable(inputs.data.new().resize_(self.num_layers, sequence_length, batch_size, 6 * self.hidden_size)) lengths_variable = Variable(torch.IntTensor(lengths)) implementation = _AlternatingHighwayLSTMFunction(self.input_size, self.hidden_size, num_layers=self.num_layers, train=self.training) output, _ = implementation(inputs, self.weight, self.bias, state_accumulator, memory_accumulator, dropout_weights, lengths_variable, gates) output = pack_padded_sequence(output, lengths, batch_first=False) return output, None ================================================ FILE: lib/lstm/highway_lstm_cuda/build.py ================================================ # pylint: disable=invalid-name import os import torch from torch.utils.ffi import create_extension if not torch.cuda.is_available(): raise Exception('HighwayLSTM can only be compiled with CUDA') sources = ['src/highway_lstm_cuda.c'] headers = ['src/highway_lstm_cuda.h'] defines = [('WITH_CUDA', None)] with_cuda = True this_file = os.path.dirname(os.path.realpath(__file__)) extra_objects = ['src/highway_lstm_kernel.cu.o'] extra_objects = [os.path.join(this_file, fname) for fname in extra_objects] ffi = create_extension( '_ext.highway_lstm_layer', headers=headers, sources=sources, define_macros=defines, relative_to=__file__, with_cuda=with_cuda, extra_objects=extra_objects ) if __name__ == '__main__': ffi.build() ================================================ FILE: lib/lstm/highway_lstm_cuda/make.sh ================================================ #!/usr/bin/env bash CUDA_PATH=/usr/local/cuda/ # Which CUDA capabilities do we want to pre-build for? # https://developer.nvidia.com/cuda-gpus # Compute/shader model Cards # 61 P4, P40, Titan X # 60 P100 # 52 M40 # 37 K80 # 35 K40, K20 # 30 K10, Grid K520 (AWS G2) CUDA_MODELS=(52 61) # Nvidia doesn't guarantee binary compatability across GPU versions. # However, binary compatibility within one GPU generation can be guaranteed # under certain conditions because they share the basic instruction set. # This is the case between two GPU versions that do not show functional # differences at all (for instance when one version is a scaled down version # of the other), or when one version is functionally included in the other. # To fix this problem, we can create a 'fat binary' which generates multiple # translations of the CUDA source. The most appropriate version is chosen at # runtime by the CUDA driver. See: # http://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#gpu-compilation # http://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#fatbinaries CUDA_MODEL_TARGETS="" for i in "${CUDA_MODELS[@]}" do CUDA_MODEL_TARGETS+=" -gencode arch=compute_${i},code=sm_${i}" done echo "Building kernel for following target architectures: " echo $CUDA_MODEL_TARGETS cd src echo "Compiling kernel" /usr/local/cuda/bin/nvcc -c -o highway_lstm_kernel.cu.o highway_lstm_kernel.cu --compiler-options -fPIC $CUDA_MODEL_TARGETS cd ../ python build.py ================================================ FILE: lib/lstm/highway_lstm_cuda/src/highway_lstm_cuda.c ================================================ #include #include "highway_lstm_kernel.h" extern THCState *state; int highway_lstm_forward_cuda(int inputSize, int hiddenSize, int miniBatch, int numLayers, int seqLength, THCudaTensor *x, THIntTensor *lengths, THCudaTensor *h_data, THCudaTensor *c_data, THCudaTensor *tmp_i, THCudaTensor *tmp_h, THCudaTensor *T, THCudaTensor *bias, THCudaTensor *dropout, THCudaTensor *gates, int isTraining) { float * x_ptr = THCudaTensor_data(state, x); int * lengths_ptr = THIntTensor_data(lengths); float * h_data_ptr = THCudaTensor_data(state, h_data); float * c_data_ptr = THCudaTensor_data(state, c_data); float * tmp_i_ptr = THCudaTensor_data(state, tmp_i); float * tmp_h_ptr = THCudaTensor_data(state, tmp_h); float * T_ptr = THCudaTensor_data(state, T); float * bias_ptr = THCudaTensor_data(state, bias); float * dropout_ptr = THCudaTensor_data(state, dropout); float * gates_ptr; if (isTraining == 1) { gates_ptr = THCudaTensor_data(state, gates); } else { gates_ptr = NULL; } cudaStream_t stream = THCState_getCurrentStream(state); cublasHandle_t handle = THCState_getCurrentBlasHandle(state); highway_lstm_forward_ongpu(inputSize, hiddenSize, miniBatch, numLayers, seqLength, x_ptr, lengths_ptr, h_data_ptr, c_data_ptr, tmp_i_ptr, tmp_h_ptr, T_ptr, bias_ptr, dropout_ptr, gates_ptr, isTraining, stream, handle); return 1; } int highway_lstm_backward_cuda(int inputSize, int hiddenSize, int miniBatch, int numLayers, int seqLength, THCudaTensor *out_grad, THIntTensor *lengths, THCudaTensor *h_data_grad, THCudaTensor *c_data_grad, THCudaTensor *x, THCudaTensor *h_data, THCudaTensor *c_data, THCudaTensor *T, THCudaTensor *gates_out, THCudaTensor *dropout_in, THCudaTensor *h_gates_grad, THCudaTensor *i_gates_grad, THCudaTensor *h_out_grad, THCudaTensor *x_grad, THCudaTensor *T_grad, THCudaTensor *bias_grad, int isTraining, int do_weight_grad) { float * out_grad_ptr = THCudaTensor_data(state, out_grad); int * lengths_ptr = THIntTensor_data(lengths); float * h_data_grad_ptr = THCudaTensor_data(state, h_data_grad); float * c_data_grad_ptr = THCudaTensor_data(state, c_data_grad); float * x_ptr = THCudaTensor_data(state, x); float * h_data_ptr = THCudaTensor_data(state, h_data); float * c_data_ptr = THCudaTensor_data(state, c_data); float * T_ptr = THCudaTensor_data(state, T); float * gates_out_ptr = THCudaTensor_data(state, gates_out); float * dropout_in_ptr = THCudaTensor_data(state, dropout_in); float * h_gates_grad_ptr = THCudaTensor_data(state, h_gates_grad); float * i_gates_grad_ptr = THCudaTensor_data(state, i_gates_grad); float * h_out_grad_ptr = THCudaTensor_data(state, h_out_grad); float * x_grad_ptr = THCudaTensor_data(state, x_grad); float * T_grad_ptr = THCudaTensor_data(state, T_grad); float * bias_grad_ptr = THCudaTensor_data(state, bias_grad); cudaStream_t stream = THCState_getCurrentStream(state); cublasHandle_t handle = THCState_getCurrentBlasHandle(state); highway_lstm_backward_ongpu(inputSize, hiddenSize, miniBatch, numLayers, seqLength, out_grad_ptr, lengths_ptr, h_data_grad_ptr, c_data_grad_ptr, x_ptr, h_data_ptr, c_data_ptr, T_ptr, gates_out_ptr, dropout_in_ptr, h_gates_grad_ptr, i_gates_grad_ptr, h_out_grad_ptr, x_grad_ptr, T_grad_ptr, bias_grad_ptr, isTraining, do_weight_grad, stream, handle); return 1; } ================================================ FILE: lib/lstm/highway_lstm_cuda/src/highway_lstm_cuda.h ================================================ int highway_lstm_forward_cuda(int inputSize, int hiddenSize, int miniBatch, int numLayers, int seqLength, THCudaTensor *x, THIntTensor *lengths, THCudaTensor *h_data, THCudaTensor *c_data, THCudaTensor *tmp_i, THCudaTensor *tmp_h, THCudaTensor *T, THCudaTensor *bias, THCudaTensor *dropout, THCudaTensor *gates, int isTraining); int highway_lstm_backward_cuda(int inputSize, int hiddenSize, int miniBatch, int numLayers, int seqLength, THCudaTensor *out_grad, THIntTensor *lengths, THCudaTensor *h_data_grad, THCudaTensor *c_data_grad, THCudaTensor *x, THCudaTensor *h_data, THCudaTensor *c_data, THCudaTensor *T, THCudaTensor *gates_out, THCudaTensor *dropout_in, THCudaTensor *h_gates_grad, THCudaTensor *i_gates_grad, THCudaTensor *h_out_grad, THCudaTensor *x_grad, THCudaTensor *T_grad, THCudaTensor *bias_grad, int isTraining, int do_weight_grad); ================================================ FILE: lib/lstm/highway_lstm_cuda/src/highway_lstm_kernel.cu ================================================ #include "cuda_runtime.h" #include "curand.h" #include "cublas_v2.h" #include #ifdef __cplusplus extern "C" { #endif #include #include #include "highway_lstm_kernel.h" #define BLOCK 256 // Define some error checking macros. #define cudaErrCheck(stat) { cudaErrCheck_((stat), __FILE__, __LINE__); } void cudaErrCheck_(cudaError_t stat, const char *file, int line) { if (stat != cudaSuccess) { fprintf(stderr, "CUDA Error: %s %s %d\n", cudaGetErrorString(stat), file, line); } } #define cublasErrCheck(stat) { cublasErrCheck_((stat), __FILE__, __LINE__); } void cublasErrCheck_(cublasStatus_t stat, const char *file, int line) { if (stat != CUBLAS_STATUS_SUCCESS) { fprintf(stderr, "cuBLAS Error: %d %s %d\n", stat, file, line); } } // Device functions __forceinline__ __device__ float sigmoidf(float in) { return 1.f / (1.f + expf(-in)); } __forceinline__ __device__ float dsigmoidf(float in) { float s = sigmoidf(in); return s * (1.f - s); } __forceinline__ __device__ float tanh2f(float in) { float t = tanhf(in); return t*t; } __global__ void elementWise_bp(int hiddenSize, int miniBatch, int numCovered, // Inputs float *out_grad, float *h_out_grad, float *c_out_grad, float *c_in, float *c_out, float *h_out, float *gates_out, float *dropout_in, // Outputs float *c_in_grad, float *i_gates_grad, float *h_gates_grad, int training) { int index = blockIdx.x * blockDim.x + threadIdx.x; if (index >= numCovered * hiddenSize) return; int batch = index / hiddenSize; int h_gateIndex = (index % hiddenSize) + 5 * batch * hiddenSize; int i_gateIndex = (index % hiddenSize) + 6 * batch * hiddenSize; float d_h = out_grad[index] + h_out_grad[index]; d_h = d_h * dropout_in[index]; float in_gate = gates_out[i_gateIndex]; float forget_gate = gates_out[i_gateIndex + 1 * hiddenSize]; float act_gate = gates_out[i_gateIndex + 2 * hiddenSize]; float out_gate = gates_out[i_gateIndex + 3 * hiddenSize]; float r_gate = gates_out[i_gateIndex + 4 * hiddenSize]; float lin_gate = gates_out[i_gateIndex + 5 * hiddenSize]; float d_out = d_h * r_gate; float d_c = d_out * out_gate * (1.f - tanh2f(c_out[index])) + c_out_grad[index]; float h_prime = out_gate * tanhf(c_out[index]); float d_in_gate = d_c * act_gate * in_gate * (1.f - in_gate); float d_forget_gate = d_c * c_in[index] * forget_gate * (1.f - forget_gate); float d_act_gate = d_c * in_gate * (1.f - act_gate * act_gate); float d_out_gate = d_out * tanhf(c_out[index]) * out_gate * (1.f - out_gate); float d_r_gate = d_h * (h_prime - lin_gate) * r_gate * (1.f - r_gate); float d_lin_gate = d_h * (1 - r_gate); i_gates_grad[i_gateIndex] = d_in_gate; i_gates_grad[i_gateIndex + 1 * hiddenSize] = d_forget_gate; i_gates_grad[i_gateIndex + 2 * hiddenSize] = d_act_gate; i_gates_grad[i_gateIndex + 3 * hiddenSize] = d_out_gate; i_gates_grad[i_gateIndex + 4 * hiddenSize] = d_r_gate; i_gates_grad[i_gateIndex + 5 * hiddenSize] = d_lin_gate; h_gates_grad[h_gateIndex] = d_in_gate; h_gates_grad[h_gateIndex + 1 * hiddenSize] = d_forget_gate; h_gates_grad[h_gateIndex + 2 * hiddenSize] = d_act_gate; h_gates_grad[h_gateIndex + 3 * hiddenSize] = d_out_gate; h_gates_grad[h_gateIndex + 4 * hiddenSize] = d_r_gate; c_in_grad[index] = forget_gate * d_c; } // Fused forward kernel __global__ void elementWise_fp(int hiddenSize, int miniBatch, int numCovered, float *tmp_h, float *tmp_i, float *bias, float *linearGates, float *h_out, float *dropout_in, float *c_in, float *c_out, int training) { int index = blockIdx.x * blockDim.x + threadIdx.x; if (index >= numCovered * hiddenSize) return; int batch = index / hiddenSize; int h_gateIndex = (index % hiddenSize) + 5 * batch * hiddenSize; int i_gateIndex = (index % hiddenSize) + 6 * batch * hiddenSize; float g[6]; for (int i = 0; i < 5; i++) { g[i] = tmp_i[i * hiddenSize + i_gateIndex] + tmp_h[i * hiddenSize + h_gateIndex]; g[i] += bias[i * hiddenSize + index % hiddenSize]; } // extra for highway g[5] = tmp_i[5 * hiddenSize + i_gateIndex]; float in_gate = sigmoidf(g[0]); float forget_gate = sigmoidf(g[1]); float act_gate = tanhf(g[2]); float out_gate = sigmoidf(g[3]); float r_gate = sigmoidf(g[4]); float lin_gate = g[5]; if (training == 1) { linearGates[i_gateIndex] = in_gate; linearGates[i_gateIndex + 1 * hiddenSize] = forget_gate; linearGates[i_gateIndex + 2 * hiddenSize] = act_gate; linearGates[i_gateIndex + 3 * hiddenSize] = out_gate; linearGates[i_gateIndex + 4 * hiddenSize] = r_gate; linearGates[i_gateIndex + 5 * hiddenSize] = lin_gate; } float val = (forget_gate * c_in[index]) + (in_gate * act_gate); c_out[index] = val; val = out_gate * tanhf(val); val = val * r_gate + (1. - r_gate) * lin_gate; val = val * dropout_in[index]; h_out[index] = val; } void highway_lstm_backward_ongpu(int inputSize, int hiddenSize, int miniBatch, int numLayers, int seqLength, float *out_grad, int *lengths, float *h_data_grad, float * c_data_grad, float *x, float *h_data, float *c_data, float *T, float *gates_out, float *dropout_in, float *h_gates_grad, float *i_gates_grad, float *h_out_grad, float *x_grad, float *T_grad, float *bias_grad, int isTraining, int do_weight_grad, cudaStream_t stream, cublasHandle_t handle) { const int numElements = hiddenSize * miniBatch; cudaStream_t stream_i; cudaStream_t stream_h; cudaStream_t stream_wi; cudaStream_t stream_wh; cudaStream_t stream_wb; cudaErrCheck(cudaStreamCreate(&stream_i)); cudaErrCheck(cudaStreamCreate(&stream_h)); cudaErrCheck(cudaStreamCreate(&stream_wi)); cudaErrCheck(cudaStreamCreate(&stream_wh)); cudaErrCheck(cudaStreamCreate(&stream_wb)); float one = 1.f; float zero = 0.f; float *ones_host = new float[miniBatch]; for (int i=0; i < miniBatch; i++) { ones_host[i] = 1.f; } float *ones; cudaErrCheck(cudaMalloc((void**)&ones, miniBatch * sizeof(float))); cudaErrCheck(cudaMemcpy(ones, ones_host, miniBatch * sizeof(float), cudaMemcpyHostToDevice)); for (int layer = numLayers-1; layer >= 0; layer--) { int direction; int startInd; int currNumCovered; if (layer % 2 == 0) { // forward direction direction = -1; startInd = seqLength-1; currNumCovered = 0; } else { // backward direction direction = 1; startInd = 0; currNumCovered = miniBatch; } for (int t = startInd; t < seqLength && t >= 0; t = t + direction) { int prevIndex; int prevGradIndex; if (direction == 1) { while (lengths[currNumCovered-1] <= t) { currNumCovered--; } prevGradIndex = t; prevIndex = (t+2)%(seqLength+1); } else { while ((currNumCovered < miniBatch) && (lengths[currNumCovered] > t)) { currNumCovered++; } prevGradIndex = (t+2)%(seqLength+1); prevIndex = t; } float * gradPtr; if (layer == numLayers-1) { gradPtr = out_grad + t * numElements; } else { gradPtr = h_out_grad + t * numElements + layer * seqLength * numElements; } cublasErrCheck(cublasSetStream(handle, stream_i)); dim3 blockDim; dim3 gridDim; blockDim.x = BLOCK; gridDim.x = ((currNumCovered * hiddenSize) + blockDim.x - 1) / blockDim.x; elementWise_bp <<< gridDim, blockDim , 0, stream>>> (hiddenSize, miniBatch, currNumCovered, gradPtr, h_data_grad + prevGradIndex * numElements + layer * (seqLength + 1) * numElements, c_data_grad + prevGradIndex * numElements + layer * (seqLength + 1) * numElements, c_data + prevIndex * numElements + layer * (seqLength + 1) * numElements, c_data + (t+1) * numElements + layer * (seqLength + 1) * numElements, h_data + (t+1) * numElements + layer * (seqLength + 1) * numElements, gates_out + t * 6 * numElements + layer * seqLength * 6 * numElements, dropout_in + layer * numElements, c_data_grad + (t+1) * numElements + layer * (seqLength + 1) * numElements, i_gates_grad, h_gates_grad, isTraining); cudaErrCheck(cudaGetLastError()); // END cudaErrCheck(cudaDeviceSynchronize()); float *out_grad_ptr; int weightStart; int inSize; if (layer == 0) { inSize = inputSize; out_grad_ptr = x_grad + t * inputSize * miniBatch; weightStart = 0; } else { inSize = hiddenSize; out_grad_ptr = h_out_grad + t * numElements + (layer-1) * seqLength * numElements; weightStart = 6 * hiddenSize * inputSize + 5 * hiddenSize * hiddenSize + (layer - 1) * 11 * hiddenSize * hiddenSize; } cublasErrCheck(cublasSgemm(handle, CUBLAS_OP_T, CUBLAS_OP_N, inSize, currNumCovered, 6*hiddenSize, &one, &T[weightStart], 6 * hiddenSize, i_gates_grad, 6 * hiddenSize, &zero, out_grad_ptr, inSize)); cublasErrCheck(cublasSetStream(handle, stream_h)); cublasErrCheck(cublasSgemm(handle, CUBLAS_OP_T, CUBLAS_OP_N, hiddenSize, currNumCovered, 5*hiddenSize, &one, &T[weightStart + 6*hiddenSize*inSize], 5 * hiddenSize, h_gates_grad, 5 * hiddenSize, &zero, h_data_grad + (t+1) * numElements + layer * (seqLength+1) * numElements, hiddenSize)); if (do_weight_grad == 1) { float *inputPtr; if (layer == 0) { inputPtr = x + t * inputSize * miniBatch; } else { inputPtr = h_data + (t+1) * numElements + (layer - 1) * (seqLength+1) * numElements; } cublasErrCheck(cublasSetStream(handle, stream_wi)); // Update i_weights cublasErrCheck(cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_T, 6 * hiddenSize, inSize, currNumCovered, &one, i_gates_grad, 6 * hiddenSize, inputPtr, inSize, &one, &T_grad[weightStart], 6 * hiddenSize)); cublasErrCheck(cublasSetStream(handle, stream_wh)); // Update h_weights cublasErrCheck(cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_T, 5 * hiddenSize, hiddenSize, currNumCovered, &one, h_gates_grad, 5 * hiddenSize, h_data + prevIndex * numElements + layer * (seqLength+1) * numElements, hiddenSize, &one, &T_grad[weightStart + 6 *hiddenSize*inSize], 5 * hiddenSize)); cublasErrCheck(cublasSetStream(handle, stream_wb)); // Update bias_weights cublasErrCheck(cublasSgemv(handle, CUBLAS_OP_N, 5 * hiddenSize, currNumCovered, &one, h_gates_grad, 5 * hiddenSize, ones, 1, &one, &bias_grad[layer * 5 * hiddenSize], 1)); } cudaErrCheck(cudaDeviceSynchronize()); } } cublasErrCheck(cublasSetStream(handle, stream)); cudaErrCheck(cudaStreamDestroy(stream_i)); cudaErrCheck(cudaStreamDestroy(stream_h)); cudaErrCheck(cudaStreamDestroy(stream_wi)); cudaErrCheck(cudaStreamDestroy(stream_wh)); cudaErrCheck(cudaStreamDestroy(stream_wb)); cudaErrCheck(cudaFree(ones)); delete [] ones_host; cudaErrCheck(cudaDeviceSynchronize()); } void highway_lstm_forward_ongpu(int inputSize, int hiddenSize, int miniBatch, int numLayers, int seqLength, float *x, int *lengths, float *h_data, float *c_data, float *tmp_i, float *tmp_h, float *T, float *bias, float *dropout, float *gates, int is_training, cudaStream_t stream, cublasHandle_t handle) { const int numElements = hiddenSize * miniBatch; float zero = 0.f; float one = 1.f; cudaStream_t stream_i; cudaStream_t stream_h; cudaErrCheck(cudaStreamCreate(&stream_i)); cudaErrCheck(cudaStreamCreate(&stream_h)); for (int layer = 0; layer < numLayers; layer++) { int direction; int startInd; int currNumCovered; if (layer % 2 == 0) { // forward direction direction = 1; startInd = 0; currNumCovered = miniBatch; } else { // backward direction direction = -1; startInd = seqLength-1; currNumCovered = 0; } cublasErrCheck(cublasSetStream(handle, stream)); for (int t = startInd; t < seqLength && t >= 0; t = t + direction) { int prevIndex; if (direction == 1) { while (lengths[currNumCovered-1] <= t) { currNumCovered--; } prevIndex = t; } else { while ((currNumCovered < miniBatch) && (lengths[currNumCovered] > t)) { currNumCovered++; } prevIndex = (t+2)%(seqLength+1); } int inSize; int weightStart; float *inputPtr; if (layer == 0) { inSize = inputSize; weightStart = 0; inputPtr = x + t * inputSize * miniBatch; prevIndex = t; } else { inSize = hiddenSize; weightStart = 6 * hiddenSize * inputSize + 5 * hiddenSize * hiddenSize + (layer - 1) * 11 * hiddenSize * hiddenSize; inputPtr = h_data + (t+1) * numElements + (layer - 1) * (seqLength+1) * numElements; } cublasErrCheck(cublasSetStream(handle, stream_i)); cublasErrCheck(cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, 6*hiddenSize, currNumCovered, inSize, &one, &T[weightStart], 6 * hiddenSize, inputPtr, inSize, &zero, tmp_i, 6 * hiddenSize)); cublasErrCheck(cublasSetStream(handle, stream_h)); cublasErrCheck(cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, 5*hiddenSize, currNumCovered, hiddenSize, &one, &T[6 * hiddenSize * inSize + weightStart], 5 * hiddenSize, h_data + prevIndex * numElements + layer * (seqLength + 1) * numElements, hiddenSize, &zero, tmp_h, 5 * hiddenSize)); cudaErrCheck(cudaDeviceSynchronize()); dim3 blockDim; dim3 gridDim; blockDim.x = BLOCK; gridDim.x = ((currNumCovered * hiddenSize) + blockDim.x - 1) / blockDim.x; elementWise_fp <<< gridDim, blockDim , 0, stream>>> (hiddenSize, miniBatch, currNumCovered, tmp_h, tmp_i, bias + 5 * layer * hiddenSize, is_training ? gates + 6 * (t * numElements + layer * seqLength * numElements) : NULL, h_data + (t + 1) * numElements + layer * (seqLength + 1) * numElements, dropout + layer * numElements, c_data + prevIndex * numElements + layer * (seqLength + 1) * numElements, c_data + (t + 1) * numElements + layer * (seqLength + 1) * numElements, is_training); cudaErrCheck(cudaGetLastError()); cudaErrCheck(cudaDeviceSynchronize()); } } cublasErrCheck(cublasSetStream(handle, stream)); cudaErrCheck(cudaStreamDestroy(stream_i)); cudaErrCheck(cudaStreamDestroy(stream_h)); cudaErrCheck(cudaDeviceSynchronize()); } #ifdef __cplusplus } #endif ================================================ FILE: lib/lstm/highway_lstm_cuda/src/highway_lstm_kernel.h ================================================ #include #ifdef __cplusplus extern "C" { #endif void highway_lstm_forward_ongpu(int inputSize, int hiddenSize, int miniBatch, int numLayers, int seqLength, float *x, int *lengths, float*h_data, float *c_data, float *tmp_i, float *tmp_h, float *T, float *bias, float *dropout, float *gates, int is_training, cudaStream_t stream, cublasHandle_t handle); void highway_lstm_backward_ongpu(int inputSize, int hiddenSize, int miniBatch, int numLayers, int seqLength, float *out_grad, int *lengths, float *h_data_grad, float *c_data_grad, float *x, float *h_data, float *c_data, float *T, float *gates_out, float *dropout_in, float *h_gates_grad, float *i_gates_grad, float *h_out_grad, float *x_grad, float *T_grad, float *bias_grad, int isTraining, int do_weight_grad, cudaStream_t stream, cublasHandle_t handle); #ifdef __cplusplus } #endif ================================================ FILE: lib/object_detector.py ================================================ import numpy as np import torch import torch.nn as nn import torch.nn.parallel from torch.autograd import Variable from torch.nn import functional as F from config import ANCHOR_SIZE, ANCHOR_RATIOS, ANCHOR_SCALES from lib.fpn.generate_anchors import generate_anchors from lib.fpn.box_utils import bbox_preds, center_size, bbox_overlaps from lib.fpn.nms.functions.nms import apply_nms from lib.fpn.proposal_assignments.proposal_assignments_gtbox import proposal_assignments_gtbox from lib.fpn.proposal_assignments.proposal_assignments_det import proposal_assignments_det from lib.fpn.roi_align.functions.roi_align import RoIAlignFunction from lib.pytorch_misc import enumerate_by_image, gather_nd, diagonal_inds, Flattener from torchvision.models.vgg import vgg16 from torchvision.models.resnet import resnet101 from torch.nn.parallel._functions import Gather class Result(object): """ little container class for holding the detection result od: object detector, rm: rel model""" def __init__(self, od_obj_dists=None, rm_obj_dists=None, obj_scores=None, obj_preds=None, obj_fmap=None, od_box_deltas=None, rm_box_deltas=None, od_box_targets=None, rm_box_targets=None, od_box_priors=None, rm_box_priors=None, boxes_assigned=None, boxes_all=None, od_obj_labels=None, rm_obj_labels=None, rpn_scores=None, rpn_box_deltas=None, rel_labels=None, im_inds=None, fmap=None, rel_dists=None, rel_inds=None, rel_rep=None): self.__dict__.update(locals()) del self.__dict__['self'] def is_none(self): return all([v is None for k, v in self.__dict__.items() if k != 'self']) def gather_res(outputs, target_device, dim=0): """ Assuming the signatures are the same accross results! """ out = outputs[0] args = {field: Gather.apply(target_device, dim, *[getattr(o, field) for o in outputs]) for field, v in out.__dict__.items() if v is not None} return type(out)(**args) class ObjectDetector(nn.Module): """ Core model for doing object detection + getting the visual features. This could be the first step in a pipeline. We can provide GT rois or use the RPN (which would then be classification!) """ MODES = ('rpntrain', 'gtbox', 'refinerels', 'proposals') def __init__(self, classes, mode='rpntrain', num_gpus=1, nms_filter_duplicates=True, max_per_img=64, use_resnet=False, thresh=0.05): """ :param classes: Object classes :param rel_classes: Relationship classes. None if were not using rel mode :param num_gpus: how many GPUS 2 use """ super(ObjectDetector, self).__init__() if mode not in self.MODES: raise ValueError("invalid mode") self.mode = mode self.classes = classes self.num_gpus = num_gpus self.pooling_size = 7 self.nms_filter_duplicates = nms_filter_duplicates self.max_per_img = max_per_img self.use_resnet = use_resnet self.thresh = thresh if not self.use_resnet: vgg_model = load_vgg() self.features = vgg_model.features self.roi_fmap = vgg_model.classifier rpn_input_dim = 512 output_dim = 4096 else: # Deprecated self.features = load_resnet() self.compress = nn.Sequential( nn.Conv2d(1024, 256, kernel_size=1), nn.ReLU(inplace=True), nn.BatchNorm2d(256), ) self.roi_fmap = nn.Sequential( nn.Linear(256 * 7 * 7, 2048), nn.SELU(inplace=True), nn.AlphaDropout(p=0.05), nn.Linear(2048, 2048), nn.SELU(inplace=True), nn.AlphaDropout(p=0.05), ) rpn_input_dim = 1024 output_dim = 2048 self.score_fc = nn.Linear(output_dim, self.num_classes) self.bbox_fc = nn.Linear(output_dim, self.num_classes * 4) self.rpn_head = RPNHead(dim=512, input_dim=rpn_input_dim) @property def num_classes(self): return len(self.classes) def feature_map(self, x): """ Produces feature map from the input image :param x: [batch_size, 3, size, size] float32 padded image :return: Feature maps at 1/16 the original size. Each one is [batch_size, dim, IM_SIZE/k, IM_SIZE/k]. """ if not self.use_resnet: return self.features(x) # Uncomment this for "stanford" setting in which it's frozen: .detach() x = self.features.conv1(x) x = self.features.bn1(x) x = self.features.relu(x) x = self.features.maxpool(x) c2 = self.features.layer1(x) c3 = self.features.layer2(c2) c4 = self.features.layer3(c3) return c4 def obj_feature_map(self, features, rois): """ Gets the ROI features :param features: [batch_size, dim, IM_SIZE/4, IM_SIZE/4] (features at level p2) :param rois: [num_rois, 5] array of [img_num, x0, y0, x1, y1]. :return: [num_rois, #dim] array """ feature_pool = RoIAlignFunction(self.pooling_size, self.pooling_size, spatial_scale=1 / 16)( self.compress(features) if self.use_resnet else features, rois) return self.roi_fmap(feature_pool.view(rois.size(0), -1)) def rpn_boxes(self, fmap, im_sizes, image_offset, gt_boxes=None, gt_classes=None, gt_rels=None, train_anchor_inds=None, proposals=None): """ Gets boxes from the RPN :param fmap: :param im_sizes: :param image_offset: :param gt_boxes: :param gt_classes: :param gt_rels: :param train_anchor_inds: :return: """ rpn_feats = self.rpn_head(fmap) rois = self.rpn_head.roi_proposals( rpn_feats, im_sizes, nms_thresh=0.7, pre_nms_topn=12000 if self.training and self.mode == 'rpntrain' else 6000, post_nms_topn=2000 if self.training and self.mode == 'rpntrain' else 1000, ) if self.training: if gt_boxes is None or gt_classes is None or train_anchor_inds is None: raise ValueError( "Must supply GT boxes, GT classes, trainanchors when in train mode") rpn_scores, rpn_box_deltas = self.rpn_head.anchor_preds(rpn_feats, train_anchor_inds, image_offset) if gt_rels is not None and self.mode == 'rpntrain': raise ValueError("Training the object detector and the relationship model with detection" "at the same time isn't supported") if self.mode == 'refinerels': all_rois = Variable(rois) # Potentially you could add in GT rois if none match # is_match = (bbox_overlaps(rois[:,1:].contiguous(), gt_boxes.data) > 0.5).long() # gt_not_matched = (is_match.sum(0) == 0).nonzero() # # if gt_not_matched.dim() > 0: # gt_to_add = torch.cat((gt_classes[:,0,None][gt_not_matched.squeeze(1)].float(), # gt_boxes[gt_not_matched.squeeze(1)]), 1) # # all_rois = torch.cat((all_rois, gt_to_add),0) # num_gt = gt_to_add.size(0) labels = None bbox_targets = None rel_labels = None else: all_rois, labels, bbox_targets = proposal_assignments_det( rois, gt_boxes.data, gt_classes.data, image_offset, fg_thresh=0.5) rel_labels = None else: all_rois = Variable(rois, volatile=True) labels = None bbox_targets = None rel_labels = None rpn_box_deltas = None rpn_scores = None return all_rois, labels, bbox_targets, rpn_scores, rpn_box_deltas, rel_labels def gt_boxes(self, fmap, im_sizes, image_offset, gt_boxes=None, gt_classes=None, gt_rels=None, train_anchor_inds=None, proposals=None): """ Gets GT boxes! :param fmap: :param im_sizes: :param image_offset: :param gt_boxes: :param gt_classes: :param gt_rels: :param train_anchor_inds: :return: """ assert gt_boxes is not None im_inds = gt_classes[:, 0] - image_offset rois = torch.cat((im_inds.float()[:, None], gt_boxes), 1) if gt_rels is not None and self.training: rois, labels, rel_labels = proposal_assignments_gtbox( rois.data, gt_boxes.data, gt_classes.data, gt_rels.data, image_offset, fg_thresh=0.5) else: labels = gt_classes[:, 1] rel_labels = None return rois, labels, None, None, None, rel_labels def proposal_boxes(self, fmap, im_sizes, image_offset, gt_boxes=None, gt_classes=None, gt_rels=None, train_anchor_inds=None, proposals=None): """ Gets boxes from the RPN :param fmap: :param im_sizes: :param image_offset: :param gt_boxes: :param gt_classes: :param gt_rels: :param train_anchor_inds: :return: """ assert proposals is not None rois = filter_roi_proposals(proposals[:, 2:].data.contiguous(), proposals[:, 1].data.contiguous(), np.array([2000] * len(im_sizes)), nms_thresh=0.7, pre_nms_topn=12000 if self.training and self.mode == 'rpntrain' else 6000, post_nms_topn=2000 if self.training and self.mode == 'rpntrain' else 1000, ) if self.training: all_rois, labels, bbox_targets = proposal_assignments_det( rois, gt_boxes.data, gt_classes.data, image_offset, fg_thresh=0.5) # RETRAINING FOR DETECTION HERE. all_rois = torch.cat((all_rois, Variable(rois)), 0) else: all_rois = Variable(rois, volatile=True) labels = None bbox_targets = None rpn_scores = None rpn_box_deltas = None rel_labels = None return all_rois, labels, bbox_targets, rpn_scores, rpn_box_deltas, rel_labels def get_boxes(self, *args, **kwargs): if self.mode == 'gtbox': fn = self.gt_boxes elif self.mode == 'proposals': assert kwargs['proposals'] is not None fn = self.proposal_boxes else: fn = self.rpn_boxes return fn(*args, **kwargs) def forward(self, x, im_sizes, image_offset, gt_boxes=None, gt_classes=None, gt_rels=None, proposals=None, train_anchor_inds=None, return_fmap=False): """ Forward pass for detection :param x: Images@[batch_size, 3, IM_SIZE, IM_SIZE] :param im_sizes: A numpy array of (h, w, scale) for each image. :param image_offset: Offset onto what image we're on for MGPU training (if single GPU this is 0) :param gt_boxes: Training parameters: :param gt_boxes: [num_gt, 4] GT boxes over the batch. :param gt_classes: [num_gt, 2] gt boxes where each one is (img_id, class) :param proposals: things :param train_anchor_inds: a [num_train, 2] array of indices for the anchors that will be used to compute the training loss. Each (img_ind, fpn_idx) :return: If train: """ fmap = self.feature_map(x) # Get boxes from RPN rois, obj_labels, bbox_targets, rpn_scores, rpn_box_deltas, rel_labels = \ self.get_boxes(fmap, im_sizes, image_offset, gt_boxes, gt_classes, gt_rels, train_anchor_inds, proposals=proposals) # Now classify them obj_fmap = self.obj_feature_map(fmap, rois) od_obj_dists = self.score_fc(obj_fmap) od_box_deltas = self.bbox_fc(obj_fmap).view( -1, len(self.classes), 4) if self.mode != 'gtbox' else None od_box_priors = rois[:, 1:] if (not self.training and not self.mode == 'gtbox') or self.mode in ('proposals', 'refinerels'): nms_inds, nms_scores, nms_preds, nms_boxes_assign, nms_boxes, nms_imgs = self.nms_boxes( od_obj_dists, rois, od_box_deltas, im_sizes, ) im_inds = nms_imgs + image_offset obj_dists = od_obj_dists[nms_inds] obj_fmap = obj_fmap[nms_inds] box_deltas = od_box_deltas[nms_inds] box_priors = nms_boxes[:, 0] if self.training and not self.mode == 'gtbox': # NOTE: If we're doing this during training, we need to assign labels here. pred_to_gtbox = bbox_overlaps(box_priors, gt_boxes).data pred_to_gtbox[im_inds.data[:, None] != gt_classes.data[None, :, 0]] = 0.0 max_overlaps, argmax_overlaps = pred_to_gtbox.max(1) rm_obj_labels = gt_classes[:, 1][argmax_overlaps] rm_obj_labels[max_overlaps < 0.5] = 0 else: rm_obj_labels = None else: im_inds = rois[:, 0].long().contiguous() + image_offset nms_scores = None nms_preds = None nms_boxes_assign = None nms_boxes = None box_priors = rois[:, 1:] rm_obj_labels = obj_labels box_deltas = od_box_deltas obj_dists = od_obj_dists return Result( od_obj_dists=od_obj_dists, rm_obj_dists=obj_dists, obj_scores=nms_scores, obj_preds=nms_preds, obj_fmap=obj_fmap, od_box_deltas=od_box_deltas, rm_box_deltas=box_deltas, od_box_targets=bbox_targets, rm_box_targets=bbox_targets, od_box_priors=od_box_priors, rm_box_priors=box_priors, boxes_assigned=nms_boxes_assign, boxes_all=nms_boxes, od_obj_labels=obj_labels, rm_obj_labels=rm_obj_labels, rpn_scores=rpn_scores, rpn_box_deltas=rpn_box_deltas, rel_labels=rel_labels, im_inds=im_inds, fmap=fmap if return_fmap else None, ) def nms_boxes(self, obj_dists, rois, box_deltas, im_sizes): """ Performs NMS on the boxes :param obj_dists: [#rois, #classes] :param rois: [#rois, 5] :param box_deltas: [#rois, #classes, 4] :param im_sizes: sizes of images :return nms_inds [#nms] nms_scores [#nms] nms_labels [#nms] nms_boxes_assign [#nms, 4] nms_boxes [#nms, #classes, 4]. classid=0 is the box prior. """ # Now produce the boxes # box deltas is (num_rois, num_classes, 4) but rois is only #(num_rois, 4) boxes = bbox_preds(rois[:, None, 1:].expand_as(box_deltas).contiguous().view(-1, 4), box_deltas.view(-1, 4)).view(*box_deltas.size()) # Clip the boxes and get the best N dets per image. inds = rois[:, 0].long().contiguous() dets = [] for i, s, e in enumerate_by_image(inds.data): h, w = im_sizes[i, :2] boxes[s:e, :, 0].data.clamp_(min=0, max=w - 1) boxes[s:e, :, 1].data.clamp_(min=0, max=h - 1) boxes[s:e, :, 2].data.clamp_(min=0, max=w - 1) boxes[s:e, :, 3].data.clamp_(min=0, max=h - 1) d_filtered = filter_det( F.softmax(obj_dists[s:e], 1), boxes[s:e], start_ind=s, nms_filter_duplicates=self.nms_filter_duplicates, max_per_img=self.max_per_img, thresh=self.thresh, ) if d_filtered is not None: dets.append(d_filtered) if len(dets) == 0: print("nothing was detected", flush=True) return None nms_inds, nms_scores, nms_labels = [torch.cat(x, 0) for x in zip(*dets)] twod_inds = nms_inds * boxes.size(1) + nms_labels.data nms_boxes_assign = boxes.view(-1, 4)[twod_inds] nms_boxes = torch.cat((rois[:, 1:][nms_inds][:, None], boxes[nms_inds][:, 1:]), 1) return nms_inds, nms_scores, nms_labels, nms_boxes_assign, nms_boxes, inds[nms_inds] def __getitem__(self, batch): """ Hack to do multi-GPU training""" batch.scatter() if self.num_gpus == 1: return self(*batch[0]) replicas = nn.parallel.replicate(self, devices=list(range(self.num_gpus))) outputs = nn.parallel.parallel_apply(replicas, [batch[i] for i in range(self.num_gpus)]) if any([x.is_none() for x in outputs]): assert not self.training return None return gather_res(outputs, 0, dim=0) def filter_det(scores, boxes, start_ind=0, max_per_img=100, thresh=0.001, pre_nms_topn=6000, post_nms_topn=300, nms_thresh=0.3, nms_filter_duplicates=True): """ Filters the detections for a single image :param scores: [num_rois, num_classes] :param boxes: [num_rois, num_classes, 4]. Assumes the boxes have been clamped :param max_per_img: Max detections per image :param thresh: Threshold for calling it a good box :param nms_filter_duplicates: True if we shouldn't allow for mulitple detections of the same box (with different labels) :return: A numpy concatenated array with up to 100 detections/img [num_im, x1, y1, x2, y2, score, cls] """ valid_cls = (scores[:, 1:].data.max(0)[0] > thresh).nonzero() + 1 if valid_cls.dim() == 0: return None nms_mask = scores.data.clone() nms_mask.zero_() for c_i in valid_cls.squeeze(1).cpu(): scores_ci = scores.data[:, c_i] boxes_ci = boxes.data[:, c_i] keep = apply_nms(scores_ci, boxes_ci, pre_nms_topn=pre_nms_topn, post_nms_topn=post_nms_topn, nms_thresh=nms_thresh) nms_mask[:, c_i][keep] = 1 dists_all = Variable(nms_mask * scores.data, volatile=True) if nms_filter_duplicates: scores_pre, labels_pre = dists_all.data.max(1) inds_all = scores_pre.nonzero() assert inds_all.dim() != 0 inds_all = inds_all.squeeze(1) labels_all = labels_pre[inds_all] scores_all = scores_pre[inds_all] else: nz = nms_mask.nonzero() assert nz.dim() != 0 inds_all = nz[:, 0] labels_all = nz[:, 1] scores_all = scores.data.view(-1)[inds_all * scores.data.size(1) + labels_all] # dists_all = dists_all[inds_all] # dists_all[:,0] = 1.0-dists_all.sum(1) # # Limit to max per image detections vs, idx = torch.sort(scores_all, dim=0, descending=True) idx = idx[vs > thresh] if max_per_img < idx.size(0): idx = idx[:max_per_img] inds_all = inds_all[idx] + start_ind scores_all = Variable(scores_all[idx], volatile=True) labels_all = Variable(labels_all[idx], volatile=True) # dists_all = dists_all[idx] return inds_all, scores_all, labels_all class RPNHead(nn.Module): """ Serves as the class + box outputs for each level in the FPN. """ def __init__(self, dim=512, input_dim=1024): """ :param aspect_ratios: Aspect ratios for the anchors. NOTE - this can't be changed now as it depends on other things in the C code... """ super(RPNHead, self).__init__() self.anchor_target_dim = 6 self.stride = 16 self.conv = nn.Sequential( nn.Conv2d(input_dim, dim, kernel_size=3, padding=1), nn.ReLU6(inplace=True), # Tensorflow docs use Relu6, so let's use it too.... nn.Conv2d(dim, self.anchor_target_dim * self._A, kernel_size=1) ) ans_np = generate_anchors(base_size=ANCHOR_SIZE, feat_stride=self.stride, anchor_scales=ANCHOR_SCALES, anchor_ratios=ANCHOR_RATIOS, ) self.register_buffer('anchors', torch.FloatTensor(ans_np)) @property def _A(self): return len(ANCHOR_RATIOS) * len(ANCHOR_SCALES) def forward(self, fmap): """ Gets the class / noclass predictions over all the scales :param fmap: [batch_size, dim, IM_SIZE/16, IM_SIZE/16] featuremap :return: [batch_size, IM_SIZE/16, IM_SIZE/16, A, 6] """ rez = self._reshape_channels(self.conv(fmap)) rez = rez.view(rez.size(0), rez.size(1), rez.size(2), self._A, self.anchor_target_dim) return rez def anchor_preds(self, preds, train_anchor_inds, image_offset): """ Get predictions for the training indices :param preds: [batch_size, IM_SIZE/16, IM_SIZE/16, A, 6] :param train_anchor_inds: [num_train, 4] indices into the predictions :return: class_preds: [num_train, 2] array of yes/no box_preds: [num_train, 4] array of predicted boxes """ assert train_anchor_inds.size(1) == 4 tai = train_anchor_inds.data.clone() tai[:, 0] -= image_offset train_regions = gather_nd(preds, tai) class_preds = train_regions[:, :2] box_preds = train_regions[:, 2:] return class_preds, box_preds @staticmethod def _reshape_channels(x): """ [batch_size, channels, h, w] -> [batch_size, h, w, channels] """ assert x.dim() == 4 batch_size, nc, h, w = x.size() x_t = x.view(batch_size, nc, -1).transpose(1, 2).contiguous() x_t = x_t.view(batch_size, h, w, nc) return x_t def roi_proposals(self, fmap, im_sizes, nms_thresh=0.7, pre_nms_topn=12000, post_nms_topn=2000): """ :param fmap: [batch_size, IM_SIZE/16, IM_SIZE/16, A, 6] :param im_sizes: [batch_size, 3] numpy array of (h, w, scale) :return: ROIS: shape [a <=post_nms_topn, 5] array of ROIS. """ class_fmap = fmap[:, :, :, :, :2].contiguous() # GET THE GOOD BOXES AYY LMAO :') class_preds = F.softmax(class_fmap, 4)[..., 1].data.contiguous() box_fmap = fmap[:, :, :, :, 2:].data.contiguous() anchor_stacked = torch.cat([self.anchors[None]] * fmap.size(0), 0) box_preds = bbox_preds(anchor_stacked.view(-1, 4), box_fmap.view(-1, 4)).view( *box_fmap.size()) for i, (h, w, scale) in enumerate(im_sizes): # Zero out all the bad boxes h, w, A, 4 h_end = int(h) // self.stride w_end = int(w) // self.stride if h_end < class_preds.size(1): class_preds[i, h_end:] = -0.01 if w_end < class_preds.size(2): class_preds[i, :, w_end:] = -0.01 # and clamp the others box_preds[i, :, :, :, 0].clamp_(min=0, max=w - 1) box_preds[i, :, :, :, 1].clamp_(min=0, max=h - 1) box_preds[i, :, :, :, 2].clamp_(min=0, max=w - 1) box_preds[i, :, :, :, 3].clamp_(min=0, max=h - 1) sizes = center_size(box_preds.view(-1, 4)) class_preds.view(-1)[(sizes[:, 2] < 4) | (sizes[:, 3] < 4)] = -0.01 return filter_roi_proposals(box_preds.view(-1, 4), class_preds.view(-1), boxes_per_im=np.array([np.prod(box_preds.size()[1:-1])] * fmap.size(0)), nms_thresh=nms_thresh, pre_nms_topn=pre_nms_topn, post_nms_topn=post_nms_topn) def filter_roi_proposals(box_preds, class_preds, boxes_per_im, nms_thresh=0.7, pre_nms_topn=12000, post_nms_topn=2000): inds, im_per = apply_nms( class_preds, box_preds, pre_nms_topn=pre_nms_topn, post_nms_topn=post_nms_topn, boxes_per_im=boxes_per_im, nms_thresh=nms_thresh, ) img_inds = torch.cat([val * torch.ones(i) for val, i in enumerate(im_per)], 0).cuda( box_preds.get_device()) rois = torch.cat((img_inds[:, None], box_preds[inds]), 1) return rois def load_resnet(): model = resnet101(pretrained=True) del model.layer4 del model.avgpool del model.fc return model def load_vgg(use_dropout=True, use_relu=True, use_linear=True, pretrained=True): model = vgg16(pretrained=pretrained) del model.features._modules['30'] # Get rid of the maxpool del model.classifier._modules['6'] # Get rid of class layer if not use_dropout: del model.classifier._modules['5'] # Get rid of dropout if not use_relu: del model.classifier._modules['4'] # Get rid of relu activation if not use_linear: del model.classifier._modules['3'] # Get rid of linear layer return model ================================================ FILE: lib/pytorch_misc.py ================================================ """ Miscellaneous functions that might be useful for pytorch """ import h5py import numpy as np import torch from torch.autograd import Variable import os import dill as pkl from itertools import tee from torch import nn def optimistic_restore(network, state_dict): mismatch = False own_state = network.state_dict() for name, param in state_dict.items(): if name not in own_state: print("Unexpected key {} in state_dict with size {}".format(name, param.size())) mismatch = True elif param.size() == own_state[name].size(): own_state[name].copy_(param) else: print("Network has {} with size {}, ckpt has {}".format(name, own_state[name].size(), param.size())) mismatch = True missing = set(own_state.keys()) - set(state_dict.keys()) if len(missing) > 0: print("We couldn't find {}".format(','.join(missing))) mismatch = True return not mismatch def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return zip(a, b) def get_ranking(predictions, labels, num_guesses=5): """ Given a matrix of predictions and labels for the correct ones, get the number of guesses required to get the prediction right per example. :param predictions: [batch_size, range_size] predictions :param labels: [batch_size] array of labels :param num_guesses: Number of guesses to return :return: """ assert labels.size(0) == predictions.size(0) assert labels.dim() == 1 assert predictions.dim() == 2 values, full_guesses = predictions.topk(predictions.size(1), dim=1) _, ranking = full_guesses.topk(full_guesses.size(1), dim=1, largest=False) gt_ranks = torch.gather(ranking.data, 1, labels.data[:, None]).squeeze() guesses = full_guesses[:, :num_guesses] return gt_ranks, guesses def cache(f): """ Caches a computation """ def cache_wrapper(fn, *args, **kwargs): if os.path.exists(fn): with open(fn, 'rb') as file: data = pkl.load(file) else: print("file {} not found, so rebuilding".format(fn)) data = f(*args, **kwargs) with open(fn, 'wb') as file: pkl.dump(data, file) return data return cache_wrapper class Flattener(nn.Module): def __init__(self): """ Flattens last 3 dimensions to make it only batch size, -1 """ super(Flattener, self).__init__() def forward(self, x): return x.view(x.size(0), -1) def to_variable(f): """ Decorator that pushes all the outputs to a variable :param f: :return: """ def variable_wrapper(*args, **kwargs): rez = f(*args, **kwargs) if isinstance(rez, tuple): return tuple([Variable(x) for x in rez]) return Variable(rez) return variable_wrapper def arange(base_tensor, n=None): new_size = base_tensor.size(0) if n is None else n new_vec = base_tensor.new(new_size).long() torch.arange(0, new_size, out=new_vec) return new_vec def to_onehot(vec, num_classes, fill=1000): """ Creates a [size, num_classes] torch FloatTensor where one_hot[i, vec[i]] = fill :param vec: 1d torch tensor :param num_classes: int :param fill: value that we want + and - things to be. :return: """ onehot_result = vec.new(vec.size(0), num_classes).float().fill_(-fill) arange_inds = vec.new(vec.size(0)).long() torch.arange(0, vec.size(0), out=arange_inds) onehot_result.view(-1)[vec + num_classes*arange_inds] = fill return onehot_result def save_net(fname, net): h5f = h5py.File(fname, mode='w') for k, v in list(net.state_dict().items()): h5f.create_dataset(k, data=v.cpu().numpy()) def load_net(fname, net): h5f = h5py.File(fname, mode='r') for k, v in list(net.state_dict().items()): param = torch.from_numpy(np.asarray(h5f[k])) if v.size() != param.size(): print("On k={} desired size is {} but supplied {}".format(k, v.size(), param.size())) else: v.copy_(param) def batch_index_iterator(len_l, batch_size, skip_end=True): """ Provides indices that iterate over a list :param len_l: int representing size of thing that we will iterate over :param batch_size: size of each batch :param skip_end: if true, don't iterate over the last batch :return: A generator that returns (start, end) tuples as it goes through all batches """ iterate_until = len_l if skip_end: iterate_until = (len_l // batch_size) * batch_size for b_start in range(0, iterate_until, batch_size): yield (b_start, min(b_start+batch_size, len_l)) def batch_map(f, a, batch_size): """ Maps f over the array a in chunks of batch_size. :param f: function to be applied. Must take in a block of (batch_size, dim_a) and map it to (batch_size, something). :param a: Array to be applied over of shape (num_rows, dim_a). :param batch_size: size of each array :return: Array of size (num_rows, something). """ rez = [] for s, e in batch_index_iterator(a.size(0), batch_size, skip_end=False): print("Calling on {}".format(a[s:e].size())) rez.append(f(a[s:e])) return torch.cat(rez) def const_row(fill, l, volatile=False): input_tok = Variable(torch.LongTensor([fill] * l),volatile=volatile) if torch.cuda.is_available(): input_tok = input_tok.cuda() return input_tok def print_para(model): """ Prints parameters of a model :param opt: :return: """ st = {} strings = [] total_params = 0 for p_name, p in model.named_parameters(): if not ('bias' in p_name.split('.')[-1] or 'bn' in p_name.split('.')[-1]): st[p_name] = ([str(x) for x in p.size()], np.prod(p.size()), p.requires_grad) total_params += np.prod(p.size()) for p_name, (size, prod, p_req_grad) in sorted(st.items(), key=lambda x: -x[1][1]): strings.append("{:<50s}: {:<16s}({:8d}) ({})".format( p_name, '[{}]'.format(','.join(size)), prod, 'grad' if p_req_grad else ' ' )) return '\n {:.1f}M total parameters \n ----- \n \n{}'.format(total_params / 1000000.0, '\n'.join(strings)) def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0) res.append(correct_k.mul_(100.0 / batch_size)) return res def nonintersecting_2d_inds(x): """ Returns np.array([(a,b) for a in range(x) for b in range(x) if a != b]) efficiently :param x: Size :return: a x*(x-1) array that is [(0,1), (0,2)... (0, x-1), (1,0), (1,2), ..., (x-1, x-2)] """ rs = 1 - np.diag(np.ones(x, dtype=np.int32)) relations = np.column_stack(np.where(rs)) return relations def intersect_2d(x1, x2): """ Given two arrays [m1, n], [m2,n], returns a [m1, m2] array where each entry is True if those rows match. :param x1: [m1, n] numpy array :param x2: [m2, n] numpy array :return: [m1, m2] bool array of the intersections """ if x1.shape[1] != x2.shape[1]: raise ValueError("Input arrays must have same #columns") # This performs a matrix multiplication-esque thing between the two arrays # Instead of summing, we want the equality, so we reduce in that way res = (x1[..., None] == x2.T[None, ...]).all(1) return res def np_to_variable(x, is_cuda=True, dtype=torch.FloatTensor): v = Variable(torch.from_numpy(x).type(dtype)) if is_cuda: v = v.cuda() return v def gather_nd(x, index): """ :param x: n dimensional tensor [x0, x1, x2, ... x{n-1}, dim] :param index: [num, n-1] where each row contains the indices we'll use :return: [num, dim] """ nd = x.dim() - 1 assert nd > 0 assert index.dim() == 2 assert index.size(1) == nd dim = x.size(-1) sel_inds = index[:,nd-1].clone() mult_factor = x.size(nd-1) for col in range(nd-2, -1, -1): # [n-2, n-3, ..., 1, 0] sel_inds += index[:,col] * mult_factor mult_factor *= x.size(col) grouped = x.view(-1, dim)[sel_inds] return grouped def enumerate_by_image(im_inds): im_inds_np = im_inds.cpu().numpy() initial_ind = int(im_inds_np[0]) s = 0 for i, val in enumerate(im_inds_np): if val != initial_ind: yield initial_ind, s, i initial_ind = int(val) s = i yield initial_ind, s, len(im_inds_np) # num_im = im_inds[-1] + 1 # # print("Num im is {}".format(num_im)) # for i in range(num_im): # # print("On i={}".format(i)) # inds_i = (im_inds == i).nonzero() # if inds_i.dim() == 0: # continue # inds_i = inds_i.squeeze(1) # s = inds_i[0] # e = inds_i[-1] + 1 # # print("On i={} we have s={} e={}".format(i, s, e)) # yield i, s, e def diagonal_inds(tensor): """ Returns the indices required to go along first 2 dims of tensor in diag fashion :param tensor: thing :return: """ assert tensor.dim() >= 2 assert tensor.size(0) == tensor.size(1) size = tensor.size(0) arange_inds = tensor.new(size).long() torch.arange(0, tensor.size(0), out=arange_inds) return (size+1)*arange_inds def enumerate_imsize(im_sizes): s = 0 for i, (h, w, scale, num_anchors) in enumerate(im_sizes): na = int(num_anchors) e = s + na yield i, s, e, h, w, scale, na s = e def argsort_desc(scores): """ Returns the indices that sort scores descending in a smart way :param scores: Numpy array of arbitrary size :return: an array of size [numel(scores), dim(scores)] where each row is the index you'd need to get the score. """ return np.column_stack(np.unravel_index(np.argsort(-scores.ravel()), scores.shape)) def unravel_index(index, dims): unraveled = [] index_cp = index.clone() for d in dims[::-1]: unraveled.append(index_cp % d) index_cp /= d return torch.cat([x[:,None] for x in unraveled[::-1]], 1) def de_chunkize(tensor, chunks): s = 0 for c in chunks: yield tensor[s:(s+c)] s = s+c def random_choose(tensor, num): "randomly choose indices" num_choose = min(tensor.size(0), num) if num_choose == tensor.size(0): return tensor # Gotta do this in numpy because of https://github.com/pytorch/pytorch/issues/1868 rand_idx = np.random.choice(tensor.size(0), size=num, replace=False) rand_idx = torch.LongTensor(rand_idx).cuda(tensor.get_device()) chosen = tensor[rand_idx].contiguous() # rand_values = tensor.new(tensor.size(0)).float().normal_() # _, idx = torch.sort(rand_values) # # chosen = tensor[idx[:num]].contiguous() return chosen def transpose_packed_sequence_inds(lengths): """ Goes from a TxB packed sequence to a BxT or vice versa. Assumes that nothing is a variable :param ps: PackedSequence :return: """ new_inds = [] new_lens = [] cum_add = np.cumsum([0] + lengths) max_len = lengths[0] length_pointer = len(lengths) - 1 for i in range(max_len): while length_pointer > 0 and lengths[length_pointer] <= i: length_pointer -= 1 new_inds.append(cum_add[:(length_pointer+1)].copy()) cum_add[:(length_pointer+1)] += 1 new_lens.append(length_pointer+1) new_inds = np.concatenate(new_inds, 0) return new_inds, new_lens def right_shift_packed_sequence_inds(lengths): """ :param lengths: e.g. [2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1] :return: perm indices for the old stuff (TxB) to shift it right 1 slot so as to accomodate BOS toks visual example: of lengths = [4,3,1,1] before: a (0) b (4) c (7) d (8) a (1) b (5) a (2) b (6) a (3) after: bos a (0) b (4) c (7) bos a (1) bos a (2) bos """ cur_ind = 0 inds = [] for (l1, l2) in zip(lengths[:-1], lengths[1:]): for i in range(l2): inds.append(cur_ind + i) cur_ind += l1 return inds def clip_grad_norm(named_parameters, max_norm, clip=False, verbose=False): r"""Clips gradient norm of an iterable of parameters. The norm is computed over all gradients together, as if they were concatenated into a single vector. Gradients are modified in-place. Arguments: parameters (Iterable[Variable]): an iterable of Variables that will have gradients normalized max_norm (float or int): max norm of the gradients Returns: Total norm of the parameters (viewed as a single vector). """ max_norm = float(max_norm) total_norm = 0 param_to_norm = {} param_to_shape = {} for n, p in named_parameters: if p.grad is not None: param_norm = p.grad.data.norm(2) total_norm += param_norm ** 2 param_to_norm[n] = param_norm param_to_shape[n] = p.size() total_norm = total_norm ** (1. / 2) clip_coef = max_norm / (total_norm + 1e-6) if clip_coef < 1 and clip: for _, p in named_parameters: if p.grad is not None: p.grad.data.mul_(clip_coef) if verbose: print('---Total norm {:.3f} clip coef {:.3f}-----------------'.format(total_norm, clip_coef)) for name, norm in sorted(param_to_norm.items(), key=lambda x: -x[1]): print("{:<50s}: {:.3f}, ({})".format(name, norm, param_to_shape[name])) print('-------------------------------', flush=True) return total_norm def update_lr(optimizer, lr=1e-4): print("------ Learning rate -> {}".format(lr)) for param_group in optimizer.param_groups: param_group['lr'] = lr ================================================ FILE: lib/rel_model.py ================================================ """ Let's get the relationships yo """ import numpy as np import torch import torch.nn as nn import torch.nn.parallel from torch.autograd import Variable from torch.nn import functional as F from torch.nn.utils.rnn import PackedSequence from lib.resnet import resnet_l4 from config import BATCHNORM_MOMENTUM from lib.fpn.nms.functions.nms import apply_nms # from lib.decoder_rnn import DecoderRNN, lstm_factory, LockedDropout from lib.lstm.decoder_rnn import DecoderRNN from lib.lstm.highway_lstm_cuda.alternating_highway_lstm import AlternatingHighwayLSTM from lib.fpn.box_utils import bbox_overlaps, center_size from lib.get_union_boxes import UnionBoxesAndFeats from lib.fpn.proposal_assignments.rel_assignments import rel_assignments from lib.object_detector import ObjectDetector, gather_res, load_vgg from lib.pytorch_misc import transpose_packed_sequence_inds, to_onehot, arange, enumerate_by_image, diagonal_inds, Flattener from lib.sparse_targets import FrequencyBias from lib.surgery import filter_dets from lib.word_vectors import obj_edge_vectors from lib.fpn.roi_align.functions.roi_align import RoIAlignFunction import math def _sort_by_score(im_inds, scores): """ We'll sort everything scorewise from Hi->low, BUT we need to keep images together and sort LSTM from l :param im_inds: Which im we're on :param scores: Goodness ranging between [0, 1]. Higher numbers come FIRST :return: Permutation to put everything in the right order for the LSTM Inverse permutation Lengths for the TxB packed sequence. """ num_im = im_inds[-1] + 1 rois_per_image = scores.new(num_im) lengths = [] for i, s, e in enumerate_by_image(im_inds): rois_per_image[i] = 2 * (s - e) * num_im + i lengths.append(e - s) lengths = sorted(lengths, reverse=True) inds, ls_transposed = transpose_packed_sequence_inds(lengths) # move it to TxB form inds = torch.LongTensor(inds).cuda(im_inds.get_device()) # ~~~~~~~~~~~~~~~~ # HACKY CODE ALERT!!! # we're sorting by confidence which is in the range (0,1), but more importantly by longest # img.... # ~~~~~~~~~~~~~~~~ roi_order = scores - 2 * rois_per_image[im_inds] _, perm = torch.sort(roi_order, 0, descending=True) perm = perm[inds] _, inv_perm = torch.sort(perm) return perm, inv_perm, ls_transposed MODES = ('sgdet', 'sgcls', 'predcls') class LinearizedContext(nn.Module): """ Module for computing the object contexts and edge contexts """ def __init__(self, classes, rel_classes, mode='sgdet', embed_dim=200, hidden_dim=256, obj_dim=2048, nl_obj=2, nl_edge=2, dropout_rate=0.2, order='confidence', pass_in_obj_feats_to_decoder=True, pass_in_obj_feats_to_edge=True): super(LinearizedContext, self).__init__() self.classes = classes self.rel_classes = rel_classes assert mode in MODES self.mode = mode self.nl_obj = nl_obj self.nl_edge = nl_edge self.embed_dim = embed_dim self.hidden_dim = hidden_dim self.obj_dim = obj_dim self.dropout_rate = dropout_rate self.pass_in_obj_feats_to_decoder = pass_in_obj_feats_to_decoder self.pass_in_obj_feats_to_edge = pass_in_obj_feats_to_edge assert order in ('size', 'confidence', 'random', 'leftright') self.order = order # EMBEDDINGS embed_vecs = obj_edge_vectors(self.classes, wv_dim=self.embed_dim) self.obj_embed = nn.Embedding(self.num_classes, self.embed_dim) self.obj_embed.weight.data = embed_vecs.clone() self.obj_embed2 = nn.Embedding(self.num_classes, self.embed_dim) self.obj_embed2.weight.data = embed_vecs.clone() # This probably doesn't help it much self.pos_embed = nn.Sequential(*[ nn.BatchNorm1d(4, momentum=BATCHNORM_MOMENTUM / 10.0), nn.Linear(4, 128), nn.ReLU(inplace=True), nn.Dropout(0.1), ]) if self.nl_obj > 0: self.obj_ctx_rnn = AlternatingHighwayLSTM( input_size=self.obj_dim+self.embed_dim+128, hidden_size=self.hidden_dim, num_layers=self.nl_obj, recurrent_dropout_probability=dropout_rate) decoder_inputs_dim = self.hidden_dim if self.pass_in_obj_feats_to_decoder: decoder_inputs_dim += self.obj_dim + self.embed_dim self.decoder_rnn = DecoderRNN(self.classes, embed_dim=self.embed_dim, inputs_dim=decoder_inputs_dim, hidden_dim=self.hidden_dim, recurrent_dropout_probability=dropout_rate) else: self.decoder_lin = nn.Linear(self.obj_dim + self.embed_dim + 128, self.num_classes) if self.nl_edge > 0: input_dim = self.embed_dim if self.nl_obj > 0: input_dim += self.hidden_dim if self.pass_in_obj_feats_to_edge: input_dim += self.obj_dim self.edge_ctx_rnn = AlternatingHighwayLSTM(input_size=input_dim, hidden_size=self.hidden_dim, num_layers=self.nl_edge, recurrent_dropout_probability=dropout_rate) def sort_rois(self, batch_idx, confidence, box_priors): """ :param batch_idx: tensor with what index we're on :param confidence: tensor with confidences between [0,1) :param boxes: tensor with (x1, y1, x2, y2) :return: Permutation, inverse permutation, and the lengths transposed (same as _sort_by_score) """ cxcywh = center_size(box_priors) if self.order == 'size': sizes = cxcywh[:,2] * cxcywh[:, 3] # sizes = (box_priors[:, 2] - box_priors[:, 0] + 1) * (box_priors[:, 3] - box_priors[:, 1] + 1) assert sizes.min() > 0.0 scores = sizes / (sizes.max() + 1) elif self.order == 'confidence': scores = confidence elif self.order == 'random': scores = torch.FloatTensor(np.random.rand(batch_idx.size(0))).cuda(batch_idx.get_device()) elif self.order == 'leftright': centers = cxcywh[:,0] scores = centers / (centers.max() + 1) else: raise ValueError("invalid mode {}".format(self.order)) return _sort_by_score(batch_idx, scores) @property def num_classes(self): return len(self.classes) @property def num_rels(self): return len(self.rel_classes) def edge_ctx(self, obj_feats, obj_dists, im_inds, obj_preds, box_priors=None): """ Object context and object classification. :param obj_feats: [num_obj, img_dim + object embedding0 dim] :param obj_dists: [num_obj, #classes] :param im_inds: [num_obj] the indices of the images :return: edge_ctx: [num_obj, #feats] For later! """ # Only use hard embeddings obj_embed2 = self.obj_embed2(obj_preds) # obj_embed3 = F.softmax(obj_dists, dim=1) @ self.obj_embed3.weight inp_feats = torch.cat((obj_embed2, obj_feats), 1) # Sort by the confidence of the maximum detection. confidence = F.softmax(obj_dists, dim=1).data.view(-1)[ obj_preds.data + arange(obj_preds.data) * self.num_classes] perm, inv_perm, ls_transposed = self.sort_rois(im_inds.data, confidence, box_priors) edge_input_packed = PackedSequence(inp_feats[perm], ls_transposed) edge_reps = self.edge_ctx_rnn(edge_input_packed)[0][0] # now we're good! unperm edge_ctx = edge_reps[inv_perm] return edge_ctx def obj_ctx(self, obj_feats, obj_dists, im_inds, obj_labels=None, box_priors=None, boxes_per_cls=None): """ Object context and object classification. :param obj_feats: [num_obj, img_dim + object embedding0 dim] :param obj_dists: [num_obj, #classes] :param im_inds: [num_obj] the indices of the images :param obj_labels: [num_obj] the GT labels of the image :param boxes: [num_obj, 4] boxes. We'll use this for NMS :return: obj_dists: [num_obj, #classes] new probability distribution. obj_preds: argmax of that distribution. obj_final_ctx: [num_obj, #feats] For later! """ # Sort by the confidence of the maximum detection. confidence = F.softmax(obj_dists, dim=1).data[:, 1:].max(1)[0] perm, inv_perm, ls_transposed = self.sort_rois(im_inds.data, confidence, box_priors) # Pass object features, sorted by score, into the encoder LSTM obj_inp_rep = obj_feats[perm].contiguous() input_packed = PackedSequence(obj_inp_rep, ls_transposed) encoder_rep = self.obj_ctx_rnn(input_packed)[0][0] # Decode in order if self.mode != 'predcls': decoder_inp = PackedSequence(torch.cat((obj_inp_rep, encoder_rep), 1) if self.pass_in_obj_feats_to_decoder else encoder_rep, ls_transposed) obj_dists, obj_preds = self.decoder_rnn( decoder_inp, #obj_dists[perm], labels=obj_labels[perm] if obj_labels is not None else None, boxes_for_nms=boxes_per_cls[perm] if boxes_per_cls is not None else None, ) obj_preds = obj_preds[inv_perm] obj_dists = obj_dists[inv_perm] else: assert obj_labels is not None obj_preds = obj_labels obj_dists = Variable(to_onehot(obj_preds.data, self.num_classes)) encoder_rep = encoder_rep[inv_perm] return obj_dists, obj_preds, encoder_rep def forward(self, obj_fmaps, obj_logits, im_inds, obj_labels=None, box_priors=None, boxes_per_cls=None): """ Forward pass through the object and edge context :param obj_priors: :param obj_fmaps: :param im_inds: :param obj_labels: :param boxes: :return: """ obj_embed = F.softmax(obj_logits, dim=1) @ self.obj_embed.weight pos_embed = self.pos_embed(Variable(center_size(box_priors))) obj_pre_rep = torch.cat((obj_fmaps, obj_embed, pos_embed), 1) if self.nl_obj > 0: obj_dists2, obj_preds, obj_ctx = self.obj_ctx( obj_pre_rep, obj_logits, im_inds, obj_labels, box_priors, boxes_per_cls, ) else: # UNSURE WHAT TO DO HERE if self.mode == 'predcls': obj_dists2 = Variable(to_onehot(obj_labels.data, self.num_classes)) else: obj_dists2 = self.decoder_lin(obj_pre_rep) if self.mode == 'sgdet' and not self.training: # NMS here for baseline probs = F.softmax(obj_dists2, 1) nms_mask = obj_dists2.data.clone() nms_mask.zero_() for c_i in range(1, obj_dists2.size(1)): scores_ci = probs.data[:, c_i] boxes_ci = boxes_per_cls.data[:, c_i] keep = apply_nms(scores_ci, boxes_ci, pre_nms_topn=scores_ci.size(0), post_nms_topn=scores_ci.size(0), nms_thresh=0.3) nms_mask[:, c_i][keep] = 1 obj_preds = Variable(nms_mask * probs.data, volatile=True)[:,1:].max(1)[1] + 1 else: obj_preds = obj_labels if obj_labels is not None else obj_dists2[:,1:].max(1)[1] + 1 obj_ctx = obj_pre_rep edge_ctx = None if self.nl_edge > 0: edge_ctx = self.edge_ctx( torch.cat((obj_fmaps, obj_ctx), 1) if self.pass_in_obj_feats_to_edge else obj_ctx, obj_dists=obj_dists2.detach(), # Was previously obj_logits. im_inds=im_inds, obj_preds=obj_preds, box_priors=box_priors, ) return obj_dists2, obj_preds, edge_ctx class RelModel(nn.Module): """ RELATIONSHIPS """ def __init__(self, classes, rel_classes, mode='sgdet', num_gpus=1, use_vision=True, require_overlap_det=True, embed_dim=200, hidden_dim=256, pooling_dim=2048, nl_obj=1, nl_edge=2, use_resnet=False, order='confidence', thresh=0.01, use_proposals=False, pass_in_obj_feats_to_decoder=True, pass_in_obj_feats_to_edge=True, rec_dropout=0.0, use_bias=True, use_tanh=True, limit_vision=True): """ :param classes: Object classes :param rel_classes: Relationship classes. None if were not using rel mode :param mode: (sgcls, predcls, or sgdet) :param num_gpus: how many GPUS 2 use :param use_vision: Whether to use vision in the final product :param require_overlap_det: Whether two objects must intersect :param embed_dim: Dimension for all embeddings :param hidden_dim: LSTM hidden size :param obj_dim: """ super(RelModel, self).__init__() self.classes = classes self.rel_classes = rel_classes self.num_gpus = num_gpus assert mode in MODES self.mode = mode self.pooling_size = 7 self.embed_dim = embed_dim self.hidden_dim = hidden_dim self.obj_dim = 2048 if use_resnet else 4096 self.pooling_dim = pooling_dim self.use_bias = use_bias self.use_vision = use_vision self.use_tanh = use_tanh self.limit_vision=limit_vision self.require_overlap = require_overlap_det and self.mode == 'sgdet' self.detector = ObjectDetector( classes=classes, mode=('proposals' if use_proposals else 'refinerels') if mode == 'sgdet' else 'gtbox', use_resnet=use_resnet, thresh=thresh, max_per_img=64, ) self.context = LinearizedContext(self.classes, self.rel_classes, mode=self.mode, embed_dim=self.embed_dim, hidden_dim=self.hidden_dim, obj_dim=self.obj_dim, nl_obj=nl_obj, nl_edge=nl_edge, dropout_rate=rec_dropout, order=order, pass_in_obj_feats_to_decoder=pass_in_obj_feats_to_decoder, pass_in_obj_feats_to_edge=pass_in_obj_feats_to_edge) # Image Feats (You'll have to disable if you want to turn off the features from here) self.union_boxes = UnionBoxesAndFeats(pooling_size=self.pooling_size, stride=16, dim=1024 if use_resnet else 512) if use_resnet: self.roi_fmap = nn.Sequential( resnet_l4(relu_end=False), nn.AvgPool2d(self.pooling_size), Flattener(), ) else: roi_fmap = [ Flattener(), load_vgg(use_dropout=False, use_relu=False, use_linear=pooling_dim == 4096, pretrained=False).classifier, ] if pooling_dim != 4096: roi_fmap.append(nn.Linear(4096, pooling_dim)) self.roi_fmap = nn.Sequential(*roi_fmap) self.roi_fmap_obj = load_vgg(pretrained=False).classifier ################################### self.post_lstm = nn.Linear(self.hidden_dim, self.pooling_dim * 2) # Initialize to sqrt(1/2n) so that the outputs all have mean 0 and variance 1. # (Half contribution comes from LSTM, half from embedding. # In practice the pre-lstm stuff tends to have stdev 0.1 so I multiplied this by 10. self.post_lstm.weight.data.normal_(0, 10.0 * math.sqrt(1.0 / self.hidden_dim)) self.post_lstm.bias.data.zero_() if nl_edge == 0: self.post_emb = nn.Embedding(self.num_classes, self.pooling_dim*2) self.post_emb.weight.data.normal_(0, math.sqrt(1.0)) self.rel_compress = nn.Linear(self.pooling_dim, self.num_rels, bias=True) self.rel_compress.weight = torch.nn.init.xavier_normal(self.rel_compress.weight, gain=1.0) if self.use_bias: self.freq_bias = FrequencyBias() @property def num_classes(self): return len(self.classes) @property def num_rels(self): return len(self.rel_classes) def visual_rep(self, features, rois, pair_inds): """ Classify the features :param features: [batch_size, dim, IM_SIZE/4, IM_SIZE/4] :param rois: [num_rois, 5] array of [img_num, x0, y0, x1, y1]. :param pair_inds inds to use when predicting :return: score_pred, a [num_rois, num_classes] array box_pred, a [num_rois, num_classes, 4] array """ assert pair_inds.size(1) == 2 uboxes = self.union_boxes(features, rois, pair_inds) return self.roi_fmap(uboxes) def get_rel_inds(self, rel_labels, im_inds, box_priors): # Get the relationship candidates if self.training: rel_inds = rel_labels[:, :3].data.clone() else: rel_cands = im_inds.data[:, None] == im_inds.data[None] rel_cands.view(-1)[diagonal_inds(rel_cands)] = 0 # Require overlap for detection if self.require_overlap: rel_cands = rel_cands & (bbox_overlaps(box_priors.data, box_priors.data) > 0) # if there are fewer then 100 things then we might as well add some? amt_to_add = 100 - rel_cands.long().sum() rel_cands = rel_cands.nonzero() if rel_cands.dim() == 0: rel_cands = im_inds.data.new(1, 2).fill_(0) rel_inds = torch.cat((im_inds.data[rel_cands[:, 0]][:, None], rel_cands), 1) return rel_inds def obj_feature_map(self, features, rois): """ Gets the ROI features :param features: [batch_size, dim, IM_SIZE/4, IM_SIZE/4] (features at level p2) :param rois: [num_rois, 5] array of [img_num, x0, y0, x1, y1]. :return: [num_rois, #dim] array """ feature_pool = RoIAlignFunction(self.pooling_size, self.pooling_size, spatial_scale=1 / 16)( features, rois) return self.roi_fmap_obj(feature_pool.view(rois.size(0), -1)) def forward(self, x, im_sizes, image_offset, gt_boxes=None, gt_classes=None, gt_rels=None, proposals=None, train_anchor_inds=None, return_fmap=False): """ Forward pass for detection :param x: Images@[batch_size, 3, IM_SIZE, IM_SIZE] :param im_sizes: A numpy array of (h, w, scale) for each image. :param image_offset: Offset onto what image we're on for MGPU training (if single GPU this is 0) :param gt_boxes: Training parameters: :param gt_boxes: [num_gt, 4] GT boxes over the batch. :param gt_classes: [num_gt, 2] gt boxes where each one is (img_id, class) :param train_anchor_inds: a [num_train, 2] array of indices for the anchors that will be used to compute the training loss. Each (img_ind, fpn_idx) :return: If train: scores, boxdeltas, labels, boxes, boxtargets, rpnscores, rpnboxes, rellabels if test: prob dists, boxes, img inds, maxscores, classes """ result = self.detector(x, im_sizes, image_offset, gt_boxes, gt_classes, gt_rels, proposals, train_anchor_inds, return_fmap=True) if result.is_none(): return ValueError("heck") im_inds = result.im_inds - image_offset boxes = result.rm_box_priors if self.training and result.rel_labels is None: assert self.mode == 'sgdet' result.rel_labels = rel_assignments(im_inds.data, boxes.data, result.rm_obj_labels.data, gt_boxes.data, gt_classes.data, gt_rels.data, image_offset, filter_non_overlap=True, num_sample_per_gt=1) rel_inds = self.get_rel_inds(result.rel_labels, im_inds, boxes) rois = torch.cat((im_inds[:, None].float(), boxes), 1) result.obj_fmap = self.obj_feature_map(result.fmap.detach(), rois) # Prevent gradients from flowing back into score_fc from elsewhere result.rm_obj_dists, result.obj_preds, edge_ctx = self.context( result.obj_fmap, result.rm_obj_dists.detach(), im_inds, result.rm_obj_labels if self.training or self.mode == 'predcls' else None, boxes.data, result.boxes_all) if edge_ctx is None: edge_rep = self.post_emb(result.obj_preds) else: edge_rep = self.post_lstm(edge_ctx) # Split into subject and object representations edge_rep = edge_rep.view(edge_rep.size(0), 2, self.pooling_dim) subj_rep = edge_rep[:, 0] obj_rep = edge_rep[:, 1] prod_rep = subj_rep[rel_inds[:, 1]] * obj_rep[rel_inds[:, 2]] if self.use_vision: vr = self.visual_rep(result.fmap.detach(), rois, rel_inds[:, 1:]) if self.limit_vision: # exact value TBD prod_rep = torch.cat((prod_rep[:,:2048] * vr[:,:2048], prod_rep[:,2048:]), 1) else: prod_rep = prod_rep * vr if self.use_tanh: prod_rep = F.tanh(prod_rep) result.rel_dists = self.rel_compress(prod_rep) if self.use_bias: result.rel_dists = result.rel_dists + self.freq_bias.index_with_labels(torch.stack(( result.obj_preds[rel_inds[:, 1]], result.obj_preds[rel_inds[:, 2]], ), 1)) if self.training: return result twod_inds = arange(result.obj_preds.data) * self.num_classes + result.obj_preds.data result.obj_scores = F.softmax(result.rm_obj_dists, dim=1).view(-1)[twod_inds] # Bbox regression if self.mode == 'sgdet': bboxes = result.boxes_all.view(-1, 4)[twod_inds].view(result.boxes_all.size(0), 4) else: # Boxes will get fixed by filter_dets function. bboxes = result.rm_box_priors rel_rep = F.softmax(result.rel_dists, dim=1) return filter_dets(bboxes, result.obj_scores, result.obj_preds, rel_inds[:, 1:], rel_rep) def __getitem__(self, batch): """ Hack to do multi-GPU training""" batch.scatter() if self.num_gpus == 1: return self(*batch[0]) replicas = nn.parallel.replicate(self, devices=list(range(self.num_gpus))) outputs = nn.parallel.parallel_apply(replicas, [batch[i] for i in range(self.num_gpus)]) if self.training: return gather_res(outputs, 0, dim=0) return outputs ================================================ FILE: lib/rel_model_stanford.py ================================================ """ Let's get the relationships yo """ import torch import torch.nn as nn import torch.nn.parallel from torch.autograd import Variable from torch.nn import functional as F from lib.surgery import filter_dets from lib.fpn.proposal_assignments.rel_assignments import rel_assignments from lib.pytorch_misc import arange from lib.object_detector import filter_det from lib.rel_model import RelModel MODES = ('sgdet', 'sgcls', 'predcls') SIZE=512 class RelModelStanford(RelModel): """ RELATIONSHIPS """ def __init__(self, classes, rel_classes, mode='sgdet', num_gpus=1, require_overlap_det=True, use_resnet=False, use_proposals=False, **kwargs): """ :param classes: Object classes :param rel_classes: Relationship classes. None if were not using rel mode :param num_gpus: how many GPUS 2 use """ super(RelModelStanford, self).__init__(classes, rel_classes, mode=mode, num_gpus=num_gpus, require_overlap_det=require_overlap_det, use_resnet=use_resnet, nl_obj=0, nl_edge=0, use_proposals=use_proposals, thresh=0.01, pooling_dim=4096) del self.context del self.post_lstm del self.post_emb self.rel_fc = nn.Linear(SIZE, self.num_rels) self.obj_fc = nn.Linear(SIZE, self.num_classes) self.obj_unary = nn.Linear(self.obj_dim, SIZE) self.edge_unary = nn.Linear(4096, SIZE) self.edge_gru = nn.GRUCell(input_size=SIZE, hidden_size=SIZE) self.node_gru = nn.GRUCell(input_size=SIZE, hidden_size=SIZE) self.n_iter = 3 self.sub_vert_w_fc = nn.Sequential(nn.Linear(SIZE*2, 1), nn.Sigmoid()) self.obj_vert_w_fc = nn.Sequential(nn.Linear(SIZE*2, 1), nn.Sigmoid()) self.out_edge_w_fc = nn.Sequential(nn.Linear(SIZE*2, 1), nn.Sigmoid()) self.in_edge_w_fc = nn.Sequential(nn.Linear(SIZE*2, 1), nn.Sigmoid()) def message_pass(self, rel_rep, obj_rep, rel_inds): """ :param rel_rep: [num_rel, fc] :param obj_rep: [num_obj, fc] :param rel_inds: [num_rel, 2] of the valid relationships :return: object prediction [num_obj, 151], bbox_prediction [num_obj, 151*4] and rel prediction [num_rel, 51] """ # [num_obj, num_rel] with binary! numer = torch.arange(0, rel_inds.size(0)).long().cuda(rel_inds.get_device()) objs_to_outrels = rel_rep.data.new(obj_rep.size(0), rel_rep.size(0)).zero_() objs_to_outrels.view(-1)[rel_inds[:, 0] * rel_rep.size(0) + numer] = 1 objs_to_outrels = Variable(objs_to_outrels) objs_to_inrels = rel_rep.data.new(obj_rep.size(0), rel_rep.size(0)).zero_() objs_to_inrels.view(-1)[rel_inds[:, 1] * rel_rep.size(0) + numer] = 1 objs_to_inrels = Variable(objs_to_inrels) hx_rel = Variable(rel_rep.data.new(rel_rep.size(0), SIZE).zero_(), requires_grad=False) hx_obj = Variable(obj_rep.data.new(obj_rep.size(0), SIZE).zero_(), requires_grad=False) vert_factor = [self.node_gru(obj_rep, hx_obj)] edge_factor = [self.edge_gru(rel_rep, hx_rel)] for i in range(3): # compute edge context sub_vert = vert_factor[i][rel_inds[:, 0]] obj_vert = vert_factor[i][rel_inds[:, 1]] weighted_sub = self.sub_vert_w_fc( torch.cat((sub_vert, edge_factor[i]), 1)) * sub_vert weighted_obj = self.obj_vert_w_fc( torch.cat((obj_vert, edge_factor[i]), 1)) * obj_vert edge_factor.append(self.edge_gru(weighted_sub + weighted_obj, edge_factor[i])) # Compute vertex context pre_out = self.out_edge_w_fc(torch.cat((sub_vert, edge_factor[i]), 1)) * \ edge_factor[i] pre_in = self.in_edge_w_fc(torch.cat((obj_vert, edge_factor[i]), 1)) * edge_factor[ i] vert_ctx = objs_to_outrels @ pre_out + objs_to_inrels @ pre_in vert_factor.append(self.node_gru(vert_ctx, vert_factor[i])) # woohoo! done return self.obj_fc(vert_factor[-1]), self.rel_fc(edge_factor[-1]) # self.box_fc(vert_factor[-1]).view(-1, self.num_classes, 4), \ # self.rel_fc(edge_factor[-1]) def forward(self, x, im_sizes, image_offset, gt_boxes=None, gt_classes=None, gt_rels=None, proposals=None, train_anchor_inds=None, return_fmap=False): """ Forward pass for detection :param x: Images@[batch_size, 3, IM_SIZE, IM_SIZE] :param im_sizes: A numpy array of (h, w, scale) for each image. :param image_offset: Offset onto what image we're on for MGPU training (if single GPU this is 0) :param gt_boxes: Training parameters: :param gt_boxes: [num_gt, 4] GT boxes over the batch. :param gt_classes: [num_gt, 2] gt boxes where each one is (img_id, class) :param train_anchor_inds: a [num_train, 2] array of indices for the anchors that will be used to compute the training loss. Each (img_ind, fpn_idx) :return: If train: scores, boxdeltas, labels, boxes, boxtargets, rpnscores, rpnboxes, rellabels if test: prob dists, boxes, img inds, maxscores, classes """ result = self.detector(x, im_sizes, image_offset, gt_boxes, gt_classes, gt_rels, proposals, train_anchor_inds, return_fmap=True) if result.is_none(): return ValueError("heck") im_inds = result.im_inds - image_offset boxes = result.rm_box_priors if self.training and result.rel_labels is None: assert self.mode == 'sgdet' result.rel_labels = rel_assignments(im_inds.data, boxes.data, result.rm_obj_labels.data, gt_boxes.data, gt_classes.data, gt_rels.data, image_offset, filter_non_overlap=True, num_sample_per_gt=1) rel_inds = self.get_rel_inds(result.rel_labels, im_inds, boxes) rois = torch.cat((im_inds[:, None].float(), boxes), 1) visual_rep = self.visual_rep(result.fmap, rois, rel_inds[:, 1:]) result.obj_fmap = self.obj_feature_map(result.fmap.detach(), rois) # Now do the approximation WHEREVER THERES A VALID RELATIONSHIP. result.rm_obj_dists, result.rel_dists = self.message_pass( F.relu(self.edge_unary(visual_rep)), self.obj_unary(result.obj_fmap), rel_inds[:, 1:]) # result.box_deltas_update = box_deltas if self.training: return result # Decode here ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if self.mode == 'predcls': # Hack to get the GT object labels result.obj_scores = result.rm_obj_dists.data.new(gt_classes.size(0)).fill_(1) result.obj_preds = gt_classes.data[:, 1] elif self.mode == 'sgdet': order, obj_scores, obj_preds= filter_det(F.softmax(result.rm_obj_dists), result.boxes_all, start_ind=0, max_per_img=100, thresh=0.00, pre_nms_topn=6000, post_nms_topn=300, nms_thresh=0.3, nms_filter_duplicates=True) idx, perm = torch.sort(order) result.obj_preds = rel_inds.new(result.rm_obj_dists.size(0)).fill_(1) result.obj_scores = result.rm_obj_dists.data.new(result.rm_obj_dists.size(0)).fill_(0) result.obj_scores[idx] = obj_scores.data[perm] result.obj_preds[idx] = obj_preds.data[perm] else: scores_nz = F.softmax(result.rm_obj_dists).data scores_nz[:, 0] = 0.0 result.obj_scores, score_ord = scores_nz[:, 1:].sort(dim=1, descending=True) result.obj_preds = score_ord[:,0] + 1 result.obj_scores = result.obj_scores[:,0] result.obj_preds = Variable(result.obj_preds) result.obj_scores = Variable(result.obj_scores) # Set result's bounding boxes to be size # [num_boxes, topk, 4] instead of considering every single object assignment. twod_inds = arange(result.obj_preds.data) * self.num_classes + result.obj_preds.data if self.mode == 'sgdet': bboxes = result.boxes_all.view(-1, 4)[twod_inds].view(result.boxes_all.size(0), 4) else: # Boxes will get fixed by filter_dets function. bboxes = result.rm_box_priors rel_rep = F.softmax(result.rel_dists) return filter_dets(bboxes, result.obj_scores, result.obj_preds, rel_inds[:, 1:], rel_rep) ================================================ FILE: lib/resnet.py ================================================ import torch.nn as nn import math import torch.utils.model_zoo as model_zoo from torchvision.models.resnet import model_urls, conv3x3, BasicBlock from torchvision.models.vgg import vgg16 from config import BATCHNORM_MOMENTUM class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, relu_end=True): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes, momentum=BATCHNORM_MOMENTUM) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes, momentum=BATCHNORM_MOMENTUM) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes * 4, momentum=BATCHNORM_MOMENTUM) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.relu_end = relu_end def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: residual = self.downsample(x) out += residual if self.relu_end: out = self.relu(out) return out class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000): self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64, momentum=BATCHNORM_MOMENTUM) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=1) # HACK self.avgpool = nn.AvgPool2d(7) self.fc = nn.Linear(512 * block.expansion, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.expansion, momentum=BATCHNORM_MOMENTUM), ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes)) return nn.Sequential(*layers) def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = x.view(x.size(0), -1) x = self.fc(x) return x def resnet101(pretrained=False, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) return model def resnet_l123(): model = resnet101(pretrained=True) del model.layer4 del model.avgpool del model.fc return model def resnet_l4(relu_end=True): model = resnet101(pretrained=True) l4 = model.layer4 if not relu_end: l4[-1].relu_end = False l4[0].conv2.stride = (1, 1) l4[0].downsample[0].stride = (1, 1) return l4 def vgg_fc(relu_end=True, linear_end=True): model = vgg16(pretrained=True) vfc = model.classifier del vfc._modules['6'] # Get rid of linear layer del vfc._modules['5'] # Get rid of linear layer if not relu_end: del vfc._modules['4'] # Get rid of linear layer if not linear_end: del vfc._modules['3'] return vfc ================================================ FILE: lib/sparse_targets.py ================================================ from lib.word_vectors import obj_edge_vectors import torch.nn as nn import torch from torch.autograd import Variable import numpy as np from config import DATA_PATH import os from lib.get_dataset_counts import get_counts class FrequencyBias(nn.Module): """ The goal of this is to provide a simplified way of computing P(predicate | obj1, obj2, img). """ def __init__(self, eps=1e-3): super(FrequencyBias, self).__init__() fg_matrix, bg_matrix = get_counts(must_overlap=True) bg_matrix += 1 fg_matrix[:, :, 0] = bg_matrix pred_dist = np.log(fg_matrix / fg_matrix.sum(2)[:, :, None] + eps) self.num_objs = pred_dist.shape[0] pred_dist = torch.FloatTensor(pred_dist).view(-1, pred_dist.shape[2]) self.obj_baseline = nn.Embedding(pred_dist.size(0), pred_dist.size(1)) self.obj_baseline.weight.data = pred_dist def index_with_labels(self, labels): """ :param labels: [batch_size, 2] :return: """ return self.obj_baseline(labels[:, 0] * self.num_objs + labels[:, 1]) def forward(self, obj_cands0, obj_cands1): """ :param obj_cands0: [batch_size, 151] prob distibution over cands. :param obj_cands1: [batch_size, 151] prob distibution over cands. :return: [batch_size, #predicates] array, which contains potentials for each possibility """ # [batch_size, 151, 151] repr of the joint distribution joint_cands = obj_cands0[:, :, None] * obj_cands1[:, None] # [151, 151, 51] of targets per. baseline = joint_cands.view(joint_cands.size(0), -1) @ self.obj_baseline.weight return baseline ================================================ FILE: lib/surgery.py ================================================ # create predictions from the other stuff """ Go from proposals + scores to relationships. pred-cls: No bbox regression, obj dist is exactly known sg-cls : No bbox regression sg-det : Bbox regression in all cases we'll return: boxes, objs, rels, pred_scores """ import numpy as np import torch from lib.pytorch_misc import unravel_index from lib.fpn.box_utils import bbox_overlaps # from ad3 import factor_graph as fg from time import time def filter_dets(boxes, obj_scores, obj_classes, rel_inds, pred_scores): """ Filters detections.... :param boxes: [num_box, topk, 4] if bbox regression else [num_box, 4] :param obj_scores: [num_box] probabilities for the scores :param obj_classes: [num_box] class labels for the topk :param rel_inds: [num_rel, 2] TENSOR consisting of (im_ind0, im_ind1) :param pred_scores: [topk, topk, num_rel, num_predicates] :param use_nms: True if use NMS to filter dets. :return: boxes, objs, rels, pred_scores """ if boxes.dim() != 2: raise ValueError("Boxes needs to be [num_box, 4] but its {}".format(boxes.size())) num_box = boxes.size(0) assert obj_scores.size(0) == num_box assert obj_classes.size() == obj_scores.size() num_rel = rel_inds.size(0) assert rel_inds.size(1) == 2 assert pred_scores.size(0) == num_rel obj_scores0 = obj_scores.data[rel_inds[:,0]] obj_scores1 = obj_scores.data[rel_inds[:,1]] pred_scores_max, pred_classes_argmax = pred_scores.data[:,1:].max(1) pred_classes_argmax = pred_classes_argmax + 1 rel_scores_argmaxed = pred_scores_max * obj_scores0 * obj_scores1 rel_scores_vs, rel_scores_idx = torch.sort(rel_scores_argmaxed.view(-1), dim=0, descending=True) rels = rel_inds[rel_scores_idx].cpu().numpy() pred_scores_sorted = pred_scores[rel_scores_idx].data.cpu().numpy() obj_scores_np = obj_scores.data.cpu().numpy() objs_np = obj_classes.data.cpu().numpy() boxes_out = boxes.data.cpu().numpy() return boxes_out, objs_np, obj_scores_np, rels, pred_scores_sorted # def _get_similar_boxes(boxes, obj_classes_topk, nms_thresh=0.3): # """ # Assuming bg is NOT A LABEL. # :param boxes: [num_box, topk, 4] if bbox regression else [num_box, 4] # :param obj_classes: [num_box, topk] class labels # :return: num_box, topk, num_box, topk array containing similarities. # """ # topk = obj_classes_topk.size(1) # num_box = boxes.size(0) # # box_flat = boxes.view(-1, 4) if boxes.dim() == 3 else boxes[:, None].expand( # num_box, topk, 4).contiguous().view(-1, 4) # jax = bbox_overlaps(box_flat, box_flat).data > nms_thresh # # Filter out things that are not gonna compete. # classes_eq = obj_classes_topk.data.view(-1)[:, None] == obj_classes_topk.data.view(-1)[None, :] # jax &= classes_eq # boxes_are_similar = jax.view(num_box, topk, num_box, topk) # return boxes_are_similar.cpu().numpy().astype(np.bool) ================================================ FILE: lib/word_vectors.py ================================================ """ Adapted from PyTorch's text library. """ import array import os import zipfile import six import torch from six.moves.urllib.request import urlretrieve from tqdm import tqdm from config import DATA_PATH import sys def obj_edge_vectors(names, wv_type='glove.6B', wv_dir=DATA_PATH, wv_dim=300): wv_dict, wv_arr, wv_size = load_word_vectors(wv_dir, wv_type, wv_dim) vectors = torch.Tensor(len(names), wv_dim) vectors.normal_(0,1) for i, token in enumerate(names): wv_index = wv_dict.get(token, None) if wv_index is not None: vectors[i] = wv_arr[wv_index] else: # Try the longest word (hopefully won't be a preposition lw_token = sorted(token.split(' '), key=lambda x: len(x), reverse=True)[0] print("{} -> {} ".format(token, lw_token)) wv_index = wv_dict.get(lw_token, None) if wv_index is not None: vectors[i] = wv_arr[wv_index] else: print("fail on {}".format(token)) return vectors URL = { 'glove.42B': 'http://nlp.stanford.edu/data/glove.42B.300d.zip', 'glove.840B': 'http://nlp.stanford.edu/data/glove.840B.300d.zip', 'glove.twitter.27B': 'http://nlp.stanford.edu/data/glove.twitter.27B.zip', 'glove.6B': 'http://nlp.stanford.edu/data/glove.6B.zip', } def load_word_vectors(root, wv_type, dim): """Load word vectors from a path, trying .pt, .txt, and .zip extensions.""" if isinstance(dim, int): dim = str(dim) + 'd' fname = os.path.join(root, wv_type + '.' + dim) if os.path.isfile(fname + '.pt'): fname_pt = fname + '.pt' print('loading word vectors from', fname_pt) try: return torch.load(fname_pt) except Exception as e: print(""" Error loading the model from {} This could be because this code was previously run with one PyTorch version to generate cached data and is now being run with another version. You can try to delete the cached files on disk (this file and others) and re-running the code Error message: --------- {} """.format(fname_pt, str(e))) sys.exit(-1) if os.path.isfile(fname + '.txt'): fname_txt = fname + '.txt' cm = open(fname_txt, 'rb') cm = [line for line in cm] elif os.path.basename(wv_type) in URL: url = URL[wv_type] print('downloading word vectors from {}'.format(url)) filename = os.path.basename(fname) if not os.path.exists(root): os.makedirs(root) with tqdm(unit='B', unit_scale=True, miniters=1, desc=filename) as t: fname, _ = urlretrieve(url, fname, reporthook=reporthook(t)) with zipfile.ZipFile(fname, "r") as zf: print('extracting word vectors into {}'.format(root)) zf.extractall(root) if not os.path.isfile(fname + '.txt'): raise RuntimeError('no word vectors of requested dimension found') return load_word_vectors(root, wv_type, dim) else: raise RuntimeError('unable to load word vectors') wv_tokens, wv_arr, wv_size = [], array.array('d'), None if cm is not None: for line in tqdm(range(len(cm)), desc="loading word vectors from {}".format(fname_txt)): entries = cm[line].strip().split(b' ') word, entries = entries[0], entries[1:] if wv_size is None: wv_size = len(entries) try: if isinstance(word, six.binary_type): word = word.decode('utf-8') except: print('non-UTF8 token', repr(word), 'ignored') continue wv_arr.extend(float(x) for x in entries) wv_tokens.append(word) wv_dict = {word: i for i, word in enumerate(wv_tokens)} wv_arr = torch.Tensor(wv_arr).view(-1, wv_size) ret = (wv_dict, wv_arr, wv_size) torch.save(ret, fname + '.pt') return ret def reporthook(t): """https://github.com/tqdm/tqdm""" last_b = [0] def inner(b=1, bsize=1, tsize=None): """ b: int, optionala Number of blocks just transferred [default: 1]. bsize: int, optional Size of each block (in tqdm units) [default: 1]. tsize: int, optional Total size (in tqdm units). If [default: None] remains unchanged. """ if tsize is not None: t.total = tsize t.update((b - last_b[0]) * bsize) last_b[0] = b return inner ================================================ FILE: misc/__init__.py ================================================ ================================================ FILE: misc/motifs.py ================================================ """ SCRIPT TO MAKE MEMES. this was from an old version of the code, so it might require some fixes to get working. """ from dataloaders.visual_genome import VG # import matplotlib # # matplotlib.use('Agg') from tqdm import tqdm import seaborn as sns import numpy as np from lib.fpn.box_intersections_cpu.bbox import bbox_overlaps from collections import defaultdict train, val, test = VG.splits(filter_non_overlap=False, num_val_im=2000) count_threshold = 50 pmi_threshold = 10 o_type = [] f = open("object_types.txt") for line in f.readlines(): tabs = line.strip().split("\t") t = tabs[1].split("_")[0] o_type.append(t) r_type = [] f = open("relation_types.txt") for line in f.readlines(): tabs = line.strip().split("\t") t = tabs[1].split("_")[0] r_type.append(t) max_id = 0 memes_id_id = {} memes_id = {} id_memes = {} id_key = {} key_id = {} #go through and assign keys dataset = [] for i in range(0, len(train)): item = [] _r = train.relationships[i] _o = train.gt_classes[i] for j in range(0, len(_r)): h = _o[_r[j][0]] t = _o[_r[j][1]] e = _r[j][2] key1 = (h,e,t) if key1 not in key_id: id_key[max_id] = key1 key_id[key1] = max_id max_id += 1 item.append(key_id[key1]) dataset.append(item) cids = train.ind_to_classes rids = train.ind_to_predicates all_memes = [] def id_to_str(_id): key = id_key[_id] if len(key) == 2: pair = key l1, s1 = id_to_str(pair[0]) l2, s2 = id_to_str(pair[1]) return (l1 + l2, s1 + " & " + s2) else: return (1,"{}--{}-->{}".format(cids[key[0]], rids[key[1]], cids[key[2]])) new_meme_score = {} for p in range(0,25): print("iteration : {}".format(p)) unigrams = defaultdict(float) bigrams = defaultdict(float) unigrams_ori = defaultdict(float) T = 0 T2 = 0 for i in range(0, len(dataset)): item = dataset[i] for j in range(0, len(item)): key1 = item[j] unigrams_ori[key1] += 1 #T += 1 for j2 in range(j+1 , len(item)): key2 = item[j2] if key1 > key2 : jkey = (key1, key2) else: jkey = (key2, key1) unigrams[key1] += 1 unigrams[key2] += 1 bigrams[jkey] += 1 T2 += 1 pmi = [] for (jkey,val) in bigrams.items(): pval = (val / T2) / ( (unigrams[jkey[0]]/ T2) * (unigrams[jkey[0]] / T2 )) #print("{} {} {}".format(jkey, val, pval)) if val > count_threshold and unigrams_ori[jkey[0]] > count_threshold and unigrams_ori[jkey[1]] > count_threshold and pval > pmi_threshold : pmi.append( (pval , jkey, val) ) # new_memes.add(jkey) new_memes = set() pmi = sorted(pmi, key = lambda x: -x[0]) new_meme_c = set() for (v,k, f) in pmi: #if k[0] in all_memes and k[1] in all_memes: continue #if len( new_memes) > 1000: break if k[0] in new_meme_c or k[1] in new_meme_c: continue new_meme_c.add(k[0]) new_meme_c.add(k[1]) print("{} & {} \t {} \t {} \t {} \t {}".format(id_to_str(k[0]), id_to_str(k[1]), v, unigrams[k[0]], unigrams[k[1]], bigrams[k])) new_memes.add(k) #assign new ids to the memes new_meme_score[k] = v #break for meme in new_memes: if meme in key_id: continue all_memes.append(max_id) id_key[max_id] = meme key_id[meme] = max_id max_id+=1 print("{} memes discovered ".format(len(new_memes))) #go through and adjust the dataset new_dataset = [] eliminated = 0 for i in range(0,len(dataset)): item_save = dataset[i] item = item_save new_item = [] #merges = {} while True: best = None best_score = 0 for j in range(0, len(item)): key1 = item[j] for j2 in range(j+1 , len(item)): key2 = item[j2] if key1 > key2 : jkey = (key1, key2) else: jkey = (key2, key1) if jkey in new_meme_score and new_meme_score[jkey] > best_score: best = (j, j2) best_score = new_meme_score[jkey] #if jkey in key_id and j not in merges and j2 not in merges: # merges[j] = j2 # merges[j2] = j if best is not None: for j in range(0, len(item)): if j == best[0]: key1 = item[j] key2 = item[best[1]] if key1 > key2 : jkey = (key1, key2) else: jkey = (key2, key1) new_item.append(key_id[jkey]) elif j == best[1]: continue else: new_item.append(item[j]) #break item = new_item new_item = [] else: #print("done") new_item = item break #for j in range(0, len(item)): # if j not in merges: new_item.append(item[j]) # elif j < merges[j]: # key1 = item[j] # key2 = item[merges[j]] # if key1 > key2 : jkey = (key1, key2) # else: jkey = (key2, key1) # new_item.append(key_id[jkey]) eliminated += len(item_save) - len(new_item) new_dataset.append(new_item) print ("{} total eliminated".format(eliminated)) dataset = new_dataset meme_freq = defaultdict(float) def increment_recursive(i): #meme = id_key[i] if i in all_memes: meme_freq[i] += 1 key1 = id_key[i][0] key2 = id_key[i][1] increment_recursive(key1) increment_recursive(key2) def meme_length(i): if i in all_memes: return meme_length(id_key[i][0]) + meme_length(id_key[i][1]) else: return 1 #compute statistics of memes for i in range(0,len(dataset)): item = dataset[i] for j in range(0, len(item)): increment_recursive(item[j]) for meme in all_memes: print ("{} {}".format( id_to_str(meme), meme_freq[meme])) T = 0 T2 = 0 n_images = defaultdict(float) n_edges = defaultdict(float) for item in dataset: meme_lengths = [] for j in range(0, len(item)): meme_lengths.append(meme_length(item[j])) n_images[max(meme_lengths)] += 1 #for l in meme_lengths: n_images[l] +=1 T += 1 for item in dataset: for j in range(0, len(item)): l = meme_length(item[j]) n_edges[l] += l T2 += l for (k,v) in n_images.items(): print("{} {}".format(k, v/T)) print("---") for (k,v) in n_edges.items(): print("{} {}".format(k, v/T2)) ================================================ FILE: misc/object_types.txt ================================================ __background__ background airplane vehicle animal animal arm part_animal_person bag clothes banana food basket artifact beach location bear animal bed furniture bench furniture bike vehicle bird animal board artifact boat vehicle book artifact boot clothes bottle artifact bowl artifact box artifact boy person branch part_flora building building bus vehicle cabinet furniture cap clothes car vehicle cat animal chair furniture child person clock artifact coat clothes counter furniture cow animal cup artifact curtain artifact desk furniture dog animal door part_building drawer part_table ear part_animal_person elephant animal engine part_vehicle eye part_animal_person face part_animal_person fence structure finger part_animal_person flag artifact flower flora food food fork artifact fruit food giraffe animal girl person glass artifact glove clothes guy person hair part_animal_person hand part_animal_person handle part_door hat clothes head part_animal_person helmet clothes hill location horse animal house building jacket clothes jean clothes kid person kite artifact lady person lamp artifact laptop artifact leaf part_flora leg part_animal_person letter artifact light artifact logo part_clothes man person men person motorcycle vehicle mountain location mouth part_animal_perosn neck part_animal_person nose part_animal_person number artifact orange food pant clothes paper artifact paw part_animal people person person person phone artifact pillow artifact pizza food plane vehicle plant flora plate artifact player person pole artifact post structure pot artifact racket artifact railing furniture rock location roof part_building room location screen part_laptop_phone seat part_vehicle sheep animal shelf artifact shirt clothes shoe clothes short clothes sidewalk location sign structure sink furniture skateboard vehicle ski artifact skier person sneaker clothes snow location sock clothes stand artifact street location surfboard vehicle table furniture tail part_animal tie clothes tile part_building tire part_vehicle toilet artifact towel artifact tower part_building track artifact train vehicle tree flora truck vehicle trunk part_flora umbrella artifact vase artifact vegetable food vehicle vehicle wave location wheel part_vehicle window part_building windshield part_vehicle wing part_animal wire artifact woman person zebra animal ================================================ FILE: misc/relation_types.txt ================================================ __background__ background above geometric across geometric against geometric along geometric and geometric at geometric attached to semantic behind geometric belonging to posession between geometric carrying semantic covered in semantic covering semantic eating semantic flying in semantic for misc from misc growing on semantic hanging from semantic has posession holding light_semantic_posession in geometric in front of geometric laying on semantic looking at semantic lying on semantic made of misc mounted on semantic near geometric of posession on geometric on back of geometric over geometric painted on semantic parked on semantic part of posession playing semantic riding semantic says semantic sitting on semantic standing on semantic to posession under geometric using light_semantic_posession walking in semantic walking on semantic watching semantic wearing wearing wears wearing with posession ================================================ FILE: models/_visualize.py ================================================ """ Visualization script. I used this to create the figures in the paper. WARNING: I haven't tested this in a while. It's possible that some later features I added break things here, but hopefully there should be easy fixes. I'm uploading this in the off chance it might help someone. If you get it to work, let me know (and also send a PR with bugs/etc) """ from dataloaders.visual_genome import VGDataLoader, VG from lib.rel_model import RelModel import numpy as np import torch from config import ModelConfig from lib.pytorch_misc import optimistic_restore from lib.evaluation.sg_eval import BasicSceneGraphEvaluator from tqdm import tqdm from config import BOX_SCALE, IM_SCALE from lib.fpn.box_utils import bbox_overlaps from collections import defaultdict from PIL import Image, ImageDraw, ImageFont import os from functools import reduce conf = ModelConfig() train, val, test = VG.splits(num_val_im=conf.val_size) if conf.test: val = test train_loader, val_loader = VGDataLoader.splits(train, val, mode='rel', batch_size=conf.batch_size, num_workers=conf.num_workers, num_gpus=conf.num_gpus) detector = RelModel(classes=train.ind_to_classes, rel_classes=train.ind_to_predicates, num_gpus=conf.num_gpus, mode=conf.mode, require_overlap_det=True, use_resnet=conf.use_resnet, order=conf.order, nl_edge=conf.nl_edge, nl_obj=conf.nl_obj, hidden_dim=conf.hidden_dim, use_proposals=conf.use_proposals, pass_in_obj_feats_to_decoder=conf.pass_in_obj_feats_to_decoder, pass_in_obj_feats_to_edge=conf.pass_in_obj_feats_to_edge, pooling_dim=conf.pooling_dim, rec_dropout=conf.rec_dropout, use_bias=conf.use_bias, use_tanh=conf.use_tanh, limit_vision=conf.limit_vision ) detector.cuda() ckpt = torch.load(conf.ckpt) optimistic_restore(detector, ckpt['state_dict']) ############################################ HELPER FUNCTIONS ################################### def get_cmap(N): import matplotlib.cm as cmx import matplotlib.colors as colors """Returns a function that maps each index in 0, 1, ... N-1 to a distinct RGB color.""" color_norm = colors.Normalize(vmin=0, vmax=N - 1) scalar_map = cmx.ScalarMappable(norm=color_norm, cmap='hsv') def map_index_to_rgb_color(index): pad = 40 return np.round(np.array(scalar_map.to_rgba(index)) * (255 - pad) + pad) return map_index_to_rgb_color cmap = get_cmap(len(train.ind_to_classes) + 1) def load_unscaled(fn): """ Loads and scales images so that it's 1024 max-dimension""" image_unpadded = Image.open(fn).convert('RGB') im_scale = 1024.0 / max(image_unpadded.size) image = image_unpadded.resize((int(im_scale * image_unpadded.size[0]), int(im_scale * image_unpadded.size[1])), resample=Image.BICUBIC) return image font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 32) def draw_box(draw, boxx, cls_ind, text_str): box = tuple([float(b) for b in boxx]) if '-GT' in text_str: color = (255, 128, 0, 255) else: color = (0, 128, 0, 255) # color = tuple([int(x) for x in cmap(cls_ind)]) # draw the fucking box draw.line([(box[0], box[1]), (box[2], box[1])], fill=color, width=8) draw.line([(box[2], box[1]), (box[2], box[3])], fill=color, width=8) draw.line([(box[2], box[3]), (box[0], box[3])], fill=color, width=8) draw.line([(box[0], box[3]), (box[0], box[1])], fill=color, width=8) # draw.rectangle(box, outline=color) w, h = draw.textsize(text_str, font=font) x1text = box[0] y1text = max(box[1] - h, 0) x2text = min(x1text + w, draw.im.size[0]) y2text = y1text + h print("drawing {}x{} rectangle at {:.1f} {:.1f} {:.1f} {:.1f}".format( h, w, x1text, y1text, x2text, y2text)) draw.rectangle((x1text, y1text, x2text, y2text), fill=color) draw.text((x1text, y1text), text_str, fill='black', font=font) return draw def val_epoch(): detector.eval() evaluator = BasicSceneGraphEvaluator.all_modes() for val_b, batch in enumerate(tqdm(val_loader)): val_batch(conf.num_gpus * val_b, batch, evaluator) evaluator[conf.mode].print_stats() def val_batch(batch_num, b, evaluator, thrs=(20, 50, 100)): det_res = detector[b] # if conf.num_gpus == 1: # det_res = [det_res] assert conf.num_gpus == 1 boxes_i, objs_i, obj_scores_i, rels_i, pred_scores_i = det_res gt_entry = { 'gt_classes': val.gt_classes[batch_num].copy(), 'gt_relations': val.relationships[batch_num].copy(), 'gt_boxes': val.gt_boxes[batch_num].copy(), } # gt_entry = {'gt_classes': gtc[i], 'gt_relations': gtr[i], 'gt_boxes': gtb[i]} assert np.all(objs_i[rels_i[:, 0]] > 0) and np.all(objs_i[rels_i[:, 1]] > 0) # assert np.all(rels_i[:, 2] > 0) pred_entry = { 'pred_boxes': boxes_i * BOX_SCALE / IM_SCALE, 'pred_classes': objs_i, 'pred_rel_inds': rels_i, 'obj_scores': obj_scores_i, 'rel_scores': pred_scores_i, } pred_to_gt, pred_5ples, rel_scores = evaluator[conf.mode].evaluate_scene_graph_entry( gt_entry, pred_entry, ) # SET RECALL THRESHOLD HERE pred_to_gt = pred_to_gt[:20] pred_5ples = pred_5ples[:20] # Get a list of objects that match, and GT objects that dont objs_match = (bbox_overlaps(pred_entry['pred_boxes'], gt_entry['gt_boxes']) >= 0.5) & ( objs_i[:, None] == gt_entry['gt_classes'][None] ) objs_matched = objs_match.any(1) has_seen = defaultdict(int) has_seen_gt = defaultdict(int) pred_ind2name = {} gt_ind2name = {} edges = {} missededges = {} badedges = {} if val.filenames[batch_num].startswith('2343676'): import ipdb ipdb.set_trace() def query_pred(pred_ind): if pred_ind not in pred_ind2name: has_seen[objs_i[pred_ind]] += 1 pred_ind2name[pred_ind] = '{}-{}'.format(train.ind_to_classes[objs_i[pred_ind]], has_seen[objs_i[pred_ind]]) return pred_ind2name[pred_ind] def query_gt(gt_ind): gt_cls = gt_entry['gt_classes'][gt_ind] if gt_ind not in gt_ind2name: has_seen_gt[gt_cls] += 1 gt_ind2name[gt_ind] = '{}-GT{}'.format(train.ind_to_classes[gt_cls], has_seen_gt[gt_cls]) return gt_ind2name[gt_ind] matching_pred5ples = pred_5ples[np.array([len(x) > 0 for x in pred_to_gt])] for fiveple in matching_pred5ples: head_name = query_pred(fiveple[0]) tail_name = query_pred(fiveple[1]) edges[(head_name, tail_name)] = train.ind_to_predicates[fiveple[4]] gt_5ples = np.column_stack((gt_entry['gt_relations'][:, :2], gt_entry['gt_classes'][gt_entry['gt_relations'][:, 0]], gt_entry['gt_classes'][gt_entry['gt_relations'][:, 1]], gt_entry['gt_relations'][:, 2], )) has_match = reduce(np.union1d, pred_to_gt) for gt in gt_5ples[np.setdiff1d(np.arange(gt_5ples.shape[0]), has_match)]: # Head and tail namez = [] for i in range(2): matching_obj = np.where(objs_match[:, gt[i]])[0] if matching_obj.size > 0: name = query_pred(matching_obj[0]) else: name = query_gt(gt[i]) namez.append(name) missededges[tuple(namez)] = train.ind_to_predicates[gt[4]] for fiveple in pred_5ples[np.setdiff1d(np.arange(pred_5ples.shape[0]), matching_pred5ples)]: if fiveple[0] in pred_ind2name: if fiveple[1] in pred_ind2name: badedges[(pred_ind2name[fiveple[0]], pred_ind2name[fiveple[1]])] = train.ind_to_predicates[fiveple[4]] theimg = load_unscaled(val.filenames[batch_num]) theimg2 = theimg.copy() draw2 = ImageDraw.Draw(theimg2) # Fix the names for pred_ind in pred_ind2name.keys(): draw2 = draw_box(draw2, pred_entry['pred_boxes'][pred_ind], cls_ind=objs_i[pred_ind], text_str=pred_ind2name[pred_ind]) for gt_ind in gt_ind2name.keys(): draw2 = draw_box(draw2, gt_entry['gt_boxes'][gt_ind], cls_ind=gt_entry['gt_classes'][gt_ind], text_str=gt_ind2name[gt_ind]) recall = int(100 * len(reduce(np.union1d, pred_to_gt)) / gt_entry['gt_relations'].shape[0]) id = '{}-{}'.format(val.filenames[batch_num].split('/')[-1][:-4], recall) pathname = os.path.join('qualitative', id) if not os.path.exists(pathname): os.mkdir(pathname) theimg.save(os.path.join(pathname, 'img.jpg'), quality=100, subsampling=0) theimg2.save(os.path.join(pathname, 'imgbox.jpg'), quality=100, subsampling=0) with open(os.path.join(pathname, 'shit.txt'), 'w') as f: f.write('good:\n') for (o1, o2), p in edges.items(): f.write('{} - {} - {}\n'.format(o1, p, o2)) f.write('fn:\n') for (o1, o2), p in missededges.items(): f.write('{} - {} - {}\n'.format(o1, p, o2)) f.write('shit:\n') for (o1, o2), p in badedges.items(): f.write('{} - {} - {}\n'.format(o1, p, o2)) mAp = val_epoch() ================================================ FILE: models/eval_rel_count.py ================================================ """ Baseline model that works by simply iterating through the training set to make a dictionary. Also, caches this (we can use this for training). The model is quite simple, so we don't use the base train/test code """ from dataloaders.visual_genome import VGDataLoader, VG from lib.object_detector import ObjectDetector import numpy as np import torch import os from lib.get_dataset_counts import get_counts, box_filter from config import ModelConfig, FG_FRACTION, RPN_FG_FRACTION, DATA_PATH, BOX_SCALE, IM_SCALE, PROPOSAL_FN import torch.backends.cudnn as cudnn from lib.pytorch_misc import optimistic_restore, nonintersecting_2d_inds from lib.evaluation.sg_eval import BasicSceneGraphEvaluator from tqdm import tqdm from copy import deepcopy import dill as pkl cudnn.benchmark = True conf = ModelConfig() MUST_OVERLAP=False train, val, test = VG.splits(num_val_im=conf.val_size, filter_non_overlap=MUST_OVERLAP, filter_duplicate_rels=True, use_proposals=conf.use_proposals) if conf.test: print("test data!") val = test train_loader, val_loader = VGDataLoader.splits(train, val, mode='rel', batch_size=conf.batch_size, num_workers=conf.num_workers, num_gpus=conf.num_gpus) fg_matrix, bg_matrix = get_counts(train_data=train, must_overlap=MUST_OVERLAP) detector = ObjectDetector(classes=train.ind_to_classes, num_gpus=conf.num_gpus, mode='rpntrain' if not conf.use_proposals else 'proposals', use_resnet=conf.use_resnet, nms_filter_duplicates=True, thresh=0.01) detector.eval() detector.cuda() classifier = ObjectDetector(classes=train.ind_to_classes, num_gpus=conf.num_gpus, mode='gtbox', use_resnet=conf.use_resnet, nms_filter_duplicates=True, thresh=0.01) classifier.eval() classifier.cuda() ckpt = torch.load(conf.ckpt) mismatch = optimistic_restore(detector, ckpt['state_dict']) mismatch = optimistic_restore(classifier, ckpt['state_dict']) MOST_COMMON_MODE = True if MOST_COMMON_MODE: prob_matrix = fg_matrix.astype(np.float32) prob_matrix[:,:,0] = bg_matrix # TRYING SOMETHING NEW. prob_matrix[:,:,0] += 1 prob_matrix /= np.sum(prob_matrix, 2)[:,:,None] # prob_matrix /= float(fg_matrix.max()) np.save(os.path.join(DATA_PATH, 'pred_stats.npy'), prob_matrix) prob_matrix[:,:,0] = 0 # Zero out BG else: prob_matrix = fg_matrix.astype(np.float64) prob_matrix = prob_matrix / prob_matrix.max(2)[:,:,None] np.save(os.path.join(DATA_PATH, 'pred_dist.npy'), prob_matrix) # It's test time! def predict(boxes, classes): relation_possibilities_ = np.array(box_filter(boxes, must_overlap=MUST_OVERLAP), dtype=int) full_preds = np.zeros((boxes.shape[0], boxes.shape[0], train.num_predicates)) for o1, o2 in relation_possibilities_: c1, c2 = classes[[o1, o2]] full_preds[o1, o2] = prob_matrix[c1, c2] full_preds[:,:,0] = 0.0 # Zero out BG. return full_preds # ########################################################################################## # ########################################################################################## # For visualizing / exploring c_to_ind = {c: i for i, c in enumerate(train.ind_to_classes)} def gimme_the_dist(c1name, c2name): c1 = c_to_ind[c1name] c2 = c_to_ind[c2name] dist = prob_matrix[c1, c2] argz = np.argsort(-dist) for i, a in enumerate(argz): if dist[a] > 0.0: print("{:3d}: {:10s} ({:.4f})".format(i, train.ind_to_predicates[a], dist[a])) counts = np.zeros((train.num_classes, train.num_classes, train.num_predicates), dtype=np.int64) for ex_ind in tqdm(range(len(val))): gt_relations = val.relationships[ex_ind].copy() gt_classes = val.gt_classes[ex_ind].copy() o1o2 = gt_classes[gt_relations[:, :2]].tolist() for (o1, o2), pred in zip(o1o2, gt_relations[:, 2]): counts[o1, o2, pred] += 1 zeroshot_case = counts[np.where(prob_matrix == 0)].sum() / float(counts.sum()) max_inds = prob_matrix.argmax(2).ravel() max_counts = counts.reshape(-1, 51)[np.arange(max_inds.shape[0]), max_inds] most_freq_port = max_counts.sum()/float(counts.sum()) print(" Rel acc={:.2f}%, {:.2f}% zsl".format( most_freq_port*100, zeroshot_case*100)) # ########################################################################################## # ########################################################################################## T = len(val) evaluator = BasicSceneGraphEvaluator.all_modes(multiple_preds=conf.multi_pred) # First do detection results img_offset = 0 all_pred_entries = {'sgdet':[], 'sgcls':[], 'predcls':[]} for val_b, b in enumerate(tqdm(val_loader)): det_result = detector[b] img_ids = b.gt_classes_primary.data.cpu().numpy()[:,0] scores_np = det_result.obj_scores.data.cpu().numpy() cls_preds_np = det_result.obj_preds.data.cpu().numpy() boxes_np = det_result.boxes_assigned.data.cpu().numpy()* BOX_SCALE/IM_SCALE # boxpriors_np = det_result.box_priors.data.cpu().numpy() im_inds_np = det_result.im_inds.data.cpu().numpy() + img_offset for img_i in np.unique(img_ids + img_offset): gt_entry = { 'gt_classes': val.gt_classes[img_i].copy(), 'gt_relations': val.relationships[img_i].copy(), 'gt_boxes': val.gt_boxes[img_i].copy(), } pred_boxes = boxes_np[im_inds_np == img_i] pred_classes = cls_preds_np[im_inds_np == img_i] obj_scores = scores_np[im_inds_np == img_i] all_rels = nonintersecting_2d_inds(pred_boxes.shape[0]) fp = predict(pred_boxes, pred_classes) fp_pred = fp[all_rels[:,0], all_rels[:,1]] scores = np.column_stack(( obj_scores[all_rels[:,0]], obj_scores[all_rels[:,1]], fp_pred.max(1) )).prod(1) sorted_inds = np.argsort(-scores) sorted_inds = sorted_inds[scores[sorted_inds] > 0] #[:100] pred_entry = { 'pred_boxes': pred_boxes, 'pred_classes': pred_classes, 'obj_scores': obj_scores, 'pred_rel_inds': all_rels[sorted_inds], 'rel_scores': fp_pred[sorted_inds], } all_pred_entries['sgdet'].append(pred_entry) evaluator['sgdet'].evaluate_scene_graph_entry( gt_entry, pred_entry, ) img_offset += img_ids.max() + 1 evaluator['sgdet'].print_stats() # ----------------------------------------------------------------------------------------- # EVAL CLS AND SG img_offset = 0 for val_b, b in enumerate(tqdm(val_loader)): det_result = classifier[b] scores, cls_preds = det_result.rm_obj_dists[:,1:].data.max(1) scores_np = scores.cpu().numpy() cls_preds_np = (cls_preds+1).cpu().numpy() img_ids = b.gt_classes_primary.data.cpu().numpy()[:,0] boxes_np = b.gt_boxes_primary.data.cpu().numpy() im_inds_np = det_result.im_inds.data.cpu().numpy() + img_offset for img_i in np.unique(img_ids + img_offset): gt_entry = { 'gt_classes': val.gt_classes[img_i].copy(), 'gt_relations': val.relationships[img_i].copy(), 'gt_boxes': val.gt_boxes[img_i].copy(), } pred_boxes = boxes_np[im_inds_np == img_i] pred_classes = cls_preds_np[im_inds_np == img_i] obj_scores = scores_np[im_inds_np == img_i] all_rels = nonintersecting_2d_inds(pred_boxes.shape[0]) fp = predict(pred_boxes, pred_classes) fp_pred = fp[all_rels[:,0], all_rels[:,1]] sg_cls_scores = np.column_stack(( obj_scores[all_rels[:,0]], obj_scores[all_rels[:,1]], fp_pred.max(1) )).prod(1) sg_cls_inds = np.argsort(-sg_cls_scores) sg_cls_inds = sg_cls_inds[sg_cls_scores[sg_cls_inds] > 0] #[:100] pred_entry = { 'pred_boxes': pred_boxes, 'pred_classes': pred_classes, 'obj_scores': obj_scores, 'pred_rel_inds': all_rels[sg_cls_inds], 'rel_scores': fp_pred[sg_cls_inds], } all_pred_entries['sgcls'].append(deepcopy(pred_entry)) evaluator['sgcls'].evaluate_scene_graph_entry( gt_entry, pred_entry, ) ######################################################## fp = predict(gt_entry['gt_boxes'], gt_entry['gt_classes']) fp_pred = fp[all_rels[:, 0], all_rels[:, 1]] pred_cls_scores = fp_pred.max(1) pred_cls_inds = np.argsort(-pred_cls_scores) pred_cls_inds = pred_cls_inds[pred_cls_scores[pred_cls_inds] > 0][:100] pred_entry['pred_rel_inds'] = all_rels[pred_cls_inds] pred_entry['rel_scores'] = fp_pred[pred_cls_inds] pred_entry['pred_classes'] = gt_entry['gt_classes'] pred_entry['obj_scores'] = np.ones(pred_entry['pred_classes'].shape[0]) all_pred_entries['predcls'].append(pred_entry) evaluator['predcls'].evaluate_scene_graph_entry( gt_entry, pred_entry, ) img_offset += img_ids.max() + 1 evaluator['predcls'].print_stats() evaluator['sgcls'].print_stats() for mode, entries in all_pred_entries.items(): with open('caches/freqbaseline-{}-{}.pkl'.format('overlap' if MUST_OVERLAP else 'nonoverlap', mode), 'wb') as f: pkl.dump(entries, f) ================================================ FILE: models/eval_rels.py ================================================ from dataloaders.visual_genome import VGDataLoader, VG import numpy as np import torch from config import ModelConfig from lib.pytorch_misc import optimistic_restore from lib.evaluation.sg_eval import BasicSceneGraphEvaluator from tqdm import tqdm from config import BOX_SCALE, IM_SCALE import dill as pkl import os conf = ModelConfig() if conf.model == 'motifnet': from lib.rel_model import RelModel elif conf.model == 'stanford': from lib.rel_model_stanford import RelModelStanford as RelModel else: raise ValueError() train, val, test = VG.splits(num_val_im=conf.val_size, filter_duplicate_rels=True, use_proposals=conf.use_proposals, filter_non_overlap=conf.mode == 'sgdet') if conf.test: val = test train_loader, val_loader = VGDataLoader.splits(train, val, mode='rel', batch_size=conf.batch_size, num_workers=conf.num_workers, num_gpus=conf.num_gpus) detector = RelModel(classes=train.ind_to_classes, rel_classes=train.ind_to_predicates, num_gpus=conf.num_gpus, mode=conf.mode, require_overlap_det=True, use_resnet=conf.use_resnet, order=conf.order, nl_edge=conf.nl_edge, nl_obj=conf.nl_obj, hidden_dim=conf.hidden_dim, use_proposals=conf.use_proposals, pass_in_obj_feats_to_decoder=conf.pass_in_obj_feats_to_decoder, pass_in_obj_feats_to_edge=conf.pass_in_obj_feats_to_edge, pooling_dim=conf.pooling_dim, rec_dropout=conf.rec_dropout, use_bias=conf.use_bias, use_tanh=conf.use_tanh, limit_vision=conf.limit_vision ) detector.cuda() ckpt = torch.load(conf.ckpt) optimistic_restore(detector, ckpt['state_dict']) # if conf.mode == 'sgdet': # det_ckpt = torch.load('checkpoints/new_vgdet/vg-19.tar')['state_dict'] # detector.detector.bbox_fc.weight.data.copy_(det_ckpt['bbox_fc.weight']) # detector.detector.bbox_fc.bias.data.copy_(det_ckpt['bbox_fc.bias']) # detector.detector.score_fc.weight.data.copy_(det_ckpt['score_fc.weight']) # detector.detector.score_fc.bias.data.copy_(det_ckpt['score_fc.bias']) all_pred_entries = [] def val_batch(batch_num, b, evaluator, thrs=(20, 50, 100)): det_res = detector[b] if conf.num_gpus == 1: det_res = [det_res] for i, (boxes_i, objs_i, obj_scores_i, rels_i, pred_scores_i) in enumerate(det_res): gt_entry = { 'gt_classes': val.gt_classes[batch_num + i].copy(), 'gt_relations': val.relationships[batch_num + i].copy(), 'gt_boxes': val.gt_boxes[batch_num + i].copy(), } assert np.all(objs_i[rels_i[:,0]] > 0) and np.all(objs_i[rels_i[:,1]] > 0) # assert np.all(rels_i[:,2] > 0) pred_entry = { 'pred_boxes': boxes_i * BOX_SCALE/IM_SCALE, 'pred_classes': objs_i, 'pred_rel_inds': rels_i, 'obj_scores': obj_scores_i, 'rel_scores': pred_scores_i, } all_pred_entries.append(pred_entry) evaluator[conf.mode].evaluate_scene_graph_entry( gt_entry, pred_entry, ) evaluator = BasicSceneGraphEvaluator.all_modes(multiple_preds=conf.multi_pred) if conf.cache is not None and os.path.exists(conf.cache): print("Found {}! Loading from it".format(conf.cache)) with open(conf.cache,'rb') as f: all_pred_entries = pkl.load(f) for i, pred_entry in enumerate(tqdm(all_pred_entries)): gt_entry = { 'gt_classes': val.gt_classes[i].copy(), 'gt_relations': val.relationships[i].copy(), 'gt_boxes': val.gt_boxes[i].copy(), } evaluator[conf.mode].evaluate_scene_graph_entry( gt_entry, pred_entry, ) evaluator[conf.mode].print_stats() else: detector.eval() for val_b, batch in enumerate(tqdm(val_loader)): val_batch(conf.num_gpus*val_b, batch, evaluator) evaluator[conf.mode].print_stats() if conf.cache is not None: with open(conf.cache,'wb') as f: pkl.dump(all_pred_entries, f) ================================================ FILE: models/train_detector.py ================================================ """ Training script 4 Detection """ from dataloaders.mscoco import CocoDetection, CocoDataLoader from dataloaders.visual_genome import VGDataLoader, VG from lib.object_detector import ObjectDetector import numpy as np from torch import optim import torch import pandas as pd import time import os from config import ModelConfig, FG_FRACTION, RPN_FG_FRACTION, IM_SCALE, BOX_SCALE from torch.nn import functional as F from lib.fpn.box_utils import bbox_loss import torch.backends.cudnn as cudnn from pycocotools.cocoeval import COCOeval from lib.pytorch_misc import optimistic_restore, clip_grad_norm from torch.optim.lr_scheduler import ReduceLROnPlateau cudnn.benchmark = True conf = ModelConfig() if conf.coco: train, val = CocoDetection.splits() val.ids = val.ids[:conf.val_size] train.ids = train.ids train_loader, val_loader = CocoDataLoader.splits(train, val, batch_size=conf.batch_size, num_workers=conf.num_workers, num_gpus=conf.num_gpus) else: train, val, _ = VG.splits(num_val_im=conf.val_size, filter_non_overlap=False, filter_empty_rels=False, use_proposals=conf.use_proposals) train_loader, val_loader = VGDataLoader.splits(train, val, batch_size=conf.batch_size, num_workers=conf.num_workers, num_gpus=conf.num_gpus) detector = ObjectDetector(classes=train.ind_to_classes, num_gpus=conf.num_gpus, mode='rpntrain' if not conf.use_proposals else 'proposals', use_resnet=conf.use_resnet) detector.cuda() # Note: if you're doing the stanford setup, you'll need to change this to freeze the lower layers if conf.use_proposals: for n, param in detector.named_parameters(): if n.startswith('features'): param.requires_grad = False optimizer = optim.SGD([p for p in detector.parameters() if p.requires_grad], weight_decay=conf.l2, lr=conf.lr * conf.num_gpus * conf.batch_size, momentum=0.9) scheduler = ReduceLROnPlateau(optimizer, 'max', patience=3, factor=0.1, verbose=True, threshold=0.001, threshold_mode='abs', cooldown=1) start_epoch = -1 if conf.ckpt is not None: ckpt = torch.load(conf.ckpt) if optimistic_restore(detector, ckpt['state_dict']): start_epoch = ckpt['epoch'] def train_epoch(epoch_num): detector.train() tr = [] start = time.time() for b, batch in enumerate(train_loader): tr.append(train_batch(batch)) if b % conf.print_interval == 0 and b >= conf.print_interval: mn = pd.concat(tr[-conf.print_interval:], axis=1).mean(1) time_per_batch = (time.time() - start) / conf.print_interval print("\ne{:2d}b{:5d}/{:5d} {:.3f}s/batch, {:.1f}m/epoch".format( epoch_num, b, len(train_loader), time_per_batch, len(train_loader) * time_per_batch / 60)) print(mn) print('-----------', flush=True) start = time.time() return pd.concat(tr, axis=1) def train_batch(b): """ :param b: contains: :param imgs: the image, [batch_size, 3, IM_SIZE, IM_SIZE] :param all_anchors: [num_anchors, 4] the boxes of all anchors that we'll be using :param all_anchor_inds: [num_anchors, 2] array of the indices into the concatenated RPN feature vector that give us all_anchors, each one (img_ind, fpn_idx) :param im_sizes: a [batch_size, 4] numpy array of (h, w, scale, num_good_anchors) for each image. :param num_anchors_per_img: int, number of anchors in total over the feature pyramid per img Training parameters: :param train_anchor_inds: a [num_train, 5] array of indices for the anchors that will be used to compute the training loss (img_ind, fpn_idx) :param gt_boxes: [num_gt, 4] GT boxes over the batch. :param gt_classes: [num_gt, 2] gt boxes where each one is (img_id, class) :return: """ result = detector[b] scores = result.od_obj_dists box_deltas = result.od_box_deltas labels = result.od_obj_labels roi_boxes = result.od_box_priors bbox_targets = result.od_box_targets rpn_scores = result.rpn_scores rpn_box_deltas = result.rpn_box_deltas # detector loss valid_inds = (labels.data != 0).nonzero().squeeze(1) fg_cnt = valid_inds.size(0) bg_cnt = labels.size(0) - fg_cnt class_loss = F.cross_entropy(scores, labels) # No gather_nd in pytorch so instead convert first 2 dims of tensor to 1d box_reg_mult = 2 * (1. / FG_FRACTION) * fg_cnt / (fg_cnt + bg_cnt + 1e-4) twod_inds = valid_inds * box_deltas.size(1) + labels[valid_inds].data box_loss = bbox_loss(roi_boxes[valid_inds], box_deltas.view(-1, 4)[twod_inds], bbox_targets[valid_inds]) * box_reg_mult loss = class_loss + box_loss # RPN loss if not conf.use_proposals: train_anchor_labels = b.train_anchor_labels[:, -1] train_anchors = b.train_anchors[:, :4] train_anchor_targets = b.train_anchors[:, 4:] train_valid_inds = (train_anchor_labels.data == 1).nonzero().squeeze(1) rpn_class_loss = F.cross_entropy(rpn_scores, train_anchor_labels) # print("{} fg {} bg, ratio of {:.3f} vs {:.3f}. RPN {}fg {}bg ratio of {:.3f} vs {:.3f}".format( # fg_cnt, bg_cnt, fg_cnt / (fg_cnt + bg_cnt + 1e-4), FG_FRACTION, # train_valid_inds.size(0), train_anchor_labels.size(0)-train_valid_inds.size(0), # train_valid_inds.size(0) / (train_anchor_labels.size(0) + 1e-4), RPN_FG_FRACTION), flush=True) rpn_box_mult = 2 * (1. / RPN_FG_FRACTION) * train_valid_inds.size(0) / (train_anchor_labels.size(0) + 1e-4) rpn_box_loss = bbox_loss(train_anchors[train_valid_inds], rpn_box_deltas[train_valid_inds], train_anchor_targets[train_valid_inds]) * rpn_box_mult loss += rpn_class_loss + rpn_box_loss res = pd.Series([rpn_class_loss.data[0], rpn_box_loss.data[0], class_loss.data[0], box_loss.data[0], loss.data[0]], ['rpn_class_loss', 'rpn_box_loss', 'class_loss', 'box_loss', 'total']) else: res = pd.Series([class_loss.data[0], box_loss.data[0], loss.data[0]], ['class_loss', 'box_loss', 'total']) optimizer.zero_grad() loss.backward() clip_grad_norm( [(n, p) for n, p in detector.named_parameters() if p.grad is not None], max_norm=conf.clip, clip=True) optimizer.step() return res def val_epoch(): detector.eval() # all_boxes is a list of length number-of-classes. # Each list element is a list of length number-of-images. # Each of those list elements is either an empty list [] # or a numpy array of detection. vr = [] for val_b, batch in enumerate(val_loader): vr.append(val_batch(val_b, batch)) vr = np.concatenate(vr, 0) if vr.shape[0] == 0: print("No detections anywhere") return 0.0 val_coco = val.coco coco_dt = val_coco.loadRes(vr) coco_eval = COCOeval(val_coco, coco_dt, 'bbox') coco_eval.params.imgIds = val.ids if conf.coco else [x for x in range(len(val))] coco_eval.evaluate() coco_eval.accumulate() coco_eval.summarize() mAp = coco_eval.stats[1] return mAp def val_batch(batch_num, b): result = detector[b] if result is None: return np.zeros((0, 7)) scores_np = result.obj_scores.data.cpu().numpy() cls_preds_np = result.obj_preds.data.cpu().numpy() boxes_np = result.boxes_assigned.data.cpu().numpy() im_inds_np = result.im_inds.data.cpu().numpy() im_scales = b.im_sizes.reshape((-1, 3))[:, 2] if conf.coco: boxes_np /= im_scales[im_inds_np][:, None] boxes_np[:, 2:4] = boxes_np[:, 2:4] - boxes_np[:, 0:2] + 1 cls_preds_np[:] = [val.ind_to_id[c_ind] for c_ind in cls_preds_np] im_inds_np[:] = [val.ids[im_ind + batch_num * conf.batch_size * conf.num_gpus] for im_ind in im_inds_np] else: boxes_np *= BOX_SCALE / IM_SCALE boxes_np[:, 2:4] = boxes_np[:, 2:4] - boxes_np[:, 0:2] + 1 im_inds_np += batch_num * conf.batch_size * conf.num_gpus return np.column_stack((im_inds_np, boxes_np, scores_np, cls_preds_np)) print("Training starts now!") for epoch in range(start_epoch + 1, start_epoch + 1 + conf.num_epochs): rez = train_epoch(epoch) print("overall{:2d}: ({:.3f})\n{}".format(epoch, rez.mean(1)['total'], rez.mean(1)), flush=True) mAp = val_epoch() scheduler.step(mAp) torch.save({ 'epoch': epoch, 'state_dict': detector.state_dict(), 'optimizer': optimizer.state_dict(), }, os.path.join(conf.save_dir, '{}-{}.tar'.format('coco' if conf.coco else 'vg', epoch))) ================================================ FILE: models/train_rels.py ================================================ """ Training script for scene graph detection. Integrated with my faster rcnn setup """ from dataloaders.visual_genome import VGDataLoader, VG import numpy as np from torch import optim import torch import pandas as pd import time import os from config import ModelConfig, BOX_SCALE, IM_SCALE from torch.nn import functional as F from lib.pytorch_misc import optimistic_restore, de_chunkize, clip_grad_norm from lib.evaluation.sg_eval import BasicSceneGraphEvaluator from lib.pytorch_misc import print_para from torch.optim.lr_scheduler import ReduceLROnPlateau conf = ModelConfig() if conf.model == 'motifnet': from lib.rel_model import RelModel elif conf.model == 'stanford': from lib.rel_model_stanford import RelModelStanford as RelModel else: raise ValueError() train, val, _ = VG.splits(num_val_im=conf.val_size, filter_duplicate_rels=True, use_proposals=conf.use_proposals, filter_non_overlap=conf.mode == 'sgdet') train_loader, val_loader = VGDataLoader.splits(train, val, mode='rel', batch_size=conf.batch_size, num_workers=conf.num_workers, num_gpus=conf.num_gpus) detector = RelModel(classes=train.ind_to_classes, rel_classes=train.ind_to_predicates, num_gpus=conf.num_gpus, mode=conf.mode, require_overlap_det=True, use_resnet=conf.use_resnet, order=conf.order, nl_edge=conf.nl_edge, nl_obj=conf.nl_obj, hidden_dim=conf.hidden_dim, use_proposals=conf.use_proposals, pass_in_obj_feats_to_decoder=conf.pass_in_obj_feats_to_decoder, pass_in_obj_feats_to_edge=conf.pass_in_obj_feats_to_edge, pooling_dim=conf.pooling_dim, rec_dropout=conf.rec_dropout, use_bias=conf.use_bias, use_tanh=conf.use_tanh, limit_vision=conf.limit_vision ) # Freeze the detector for n, param in detector.detector.named_parameters(): param.requires_grad = False print(print_para(detector), flush=True) def get_optim(lr): # Lower the learning rate on the VGG fully connected layers by 1/10th. It's a hack, but it helps # stabilize the models. fc_params = [p for n,p in detector.named_parameters() if n.startswith('roi_fmap') and p.requires_grad] non_fc_params = [p for n,p in detector.named_parameters() if not n.startswith('roi_fmap') and p.requires_grad] params = [{'params': fc_params, 'lr': lr / 10.0}, {'params': non_fc_params}] # params = [p for n,p in detector.named_parameters() if p.requires_grad] if conf.adam: optimizer = optim.Adam(params, weight_decay=conf.l2, lr=lr, eps=1e-3) else: optimizer = optim.SGD(params, weight_decay=conf.l2, lr=lr, momentum=0.9) scheduler = ReduceLROnPlateau(optimizer, 'max', patience=3, factor=0.1, verbose=True, threshold=0.0001, threshold_mode='abs', cooldown=1) return optimizer, scheduler ckpt = torch.load(conf.ckpt) if conf.ckpt.split('-')[-2].split('/')[-1] == 'vgrel': print("Loading EVERYTHING") start_epoch = ckpt['epoch'] if not optimistic_restore(detector, ckpt['state_dict']): start_epoch = -1 # optimistic_restore(detector.detector, torch.load('checkpoints/vgdet/vg-28.tar')['state_dict']) else: start_epoch = -1 optimistic_restore(detector.detector, ckpt['state_dict']) detector.roi_fmap[1][0].weight.data.copy_(ckpt['state_dict']['roi_fmap.0.weight']) detector.roi_fmap[1][3].weight.data.copy_(ckpt['state_dict']['roi_fmap.3.weight']) detector.roi_fmap[1][0].bias.data.copy_(ckpt['state_dict']['roi_fmap.0.bias']) detector.roi_fmap[1][3].bias.data.copy_(ckpt['state_dict']['roi_fmap.3.bias']) detector.roi_fmap_obj[0].weight.data.copy_(ckpt['state_dict']['roi_fmap.0.weight']) detector.roi_fmap_obj[3].weight.data.copy_(ckpt['state_dict']['roi_fmap.3.weight']) detector.roi_fmap_obj[0].bias.data.copy_(ckpt['state_dict']['roi_fmap.0.bias']) detector.roi_fmap_obj[3].bias.data.copy_(ckpt['state_dict']['roi_fmap.3.bias']) detector.cuda() def train_epoch(epoch_num): detector.train() tr = [] start = time.time() for b, batch in enumerate(train_loader): tr.append(train_batch(batch, verbose=b % (conf.print_interval*10) == 0)) #b == 0)) if b % conf.print_interval == 0 and b >= conf.print_interval: mn = pd.concat(tr[-conf.print_interval:], axis=1).mean(1) time_per_batch = (time.time() - start) / conf.print_interval print("\ne{:2d}b{:5d}/{:5d} {:.3f}s/batch, {:.1f}m/epoch".format( epoch_num, b, len(train_loader), time_per_batch, len(train_loader) * time_per_batch / 60)) print(mn) print('-----------', flush=True) start = time.time() return pd.concat(tr, axis=1) def train_batch(b, verbose=False): """ :param b: contains: :param imgs: the image, [batch_size, 3, IM_SIZE, IM_SIZE] :param all_anchors: [num_anchors, 4] the boxes of all anchors that we'll be using :param all_anchor_inds: [num_anchors, 2] array of the indices into the concatenated RPN feature vector that give us all_anchors, each one (img_ind, fpn_idx) :param im_sizes: a [batch_size, 4] numpy array of (h, w, scale, num_good_anchors) for each image. :param num_anchors_per_img: int, number of anchors in total over the feature pyramid per img Training parameters: :param train_anchor_inds: a [num_train, 5] array of indices for the anchors that will be used to compute the training loss (img_ind, fpn_idx) :param gt_boxes: [num_gt, 4] GT boxes over the batch. :param gt_classes: [num_gt, 2] gt boxes where each one is (img_id, class) :return: """ result = detector[b] losses = {} losses['class_loss'] = F.cross_entropy(result.rm_obj_dists, result.rm_obj_labels) losses['rel_loss'] = F.cross_entropy(result.rel_dists, result.rel_labels[:, -1]) loss = sum(losses.values()) optimizer.zero_grad() loss.backward() clip_grad_norm( [(n, p) for n, p in detector.named_parameters() if p.grad is not None], max_norm=conf.clip, verbose=verbose, clip=True) losses['total'] = loss optimizer.step() res = pd.Series({x: y.data[0] for x, y in losses.items()}) return res def val_epoch(): detector.eval() evaluator = BasicSceneGraphEvaluator.all_modes() for val_b, batch in enumerate(val_loader): val_batch(conf.num_gpus * val_b, batch, evaluator) evaluator[conf.mode].print_stats() return np.mean(evaluator[conf.mode].result_dict[conf.mode + '_recall'][100]) def val_batch(batch_num, b, evaluator): det_res = detector[b] if conf.num_gpus == 1: det_res = [det_res] for i, (boxes_i, objs_i, obj_scores_i, rels_i, pred_scores_i) in enumerate(det_res): gt_entry = { 'gt_classes': val.gt_classes[batch_num + i].copy(), 'gt_relations': val.relationships[batch_num + i].copy(), 'gt_boxes': val.gt_boxes[batch_num + i].copy(), } assert np.all(objs_i[rels_i[:, 0]] > 0) and np.all(objs_i[rels_i[:, 1]] > 0) pred_entry = { 'pred_boxes': boxes_i * BOX_SCALE/IM_SCALE, 'pred_classes': objs_i, 'pred_rel_inds': rels_i, 'obj_scores': obj_scores_i, 'rel_scores': pred_scores_i, # hack for now. } evaluator[conf.mode].evaluate_scene_graph_entry( gt_entry, pred_entry, ) print("Training starts now!") optimizer, scheduler = get_optim(conf.lr * conf.num_gpus * conf.batch_size) for epoch in range(start_epoch + 1, start_epoch + 1 + conf.num_epochs): rez = train_epoch(epoch) print("overall{:2d}: ({:.3f})\n{}".format(epoch, rez.mean(1)['total'], rez.mean(1)), flush=True) if conf.save_dir is not None: torch.save({ 'epoch': epoch, 'state_dict': detector.state_dict(), #{k:v for k,v in detector.state_dict().items() if not k.startswith('detector.')}, # 'optimizer': optimizer.state_dict(), }, os.path.join(conf.save_dir, '{}-{}.tar'.format('vgrel', epoch))) mAp = val_epoch() scheduler.step(mAp) if any([pg['lr'] <= (conf.lr * conf.num_gpus * conf.batch_size)/99.0 for pg in optimizer.param_groups]): print("exiting training early", flush=True) break ================================================ FILE: scripts/eval_models_sgcls.sh ================================================ #!/usr/bin/env bash # This is a script that will evaluate all models for SGCLS export CUDA_VISIBLE_DEVICES=$1 if [ $1 == "0" ]; then echo "EVALING THE BASELINE" python models/eval_rels.py -m sgcls -model motifnet -nl_obj 0 -nl_edge 0 -b 6 \ -clip 5 -p 100 -pooling_dim 4096 -lr 1e-3 -ngpu 1 -ckpt checkpoints/baseline-sgcls/vgrel-11.tar \ -nepoch 50 -use_bias -test -cache baseline_sgcls python models/eval_rels.py -m predcls -model motifnet -nl_obj 0 -nl_edge 0 -b 6 \ -clip 5 -p 100 -pooling_dim 4096 -lr 1e-3 -ngpu 1 -ckpt checkpoints/baseline-sgcls/vgrel-11.tar \ -nepoch 50 -use_bias -test -cache baseline_predcls elif [ $1 == "1" ]; then echo "EVALING MESSAGE PASSING" python models/eval_rels.py -m sgcls -model stanford -b 6 -p 100 -lr 1e-3 -ngpu 1 -clip 5 \ -ckpt checkpoints/stanford-sgcls/vgrel-11.tar -test -cache stanford_sgcls python models/eval_rels.py -m predcls -model stanford -b 6 -p 100 -lr 1e-3 -ngpu 1 -clip 5 \ -ckpt checkpoints/stanford-sgcls/vgrel-11.tar -test -cache stanford_predcls elif [ $1 == "2" ]; then echo "EVALING MOTIFNET" python models/eval_rels.py -m sgcls -model motifnet -order leftright -nl_obj 2 -nl_edge 4 -b 6 -clip 5 \ -p 100 -hidden_dim 512 -pooling_dim 4096 -lr 1e-3 -ngpu 1 -test -ckpt checkpoints/motifnet-sgcls/vgrel-7.tar -nepoch 50 -use_bias -cache motifnet_sgcls python models/eval_rels.py -m predcls -model motifnet -order leftright -nl_obj 2 -nl_edge 4 -b 6 -clip 5 \ -p 100 -hidden_dim 512 -pooling_dim 4096 -lr 1e-3 -ngpu 1 -test -ckpt checkpoints/motifnet-sgcls/vgrel-7.tar -nepoch 50 -use_bias -cache motifnet_predcls fi ================================================ FILE: scripts/eval_models_sgdet.sh ================================================ #!/usr/bin/env bash # This is a script that will evaluate all the models for SGDET export CUDA_VISIBLE_DEVICES=$1 if [ $1 == "0" ]; then echo "EVALING THE BASELINE" python models/eval_rels.py -m sgdet -model motifnet -nl_obj 0 -nl_edge 0 -b 6 \ -clip 5 -p 100 -pooling_dim 4096 -ngpu 1 -ckpt checkpoints/baseline-sgdet/vgrel-17.tar \ -nepoch 50 -use_bias -cache baseline_sgdet.pkl -test elif [ $1 == "1" ]; then echo "EVALING MESSAGE PASSING" python models/eval_rels.py -m sgdet -model stanford -b 6 -p 100 -lr 1e-3 -ngpu 1 -clip 5 \ -ckpt checkpoints/stanford-sgdet/vgrel-18.tar -cache stanford_sgdet.pkl -test elif [ $1 == "2" ]; then echo "EVALING MOTIFNET" python models/eval_rels.py -m sgdet -model motifnet -order leftright -nl_obj 2 -nl_edge 4 -b 6 -clip 5 \ -p 100 -hidden_dim 512 -pooling_dim 4096 -lr 1e-3 -ngpu 1 -test -ckpt checkpoints/motifnet-sgdet/vgrel-14.tar -nepoch 50 -cache motifnet_sgdet.pkl -use_bias fi ================================================ FILE: scripts/pretrain_detector.sh ================================================ #!/usr/bin/env bash # Train the model without COCO pretraining python models/train_detector.py -b 6 -lr 1e-3 -save_dir checkpoints/vgdet -nepoch 50 -ngpu 3 -nwork 3 -p 100 -clip 5 # If you want to evaluate on the frequency baseline now, run this command (replace the checkpoint with the # best checkpoint you found). #export CUDA_VISIBLE_DEVICES=0 #python models/eval_rel_count.py -ngpu 1 -b 6 -ckpt checkpoints/vgdet/vg-24.tar -nwork 1 -p 100 -test #export CUDA_VISIBLE_DEVICES=1 #python models/eval_rel_count.py -ngpu 1 -b 6 -ckpt checkpoints/vgdet/vg-28.tar -nwork 1 -p 100 -test #export CUDA_VISIBLE_DEVICES=2 #python models/eval_rel_count.py -ngpu 1 -b 6 -ckpt checkpoints/vgdet/vg-28.tar -nwork 1 -p 100 -test # # ================================================ FILE: scripts/refine_for_detection.sh ================================================ #!/usr/bin/env bash # Refine Motifnet for detection export CUDA_VISIBLE_DEVICES=$1 if [ $1 == "0" ]; then echo "TRAINING THE BASELINE" python models/train_rels.py -m sgdet -model motifnet -nl_obj 0 -nl_edge 0 -b 6 \ -clip 5 -p 100 -pooling_dim 4096 -lr 1e-4 -ngpu 1 -ckpt checkpoints/baseline-sgcls/vgrel-11.tar -save_dir checkpoints/baseline-sgdet \ -nepoch 50 -use_bias elif [ $1 == "1" ]; then echo "TRAINING STANFORD" python models/train_rels.py -m sgdet -model stanford -b 6 -p 100 -lr 1e-4 -ngpu 1 -clip 5 \ -ckpt checkpoints/stanford-sgcls/vgrel-11.tar -save_dir checkpoints/stanford-sgdet elif [ $1 == "2" ]; then echo "Refining Motifnet for detection!" python models/train_rels.py -m sgdet -model motifnet -order leftright -nl_obj 2 -nl_edge 4 -b 6 -clip 5 \ -p 100 -hidden_dim 512 -pooling_dim 4096 -lr 1e-4 -ngpu 1 -ckpt checkpoints/motifnet-sgcls/vgrel-7.tar \ -save_dir checkpoints/motifnet-sgdet -nepoch 10 -use_bias fi ================================================ FILE: scripts/train_models_sgcls.sh ================================================ #!/usr/bin/env bash # This is a script that will train all of the models for scene graph classification and then evaluate them. export CUDA_VISIBLE_DEVICES=$1 if [ $1 == "0" ]; then echo "TRAINING THE BASELINE" python models/train_rels.py -m sgcls -model motifnet -nl_obj 0 -nl_edge 0 -b 6 \ -clip 5 -p 100 -pooling_dim 4096 -lr 1e-3 -ngpu 1 -ckpt checkpoints/vgdet/vg-24.tar -save_dir checkpoints/baseline2 \ -nepoch 50 -use_bias elif [ $1 == "1" ]; then echo "TRAINING MESSAGE PASSING" python models/train_rels.py -m sgcls -model stanford -b 6 -p 100 -lr 1e-3 -ngpu 1 -clip 5 \ -ckpt checkpoints/vgdet/vg-24.tar -save_dir checkpoints/stanford2 elif [ $1 == "2" ]; then echo "TRAINING MOTIFNET" python models/train_rels.py -m sgcls -model motifnet -order leftright -nl_obj 2 -nl_edge 4 -b 6 -clip 5 \ -p 100 -hidden_dim 512 -pooling_dim 4096 -lr 1e-3 -ngpu 1 -ckpt checkpoints/vgdet/vg-24.tar \ -save_dir checkpoints/motifnet2 -nepoch 50 -use_bias fi ================================================ FILE: scripts/train_motifnet.sh ================================================ #!/usr/bin/env bash # Train Motifnet using different orderings export CUDA_VISIBLE_DEVICES=$1 if [ $1 == "0" ]; then echo "TRAINING MOTIFNET V1" python models/train_rels.py -m sgcls -model motifnet -order size -nl_obj 2 -nl_edge 4 -b 6 -clip 5 \ -p 100 -hidden_dim 512 -pooling_dim 4096 -lr 1e-3 -ngpu 1 -ckpt checkpoints/vgdet/vg-24.tar \ -save_dir checkpoints/motifnet-size-sgcls -nepoch 50 -use_bias elif [ $1 == "1" ]; then echo "TRAINING MOTIFNET V2" python models/train_rels.py -m sgcls -model motifnet -order random -nl_obj 2 -nl_edge 4 -b 6 -clip 5 \ -p 100 -hidden_dim 512 -pooling_dim 4096 -lr 1e-3 -ngpu 1 -ckpt checkpoints/vgdet/vg-24.tar \ -save_dir checkpoints/motifnet-random-sgcls -nepoch 50 -use_bias elif [ $1 == "2" ]; then echo "TRAINING MOTIFNET V3" python models/train_rels.py -m sgcls -model motifnet -order confidence -nl_obj 2 -nl_edge 4 -b 6 -clip 5 \ -p 100 -hidden_dim 512 -pooling_dim 4096 -lr 1e-3 -ngpu 1 -ckpt checkpoints/vgdet/vg-24.tar \ -save_dir checkpoints/motifnet-conf-sgcls -nepoch 50 -use_bias fi ================================================ FILE: scripts/train_stanford.sh ================================================ #!/usr/bin/env bash python models/train_rels.py -m sgcls -model stanford -b 4 -p 400 -lr 1e-4 -ngpu 1 -ckpt checkpoints/vgdet/vg-24.tar -save_dir checkpoints/stanford -adam # To test you can run this command # python models/eval_rels.py -m sgcls -model stanford -ngpu 1 -ckpt checkpoints/stanford/vgrel-28.tar -test