コード例 #1
0
  def results(cls, alg: str, ctx: Any, *args, **kwargs) -> RegionSet:
    """
    Compute and return the results of the query with the specified
    algorithm with the given context object (must have the 'dimension'
    attribute).

    Args:
      alg:
        The name of the algorithm to retrieve.
      ctx:
        The context object.
      args, kwargs:
        Additional arguments to be passed to the
        'prepare' class method of the algorithm's
        implementation class.

    Returns:
      The resulting values for the query evaluation.
    """
    assert alg in cls.algorithms
    assert ctx is not None and hasattr(ctx, 'dimension')

    results = RegionSet(dimension=ctx.dimension)
    enumerator = cls.get(alg, ctx, *args, **kwargs)
    for region, _ in enumerator():
      results.add(region)

    return results
コード例 #2
0
ファイル: test_regionset.py プロジェクト: tipech/overlapGraph
 def test_create_regionset(self):
     bounds = Region([0, 0], [100, 100])
     regionset = RegionSet(bounds=bounds)
     regions = bounds.random_regions(10)
     for region in regions:
         regionset.add(region)
     self._test_regionset(regionset, len(regions), bounds, regions)
コード例 #3
0
    def test_nxgraph_sweepctor_graph(self):
        dimension = self.test_regions[0].dimension
        nxgraph = NxGraph(dimension=dimension)
        self._naive_ctor(nxgraph)

        regionset = RegionSet(dimension=dimension)
        regionset.streamadd(self.test_regions)
        nxgraphsweepln = self._nxgraphctor(regionset)
        nxgraphmdsweepln = self._nxgraphmdctor(regionset)

        G = nxgraph.G
        S = nxgraphsweepln.G
        M = nxgraphmdsweepln.G

        self.assertEqual(nxgraph.dimension, nxgraphsweepln.dimension)
        self.assertEqual(nxgraph.dimension, nxgraphmdsweepln.dimension)

        for N in [S, M]:
            for node, region in G.nodes(data='region'):
                self.assertTrue(node in N.node)
                self.assertEqual(region, N.node[node]['region'])

            for (u, v, aregion) in G.edges(data='intersect'):
                self.assertTrue((u, v) in N.edges)
                bregion = N.edges[u, v]['intersect']
                self.assertEqual(aregion, bregion)
                self.assertTrue('intersect' in aregion)
                self.assertTrue('intersect' in bregion)
                aintersect = aregion['intersect']
                bintersect = bregion['intersect']
                self.assertTrue(all([r in bintersect for r in aintersect]))
コード例 #4
0
ファイル: onregions.py プロジェクト: tipech/overlapGraph
    def construct_regions(self, experiment: Experiment, nregions: int,
                          sizepc: float, dimension: int) -> RegionSet:
        """
    Construct a random collection of Regions for the given Experiment.

    Args:
      experiment:   The experiment for this set of Regions.
      nregions:     The number of Regions in this set.
      sizepc:       The maximum size of Regions as a percent
                    of the bounding Region.
      dimension:    The dimensionality of Regions.

    Returns:
      The newly constructed, randomly generated
      collection of Regions.
    """
        bounds = Region([0] * dimension,
                        [experiment.data['maxbound']] * dimension)
        sizepr = Region([0] * dimension, [sizepc] * dimension)
        regions = RegionSet.from_random(nregions, bounds=bounds, sizepc=sizepr)

        self.output_log(experiment, {
            'nregions': nregions,
            'sizepc': sizepc,
            'dimension': dimension
        })

        return regions
