Пример #1
0
    def test_table_caching(self):
        fd, tmp_cache = tempfile.mkstemp()
        os.close(fd)
        os.remove(tmp_cache)

        try:
            i = MemoryDescriptorIndex(tmp_cache)
            descrs = [random_descriptor() for _ in xrange(3)]
            expected_cache = dict((r.uuid(), r) for r in descrs)

            # cache should not exist yet
            ntools.assert_false(os.path.isfile(tmp_cache))

            # Should write file and should be a dictionary of 3
            # elements
            i.add_many_descriptors(descrs)
            ntools.assert_true(os.path.isfile(tmp_cache))
            with open(tmp_cache) as f:
                ntools.assert_equal(cPickle.load(f), expected_cache)

            # Changing the internal table (remove, add) it should reflect in
            # cache
            new_d = random_descriptor()
            i.add_descriptor(new_d)
            expected_cache[new_d.uuid()] = new_d
            with open(tmp_cache) as f:
                ntools.assert_equal(cPickle.load(f), expected_cache)

            rm_d = expected_cache.values()[0]
            i.remove_descriptor(rm_d.uuid())
            del expected_cache[rm_d.uuid()]
            with open(tmp_cache) as f:
                ntools.assert_equal(cPickle.load(f), expected_cache)
        finally:
            os.remove(tmp_cache)
Пример #2
0
    def test_added_descriptor_table_caching(self):
        cache_elem = DataMemoryElement(readonly=False)
        descrs = [random_descriptor() for _ in range(3)]
        expected_table = dict((r.uuid(), r) for r in descrs)

        i = MemoryDescriptorIndex(cache_elem)
        self.assertTrue(cache_elem.is_empty())

        # Should add descriptors to table, caching to writable element.
        i.add_many_descriptors(descrs)
        self.assertFalse(cache_elem.is_empty())
        self.assertEqual(pickle.loads(i.cache_element.get_bytes()),
                         expected_table)

        # Changing the internal table (remove, add) it should reflect in
        # cache
        new_d = random_descriptor()
        expected_table[new_d.uuid()] = new_d
        i.add_descriptor(new_d)
        self.assertEqual(pickle.loads(i.cache_element.get_bytes()),
                         expected_table)

        rm_d = list(expected_table.values())[0]
        del expected_table[rm_d.uuid()]
        i.remove_descriptor(rm_d.uuid())
        self.assertEqual(pickle.loads(i.cache_element.get_bytes()),
                         expected_table)
Пример #3
0
    def test_added_descriptor_table_caching(self):
        cache_elem = DataMemoryElement(readonly=False)
        descrs = [random_descriptor() for _ in range(3)]
        expected_table = dict((r.uuid(), r) for r in descrs)

        i = MemoryDescriptorIndex(cache_elem)
        ntools.assert_true(cache_elem.is_empty())

        # Should add descriptors to table, caching to writable element.
        i.add_many_descriptors(descrs)
        ntools.assert_false(cache_elem.is_empty())
        ntools.assert_equal(pickle.loads(i.cache_element.get_bytes()),
                            expected_table)

        # Changing the internal table (remove, add) it should reflect in
        # cache
        new_d = random_descriptor()
        expected_table[new_d.uuid()] = new_d
        i.add_descriptor(new_d)
        ntools.assert_equal(pickle.loads(i.cache_element.get_bytes()),
                            expected_table)

        rm_d = expected_table.values()[0]
        del expected_table[rm_d.uuid()]
        i.remove_descriptor(rm_d.uuid())
        ntools.assert_equal(pickle.loads(i.cache_element.get_bytes()),
                            expected_table)
Пример #4
0
    def test_has(self):
        i = MemoryDescriptorIndex()
        descrs = [random_descriptor() for _ in xrange(10)]
        i.add_many_descriptors(descrs)

        ntools.assert_true(i.has_descriptor(descrs[4].uuid()))
        ntools.assert_false(i.has_descriptor('not_an_int'))
Пример #5
0
    def test_has(self):
        i = MemoryDescriptorIndex()
        descrs = [random_descriptor() for _ in range(10)]
        i.add_many_descriptors(descrs)

        ntools.assert_true(i.has_descriptor(descrs[4].uuid()))
        ntools.assert_false(i.has_descriptor('not_an_int'))
Пример #6
0
    def test_clear(self):
        i = MemoryDescriptorIndex()
        n = 10

        descrs = [random_descriptor() for _ in range(n)]
        i.add_many_descriptors(descrs)
        ntools.assert_equal(len(i), n)
        i.clear()
        ntools.assert_equal(len(i), 0)
        ntools.assert_equal(i._table, {})
Пример #7
0
    def test_clear(self):
        i = MemoryDescriptorIndex()
        n = 10

        descrs = [random_descriptor() for _ in xrange(n)]
        i.add_many_descriptors(descrs)
        ntools.assert_equal(len(i), n)
        i.clear()
        ntools.assert_equal(len(i), 0)
        ntools.assert_equal(i._table, {})
Пример #8
0
    def test_update_index_existing_descriptors_frozenset(self):
        """
        Same as ``test_update_index_similar_descriptors`` but testing that
        we can update the index when seeded with structures with existing
        values.
        """
        # Similar Descriptors to build and update on (different instances)
        descriptors1 = [
            DescriptorMemoryElement('t', 0).set_vector([0]),
            DescriptorMemoryElement('t', 1).set_vector([1]),
            DescriptorMemoryElement('t', 2).set_vector([2]),
            DescriptorMemoryElement('t', 3).set_vector([3]),
            DescriptorMemoryElement('t', 4).set_vector([4]),
        ]
        descriptors2 = [
            DescriptorMemoryElement('t', 5).set_vector([0]),
            DescriptorMemoryElement('t', 6).set_vector([1]),
            DescriptorMemoryElement('t', 7).set_vector([2]),
            DescriptorMemoryElement('t', 8).set_vector([3]),
            DescriptorMemoryElement('t', 9).set_vector([4]),
        ]

        descr_index = MemoryDescriptorIndex()
        descr_index.add_many_descriptors(descriptors1)

        hash_kvs = MemoryKeyValueStore()
        hash_kvs.add(0, frozenset({0}))
        hash_kvs.add(1, frozenset({1}))
        hash_kvs.add(2, frozenset({2}))
        hash_kvs.add(3, frozenset({3}))
        hash_kvs.add(4, frozenset({4}))

        index = LSHNearestNeighborIndex(DummyHashFunctor(),
                                        descr_index, hash_kvs)
        index.update_index(descriptors2)

        assert descr_index.count() == 10
        # Above descriptors should be considered "in" the descriptor set now.
        for d in descriptors1:
            assert d in descr_index
        for d in descriptors2:
            assert d in descr_index
        # Known hashes of the above descriptors should be in the KVS
        assert set(hash_kvs.keys()) == {0, 1, 2, 3, 4}
        assert hash_kvs.get(0) == {0, 5}
        assert hash_kvs.get(1) == {1, 6}
        assert hash_kvs.get(2) == {2, 7}
        assert hash_kvs.get(3) == {3, 8}
        assert hash_kvs.get(4) == {4, 9}
Пример #9
0
    def test_update_index_existing_descriptors_frozenset(self):
        """
        Same as ``test_update_index_similar_descriptors`` but testing that
        we can update the index when seeded with structures with existing
        values.
        """
        # Similar Descriptors to build and update on (different instances)
        descriptors1 = [
            DescriptorMemoryElement('t', 0).set_vector([0]),
            DescriptorMemoryElement('t', 1).set_vector([1]),
            DescriptorMemoryElement('t', 2).set_vector([2]),
            DescriptorMemoryElement('t', 3).set_vector([3]),
            DescriptorMemoryElement('t', 4).set_vector([4]),
        ]
        descriptors2 = [
            DescriptorMemoryElement('t', 5).set_vector([0]),
            DescriptorMemoryElement('t', 6).set_vector([1]),
            DescriptorMemoryElement('t', 7).set_vector([2]),
            DescriptorMemoryElement('t', 8).set_vector([3]),
            DescriptorMemoryElement('t', 9).set_vector([4]),
        ]

        descr_index = MemoryDescriptorIndex()
        descr_index.add_many_descriptors(descriptors1)

        hash_kvs = MemoryKeyValueStore()
        hash_kvs.add(0, frozenset({0}))
        hash_kvs.add(1, frozenset({1}))
        hash_kvs.add(2, frozenset({2}))
        hash_kvs.add(3, frozenset({3}))
        hash_kvs.add(4, frozenset({4}))

        index = LSHNearestNeighborIndex(DummyHashFunctor(), descr_index,
                                        hash_kvs)
        index.update_index(descriptors2)

        assert descr_index.count() == 10
        # Above descriptors should be considered "in" the descriptor set now.
        for d in descriptors1:
            assert d in descr_index
        for d in descriptors2:
            assert d in descr_index
        # Known hashes of the above descriptors should be in the KVS
        assert set(hash_kvs.keys()) == {0, 1, 2, 3, 4}
        assert hash_kvs.get(0) == {0, 5}
        assert hash_kvs.get(1) == {1, 6}
        assert hash_kvs.get(2) == {2, 7}
        assert hash_kvs.get(3) == {3, 8}
        assert hash_kvs.get(4) == {4, 9}
