Converts the intersection into a single GC rule as a protobuf.

        :rtype: :class:`.table_v2_pb2.GcRule`
        :returns: The converted current object.
178304
def to_pb(self):
        
        intersection = table_v2_pb2.GcRule.Intersection(
            rules=[rule.to_pb() for rule in self.rules]
        )
        return table_v2_pb2.GcRule(intersection=intersection)
308144
def rlgt(self, time=None, times=1,
             disallow_sibling_lgts=False):
        

        lgt = LGT(self.copy())
        for _ in range(times):
            lgt.rlgt(time, disallow_sibling_lgts)
        return lgt.tree
57505
function Rule (subrules, type, handler, props, groupProps, encoding) {
  var self = this
  var n = subrules.length

  this.props = props

  this.debug = false

  // Used for cloning
  this.subrules = subrules

  // Required by Atok#_resolveRules
  for (var p in groupProps)
    this[p] = groupProps[p]

  // Runtime values for continue props
  this.continue = this.props.continue[0]
  this.continueOnFail = this.props.continue[1]

  this.type = type
  this.handler = handler

  // For debug
  this.prevHandler = null
  this.id = this.type !== null ? this.type : handler
  // Id for debug
  this._id = (handler !== null ? (handler.name || '#emit()') : this.type)

  // Subrule pattern index that matched (-1 if only 1 pattern)
  this.idx = -1

  // Single subrule: special case for trimRight
  this.single = (n === 1)

  // First subrule
  var subrule = this.first = n > 0
    ? SubRule.firstSubRule( subrules[0], this.props, encoding, this.single )
    // Special case: no rule given -> passthrough
    : SubRule.emptySubRule

  // Special case: one empty rule -> tokenize whole buffer
  if (n === 1 && subrule.length === 0) {
    subrule = this.first = SubRule.allSubRule
    // Make infinite loop detection ignore this
    this.length = -1
  } else {
    // First subrule pattern length (max of all patterns if many)
    // - used in infinite loop detection
    this.length = this.first.length
  }

  // Instantiate and link the subrules
  // { test: {Function}
  // , next: {SubRule|undefined}
  // }
  var prev = subrule
  // Many subrules or none
  for (var i = 1; i < n; i++) {
    subrule = SubRule.SubRule( subrules[i], this.props, encoding )
    prev.next = subrule
    subrule.prev = prev // Useful in some edge cases
    prev = subrule
    if (this.length < subrule.length) this.length = subrule.length
  }

  // Last subrule (used for trimRight and matched idx)
  this.last = subrule

  // Set the first and last subrules length based on trim properties
  if (!this.props.trimLeft) this.first.length = 0
  if (!this.single && !this.props.trimRight) this.last.length = 0

  this.next = null
  this.nextFail = null
  this.currentRule = null
}
489366
def p_seg(p1, p2, cw, interval, trim=0, align=0):
    
    case = {True: pi / -2, False: pi / 2}
    p1m, p2m = m_seg(p1, p2, case[cw], interval)
    return t_seg(p1m, p2m, trim, align)