コード例 #5
0
ファイル: test_regionset.py プロジェクト: tipech/overlapGraph
    def test_regionset_subset(self):
        nregions = 50
        bounds = Region([0] * 2, [10] * 2)
        sizepc = Region([0] * 2, [0.5] * 2)
        regionset = RegionSet.from_random(nregions,
                                          bounds,
                                          sizepc=sizepc,
                                          precision=1)
        subset = ['A', 'C', 'E', 'G', 'I', 'K'
                  ] + [regionset[r] for r in ['AA', 'P', 'Q', 'R']]
        subsetted = regionset.subset(subset)

        self.assertEqual(regionset.bounds, subsetted.bounds)
        self.assertGreaterEqual(len(regionset), len(subsetted))
        self.assertEqual(len(subset), len(subsetted))
        for r in subset:
            if isinstance(r, str):
                #print(f'{r}: {r in subsetted} {subsetted[r]}')
                self.assertIn(r, subsetted)
                self.assertIs(regionset[r], subsetted[r])
            else:
                #print(f'{r.id}: {r in subsetted} {r}')
                self.assertIsInstance(r, Region)
                self.assertIn(r, subsetted)
                self.assertIs(regionset[r.id], subsetted[r.id])
コード例 #6
0
    def test_regionsweep_random(self):
        regionset = RegionSet.from_random(30,
                                          Region([0] * 3, [100] * 3),
                                          sizepc=Region([0] * 3, [0.5] * 3),
                                          precision=0)
        actuals = []
        #for region in regionset: print(f'{region}')
        for i in range(regionset.dimension):
            #print(f'Dimension: {i}')
            expect = regionset.overlaps(i)
            actual = self._evaluate_regionsweep(regionset, i)
            #for pair in expect: print(f'Expect {i}: {pair[0].id} {pair[1].id}')
            #for pair in actual: print(f'Actual {i}: {pair[0].id} {pair[1].id}')
            for pair in expect:
                #passed = "Passed" if pair in actual else "Failed"
                #print(f'{passed} {i}: {pair[0].id} {pair[1].id}')
                self.assertTrue(pair in actual)
            self.assertEqual(len(expect), len(actual))
            actuals.append(actual)

        self.assertTrue(all([len(actual) for actual in actuals]))
        for pair in actuals[0]:
            for d in range(1, regionset.dimension):
                self.assertTrue(pair in actuals[d]
                                or (pair[1], pair[0]) in actuals[d])
コード例 #7
0
  def initialize(self, regions: RegionSet, region: RegionId = None,
                       subset: List[RegionId] = []):
    """
    Initialize the one-pass sweep-line algorithm over a
    restricted set of Regions.

    Args:
      regions:  The set of Regions to evaluate
                sweep-line algorithm over.
      region:   The Region that restricts the Begin and
                End events to Regions that intersect it.
      subset:   The subset of Regions to include within
                the Intersect events.
    """
    assert isinstance(subset, List)
    assert all([isinstance(r, (Region, str)) for r in subset])
    assert region is None or isinstance(region, (Region, str))

    if isinstance(region, str) and region in regions:
      region = regions[region]
    if region is not None:
      assert region in regions and (len(subset) == 0 or region in subset)
      assert region.dimension == regions.dimension

    for i, r in enumerate(subset):
      if isinstance(r, str) and r in regions:
        subset[i] = regions[r]

    assert all([r in regions for r in subset])

    self.regions = regions.subset(subset) if len(subset) > 0 else regions
    self.subset = subset
    self.region = region
コード例 #8
0
    def context(cls, ctx: Context) -> Context:
        """
    Given a context object (a collection of Regions or a Region
    intersection graph), converts it into the other object type.

    Args:
      ctx: The object to be converted.
    Returns:
      The converted object.
    """
        assert isinstance(ctx, (RegionSet, NxGraph))
        if isinstance(ctx, RegionSet):
            return NxGraphSweepCtor.prepare(ctx)()
        else:
            regions = RegionSet(dimension=ctx.dimension, id=ctx.id)
            regions.streamadd([region for n, region, _ in ctx.regions])
            return regions