Пример #10
0
    def test_count(self):
        index = MemoryDescriptorIndex()
        self.assertEqual(index.count(), 0)

        d1 = random_descriptor()
        index.add_descriptor(d1)
        self.assertEqual(index.count(), 1)

        d2, d3, d4 = (random_descriptor(), random_descriptor(),
                      random_descriptor())
        index.add_many_descriptors([d2, d3, d4])
        self.assertEqual(index.count(), 4)

        d5 = random_descriptor()
        index.add_descriptor(d5)
        self.assertEqual(index.count(), 5)
Пример #11
0
    def test_count(self):
        index = MemoryDescriptorIndex()
        ntools.assert_equal(index.count(), 0)

        d1 = random_descriptor()
        index.add_descriptor(d1)
        ntools.assert_equal(index.count(), 1)

        d2, d3, d4 = random_descriptor(), random_descriptor(
        ), random_descriptor()
        index.add_many_descriptors([d2, d3, d4])
        ntools.assert_equal(index.count(), 4)

        d5 = random_descriptor()
        index.add_descriptor(d5)
        ntools.assert_equal(index.count(), 5)
Пример #12
0
    def test_count(self):
        index = MemoryDescriptorIndex()
        self.assertEqual(index.count(), 0)

        d1 = random_descriptor()
        index.add_descriptor(d1)
        self.assertEqual(index.count(), 1)

        d2, d3, d4 = (random_descriptor(),
                      random_descriptor(),
                      random_descriptor())
        index.add_many_descriptors([d2, d3, d4])
        self.assertEqual(index.count(), 4)

        d5 = random_descriptor()
        index.add_descriptor(d5)
        self.assertEqual(index.count(), 5)
Пример #13
0
    def test_remove(self):
        i = MemoryDescriptorIndex()
        descrs = [random_descriptor() for _ in range(100)]
        i.add_many_descriptors(descrs)
        ntools.assert_equal(len(i), 100)
        ntools.assert_equal(list(i.iterdescriptors()), descrs)

        # remove singles
        i.remove_descriptor(descrs[0].uuid())
        ntools.assert_equal(len(i), 99)
        ntools.assert_equal(set(i.iterdescriptors()), set(descrs[1:]))

        # remove many
        rm_d = descrs[slice(45, 80, 3)]
        i.remove_many_descriptors((d.uuid() for d in rm_d))
        ntools.assert_equal(len(i), 99 - len(rm_d))
        ntools.assert_equal(set(i.iterdescriptors()),
                            set(descrs[1:]).difference(rm_d))
Пример #14
0
    def test_remove(self):
        i = MemoryDescriptorIndex()
        descrs = [random_descriptor() for _ in xrange(100)]
        i.add_many_descriptors(descrs)
        ntools.assert_equal(len(i), 100)
        ntools.assert_equal(list(i.iterdescriptors()), descrs)

        # remove singles
        i.remove_descriptor(descrs[0].uuid())
        ntools.assert_equal(len(i), 99)
        ntools.assert_equal(set(i.iterdescriptors()),
                            set(descrs[1:]))

        # remove many
        rm_d = descrs[slice(45, 80, 3)]
        i.remove_many_descriptors((d.uuid() for d in rm_d))
        ntools.assert_equal(len(i), 99 - len(rm_d))
        ntools.assert_equal(set(i.iterdescriptors()),
                            set(descrs[1:]).difference(rm_d))
Пример #15
0
    def test_get_descriptors(self):
        descrs = [
            random_descriptor(),  # [0]
            random_descriptor(),  # [1]
            random_descriptor(),  # [2]
            random_descriptor(),  # [3]
            random_descriptor(),  # [4]
        ]
        index = MemoryDescriptorIndex()
        index.add_many_descriptors(descrs)

        # single descriptor reference
        r = index.get_descriptor(descrs[1].uuid())
        ntools.assert_equal(r, descrs[1])

        # multiple descriptor reference
        r = list(
            index.get_many_descriptors([descrs[0].uuid(), descrs[3].uuid()]))
        ntools.assert_equal(len(r), 2)
        ntools.assert_equal(set(r), {descrs[0], descrs[3]})
Пример #16
0
    def test_add_many(self):
        descrs = [
            random_descriptor(),
            random_descriptor(),
            random_descriptor(),
            random_descriptor(),
            random_descriptor(),
        ]
        index = MemoryDescriptorIndex()
        index.add_many_descriptors(descrs)

        # Compare code keys of input to code keys in internal table
        ntools.assert_equal(set(index._table.keys()),
                            set([e.uuid() for e in descrs]))

        # Get the set of descriptors in the internal table and compare it with
        # the set of generated random descriptors.
        r_set = set()
        [r_set.add(d) for d in index._table.values()]
        ntools.assert_equal(set([e for e in descrs]), r_set)
Пример #17
0
    def test_get_descriptors(self):
        descrs = [
            random_descriptor(),   # [0]
            random_descriptor(),   # [1]
            random_descriptor(),   # [2]
            random_descriptor(),   # [3]
            random_descriptor(),   # [4]
        ]
        index = MemoryDescriptorIndex()
        index.add_many_descriptors(descrs)

        # single descriptor reference
        r = index.get_descriptor(descrs[1].uuid())
        ntools.assert_equal(r, descrs[1])

        # multiple descriptor reference
        r = list(index.get_many_descriptors([descrs[0].uuid(),
                                             descrs[3].uuid()]))
        ntools.assert_equal(len(r), 2)
        ntools.assert_equal(set(r),
                            {descrs[0], descrs[3]})
Пример #18
0
    def test_table_caching(self):
        fd, tmp_cache = tempfile.mkstemp()
        os.close(fd)
        os.remove(tmp_cache)

        try:
            i = MemoryDescriptorIndex(tmp_cache)
            descrs = [random_descriptor() for _ in xrange(3)]
            expected_cache = dict((r.uuid(), r) for r in descrs)

            # cache should not exist yet
            ntools.assert_false(os.path.isfile(tmp_cache))

            # Should write file and should be a dictionary of 3
            # elements
            i.add_many_descriptors(descrs)
            ntools.assert_true(os.path.isfile(tmp_cache))
            with open(tmp_cache) as f:
                ntools.assert_equal(cPickle.load(f),
                                    expected_cache)

            # Changing the internal table (remove, add) it should reflect in
            # cache
            new_d = random_descriptor()
            i.add_descriptor(new_d)
            expected_cache[new_d.uuid()] = new_d
            with open(tmp_cache) as f:
                ntools.assert_equal(cPickle.load(f),
                                    expected_cache)

            rm_d = expected_cache.values()[0]
            i.remove_descriptor(rm_d.uuid())
            del expected_cache[rm_d.uuid()]
            with open(tmp_cache) as f:
                ntools.assert_equal(cPickle.load(f),
                                    expected_cache)
        finally:
            os.remove(tmp_cache)
Пример #19
0
    def test_add_many(self):
        descrs = [
            random_descriptor(),
            random_descriptor(),
            random_descriptor(),
            random_descriptor(),
            random_descriptor(),
        ]
        index = MemoryDescriptorIndex()
        index.add_many_descriptors(descrs)

        # Compare code keys of input to code keys in internal table
        ntools.assert_equal(set(index._table.keys()),
                            set([e.uuid() for e in descrs]))

        # Get the set of descriptors in the internal table and compare it with
        # the set of generated random descriptors.
        r_set = set()
        [r_set.add(d) for d in index._table.values()]
        ntools.assert_equal(
            set([e for e in descrs]),
            r_set
        )
Пример #20
0
d_to_proc = set()
for data in eval_data_set:
    if not img_prob_descr_index.has_descriptor(data.uuid()):
        d_to_proc.add(data)
    else:
        eval_data2descr[data] = img_prob_descr_index[data.uuid()]
if d_to_proc:
    eval_data2descr.update(img_prob_gen.compute_descriptor_async(d_to_proc))
    d_to_proc.clear()
assert len(eval_data2descr) == eval_data_set.count()

index_additions = []
for data in d_to_proc:
    index_additions.append(eval_data2descr[data])
print "Adding %d new descriptors to prob index" % len(index_additions)
img_prob_descr_index.add_many_descriptors(index_additions)

eval_descr2class = img_prob_classifier.classify_async(eval_data2descr.values(),
                                                      img_c_mem_factory)

###############################################################################

# The shas that were actually computed
computed_shas = {e.uuid() for e in eval_data2descr}
len(computed_shas)