1230699
def g_to_n(self, g_interval):
        """"""

        # This code is extremely convoluted. To begin with, it
        # confuses interbase intervals for a *single* hgvs position
        # with intervals of *two* hgvs positions.  This is the origin
        # of bug #205 (now closed). Although the bug is itself fixed,
        # the mappers really need an overhaul. See #208.

        def _hgvs_offset(g_position, grs, gre, strand):
            """ Calculates the HGVS coordinate offset from a given genomic position"""
            if g_position == grs or g_position == gre:
                return 0
            mid = (grs + gre) / 2
            if g_position < mid or (g_position == mid and strand == 1):
                offset = g_position - grs
            else:
                offset = g_position - gre
            return offset

        def map_g_to_n_pos(pos):
            g_ci = _hgvs_coord_to_ci(pos, pos)
            # frs, fre = (f)orward (r)na (s)tart & (e)nd; forward w.r.t. genome
            frs, fre = self.im.map_ref_to_tgt(
                g_ci[0] - self.gc_offset, g_ci[1] - self.gc_offset, max_extent=False)
            if self.strand == -1:
                frs, fre = self.tgt_len - fre, self.tgt_len - frs
            # get BaseOffsetPosition information for n.
            if self.strand == 1:
                grs, gre = self.im.map_tgt_to_ref(frs, fre, max_extent=False)
            elif self.strand == -1:
                grs, gre = self.im.map_tgt_to_ref((self.tgt_len - fre), (self.tgt_len - frs),
                                                  max_extent=False)
            grs, gre = grs + self.gc_offset, gre + self.gc_offset
            # 0-width interval indicates an intron.  Need to calculate offsets but we"re are in ci coordinates
            # requires adding 1 strategically to get the HGVS position
            # (shift coordinates to 3' end of the ref nucleotide)

            if frs == fre:
                start_offset = _hgvs_offset(g_ci[0] + 1, grs, gre + 1, self.strand)
                end_offset = _hgvs_offset(g_ci[1], grs, gre + 1, self.strand)
            else:
                start_offset = _hgvs_offset(g_ci[0], grs, gre, self.strand)
                end_offset = _hgvs_offset(g_ci[1], grs, gre, self.strand)
            if self.strand == -1:
                start_offset, end_offset = self.strand * end_offset, self.strand * start_offset
            if start_offset > 0:
                frs -= 1
            if end_offset < 0:
                fre += 1
            start_base = _ci_to_hgvs_coord(frs, fre)[0]
            end_base = _ci_to_hgvs_coord(frs, fre)[1]
            return start_base, start_offset, end_base, end_offset

        start_bo = map_g_to_n_pos(g_interval.start.base)[0:2]
        end_bo = start_bo if g_interval.start.base == g_interval.end.base else map_g_to_n_pos(
            g_interval.end.base)[2:4]
        if self.strand == -1:
            start_bo, end_bo = end_bo, start_bo

        return hgvs.location.BaseOffsetInterval(
            start=hgvs.location.BaseOffsetPosition(
                base=start_bo[0], offset=start_bo[1], datum=Datum.SEQ_START),
            end=hgvs.location.BaseOffsetPosition(
                base=end_bo[0], offset=end_bo[1], datum=Datum.SEQ_START),
            uncertain=g_interval.uncertain)
1331441
def as_proto(self):
        """"""
        if self._dims is None:
            return tensor_shape_pb2.TensorShapeProto(unknown_rank=True)
        else:
            return tensor_shape_pb2.TensorShapeProto(
                dim=[
                    tensor_shape_pb2.TensorShapeProto.Dim(
                        size=-1 if d.value is None else d.value
                    )
                    for d in self._dims
                ]
            )
178417
def _to_protobuf(self):
        
        projection = self._normalize_projection(self._projection)
        orders = self._normalize_orders()
        start_at = self._normalize_cursor(self._start_at, orders)
        end_at = self._normalize_cursor(self._end_at, orders)

        query_kwargs = {
            "select": projection,
            "from": [
                query_pb2.StructuredQuery.CollectionSelector(
                    collection_id=self._parent.id
                )
            ],
            "where": self._filters_pb(),
            "order_by": orders,
            "start_at": _cursor_pb(start_at),
            "end_at": _cursor_pb(end_at),
        }
        if self._offset is not None:
            query_kwargs["offset"] = self._offset
        if self._limit is not None:
            query_kwargs["limit"] = wrappers_pb2.Int32Value(value=self._limit)

        return query_pb2.StructuredQuery(**query_kwargs)
735595
def from_proto_dict(proto_dict: Dict) -> 'GridQubit':
        """"""
        if 'row' not in proto_dict or 'col' not in proto_dict:
            raise ValueError(
                'Proto dict does not contain row or col: {}'.format(proto_dict))
        return GridQubit(row=proto_dict['row'], col=proto_dict['col'])
1361727
def get_geometry_from_mp_symbol(self, mp_symbol):
        
        for gg in self.cg_list:
            if gg.mp_symbol == mp_symbol:
                return gg
        raise LookupError(
            'No coordination geometry found with mp_symbol "{symbol}"'.format(
                symbol=mp_symbol))
507021
def _get_gc2_coordinates_for_rupture(self, edge_sets):
        

        # Establish GC2 length - for use with Ry0
        rup_gc2t, rup_gc2u = self.get_generalised_coordinates(
            edge_sets[:, 0], edge_sets[:, 1])
        # GC2 length should be the largest positive GC2 value of the edges
        self.gc_length = numpy.max(rup_gc2u)
980836
def convert_to_geotype(element, crs=None):
    
    geotype = getattr(gv_element, type(element).__name__, None)
    if crs is None or geotype is None or isinstance(element, _Element):
        return element
    return geotype(element, crs=crs)