コード例 #9
0
ファイル: test_regionset.py プロジェクト: tipech/overlapGraph
    def test_regionset_merge(self):
        nregions = 50
        sizepc = Region([0] * 2, [0.5] * 2)
        first = RegionSet.from_random(nregions,
                                      Region([0] * 2, [10] * 2),
                                      sizepc=sizepc,
                                      precision=1)
        second = RegionSet.from_random(nregions,
                                       Region([0] * 2, [100] * 2),
                                       sizepc=sizepc,
                                       precision=1)
        third = RegionSet(dimension=2)
        third.streamadd([
            Region([-1] * 2, [10] * 2),
            Region([-10, 0], [0, 100]),
            Region([-100, -10], [10, 10])
        ])

        merged = RegionSet.from_merge([first, second, third])
        regionkeys = []

        for region in merged:
            regionkeys.append(region.id)
        for regions in [first, second, third]:
            self.assertTrue(merged.bounds.encloses(regions.bbox))

        self.assertEqual(len(first) + len(second) + len(third), len(merged))
        self.assertEqual(len(regionkeys), len(set(regionkeys)))
コード例 #10
0
ファイル: test_regionset.py プロジェクト: tipech/overlapGraph
 def test_regionset_from_random(self):
     nregions = 50
     bounds = Region([0] * 2, [10] * 2)
     sizepc = Region([0] * 2, [0.5] * 2)
     regionset = RegionSet.from_random(nregions,
                                       bounds,
                                       sizepc=sizepc,
                                       precision=1)
     self._test_regionset(regionset, nregions, bounds, regionset)
コード例 #11
0
    def test_nxgraph_mdsweepctor(self):
        dimension = self.test_regions[0].dimension
        regionset = RegionSet(dimension=dimension)
        regionset.streamadd(self.test_regions)
        nxgraph = self._nxgraphmdctor(regionset)

        with StringIO() as output:
            for json_graph in ['node_link', 'adjacency']:
                options = {'json_graph': json_graph, 'compact': True}
                output.truncate(0)
                NxGraph.to_output(nxgraph,
                                  self._reset_output(output),
                                  options=options)
                #json_output = output.getvalue()
                #print(f'{json_graph}:')
                #print(f'{json_output}')
                newgraph = NxGraph.from_source(self._reset_output(output))
                self._check_nxgraph(nxgraph, newgraph)
コード例 #12
0
ファイル: test_rqenum.py プロジェクト: tipech/overlapGraph
    def setUp(self):
        definedset = RegionSet(dimension=2)
        definedset.streamadd([
            Region([0, 0], [5, 5], 'A'),
            Region([2, 2], [5, 10], 'B'),
            Region([1, 5], [3, 7], 'C'),
            Region([3, 3], [4, 7], 'D'),
            Region([-5, 5], [1, 7], 'E'),
            Region([-5, 5], [2, 7], 'F'),
            Region([3, 4], [5, 6], 'G')
        ])

        bounds = Region([0] * 2, [1000] * 2)

        self.regions = {'definedset': definedset}
        self.subsets = {
            'definedset': {
                'G1': ['A', 'C', 'E', 'G'],
                'G2': ['B', 'D', 'F'],
                'G3': ['A', 'B', 'C', 'D']
            }
        }

        for nregions in [pow(10, n) for n in range(1, 4)]:
            for sizepc in [0.01, 0.05, 0.1]:
                name = f'{nregions},{sizepc:.2f}'
                sizepcr = Region([0] * 2, [sizepc] * 2)
                regions = RegionSet.from_random(nregions,
                                                bounds,
                                                sizepc=sizepcr,
                                                precision=1)

                self.regions[name] = regions
                self.subsets[name] = {}

                for subsetpc in [0.01, 0.05, 0.1, 0.15, 0.2]:
                    size = round(subsetpc * len(regions))
                    if 0 < size < len(regions):
                        subname = f'{subsetpc:.2f}'
                        shuffled = regions.shuffle()
                        self.subsets[name][subname] = [
                            r.id for i, r in enumerate(shuffled) if i < size
                        ]