cluster2ads = collections.defaultdict(set)
cluster2shas = collections.defaultdict(set)
ad2shas = collections.defaultdict(set)
sha2ads = collections.defaultdict(set)
with open(EVAL_CLUSTERS_ADS_IMAGES_CSV) as f:
Пример #21
0
class IqrSession(SmqtkObject):
    """
    Encapsulation of IQR Session related data structures with a centralized lock
    for multi-thread access.

    This object is compatible with the python with-statement, so when elements
    are to be used or modified, it should be within a with-block so race
    conditions do not occur across threads/sub-processes.

    """
    @property
    def _log(self):
        return logging.getLogger('.'.join((self.__module__,
                                           self.__class__.__name__)) +
                                 "[%s]" % self.uuid)

    def __init__(self,
                 pos_seed_neighbors=500,
                 rel_index_config=DFLT_REL_INDEX_CONFIG,
                 session_uid=None):
        """
        Initialize the IQR session

        This does not initialize the working index for ranking as there are no
        known positive descriptor examples at this time.

        Adjudications
        -------------
        Adjudications are carried through between initializations. This allows
        indexed material adjudicated through-out the lifetime of the session to
        stay relevant.

        :param pos_seed_neighbors: Number of neighbors to pull from the given
            ``nn_index`` for each positive exemplar when populating the working
            index, i.e. this value determines the size of the working index for
            IQR refinement. By default, we try to get 500 neighbors.

            Since there may be partial to significant overlap of near neighbors
            as a result of nn_index queries for positive exemplars, the working
            index may contain anywhere from this value's number of entries, to
            ``N*P``, where ``N`` is this value and ``P`` is the number of
            positive examples at the time of working index initialization.
        :type pos_seed_neighbors: int

        :param rel_index_config: Plugin configuration dictionary for the
            RelevancyIndex to use for ranking user adjudications. By default we
            we use an in-memory libSVM based index using the histogram
            intersection metric.
        :type rel_index_config: dict

        :param session_uid: Optional manual specification of session UUID.
        :type session_uid: str or uuid.UUID

        """
        self.uuid = session_uid or str(uuid.uuid1()).replace('-', '')
        self.lock = multiprocessing.RLock()

        self.pos_seed_neighbors = int(pos_seed_neighbors)

        # Local descriptor index for ranking, populated by a query to the
        #   nn_index instance.
        # Added external data/descriptors not added to this index.
        self.working_index = MemoryDescriptorIndex()

        # Book-keeping set so we know what positive descriptors
        # UUIDs we've used to query the neighbor index with already.
        #: :type: set[collections.Hashable]
        self._wi_seeds_used = set()

        # Descriptor references from our index (above) that have been
        #   adjudicated.
        #: :type: set[smqtk.representation.DescriptorElement]
        self.positive_descriptors = set()
        #: :type: set[smqtk.representation.DescriptorElement]
        self.negative_descriptors = set()

        # Mapping of a DescriptorElement in our relevancy search index (not the
        #   index that the nn_index uses) to the relevancy score given the
        #   recorded positive and negative adjudications.
        # This is None before any initialization or refinement occurs.
        #: :type: None | dict[smqtk.representation.DescriptorElement, float]
        self.results = None

        #
        # Algorithm Instances [+Config]
        #
        # RelevancyIndex configuration and instance that is used for producing
        #   results.
        # This is only [re]constructed when initializing the session.
        self.rel_index_config = rel_index_config
        # This is None until session initialization happens after pos/neg
        # exemplar data has been added.
        #: :type: None | smqtk.algorithms.relevancy_index.RelevancyIndex
        self.rel_index = None

    def __enter__(self):
        """
        :rtype: IqrSession
        """
        self.lock.acquire()
        return self

    # noinspection PyUnusedLocal
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.lock.release()

    def ordered_results(self):
        """
        Return a tuple of the current (id, probability) result pairs in
        order of probability score. If there are no results yet, None is
        returned.

        :rtype: None | tuple[(smqtk.representation.DescriptorElement, float)]

        """
        with self.lock:
            if self.results:
                return tuple(
                    sorted(self.results.iteritems(),
                           key=lambda p: p[1],
                           reverse=True))
            return None

    def adjudicate(self,
                   new_positives=(),
                   new_negatives=(),
                   un_positives=(),
                   un_negatives=()):
        """
        Update current state of working index positive and negative
        adjudications based on descriptor UUIDs.

        If the same descriptor element is listed in both new positives and
        negatives, they cancel each other out, causing that descriptor to not
        be included in the adjudication.

        The given iterables must be re-traversable. Otherwise the given
        descriptors will not be properly registered.

        :param new_positives: Descriptors of elements in our working index to
            now be considered to be positively relevant.
        :type new_positives: collections.Iterable[smqtk.representation.DescriptorElement]

        :param new_negatives: Descriptors of elements in our working index to
            now be considered to be negatively relevant.
        :type new_negatives: collections.Iterable[smqtk.representation.DescriptorElement]

        :param un_positives: Descriptors of elements in our working index to now
            be considered not positive any more.
        :type un_positives: collections.Iterable[smqtk.representation.DescriptorElement]

        :param un_negatives: Descriptors of elements in our working index to now
            be considered not negative any more.
        :type un_negatives: collections.Iterable[smqtk.representation.DescriptorElement]

        """
        with self.lock:
            self.positive_descriptors.update(new_positives)
            self.positive_descriptors.difference_update(un_positives)
            self.positive_descriptors.difference_update(new_negatives)

            self.negative_descriptors.update(new_negatives)
            self.negative_descriptors.difference_update(un_negatives)
            self.negative_descriptors.difference_update(new_positives)

    def update_working_index(self, nn_index):
        """
        Initialize or update our current working index using the given
        :class:`.NearestNeighborsIndex` instance given our current positively
        labeled descriptor elements.

        We only query from the index for new positive elements since the last
        update or reset.

        :param nn_index: :class:`.NearestNeighborsIndex` to query from.
        :type nn_index: smqtk.algorithms.NearestNeighborsIndex

        :raises RuntimeError: There are no positive example descriptors in this
            session to use as a basis for querying.

        """
        if len(self.positive_descriptors) <= 0:
            raise RuntimeError("No positive descriptors to query the neighbor "
                               "index with.")

        # Not clearing working index because this step is intended to be
        # additive.
        updated = False

        # adding to working index
        for p in self.positive_descriptors:
            if p.uuid() not in self._wi_seeds_used:
                self._log.info("Querying neighbors to: %s", p)
                self.working_index.add_many_descriptors(
                    nn_index.nn(p, n=self.pos_seed_neighbors)[0])
                self._wi_seeds_used.add(p.uuid())
                updated = True

        # Make new relevancy index
        if updated:
            self._log.info("Creating new relevancy index over working index.")
            #: :type: smqtk.algorithms.relevancy_index.RelevancyIndex
            self.rel_index = plugin.from_plugin_config(
                self.rel_index_config, get_relevancy_index_impls())
            self.rel_index.build_index(self.working_index.iterdescriptors())

    def refine(self):
        """ Refine current model results based on current adjudication state

        :raises RuntimeError: No working index has been initialized.
            :meth:`update_working_index` should have been called after
            adjudicating some positive examples.
        :raises RuntimeError: There are no adjudications to run on. We must
            have at least one positive adjudication.

        """
        with self.lock:
            if not self.rel_index:
                raise RuntimeError("No relevancy index yet. Must not have "
                                   "initialized session (no working index).")

            # fuse pos/neg adjudications + added positive data descriptors
            pos = self.positive_descriptors
            neg = self.negative_descriptors

            if not pos:
                raise RuntimeError("Did not find at least one positive "
                                   "adjudication.")

            element_probability_map = self.rel_index.rank(pos, neg)

            if self.results is None:
                self.results = IqrResultsDict()
            self.results.update(element_probability_map)

            # Force adjudicated positives and negatives to be probability 1 and
            # 0, respectively, since we want to control where they show up in
            # our results view.
            # - Not all pos/neg descriptors may be in our working index.
            for d in pos:
                if d in self.results:
                    self.results[d] = 1.0
            for d in neg:
                if d in self.results:
                    self.results[d] = 0.0

    def reset(self):
        """ Reset the IQR Search state

        No positive adjudications, reload original feature data

        """
        with self.lock:
            self.working_index.clear()
            self._wi_seeds_used.clear()
            self.positive_descriptors.clear()
            self.negative_descriptors.clear()

            self.rel_index = None
            self.results = None
Пример #22
0
 def test_iteritems(self):
     i = MemoryDescriptorIndex()
     descrs = [random_descriptor() for _ in xrange(100)]
     i.add_many_descriptors(descrs)
     ntools.assert_equal(set(i.iteritems()),
                         set((d.uuid(), d) for d in descrs))
Пример #23
0
 def test_iterkeys(self):
     i = MemoryDescriptorIndex()
     descrs = [random_descriptor() for _ in range(100)]
     i.add_many_descriptors(descrs)
     self.assertEqual(set(i.iterkeys()), set(d.uuid() for d in descrs))
Пример #24
0
 def test_iterdescrs(self):
     i = MemoryDescriptorIndex()
     descrs = [random_descriptor() for _ in range(100)]
     i.add_many_descriptors(descrs)
     self.assertEqual(set(i.iterdescriptors()),
                      set(descrs))