1071560
def tsp_gurobi(edges):
    
    from gurobipy import Model, GRB, quicksum

    edges = populate_edge_weights(edges)
    incoming, outgoing, nodes = node_to_edge(edges)
    idx = dict((n, i) for i, n in enumerate(nodes))
    nedges = len(edges)
    n = len(nodes)

    m = Model()

    def step(x): return "u_{0}".format(x)
    # Create variables
    vars = {}
    for i, (a, b, w) in enumerate(edges):
        vars[i] = m.addVar(obj=w, vtype=GRB.BINARY, name=str(i))
    for u in nodes[1:]:
        u = step(u)
        vars[u] = m.addVar(obj=0, vtype=GRB.INTEGER, name=u)
    m.update()

    # Bounds for step variables
    for u in nodes[1:]:
        u = step(u)
        vars[u].lb = 1
        vars[u].ub = n - 1

    # Add degree constraint
    for v in nodes:
        incoming_edges = incoming[v]
        outgoing_edges = outgoing[v]
        m.addConstr(quicksum(vars[x] for x in incoming_edges) == 1)
        m.addConstr(quicksum(vars[x] for x in outgoing_edges) == 1)

    # Subtour elimination
    edge_store = dict(((idx[a], idx[b]), i)
                      for i, (a, b, w) in enumerate(edges))

    # Given a list of edges, finds the shortest subtour
    def subtour(s_edges):
        visited = [False] * n
        cycles = []
        lengths = []
        selected = [[] for i in range(n)]
        for x, y in s_edges:
            selected[x].append(y)
        while True:
            current = visited.index(False)
            thiscycle = [current]
            while True:
                visited[current] = True
                neighbors = [x for x in selected[current] if not visited[x]]
                if len(neighbors) == 0:
                    break
                current = neighbors[0]
                thiscycle.append(current)
            cycles.append(thiscycle)
            lengths.append(len(thiscycle))
            if sum(lengths) == n:
                break
        return cycles[lengths.index(min(lengths))]

    def subtourelim(model, where):
        if where != GRB.callback.MIPSOL:
            return
        selected = []
        # make a list of edges selected in the solution
        sol = model.cbGetSolution([model._vars[i] for i in range(nedges)])
        selected = [edges[i] for i, x in enumerate(sol) if x > .5]
        selected = [(idx[a], idx[b]) for a, b, w in selected]
        # find the shortest cycle in the selected edge list
        tour = subtour(selected)
        if len(tour) == n:
            return
        # add a subtour elimination constraint
        c = tour
        incident = [edge_store[a, b] for a, b in pairwise(c + [c[0]])]
        model.cbLazy(quicksum(model._vars[x]
                              for x in incident) <= len(tour) - 1)

    m.update()

    m._vars = vars
    m.params.LazyConstraints = 1
    m.optimize(subtourelim)

    selected = [v.varName for v in m.getVars() if v.x > .5]
    selected = [int(x) for x in selected if x[:2] != "u_"]
    results = sorted(x for i, x in enumerate(edges) if i in selected) \
        if selected else None
    return results
139602
def rule(self):
        
        if self._rule:
            return self._rule
        return self._make_rule(member_param=self._member_param,
                               unique_member_param=self._unique_member_param)
155473
def no_intersection(to_validate, constraint, violation_cfg):
    
    if len(constraint) == 0 or len(set(constraint).intersection(to_validate)) > 0:
        return None
    else:
        violation_cfg[Check.CFG_KEY_VIOLATION_MSG] = violation_cfg[Check.CFG_KEY_VIOLATION_MSG].format(constraint)
        return violation_cfg
1288380
def valid_GC(x):
    
    x = float(x)
    if x < 0.0 or x > 1.0:
        raise ArgumentTypeError("{} not in range [0.0, 1.0]".format(x))
    return x
20253
def to_pb(self):
        
        if self.gc_rule is None:
            return table_v2_pb2.ColumnFamily()
        else:
            return table_v2_pb2.ColumnFamily(gc_rule=self.gc_rule.to_pb())
789135
def tc(g):
        
        ret = {}
        for scc in tarjan(g):
                ws = set()
                ews = set()
                for v in scc:
                        ws.update(g[v])
                for w in ws:
                        assert w in ret or w in scc
                        ews.add(w)
                        ews.update(ret.get(w,()))
                if len(scc) > 1:
                        ews.update(scc)
                ews = tuple(ews)
                for v in scc:
                        ret[v] = ews
        return ret