コード例 #13
0
  def test_regiontimeln_ordering(self):
    regions = RegionSet(dimension=2)
    regions.add(Region([0, 0], [3, 5], 'A'))
    regions.add(Region([3, 1], [5, 5], 'B'))
    regions.add(Region([2, 5], [6, 5], 'C'))
    bbox = regions.bbox
    oracle = [
      [("Init" , 0, bbox),
       ("Begin", 0, regions[0]), ("Begin", 2, regions[2]),
       ("End"  , 3, regions[0]), ("Begin", 3, regions[1]),
       ("End"  , 5, regions[1]), ("End"  , 6, regions[2]),
       ("Done" , 6, bbox)],
      [("Init" , 0, bbox),
       ("Begin", 0, regions[0]), ("Begin", 1, regions[1]),
       ("End"  , 5, regions[0]), ("End"  , 5, regions[1]),
       ("Begin", 5, regions[2]), ("End"  , 5, regions[2]),
       ("Done" , 5, bbox)]
    ]

    for d in range(regions.dimension):
      for i, event in enumerate(regions.timeline.events(d)):
        #print(f'{d},{i}: {event}')
        self.assertEqual(event.kind, RegionEvtKind[oracle[d][i][0]])
        self.assertEqual(event.when, float(oracle[d][i][1]))
        if event.kind == RegionEvtKind.Begin or event.kind == RegionEvtKind.End:
          self.assertIs(event.context, oracle[d][i][2])
          self.assertTrue(-1 <= event.order <= 1)
        elif event.kind == RegionEvtKind.Init:
          self.assertEqual(i, 0)
          self.assertEqual(event.order, -2)
        else:
          self.assertEqual(event.order, 2)
コード例 #14
0
ファイル: test_regionset.py プロジェクト: tipech/overlapGraph
    def test_regionset_tofrom_output(self):
        nregions = 10
        bounds = Region([0] * 2, [100] * 2)
        sizepc = Region([0] * 2, [0.5] * 2)
        regionset = RegionSet.from_random(nregions,
                                          bounds,
                                          sizepc=sizepc,
                                          precision=1)

        with StringIO() as output:
            RegionSet.to_output(regionset, output, options={'compact': True})
            before = output.getvalue()
            #print(before)
            output.seek(0)
            newregionset = RegionSet.from_source(output, 'json')
            self._test_regionset(newregionset, nregions, bounds, regionset)

            output.truncate(0)
            output.seek(0)
            RegionSet.to_output(newregionset,
                                output,
                                options={'compact': True})
            after = output.getvalue()
            #print(after)
            self.assertEqual(before, after)
コード例 #15
0
ファイル: test_regionset.py プロジェクト: tipech/overlapGraph
    def test_regionset_tofrom_output_backlinks(self):
        nregions = 10
        bounds = Region([0] * 2, [100] * 2)
        sizepc = Region([0] * 2, [0.5] * 2)
        regionset = RegionSet.from_random(nregions,
                                          bounds,
                                          sizepc=sizepc,
                                          precision=1)
        regions = []

        for first in regionset:
            for second in regionset:
                if first is not second:
                    regions.append(first.union(second, 'reference'))
                    if first.overlaps(second):
                        regions.append(first.intersect(second, 'reference'))

        for region in regions:
            #print(f'{region}')
            regionset.add(region)

        with StringIO() as output:
            RegionSet.to_output(regionset, output, options={'compact': True})
            #print(output.getvalue())
            output.seek(0)
            newregionset = RegionSet.from_source(output, 'json')

            for region in regions:
                for field in ['intersect', 'union']:
                    if field in region:
                        self.assertTrue(field in newregionset[region.id])
                        self.assertTrue(
                            all([
                                isinstance(r, Region)
                                for r in newregionset[region.id][field]
                            ]))
                        self.assertListEqual(region[field],
                                             newregionset[region.id][field])