Пример #25
0
class IqrSession (SmqtkObject):
    """
    Encapsulation of IQR Session related data structures with a centralized lock
    for multi-thread access.

    This object is compatible with the python with-statement, so when elements
    are to be used or modified, it should be within a with-block so race
    conditions do not occur across threads/sub-processes.

    """

    @property
    def _log(self):
        return logging.getLogger(
            '.'.join((self.__module__, self.__class__.__name__)) +
            "[%s]" % self.uuid
        )

    def __init__(self, pos_seed_neighbors=500,
                 rel_index_config=DFLT_REL_INDEX_CONFIG,
                 session_uid=None):
        """
        Initialize the IQR session

        This does not initialize the working index for ranking as there are no
        known positive descriptor examples at this time.

        Adjudications
        -------------
        Adjudications are carried through between initializations. This allows
        indexed material adjudicated through-out the lifetime of the session to
        stay relevant.

        :param pos_seed_neighbors: Number of neighbors to pull from the given
            ``nn_index`` for each positive exemplar when populating the working
            index, i.e. this value determines the size of the working index for
            IQR refinement. By default, we try to get 500 neighbors.

            Since there may be partial to significant overlap of near neighbors
            as a result of nn_index queries for positive exemplars, the working
            index may contain anywhere from this value's number of entries, to
            ``N*P``, where ``N`` is this value and ``P`` is the number of
            positive examples at the time of working index initialization.
        :type pos_seed_neighbors: int

        :param rel_index_config: Plugin configuration dictionary for the
            RelevancyIndex to use for ranking user adjudications. By default we
            we use an in-memory libSVM based index using the histogram
            intersection metric.
        :type rel_index_config: dict

        :param session_uid: Optional manual specification of session UUID.
        :type session_uid: str | uuid.UUID

        """
        self.uuid = session_uid or str(uuid.uuid1()).replace('-', '')
        self.lock = threading.RLock()

        self.pos_seed_neighbors = int(pos_seed_neighbors)

        # Local descriptor index for ranking, populated by a query to the
        #   nn_index instance.
        # Added external data/descriptors not added to this index.
        self.working_index = MemoryDescriptorIndex()

        # Book-keeping set so we know what positive descriptors
        # UUIDs we've used to query the neighbor index with already.
        #: :type: set[collections.Hashable]
        self._wi_seeds_used = set()

        # Descriptor elements representing data from external sources.
        #: :type: set[smqtk.representation.DescriptorElement]
        self.external_positive_descriptors = set()
        #: :type: set[smqtk.representation.DescriptorElement]
        self.external_negative_descriptors = set()

        # Descriptor references from our index (above) that have been
        #   adjudicated.
        #: :type: set[smqtk.representation.DescriptorElement]
        self.positive_descriptors = set()
        #: :type: set[smqtk.representation.DescriptorElement]
        self.negative_descriptors = set()

        # Mapping of a DescriptorElement in our relevancy search index (not the
        #   index that the nn_index uses) to the relevancy score given the
        #   recorded positive and negative adjudications.
        # This is None before any initialization or refinement occurs.
        #: :type: None | dict[smqtk.representation.DescriptorElement, float]
        self.results = None

        #
        # Algorithm Instances [+Config]
        #
        # RelevancyIndex configuration and instance that is used for producing
        #   results.
        # This is only [re]constructed when initializing the session.
        self.rel_index_config = rel_index_config
        # This is None until session initialization happens after pos/neg
        # exemplar data has been added.
        #: :type: None | smqtk.algorithms.relevancy_index.RelevancyIndex
        self.rel_index = None

    def __enter__(self):
        """
        :rtype: IqrSession
        """
        self.lock.acquire()
        return self

    # noinspection PyUnusedLocal
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.lock.release()

    def ordered_results(self):
        """
        Return a tuple of the current (id, probability) result pairs in
        order of descending probability score. If there are no results yet, None
        is returned.

        :rtype: None | tuple[(smqtk.representation.DescriptorElement, float)]

        """
        with self.lock:
            if self.results:
                return tuple(sorted(six.iteritems(self.results),
                                    key=lambda p: p[1],
                                    reverse=True))
            return None

    def external_descriptors(self, positive=(), negative=()):
        """
        Add positive/negative descriptors from external data.

        These descriptors may not be a part of our working index.

        :param positive: Iterable of descriptors from external sources to
            consider positive examples.
        :type positive:
            collections.Iterable[smqtk.representation.DescriptorElement]

        :param negative: Iterable of descriptors from external sources to
            consider negative examples.
        :type negative:
            collections.Iterable[smqtk.representation.DescriptorElement]

        """
        positive = set(positive)
        negative = set(negative)
        with self.lock:
            self.external_positive_descriptors.update(positive)
            self.external_positive_descriptors.difference_update(negative)

            self.external_negative_descriptors.update(negative)
            self.external_negative_descriptors.difference_update(positive)

    def adjudicate(self, new_positives=(), new_negatives=(),
                   un_positives=(), un_negatives=()):
        """
        Update current state of working index positive and negative
        adjudications based on descriptor UUIDs.

        If the same descriptor element is listed in both new positives and
        negatives, they cancel each other out, causing that descriptor to not
        be included in the adjudication.

        The given iterables must be re-traversable. Otherwise the given
        descriptors will not be properly registered.

        :param new_positives: Descriptors of elements in our working index to
            now be considered to be positively relevant.
        :type new_positives:
            collections.Iterable[smqtk.representation.DescriptorElement]

        :param new_negatives: Descriptors of elements in our working index to
            now be considered to be negatively relevant.
        :type new_negatives:
            collections.Iterable[smqtk.representation.DescriptorElement]

        :param un_positives: Descriptors of elements in our working index to now
            be considered not positive any more.
        :type un_positives:
            collections.Iterable[smqtk.representation.DescriptorElement]

        :param un_negatives: Descriptors of elements in our working index to now
            be considered not negative any more.
        :type un_negatives:
            collections.Iterable[smqtk.representation.DescriptorElement]

        """
        new_positives = set(new_positives)
        new_negatives = set(new_negatives)
        un_positives = set(un_positives)
        un_negatives = set(un_negatives)

        with self.lock:
            self.positive_descriptors.update(new_positives)
            self.positive_descriptors.difference_update(un_positives)
            self.positive_descriptors.difference_update(new_negatives)

            self.negative_descriptors.update(new_negatives)
            self.negative_descriptors.difference_update(un_negatives)
            self.negative_descriptors.difference_update(new_positives)

    def update_working_index(self, nn_index):
        """
        Initialize or update our current working index using the given
        :class:`.NearestNeighborsIndex` instance given our current positively
        labeled descriptor elements.

        We only query from the index for new positive elements since the last
        update or reset.

        :param nn_index: :class:`.NearestNeighborsIndex` to query from.
        :type nn_index: smqtk.algorithms.NearestNeighborsIndex

        :raises RuntimeError: There are no positive example descriptors in this
            session to use as a basis for querying.

        """
        pos_examples = (self.external_positive_descriptors |
                        self.positive_descriptors)
        if len(pos_examples) == 0:
            raise RuntimeError("No positive descriptors to query the neighbor "
                               "index with.")

        # Not clearing working index because this step is intended to be
        # additive.
        updated = False

        # adding to working index
        self._log.info("Building working index using %d positive examples "
                       "(%d external, %d adjudicated)",
                       len(pos_examples),
                       len(self.external_positive_descriptors),
                       len(self.positive_descriptors))
        # TODO: parallel_map and reduce with merge-dict
        for p in pos_examples:
            if p.uuid() not in self._wi_seeds_used:
                self._log.debug("Querying neighbors to: %s", p)
                self.working_index.add_many_descriptors(
                    nn_index.nn(p, n=self.pos_seed_neighbors)[0]
                )
                self._wi_seeds_used.add(p.uuid())
                updated = True

        # Make new relevancy index
        if updated:
            self._log.info("Creating new relevancy index over working index.")
            #: :type: smqtk.algorithms.relevancy_index.RelevancyIndex
            self.rel_index = plugin.from_plugin_config(
                self.rel_index_config, get_relevancy_index_impls()
            )
            self.rel_index.build_index(self.working_index.iterdescriptors())

    def refine(self):
        """ Refine current model results based on current adjudication state

        :raises RuntimeError: No working index has been initialized.
            :meth:`update_working_index` should have been called after
            adjudicating some positive examples.
        :raises RuntimeError: There are no adjudications to run on. We must
            have at least one positive adjudication.

        """
        with self.lock:
            if not self.rel_index:
                raise RuntimeError("No relevancy index yet. Must not have "
                                   "initialized session (no working index).")

            # combine pos/neg adjudications + added external data descriptors
            pos = self.positive_descriptors | self.external_positive_descriptors
            neg = self.negative_descriptors | self.external_negative_descriptors

            if not pos:
                raise RuntimeError("Did not find at least one positive "
                                   "adjudication.")

            self._log.debug("Ranking working set with %d pos and %d neg total "
                            "examples.", len(pos), len(neg))
            element_probability_map = self.rel_index.rank(pos, neg)

            if self.results is None:
                self.results = IqrResultsDict()
            self.results.update(element_probability_map)

            # Force adjudicated positives and negatives to be probability 1 and
            # 0, respectively, since we want to control where they show up in
            # our results view.
            # - Not all pos/neg descriptors may be in our working index.
            for d in pos:
                if d in self.results:
                    self.results[d] = 1.0
            for d in neg:
                if d in self.results:
                    self.results[d] = 0.0

    def reset(self):
        """ Reset the IQR Search state

        No positive adjudications, reload original feature data

        """
        with self.lock:
            self.working_index.clear()
            self._wi_seeds_used.clear()
            self.positive_descriptors.clear()
            self.negative_descriptors.clear()
            self.external_positive_descriptors.clear()
            self.external_negative_descriptors.clear()

            self.rel_index = None
            self.results = None

    ###########################################################################
    # I/O Methods

    # I/O Constants. These should not be changed.
    STATE_ZIP_COMPRESSION = zipfile.ZIP_DEFLATED
    STATE_ZIP_FILENAME = "iqr_state.json"

    def get_state_bytes(self):
        """
        Get a byte representation of the current descriptor and adjudication
        state of this session.

        This does not encode current results or the relevancy index's state, but
        these can be reproduced with this state.

        :return: State representation bytes
        :rtype: bytes

        """
        def d_set_to_list(d_set):
            # Convert set of descriptors to list of tuples:
            #   [..., (uuid, type, vector), ...]
            return [(d.uuid(), d.type(), d.vector().tolist()) for d in d_set]

        with self:
            # Convert session descriptors into basic values.
            pos_d = d_set_to_list(self.positive_descriptors)
            neg_d = d_set_to_list(self.negative_descriptors)
            ext_pos_d = d_set_to_list(self.external_positive_descriptors)
            ext_neg_d = d_set_to_list(self.external_negative_descriptors)

        z_buffer = io.BytesIO()
        z = zipfile.ZipFile(z_buffer, 'w', self.STATE_ZIP_COMPRESSION)
        z.writestr(self.STATE_ZIP_FILENAME, json.dumps({
            'pos': pos_d,
            'neg': neg_d,
            'external_pos': ext_pos_d,
            'external_neg': ext_neg_d,
        }))
        z.close()
        return z_buffer.getvalue()

    def set_state_bytes(self, b, descriptor_factory):
        """
        Set this session's state to the given byte representation, resetting
        this session in the process.

        Bytes given must have been retrieved via a previous call to
        ``get_state_bytes`` otherwise this method will fail.

        Since this state may be completely different from the current state,
        this session is reset before applying the new state. Thus, any current
        ranking results are thrown away.

        :param b: Bytes to set this session's state to.
        :type b: bytes

        :param descriptor_factory: Descriptor element factory to use when
            generating descriptor elements from extracted data.
        :type descriptor_factory: smqtk.representation.DescriptorElementFactory

        :raises ValueError: The input bytes could not be loaded due to
            incompatibility.

        """
        z_buffer = io.BytesIO(b)
        z = zipfile.ZipFile(z_buffer, 'r', self.STATE_ZIP_COMPRESSION)
        if self.STATE_ZIP_FILENAME not in z.namelist():
            raise ValueError("Invalid bytes given, did not contain expected "
                             "zipped file name.")

        # Extract expected json file object
        state = json.loads(z.read(self.STATE_ZIP_FILENAME).decode())
        del z, z_buffer

        with self:
            self.reset()

            def load_descriptor(_uid, _type_str, vec_list):
                _e = descriptor_factory.new_descriptor(_type_str, _uid)
                if _e.has_vector():
                    assert _e.vector().tolist() == vec_list, \
                        "Found existing vector for UUID '%s' but vectors did " \
                        "not match."
                else:
                    _e.set_vector(vec_list)
                return _e

            # Read in raw descriptor data from the state, convert to descriptor
            # element, then store in our descriptor sets.
            for source, target in [(state['external_pos'],
                                    self.external_positive_descriptors),
                                   (state['external_neg'],
                                    self.external_negative_descriptors),
                                   (state['pos'], self.positive_descriptors),
                                   (state['neg'], self.negative_descriptors)]:
                for uid, type_str, vector_list in source:
                    e = load_descriptor(uid, type_str, vector_list)
                    target.add(e)
Пример #26
0
 def test_iteritems(self):
     i = MemoryDescriptorIndex()
     descrs = [random_descriptor() for _ in range(100)]
     i.add_many_descriptors(descrs)
     self.assertEqual(set(six.iteritems(i)),
                      set((d.uuid(), d) for d in descrs))
Пример #27
0
class IqrSession (SmqtkObject):
    """
    Encapsulation of IQR Session related data structures with a centralized lock
    for multi-thread access.

    This object is compatible with the python with-statement, so when elements
    are to be used or modified, it should be within a with-block so race
    conditions do not occur across threads/sub-processes.

    """

    @property
    def _log(self):
        return logging.getLogger(
            '.'.join((self.__module__, self.__class__.__name__)) +
            "[%s]" % self.uuid
        )

    def __init__(self, work_directory, descriptor, nn_index,
                 pos_seed_neighbors=500,
                 rel_index_config=DFLT_REL_INDEX_CONFIG,
                 descriptor_factory=DFLT_MEMORY_DESCR_FACTORY,
                 session_uid=None):
        """ Initialize the IQR session

        This does not initialize the working index for ranking as there are no
        known positive descriptor examples at this time.

        Adjudications
        -------------
        Adjudications are carried through between initializations. This allows
        indexed material adjudicated through-out the lifetime of the session to
        stay relevant.

        :param work_directory: Directory assigned to this session for temporary
            and working files.
        :type work_directory: str

        :param descriptor: Descriptor to use for this IQR session
        :type descriptor:
            smqtk.algorithms.descriptor_generator.DescriptorGenerator

        :param nn_index: NearestNeighborIndex to draw from when initializing IQR
            session.
        :type nn_index: smqtk.algorithms.nn_index.NearestNeighborsIndex

        :param pos_seed_neighbors: Number of neighbors to pull from the given
            ``nn_index`` for each positive exemplar when populating the working
            index, i.e. this value determines the size of the working index for
            IQR refinement. By default, we try to get 500 neighbors.

            Since there may be partial to significant overlap of near neighbors
            as a result of nn_index queries for positive exemplars, the working
            index may contain anywhere from this value's number of entries, to
            ``N*P``, where ``N`` is this value and ``P`` is the number of
            positive examples at the time of working index initialization.
        :type pos_seed_neighbors: int

        :param rel_index_config: Plugin configuration dictionary for the
            RelevancyIndex to use for ranking user adjudications. By default we
            we use an in-memory libSVM based index using the histogram
            intersection metric.
        :type rel_index_config: dict

        :param descriptor_factory: DescriptorElementFactory instance to use to
            produce new descriptors in output extension data. By default, we
            use a factory that produces in-memory descriptors.
        :type descriptor_factory: DescriptorElementFactory

        :param session_uid: Optional manual specification of session UUID.
        :type session_uid: str or uuid.UUID

        """
        self.uuid = session_uid or uuid.uuid1()
        self.lock = multiprocessing.RLock()

        # Local descriptor index for ranking, populated by a query to the
        #   nn_index instance.
        # Added external data/descriptors not added to this index.
        self.working_index = MemoryDescriptorIndex()

        # Initialize book-keeping set so we know what positive descriptors
        # UUIDs we've used to query the neighbor index with already.
        #: :type: set[collections.Hashable]
        self._wi_init_seeds = set()

        # Descriptor references from our index (above) that have been
        #   adjudicated.
        #: :type: set[smqtk.representation.DescriptorElement]
        self.positive_descriptors = set()
        #: :type: set[smqtk.representation.DescriptorElement]
        self.negative_descriptors = set()

        # Example pos/neg data and descriptors added to this session
        #   (external to our working index).
        # All maps keyed on UUID values (some kind of content checksum,
        #   i.e. SHA1).
        #: :type: dict[collections.Hashable, smqtk.representation.DataElement]
        self.ex_data = dict()
        #: :type: dict[collections.Hashable, smqtk.representation.DescriptorElement]
        self.ex_pos_descriptors = dict()
        #: :type: dict[collections.Hashable, smqtk.representation.DescriptorElement]
        self.ex_neg_descriptors = dict()

        self.pos_seed_neighbors = int(pos_seed_neighbors)

        # Working directory assigned to this session
        self._work_dir = work_directory

        # Mapping of a DescriptorElement in our relevancy search index (not the
        #   index that the nn_index uses) to the relevancy score given the
        #   recorded positive and negative adjudications.
        # This is None before any initialization or refinement occurs.
        #: :type: None or dict of (collections.Hashable, float)
        self.results = None

        #
        # Algorithm Instances [+Config]
        #
        # DescriptorGenerator instance assigned to this session.
        self.descriptor = descriptor
        # Factory for generating DescriptorElements of a configured impl type.
        self.descriptor_factory = descriptor_factory
        # NearestNeighborIndex instance assigned to this session.
        self.nn_index = nn_index
        # RelevancyIndex configuration and instance that is used for producing
        #   results.
        # This is only [re]constructed when initializing the session.
        self.rel_index_config = rel_index_config
        # This is None until session initialization happens after pos/neg
        # exemplar data has been added.
        #: :type: None | smqtk.algorithms.relevancy_index.RelevancyIndex
        self.rel_index = None

    def __del__(self):
        # Clean up working directory
        if osp.isdir(self.work_dir):
            shutil.rmtree(self.work_dir)

    def __enter__(self):
        """
        :rtype: IqrSession
        """
        self.lock.acquire()
        return self

    # noinspection PyUnusedLocal
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.lock.release()

    @property
    def work_dir(self):
        file_utils.safe_create_dir(self._work_dir)
        return self._work_dir

    def ordered_results(self):
        """
        Return a tuple of the current (id, probability) result pairs in
        order of probability score. If there are no results yet, None is
        returned.

        :rtype: None | tuple[(smqtk.representation.DescriptorElement, float)]

        """
        with self.lock:
            if self.results:
                return tuple(sorted(self.results.iteritems(),
                                    key=lambda p: p[1],
                                    reverse=True))
            return None

    def add_positive_data(self, *data_elements):
        """
        Add one or more data elements to this IQR session as positive examples.
        This produces descriptors on the input data with our configured
        descriptor generator.

        :param data_elements: Iterable of data elements to add as positive
            examples.
        :type data_elements: collections.Iterable[smqtk.representation.DataElement]

        """
        with self.lock:
            r = self.descriptor.compute_descriptor_async(
                data_elements, self.descriptor_factory
            )
            for da in r:
                self.ex_pos_descriptors[da.uuid()] = r[da]
                self.ex_data[da.uuid()] = da

    def add_negative_data(self, *data_elements):
        """
        Add one or more data elements to this IQR session as negative examples.
        This produces descriptors on the input data with our configured
        descriptor generator.

        :param data_elements: Iterable of data elements to add as positive
            examples.
        :type data_elements: collections.Iterable[smqtk.representation.DataElement]

        """
        with self.lock:
            r = self.descriptor.compute_descriptor_async(
                data_elements, self.descriptor_factory
            )
            for da in r:
                self.ex_neg_descriptors[da.uuid()] = r[da]
                self.ex_data[da.uuid()] = da

    def initialize(self):
        """
        Initialize working index based on currently set positive exemplar data.

        This takes into account the currently set positive data descriptors as
        well as positively adjudicated descriptors from the lifetime of this
        session.

        :raises RuntimeError: There are no positive example descriptors in this
            session to use as a basis for querying.

        """
        if len(self.ex_pos_descriptors) + \
                len(self.positive_descriptors) <= 0:
            raise RuntimeError("No positive descriptors to query the neighbor "
                               "index with.")
        # Not clearing index because this step is intended to be additive

        # build up new working index
        # TODO: Only query using new positives since previous queries
        for p in self.ex_pos_descriptors.itervalues():
            if p.uuid() not in self._wi_init_seeds:
                self._log.info("Querying neighbors to: %s", p)
                self.working_index.add_many_descriptors(
                    self.nn_index.nn(p, n=self.pos_seed_neighbors)[0]
                )
                self._wi_init_seeds.add(p.uuid())
        for p in self.positive_descriptors:
            if p.uuid() not in self._wi_init_seeds:
                self._log.info("Querying neighbors to: %s", p)
                self.working_index.add_many_descriptors(
                    self.nn_index.nn(p, n=self.pos_seed_neighbors)[0]
                )
                self._wi_init_seeds.add(p.uuid())

        # Make new relevancy index
        self._log.info("Creating new relevancy index over working index.")
        #: :type: smqtk.algorithms.relevancy_index.RelevancyIndex
        self.rel_index = plugin.from_plugin_config(self.rel_index_config,
                                                   get_relevancy_index_impls)
        self.rel_index.build_index(self.working_index.iterdescriptors())

    def adjudicate(self, new_positives=(), new_negatives=(),
                   un_positives=(), un_negatives=()):
        """
        Update current state of working index positive and negative
        adjudications based on descriptor UUIDs.

        :param new_positives: Descriptors of elements in our working index to
            now be considered to be positively relevant.
        :type new_positives: collections.Iterable[smqtk.representation.DescriptorElement]

        :param new_negatives: Descriptors of elements in our working index to
            now be considered to be negatively relevant.
        :type new_negatives: collections.Iterable[smqtk.representation.DescriptorElement]

        :param un_positives: Descriptors of elements in our working index to now
            be considered not positive any more.
        :type un_positives: collections.Iterable[smqtk.representation.DescriptorElement]

        :param un_negatives: Descriptors of elements in our working index to now
            be considered not negative any more.
        :type un_negatives: collections.Iterable[smqtk.representation.DescriptorElement]

        """
        with self.lock:
            self.positive_descriptors.update(new_positives)
            self.positive_descriptors.difference_update(un_positives)
            self.positive_descriptors.difference_update(new_negatives)

            self.negative_descriptors.update(new_negatives)
            self.negative_descriptors.difference_update(un_negatives)
            self.negative_descriptors.difference_update(new_positives)

    def refine(self):
        """ Refine current model results based on current adjudication state

        :raises RuntimeError: There are no adjudications to run on. We must have
            at least one positive adjudication.

        """
        with self.lock:
            if not self.rel_index:
                raise RuntimeError("No relevancy index yet. Must not have "
                                   "initialized session (no working index).")

            # fuse pos/neg adjudications + added positive data descriptors
            pos = self.ex_pos_descriptors.values() + list(self.positive_descriptors)
            neg = self.ex_neg_descriptors.values() + list(self.negative_descriptors)

            if not pos:
                raise RuntimeError("Did not find at least one positive "
                                   "adjudication.")

            id_probability_map = self.rel_index.rank(pos, neg)

            if self.results is None:
                self.results = IqrResultsDict()
            self.results.update(id_probability_map)

            # Force adjudicated positives and negatives to be probability 1 and
            # 0, respectively, since we want to control where they show up in
            # our results view.
            # - Not all pos/neg descriptors may be in our working index.
            for d in pos:
                if d in self.results:
                    self.results[d] = 1.0
            for d in neg:
                if d in self.results:
                    self.results[d] = 0.0

    def reset(self):
        """ Reset the IQR Search state

        No positive adjudications, reload original feature data

        """
        with self.lock:
            self.working_index.clear()
            self._wi_init_seeds.clear()
            self.positive_descriptors.clear()
            self.negative_descriptors.clear()
            self.ex_pos_descriptors.clear()
            self.ex_neg_descriptors.clear()
            self.ex_data.clear()

            self.rel_index = None
            self.results = None

            # clear contents of working directory
            shutil.rmtree(self.work_dir)