コード例 #16
0
    def setUp(self):
        definedset = RegionSet(dimension=2)
        definedset.streamadd([
            Region([0, 0], [5, 5], 'A'),
            Region([2, 2], [5, 10], 'B'),
            Region([1, 5], [3, 7], 'C'),
            Region([3, 3], [4, 7], 'D'),
            Region([-5, 5], [1, 7], 'E'),
            Region([-5, 5], [2, 7], 'F'),
            Region([3, 4], [5, 6], 'G')
        ])

        bounds = Region([0] * 2, [1000] * 2)

        self.regions = {'definedset': definedset}

        for nregions in [pow(10, n) for n in range(1, 4)]:
            for sizepc in [0.01, 0.05, *([] if nregions > 100 else [0.1])]:
                sizerng = Region([0] * 2, [sizepc] * 2)
                regions = RegionSet.from_random(nregions,
                                                bounds,
                                                sizepc=sizerng,
                                                precision=1)
                self.regions[f'{nregions},{sizepc:.2f}'] = regions
コード例 #17
0
    def test_regionsweep_simple(self):
        regionset = RegionSet(dimension=2)
        regionset.add(Region([0, 0], [3, 5]))
        regionset.add(Region([3, 1], [5, 5]))
        regionset.add(Region([2, 4], [6, 6]))

        for i in range(regionset.dimension):
            expect = regionset.overlaps(i)
            actual = self._evaluate_regionsweep(regionset, i)
            #for pair in expect: print(f'Expect {i}:\t{pair[0]}\n\t{pair[1]}')
            #for pair in actual: print(f'Actual {i}:\t{pair[0]}\n\t{pair[1]}')
            for pair in expect:
                #passed = "Passed" if pair in actual else "Failed"
                #print(f'{passed} {i}: {pair[0]} {pair[1]}')
                self.assertTrue(pair in actual)
            self.assertEqual(len(expect), len(actual))
コード例 #18
0
    def generate(cls, output: FileIO, kind: str, nregions: int, dimension: int,
                 **kwargs):
        """
    Randomly generate a new collection or intersection graph of Regions. \f

    Args:
      output:
        The file to save the newly generated set
        or intersection graph of Regions.

      kind:       The output object type.
      nregions:   The number of Regions to be generated.
      dimension:  The number of dimensions for each Region.
      kwargs:     Additional arguments.

    Keyword Args:
      id:
        The unique identifier for the output.
      bounds:
        The minimum + maximum bounding value for
        each dimension that all Region must be
        enclosed within.
      sizepc:
        The minimum + maximum size of each Region
        as a percent of the bounding Region that
        all Region must be enclosed within.
      precision:
        The number of digits after the decimal pt
        in each Region's lower + upper values.
      colored:
        Boolean flag for whether to color code the
        connected Regions and save the associated
        colors in each Region's data properties.
    """
        kwargs['bounds'] = Region.from_object((dimension, kwargs['bounds']))
        kwargs['sizepc'] = Region.from_object((dimension, kwargs['sizepc']))

        colored = kwargs.pop('colored', False)
        regions = RegionSet.from_random(nregions, **kwargs)
        bundle = cls.bundle(regions)

        if colored:
            cls.colorize_components(bundle)

        cls.write(output, cls.unbundle(bundle, kind))
コード例 #19
0
ファイル: test_regionset.py プロジェクト: tipech/overlapGraph
    def test_regionset_filter(self):
        nregions = 50
        bounds = Region([0] * 2, [10] * 2)
        sizepc = Region([0] * 2, [0.5] * 2)
        regionset = RegionSet.from_random(nregions,
                                          bounds,
                                          sizepc=sizepc,
                                          precision=1)
        filter_bound = Region([5] * 2, [10] * 2)
        filtered = regionset.filter(filter_bound)

        self.assertEqual(filter_bound, filtered.bounds)
        for region in regionset:
            #print(f'{region}: {region in filtered}')
            self.assertEqual(filter_bound.encloses(region), region in filtered)
        for region in filtered:
            #print(f'{region}')
            self.assertTrue(filter_bound.encloses(region))