Пример #28
0
 def test_iteritems(self):
     i = MemoryDescriptorIndex()
     descrs = [random_descriptor() for _ in range(100)]
     i.add_many_descriptors(descrs)
     ntools.assert_equal(set(i.iteritems()),
                         set((d.uuid(), d) for d in descrs))
Пример #29
0
class IqrSession (SmqtkObject):
    """
    Encapsulation of IQR Session related data structures with a centralized lock
    for multi-thread access.

    This object is compatible with the python with-statement, so when elements
    are to be used or modified, it should be within a with-block so race
    conditions do not occur across threads/sub-processes.

    """

    @property
    def _log(self):
        return logging.getLogger(
            '.'.join((self.__module__, self.__class__.__name__)) +
            "[%s]" % self.uuid
        )

    def __init__(self, pos_seed_neighbors=500,
                 rel_index_config=DFLT_REL_INDEX_CONFIG,
                 session_uid=None):
        """
        Initialize the IQR session

        This does not initialize the working index for ranking as there are no
        known positive descriptor examples at this time.

        Adjudications
        -------------
        Adjudications are carried through between initializations. This allows
        indexed material adjudicated through-out the lifetime of the session to
        stay relevant.

        :param pos_seed_neighbors: Number of neighbors to pull from the given
            ``nn_index`` for each positive exemplar when populating the working
            index, i.e. this value determines the size of the working index for
            IQR refinement. By default, we try to get 500 neighbors.

            Since there may be partial to significant overlap of near neighbors
            as a result of nn_index queries for positive exemplars, the working
            index may contain anywhere from this value's number of entries, to
            ``N*P``, where ``N`` is this value and ``P`` is the number of
            positive examples at the time of working index initialization.
        :type pos_seed_neighbors: int

        :param rel_index_config: Plugin configuration dictionary for the
            RelevancyIndex to use for ranking user adjudications. By default we
            we use an in-memory libSVM based index using the histogram
            intersection metric.
        :type rel_index_config: dict

        :param session_uid: Optional manual specification of session UUID.
        :type session_uid: str or uuid.UUID

        """
        self.uuid = session_uid or str(uuid.uuid1()).replace('-', '')
        self.lock = multiprocessing.RLock()

        self.pos_seed_neighbors = int(pos_seed_neighbors)

        # Local descriptor index for ranking, populated by a query to the
        #   nn_index instance.
        # Added external data/descriptors not added to this index.
        self.working_index = MemoryDescriptorIndex()

        # Book-keeping set so we know what positive descriptors
        # UUIDs we've used to query the neighbor index with already.
        #: :type: set[collections.Hashable]
        self._wi_seeds_used = set()

        # Descriptor references from our index (above) that have been
        #   adjudicated.
        #: :type: set[smqtk.representation.DescriptorElement]
        self.positive_descriptors = set()
        #: :type: set[smqtk.representation.DescriptorElement]
        self.negative_descriptors = set()

        # Mapping of a DescriptorElement in our relevancy search index (not the
        #   index that the nn_index uses) to the relevancy score given the
        #   recorded positive and negative adjudications.
        # This is None before any initialization or refinement occurs.
        #: :type: None | dict[smqtk.representation.DescriptorElement, float]
        self.results = None

        #
        # Algorithm Instances [+Config]
        #
        # RelevancyIndex configuration and instance that is used for producing
        #   results.
        # This is only [re]constructed when initializing the session.
        self.rel_index_config = rel_index_config
        # This is None until session initialization happens after pos/neg
        # exemplar data has been added.
        #: :type: None | smqtk.algorithms.relevancy_index.RelevancyIndex
        self.rel_index = None

    def __enter__(self):
        """
        :rtype: IqrSession
        """
        self.lock.acquire()
        return self

    # noinspection PyUnusedLocal
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.lock.release()

    def ordered_results(self):
        """
        Return a tuple of the current (id, probability) result pairs in
        order of probability score. If there are no results yet, None is
        returned.

        :rtype: None | tuple[(smqtk.representation.DescriptorElement, float)]

        """
        with self.lock:
            if self.results:
                return tuple(sorted(self.results.iteritems(),
                                    key=lambda p: p[1],
                                    reverse=True))
            return None

    def adjudicate(self, new_positives=(), new_negatives=(),
                   un_positives=(), un_negatives=()):
        """
        Update current state of working index positive and negative
        adjudications based on descriptor UUIDs.

        If the same descriptor element is listed in both new positives and
        negatives, they cancel each other out, causing that descriptor to not
        be included in the adjudication.

        The given iterables must be re-traversable. Otherwise the given
        descriptors will not be properly registered.

        :param new_positives: Descriptors of elements in our working index to
            now be considered to be positively relevant.
        :type new_positives: collections.Iterable[smqtk.representation.DescriptorElement]

        :param new_negatives: Descriptors of elements in our working index to
            now be considered to be negatively relevant.
        :type new_negatives: collections.Iterable[smqtk.representation.DescriptorElement]

        :param un_positives: Descriptors of elements in our working index to now
            be considered not positive any more.
        :type un_positives: collections.Iterable[smqtk.representation.DescriptorElement]

        :param un_negatives: Descriptors of elements in our working index to now
            be considered not negative any more.
        :type un_negatives: collections.Iterable[smqtk.representation.DescriptorElement]

        """
        with self.lock:
            self.positive_descriptors.update(new_positives)
            self.positive_descriptors.difference_update(un_positives)
            self.positive_descriptors.difference_update(new_negatives)

            self.negative_descriptors.update(new_negatives)
            self.negative_descriptors.difference_update(un_negatives)
            self.negative_descriptors.difference_update(new_positives)

    def update_working_index(self, nn_index):
        """
        Initialize or update our current working index using the given
        :class:`.NearestNeighborsIndex` instance given our current positively
        labeled descriptor elements.

        We only query from the index for new positive elements since the last
        update or reset.

        :param nn_index: :class:`.NearestNeighborsIndex` to query from.
        :type nn_index: smqtk.algorithms.NearestNeighborsIndex

        :raises RuntimeError: There are no positive example descriptors in this
            session to use as a basis for querying.

        """
        if len(self.positive_descriptors) <= 0:
            raise RuntimeError("No positive descriptors to query the neighbor "
                               "index with.")

        # Not clearing working index because this step is intended to be
        # additive.
        updated = False

        # adding to working index
        for p in self.positive_descriptors:
            if p.uuid() not in self._wi_seeds_used:
                self._log.info("Querying neighbors to: %s", p)
                self.working_index.add_many_descriptors(
                    nn_index.nn(p, n=self.pos_seed_neighbors)[0]
                )
                self._wi_seeds_used.add(p.uuid())
                updated = True

        # Make new relevancy index
        if updated:
            self._log.info("Creating new relevancy index over working index.")
            #: :type: smqtk.algorithms.relevancy_index.RelevancyIndex
            self.rel_index = plugin.from_plugin_config(self.rel_index_config,
                                                       get_relevancy_index_impls())
            self.rel_index.build_index(self.working_index.iterdescriptors())

    def refine(self):
        """ Refine current model results based on current adjudication state

        :raises RuntimeError: No working index has been initialized.
            :meth:`update_working_index` should have been called after
            adjudicating some positive examples.
        :raises RuntimeError: There are no adjudications to run on. We must
            have at least one positive adjudication.

        """
        with self.lock:
            if not self.rel_index:
                raise RuntimeError("No relevancy index yet. Must not have "
                                   "initialized session (no working index).")

            # fuse pos/neg adjudications + added positive data descriptors
            pos = self.positive_descriptors
            neg = self.negative_descriptors

            if not pos:
                raise RuntimeError("Did not find at least one positive "
                                   "adjudication.")

            element_probability_map = self.rel_index.rank(pos, neg)

            if self.results is None:
                self.results = IqrResultsDict()
            self.results.update(element_probability_map)

            # Force adjudicated positives and negatives to be probability 1 and
            # 0, respectively, since we want to control where they show up in
            # our results view.
            # - Not all pos/neg descriptors may be in our working index.
            for d in pos:
                if d in self.results:
                    self.results[d] = 1.0
            for d in neg:
                if d in self.results:
                    self.results[d] = 0.0

    def reset(self):
        """ Reset the IQR Search state

        No positive adjudications, reload original feature data

        """
        with self.lock:
            self.working_index.clear()
            self._wi_seeds_used.clear()
            self.positive_descriptors.clear()
            self.negative_descriptors.clear()

            self.rel_index = None
            self.results = None