コード例 #20
0
    def choose_query_subset(self, regions: RegionSet,
                            qsizepc: float) -> RQEnum:
        """
    Randomly selects and generates a subset of Regions with the given
    query (subset) size as a percentage of the bounding Region.

    Args:
      regions:  The collection of Regions.
      qsizepc:  The query (subset) size as a percent
                of the bounding Region.

    Returns:
      The list of Regions to include with the
      subset of Regions.
    """
        size = round(qsizepc * len(regions))
        subset = [r for i, r in enumerate(regions.shuffle()) if i < size]

        return subset
コード例 #21
0
ファイル: test_regionset.py プロジェクト: tipech/overlapGraph
    def test_regionset_iteration(self):
        regionset = RegionSet.from_random(100,
                                          Region([0] * 2, [10] * 2),
                                          sizepc=Region([0] * 2, [0.5] * 2))

        for region in regionset:
            self.assertIsInstance(region, Region)
            self.assertIn(region, regionset)

        for region in regionset.keys():
            self.assertIsInstance(region, str)
            self.assertIn(region, regionset)

        for rid, region in regionset.items():
            self.assertIsInstance(rid, str)
            self.assertIsInstance(region, Region)
            self.assertIn(rid, regionset)
            self.assertIn(region, regionset)
            self.assertEqual(rid, region.id)
コード例 #22
0
ファイル: drawregions.py プロジェクト: tipech/overlapGraph
def draw_regions1d(regions: RegionSet, plot: Axes, **kwargs):
    """
  Draws the Regions on a 1D plot, to visualize the
  overlapping or intersecting Regions (or intervals).

  Args:
    regions:  The set of 1D Regions to draw.
    plot:     The matplotlib plot to draw on.
    kwargs:   Additional arguments and options.

  Keyword Args:
    colored:
      Boolean flag for colored output or greyscale.
      If True, color codes the Regions based on the
      Region's stored 'color' data property. Otherwise,
      all Regions have black edges with transparent faces.
    communities:
      Boolean flag for whether or not to show the
      connected communities (or Regions with same color).
      Requires colored to be True.
    tightbounds:
      Boolean flag for whether or not to reduce the
      bounding size to the minimum bounding Region,
      instead of the defined bounds.
  """
    assert regions.dimension == 1

    black = (0, 0, 0)
    groups = {}

    colored = kwargs.get('colored', False)
    communities = kwargs.get('communities', False)
    tightbounds = kwargs.get('tightbounds', False)

    bbox = regions.bbox if tightbounds else regions.minbounds
    spacing = max(bbox[0].length / len(regions), 10)

    if colored and communities:
        for region in regions:
            color = region.getdata('color')
            if color is not None:
                group = groups.setdefault(tuple(color), RegionSet(dimension=1))
                group.add(region)

        for color, group in groups.items():
            gbbox = group.bbox[0]
            lows = (gbbox.lower, 0)
            w, h = (gbbox.length, spacing * (len(regions) + 2))

            rectangle = Rectangle(lows,
                                  w,
                                  h,
                                  facecolor=(*color, 0.05),
                                  edgecolor='none')
            rectangle.set_clip_box(plot)
            plot.add_artist(rectangle)

    for i, region in enumerate(regions):
        color = region.getdata('color', black) if colored else black
        plot.plot(list(astuple(region[0])), [spacing * (i + 1)] * 2,
                  color=color)

    plot.set_xlim(astuple(bbox[0]))
    plot.yaxis.set_visible(False)