Пример #30
0
class IqrSession(SmqtkObject):
    """
    Encapsulation of IQR Session related data structures with a centralized lock
    for multi-thread access.

    This object is compatible with the python with-statement, so when elements
    are to be used or modified, it should be within a with-block so race
    conditions do not occur across threads/sub-processes.

    """
    @property
    def _log(self):
        return logging.getLogger('.'.join((self.__module__,
                                           self.__class__.__name__)) +
                                 "[%s]" % self.uuid)

    def __init__(self,
                 pos_seed_neighbors=500,
                 rel_index_config=DFLT_REL_INDEX_CONFIG,
                 session_uid=None):
        """
        Initialize the IQR session

        This does not initialize the working index for ranking as there are no
        known positive descriptor examples at this time.

        Adjudications
        -------------
        Adjudications are carried through between initializations. This allows
        indexed material adjudicated through-out the lifetime of the session to
        stay relevant.

        :param pos_seed_neighbors: Number of neighbors to pull from the given
            ``nn_index`` for each positive exemplar when populating the working
            index, i.e. this value determines the size of the working index for
            IQR refinement. By default, we try to get 500 neighbors.

            Since there may be partial to significant overlap of near neighbors
            as a result of nn_index queries for positive exemplars, the working
            index may contain anywhere from this value's number of entries, to
            ``N*P``, where ``N`` is this value and ``P`` is the number of
            positive examples at the time of working index initialization.
        :type pos_seed_neighbors: int

        :param rel_index_config: Plugin configuration dictionary for the
            RelevancyIndex to use for ranking user adjudications. By default we
            we use an in-memory libSVM based index using the histogram
            intersection metric.
        :type rel_index_config: dict

        :param session_uid: Optional manual specification of session UUID.
        :type session_uid: str | uuid.UUID

        """
        self.uuid = session_uid or str(uuid.uuid1()).replace('-', '')
        self.lock = threading.RLock()

        self.pos_seed_neighbors = int(pos_seed_neighbors)

        # Local descriptor index for ranking, populated by a query to the
        #   nn_index instance.
        # Added external data/descriptors not added to this index.
        self.working_index = MemoryDescriptorIndex()

        # Book-keeping set so we know what positive descriptors
        # UUIDs we've used to query the neighbor index with already.
        #: :type: set[collections.Hashable]
        self._wi_seeds_used = set()

        # Descriptor elements representing data from external sources.
        #: :type: set[smqtk.representation.DescriptorElement]
        self.external_positive_descriptors = set()
        #: :type: set[smqtk.representation.DescriptorElement]
        self.external_negative_descriptors = set()

        # Descriptor references from our index (above) that have been
        #   adjudicated.
        #: :type: set[smqtk.representation.DescriptorElement]
        self.positive_descriptors = set()
        #: :type: set[smqtk.representation.DescriptorElement]
        self.negative_descriptors = set()

        # Mapping of a DescriptorElement in our relevancy search index (not the
        #   index that the nn_index uses) to the relevancy score given the
        #   recorded positive and negative adjudications.
        # This is None before any initialization or refinement occurs.
        #: :type: None | dict[smqtk.representation.DescriptorElement, float]
        self.results = None

        #
        # Algorithm Instances [+Config]
        #
        # RelevancyIndex configuration and instance that is used for producing
        #   results.
        # This is only [re]constructed when initializing the session.
        self.rel_index_config = rel_index_config
        # This is None until session initialization happens after pos/neg
        # exemplar data has been added.
        #: :type: None | smqtk.algorithms.relevancy_index.RelevancyIndex
        self.rel_index = None

    def __enter__(self):
        """
        :rtype: IqrSession
        """
        self.lock.acquire()
        return self

    # noinspection PyUnusedLocal
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.lock.release()

    def ordered_results(self):
        """
        Return a tuple of the current (id, probability) result pairs in
        order of descending probability score. If there are no results yet, None
        is returned.

        :rtype: None | tuple[(smqtk.representation.DescriptorElement, float)]

        """
        with self.lock:
            if self.results:
                return tuple(
                    sorted(six.iteritems(self.results),
                           key=lambda p: p[1],
                           reverse=True))
            return None

    def external_descriptors(self, positive=(), negative=()):
        """
        Add positive/negative descriptors from external data.

        These descriptors may not be a part of our working index.

        :param positive: Iterable of descriptors from external sources to
            consider positive examples.
        :type positive:
            collections.Iterable[smqtk.representation.DescriptorElement]

        :param negative: Iterable of descriptors from external sources to
            consider negative examples.
        :type negative:
            collections.Iterable[smqtk.representation.DescriptorElement]

        """
        positive = set(positive)
        negative = set(negative)
        with self.lock:
            self.external_positive_descriptors.update(positive)
            self.external_positive_descriptors.difference_update(negative)

            self.external_negative_descriptors.update(negative)
            self.external_negative_descriptors.difference_update(positive)

    def adjudicate(self,
                   new_positives=(),
                   new_negatives=(),
                   un_positives=(),
                   un_negatives=()):
        """
        Update current state of working index positive and negative
        adjudications based on descriptor UUIDs.

        If the same descriptor element is listed in both new positives and
        negatives, they cancel each other out, causing that descriptor to not
        be included in the adjudication.

        The given iterables must be re-traversable. Otherwise the given
        descriptors will not be properly registered.

        :param new_positives: Descriptors of elements in our working index to
            now be considered to be positively relevant.
        :type new_positives:
            collections.Iterable[smqtk.representation.DescriptorElement]

        :param new_negatives: Descriptors of elements in our working index to
            now be considered to be negatively relevant.
        :type new_negatives:
            collections.Iterable[smqtk.representation.DescriptorElement]

        :param un_positives: Descriptors of elements in our working index to now
            be considered not positive any more.
        :type un_positives:
            collections.Iterable[smqtk.representation.DescriptorElement]

        :param un_negatives: Descriptors of elements in our working index to now
            be considered not negative any more.
        :type un_negatives:
            collections.Iterable[smqtk.representation.DescriptorElement]

        """
        new_positives = set(new_positives)
        new_negatives = set(new_negatives)
        un_positives = set(un_positives)
        un_negatives = set(un_negatives)

        with self.lock:
            self.positive_descriptors.update(new_positives)
            self.positive_descriptors.difference_update(un_positives)
            self.positive_descriptors.difference_update(new_negatives)

            self.negative_descriptors.update(new_negatives)
            self.negative_descriptors.difference_update(un_negatives)
            self.negative_descriptors.difference_update(new_positives)

    def update_working_index(self, nn_index):
        """
        Initialize or update our current working index using the given
        :class:`.NearestNeighborsIndex` instance given our current positively
        labeled descriptor elements.

        We only query from the index for new positive elements since the last
        update or reset.

        :param nn_index: :class:`.NearestNeighborsIndex` to query from.
        :type nn_index: smqtk.algorithms.NearestNeighborsIndex

        :raises RuntimeError: There are no positive example descriptors in this
            session to use as a basis for querying.

        """
        pos_examples = (self.external_positive_descriptors
                        | self.positive_descriptors)
        if len(pos_examples) == 0:
            raise RuntimeError("No positive descriptors to query the neighbor "
                               "index with.")

        # Not clearing working index because this step is intended to be
        # additive.
        updated = False

        # adding to working index
        self._log.info(
            "Building working index using %d positive examples "
            "(%d external, %d adjudicated)", len(pos_examples),
            len(self.external_positive_descriptors),
            len(self.positive_descriptors))
        # TODO: parallel_map and reduce with merge-dict
        for p in pos_examples:
            if p.uuid() not in self._wi_seeds_used:
                self._log.debug("Querying neighbors to: %s", p)
                self.working_index.add_many_descriptors(
                    nn_index.nn(p, n=self.pos_seed_neighbors)[0])
                self._wi_seeds_used.add(p.uuid())
                updated = True

        # Make new relevancy index
        if updated:
            self._log.info("Creating new relevancy index over working index.")
            #: :type: smqtk.algorithms.relevancy_index.RelevancyIndex
            self.rel_index = plugin.from_plugin_config(
                self.rel_index_config, get_relevancy_index_impls())
            self.rel_index.build_index(self.working_index.iterdescriptors())

    def refine(self):
        """ Refine current model results based on current adjudication state

        :raises RuntimeError: No working index has been initialized.
            :meth:`update_working_index` should have been called after
            adjudicating some positive examples.
        :raises RuntimeError: There are no adjudications to run on. We must
            have at least one positive adjudication.

        """
        with self.lock:
            if not self.rel_index:
                raise RuntimeError("No relevancy index yet. Must not have "
                                   "initialized session (no working index).")

            # combine pos/neg adjudications + added external data descriptors
            pos = self.positive_descriptors | self.external_positive_descriptors
            neg = self.negative_descriptors | self.external_negative_descriptors

            if not pos:
                raise RuntimeError("Did not find at least one positive "
                                   "adjudication.")

            self._log.debug(
                "Ranking working set with %d pos and %d neg total "
                "examples.", len(pos), len(neg))
            element_probability_map = self.rel_index.rank(pos, neg)

            if self.results is None:
                self.results = IqrResultsDict()
            self.results.update(element_probability_map)

            # Force adjudicated positives and negatives to be probability 1 and
            # 0, respectively, since we want to control where they show up in
            # our results view.
            # - Not all pos/neg descriptors may be in our working index.
            for d in pos:
                if d in self.results:
                    self.results[d] = 1.0
            for d in neg:
                if d in self.results:
                    self.results[d] = 0.0

    def reset(self):
        """ Reset the IQR Search state

        No positive adjudications, reload original feature data

        """
        with self.lock:
            self.working_index.clear()
            self._wi_seeds_used.clear()
            self.positive_descriptors.clear()
            self.negative_descriptors.clear()
            self.external_positive_descriptors.clear()
            self.external_negative_descriptors.clear()

            self.rel_index = None
            self.results = None

    ###########################################################################
    # I/O Methods

    # I/O Constants. These should not be changed.
    STATE_ZIP_COMPRESSION = zipfile.ZIP_DEFLATED
    STATE_ZIP_FILENAME = "iqr_state.json"

    def get_state_bytes(self):
        """
        Get a byte representation of the current descriptor and adjudication
        state of this session.

        This does not encode current results or the relevancy index's state, but
        these can be reproduced with this state.

        :return: State representation bytes
        :rtype: bytes

        """
        def d_set_to_list(d_set):
            # Convert set of descriptors to list of tuples:
            #   [..., (uuid, type, vector), ...]
            return [(d.uuid(), d.type(), d.vector().tolist()) for d in d_set]

        with self:
            # Convert session descriptors into basic values.
            pos_d = d_set_to_list(self.positive_descriptors)
            neg_d = d_set_to_list(self.negative_descriptors)
            ext_pos_d = d_set_to_list(self.external_positive_descriptors)
            ext_neg_d = d_set_to_list(self.external_negative_descriptors)

        z_buffer = io.BytesIO()
        z = zipfile.ZipFile(z_buffer, 'w', self.STATE_ZIP_COMPRESSION)
        z.writestr(
            self.STATE_ZIP_FILENAME,
            json.dumps({
                'pos': pos_d,
                'neg': neg_d,
                'external_pos': ext_pos_d,
                'external_neg': ext_neg_d,
            }))
        z.close()
        return z_buffer.getvalue()

    def set_state_bytes(self, b, descriptor_factory):
        """
        Set this session's state to the given byte representation, resetting
        this session in the process.

        Bytes given must have been retrieved via a previous call to
        ``get_state_bytes`` otherwise this method will fail.

        Since this state may be completely different from the current state,
        this session is reset before applying the new state. Thus, any current
        ranking results are thrown away.

        :param b: Bytes to set this session's state to.
        :type b: bytes

        :param descriptor_factory: Descriptor element factory to use when
            generating descriptor elements from extracted data.
        :type descriptor_factory: smqtk.representation.DescriptorElementFactory

        :raises ValueError: The input bytes could not be loaded due to
            incompatibility.

        """
        z_buffer = io.BytesIO(b)
        z = zipfile.ZipFile(z_buffer, 'r', self.STATE_ZIP_COMPRESSION)
        if self.STATE_ZIP_FILENAME not in z.namelist():
            raise ValueError("Invalid bytes given, did not contain expected "
                             "zipped file name.")

        # Extract expected json file object
        state = json.loads(z.read(self.STATE_ZIP_FILENAME).decode())
        del z, z_buffer

        with self:
            self.reset()

            def load_descriptor(_uid, _type_str, vec_list):
                _e = descriptor_factory.new_descriptor(_type_str, _uid)
                if _e.has_vector():
                    assert _e.vector().tolist() == vec_list, \
                        "Found existing vector for UUID '%s' but vectors did " \
                        "not match."
                else:
                    _e.set_vector(vec_list)
                return _e

            # Read in raw descriptor data from the state, convert to descriptor
            # element, then store in our descriptor sets.
            for source, target in [
                (state['external_pos'], self.external_positive_descriptors),
                (state['external_neg'], self.external_negative_descriptors),
                (state['pos'], self.positive_descriptors),
                (state['neg'], self.negative_descriptors)
            ]:
                for uid, type_str, vector_list in source:
                    e = load_descriptor(uid, type_str, vector_list)
                    target.add(e)