コード例 #23
0
    def visualenum(cls,
                   source: FileIO,
                   output: FileIO,
                   srckind: str,
                   outkind: str,
                   queries: List[str] = [],
                   **kwargs):
        """
    Enumerate over the set or graph of Regions in the given input source file.
    Generate and output a visualization of the collection of Regions or
    Region intersection graph, based on the specified visual to output, and
    color codes the results based on the number of intersecting Regions
    involved in each enumerated intersection. Saves the visualization to the
    given destination image file.

    If no Regions given in the query, enumerate all intersecting Regions.
    If a single Region is given in the query, enumerate all intersecting
    Regions that includes that Region. If multiple Regions given in the query,
    enumerate all intersecting Regions amongst the subset of Regions. \f

    Args:
      source:   The input source file to load.
      output:   The dest image file to save visualization.
      srckind:  The input data type.
      outkind:  The output visualization type.
      queries:  The Regions to be queried.
      kwargs:   Additional arguments.

    Keyword Args:
      colormap:
        The name of a built-in matplotlib colormap to
        color code the enumerated intersecting Regions
        by, based on the number of intersecting Regions
        involved in each enumerated intersection.
      forced:
        Boolean flag whether or not to force apart
        the unconnected clusters (nodes and edges)
        within the graph.
      tightbounds:
        Boolean flag for whether or not to reduce the
        bounding size to the minimum bounding Region,
        instead of the defined bounds.
    """
        figure, ax = pyplot.subplots(subplot_kw={'aspect': 'equal'},
                                     figsize=(20, 10))
        regions, rigraph = cls.bundle(cls.read(source, srckind))
        intersects = RegionSet(dimension=regions.dimension)
        enumerator = cls.enumerator('slig', rigraph, list(queries))
        vmin, vmax = 1, 2

        for region, intersect in enumerator():
            k = len(intersect)
            if vmax < k:
                vmax = k
            intersects.add(region)

        cmap = get_cmap(kwargs.pop('colormap'))
        cnorm = Normalize(vmin=vmin, vmax=vmax)
        colors = ScalarMappable(norm=cnorm, cmap=cmap)
        ctx = cls.unbundle((regions, rigraph), outkind)
        get_color = lambda i: tuple(colors.to_rgba(i)[0:3])
        draw_plot = draw_regions if isinstance(ctx,
                                               RegionSet) else draw_rigraph

        for r in regions:
            r['color'] = tuple([0.5] * 3)
        for r in [regions[q] for q in queries]:
            r['color'] = get_color(vmin)
        for r in intersects:
            intersect = r['intersect']
            r['color'] = color = get_color(len(intersect))
            if isinstance(ctx, NxGraph):
                for i, a in enumerate(intersect):
                    a['color'] = color
                    for b in intersect[i + 1:]:
                        rigraph.region((a, b))['color'] = color

        if isinstance(ctx, RegionSet):
            ctx = ctx.merge([intersects])

        draw_plot(ctx, ax, colored=True, **kwargs)

        figure.savefig(output, bbox_inches='tight')
        pyplot.close(figure)
コード例 #24
0
    def test_nxgraph_sweepctor_random(self):
        regions = RegionSet.from_random(100, Region([0] * 3, [100] * 3))
        nxgraphsweepln = self._nxgraphctor(regions)
        nxgraphmdsweepln = self._nxgraphmdctor(regions)

        self._check_nxgraph(nxgraphsweepln, nxgraphmdsweepln)
コード例 #25
0
ファイル: test_regionset.py プロジェクト: tipech/overlapGraph
 def test_regionset_outofbounds(self):
     regionset = RegionSet(bounds=Region([0, 0], [10, 10]))
     with self.assertRaises(AssertionError):
         regionset.add(Region([-1, -1], [5, 5]))
コード例 #26
0
ファイル: test_regionset.py プロジェクト: tipech/overlapGraph
 def test_regionset_dimension_mismatch(self):
     regionset = RegionSet(dimension=2)
     with self.assertRaises(AssertionError):
         regionset.add(Region([0] * 3, [1] * 3))
コード例 #27
0
ファイル: drawregions.py プロジェクト: tipech/overlapGraph
def draw_regions2d(regions: RegionSet, plot: Axes, **kwargs):
    """
  Draws the Regions on a 2D plot, to visualize the
  overlapping or intersecting Regions (or rectangles).

  Args:
    regions:  The set of 2D Regions to draw.
    plot:     The matplotlib plot to draw on.
    kwargs:   Additional arguments and options.

  Keyword Args:
    colored:
      Boolean flag for colored output or greyscale.
      If True, color codes the Regions based on the
      Region's stored 'color' data property. Otherwise,
      all Regions have black edges with transparent faces.
    communities:
      Boolean flag for whether or not to show the
      connected communities (or Regions with same color).
      Requires colored to be True.
    tightbounds:
      Boolean flag for whether or not to reduce the
      bounding size to the minimum bounding Region,
      instead of the defined bounds.
  """
    assert regions.dimension == 2

    black = (0, 0, 0)
    groups = {}

    colored = kwargs.get('colored', False)
    communities = kwargs.get('communities', False)
    tightbounds = kwargs.get('tightbounds', False)

    bbox = regions.bbox if tightbounds else regions.minbounds

    def mkrectangle(region: Region):
        lower = tuple(region[d].lower for d in range(2))
        w, h = tuple(region[d].length for d in range(2))

        return lower, w, h

    if colored and communities:
        for region in regions:
            color = region.getdata('color')
            if color is not None:
                group = groups.setdefault(tuple(color), RegionSet(dimension=2))
                group.add(region)

        for color, group in groups.items():
            rectangle = Rectangle(*mkrectangle(group.bbox),
                                  facecolor=(*color, 0.05),
                                  edgecolor='none')
            rectangle.set_clip_box(plot)
            plot.add_artist(rectangle)

    for region in regions:
        color = region.getdata('color', black) if colored else black
        rectangle = Rectangle(*mkrectangle(region),
                              facecolor=(*color, 0.1),
                              edgecolor=color)
        rectangle.set_clip_box(plot)
        plot.add_artist(rectangle)

    plot.set_xlim(astuple(bbox[0]))
    plot.set_ylim(astuple(bbox[1]))
コード例 #28
0
    def enumerate(cls,
                  source: FileIO,
                  output: FileIO,
                  srckind: str,
                  queries: List[str] = [],
                  **kwargs):
        """
    Enumerate over the set or graph of Regions in the given input source file.
    Outputs the results to as a JSON with performance data and the results
    as a RegionSet of intersecting Regions.

    If no Regions given in the query, enumerate all intersecting Regions.
    If a single Region is given in the query, enumerate all intersecting
    Regions that includes that Region. If multiple Regions given in the query,
    enumerate all intersecting Regions amongst the subset of Regions. \f

    Args:
      source:   The input source file to load.
      output:   The destination file to save results.
      srckind:  The input data type.
      queries:  The Regions to be queried.
      kwargs:   Additional arguments.

    Keyword Args:
      naive:
        Boolean flag for whether to use the naive
        sweep-line algorithm instead of querying
        via the region intersection graph.
    """
        queries = list(queries)
        context = cls.read(source, srckind)
        intersects = RegionSet(dimension=context.dimension)
        counts = {}

        def get_header(ctx: Context) -> Dict:
            header = {
                'id': ctx.id,
                'type': type(ctx).__name__,
                'dimension': ctx.dimension,
                'length': len(ctx)
            }
            if elapse_ctor is None:
                header['elapse_query'] = elapse_query
            else:
                header['elapse_query'] = elapse_query - elapse_ctor
                header['elapse_ctor'] = elapse_ctor
            return header

        def get_enumerator():
            if isinstance(context, NxGraph):
                return (None, cls.enumerator('slig', context, queries))
            if kwargs.get('naive', False):
                return (0, cls.enumerator('naive', context, queries))

            graph = NxGraphSweepCtor.prepare(context)()
            elapsed = perf_counter() - start
            return (elapsed, cls.enumerator('slig', graph, queries))

        start = perf_counter()
        elapse_ctor, enumerator = get_enumerator()

        for region, intersect in enumerator():
            k = len(intersect)
            if k not in counts:
                counts[k] = 0
            counts[k] += 1
            intersects.add(region)

        elapse_query = perf_counter() - start
        header = get_header(context)
        cls.write(
            output, {
                'header': {
                    **header, 'query': queries,
                    'count': counts
                },
                'results': intersects
            })