Python sortedcontainers.SortedDict() Examples

The following are 30 code examples of sortedcontainers.SortedDict(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sortedcontainers , or try the search function .
Example #1
Source File: fsm.py    From rift-python with Apache License 2.0 7 votes vote down vote up
def state_actions_table(self):
        # Make sure table is sorted by state for deterministic output (needed for testing)
        sorted_state_actions = sortedcontainers.SortedDict()
        for state in self.state_actions:
            (entry_actions, exit_actions) = self.state_actions[state]
            entry_action_names = list(map(_action_to_name, entry_actions))
            if entry_action_names == []:
                entry_action_names = "-"
            exit_action_names = list(map(_action_to_name, exit_actions))
            if exit_action_names == []:
                exit_action_names = "-"
            sorted_state_actions[state.name] = (entry_action_names, exit_action_names)
        tab = table.Table()
        tab.add_row(["State", "Entry Actions", "Exit Actions"])
        for state_name in sorted_state_actions:
            (entry_action_names, exit_action_names) = sorted_state_actions[state_name]
            tab.add_row([state_name, entry_action_names, exit_action_names])
        return tab 
Example #2
Source File: order_book.py    From TradzQAI with Apache License 2.0 6 votes vote down vote up
def reset_book(self):
        self._asks = SortedDict()
        self._bids = SortedDict()
        res = self._client.get_product_order_book(product_id=self.product_id, level=3)
        for bid in res['bids']:
            self.add({
                'id': bid[2],
                'side': 'buy',
                'price': Decimal(bid[0]),
                'size': Decimal(bid[1])
            })
        for ask in res['asks']:
            self.add({
                'id': ask[2],
                'side': 'sell',
                'price': Decimal(ask[0]),
                'size': Decimal(ask[1])
            })
        self._sequence = res['sequence'] 
Example #3
Source File: memory.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, is_stack):
        """
        Constructor

        :param is_stack:    Whether this is a region map for stack frames or not. Different strategies apply for stack
                            regions.
        """
        self.is_stack = is_stack

        # A sorted list, which maps stack addresses to region IDs
        self._address_to_region_id = SortedDict()
        # A dict, which maps region IDs to memory address ranges
        self._region_id_to_address = { }

    #
    # Properties
    # 
Example #4
Source File: orderbook.py    From gdax-python-api with MIT License 6 votes vote down vote up
def __init__(self, product_ids='ETH-USD', api_key=None, api_secret=None,
                 passphrase=None, use_heartbeat=False,
                 trade_log_file_path=None):

        super().__init__(product_ids=product_ids,
                         api_key=api_key,
                         api_secret=api_secret,
                         passphrase=passphrase,
                         use_heartbeat=use_heartbeat,
                         trade_log_file_path=trade_log_file_path)

        if not isinstance(product_ids, list):
            product_ids = [product_ids]

        self.traders = {product_id: gdax.trader.Trader(product_id=product_id)
                        for product_id in product_ids}
        self._asks = {product_id: SortedDict() for product_id in product_ids}
        self._bids = {product_id: SortedDict() for product_id in product_ids}
        self._sequences = {product_id: None for product_id in product_ids} 
Example #5
Source File: io.py    From clusterman with Apache License 2.0 6 votes vote down vote up
def restore(self, data):
        return SortedDict((_python_decode(k), _python_decode(v)) for k, v in data['items']) 
Example #6
Source File: order_book.py    From coinbasepro-python with MIT License 6 votes vote down vote up
def reset_book(self):
        self._asks = SortedDict()
        self._bids = SortedDict()
        res = self._client.get_product_order_book(product_id=self.product_id, level=3)
        for bid in res['bids']:
            self.add({
                'id': bid[2],
                'side': 'buy',
                'price': Decimal(bid[0]),
                'size': Decimal(bid[1])
            })
        for ask in res['asks']:
            self.add({
                'id': ask[2],
                'side': 'sell',
                'price': Decimal(ask[0]),
                'size': Decimal(ask[1])
            })
        self._sequence = res['sequence'] 
Example #7
Source File: intervaltree.py    From intervaltree with Apache License 2.0 6 votes vote down vote up
def __init__(self, intervals=None):
        """
        Set up a tree. If intervals is provided, add all the intervals
        to the tree.

        Completes in O(n*log n) time.
        """
        intervals = set(intervals) if intervals is not None else set()
        for iv in intervals:
            if iv.is_null():
                raise ValueError(
                    "IntervalTree: Null Interval objects not allowed in IntervalTree:"
                    " {0}".format(iv)
                )
        self.all_intervals = intervals
        self.top_node = Node.from_intervals(self.all_intervals)
        self.boundary_table = SortedDict()
        for iv in self.all_intervals:
            self._add_boundaries(iv) 
Example #8
Source File: index.py    From wasabi2d with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, ctx: mgl.Context):
        self.buffer = None
        self.ctx = ctx

        # Allocation id to sort key
        self.id_lookup: Dict[int, Tuple[Any, int]] = {}

        # Sorted list of sort keys to index arrays
        self.allocations: Mapping[Tuple[Any, int], np.ndarray] = SortedDict()

        # Track whether we have updates
        self.dirty: bool = True

        # We allocate identifiers for each allocation. These are sequential
        # and form part of the sort key; this ensures that insertion order
        # can be preserved.
        self.next_id: int = 1  # start at 1 so we can test bool(id) 
Example #9
Source File: keyframe_model.py    From spimagine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def default(self, obj):
        if isinstance(obj, np.ndarray) and obj.ndim == 1:
            return obj.tolist()

        elif isinstance(obj, Quaternion):
            return obj.data.tolist()

        elif isinstance(obj, sortedcontainers.SortedDict):
            return dict(obj)

        elif isinstance(obj, (
                KeyFrame,
                KeyFrameList,
                TransformData,
                spimagine.models.transform_model.TransformData)):
            return obj.__dict__

        elif isinstance(obj, np.generic):
            return np.asscalar(obj)

        return json.JSONEncoder.default(self, obj) 
Example #10
Source File: test_splitting.py    From mikado with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_lenient_split(self):

        self.transcript.json_conf["pick"]["chimera_split"]["blast_check"] = True

        self.transcript.json_conf["pick"][
            "chimera_split"]["blast_params"]["leniency"] = "LENIENT"

        cds_boundaries = SortedDict()
        for orf in sorted(self.transcript.loaded_bed12,
                          key=operator.attrgetter("thick_start", "thick_end")):
            cds_boundaries[(orf.thick_start, orf.thick_end)] = [orf]

        self.assertEqual(1,
                         len(splitting.check_split_by_blast(self.transcript, cds_boundaries)))
        sl = loci.Superlocus(self.transcript, json_conf=self.transcript.json_conf)
        self.assertEqual(len(sl.transcripts), 1)
        sl.load_all_transcript_data(data_dict=dict())
        self.assertEqual(len(sl.transcripts), 1) 
Example #11
Source File: test_splitting.py    From mikado with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_stringent_split(self):

        self.transcript.json_conf["pick"]["chimera_split"]["blast_check"] = True

        self.transcript.json_conf["pick"][
            "chimera_split"]["blast_params"]["leniency"] = "STRINGENT"

        cds_boundaries = SortedDict()
        for orf in sorted(self.transcript.loaded_bed12,
                          key=operator.attrgetter("thick_start", "thick_end")):
            cds_boundaries[(orf.thick_start, orf.thick_end)] = [orf]

        self.assertEqual(1,
                         len(splitting.check_split_by_blast(self.transcript, cds_boundaries)))
        sl = loci.Superlocus(self.transcript, json_conf=self.transcript.json_conf)
        self.assertEqual(len(sl.transcripts), 1)
        sl.load_all_transcript_data(data_dict=dict())
        self.assertEqual(len(sl.transcripts), 1) 
Example #12
Source File: test_splitting.py    From mikado with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_permissive_split(self):

        self.transcript.logger = self.logger

        self.transcript.json_conf["pick"]["chimera_split"]["blast_check"] = True

        self.transcript.json_conf["pick"][
            "chimera_split"]["blast_params"]["leniency"] = "PERMISSIVE"

        cds_boundaries = SortedDict()
        for orf in sorted(self.transcript.loaded_bed12,
                          key=operator.attrgetter("thick_start", "thick_end")):
            cds_boundaries[(orf.thick_start, orf.thick_end)] = [orf]

        self.assertEqual(2, len(splitting.check_split_by_blast(self.transcript, cds_boundaries)))
        sl = loci.Superlocus(self.transcript, json_conf=self.transcript.json_conf)
        self.assertEqual(len(sl.transcripts), 1)
        sl.load_all_transcript_data(data_dict=dict())
        self.assertEqual(len(sl.transcripts), 2) 
Example #13
Source File: order_book.py    From TradzQAI with Apache License 2.0 6 votes vote down vote up
def __init__(self,
                 url="wss://ws-feed.pro.coinbase.com",
                 product_id='BTC-USD',
                 api_key="",
                 api_secret="",
                 api_passphrase="",
                 channels=None,
                 log_to=None):

        super(OrderBook, self).__init__(url=url, products=product_id,
            api_key=api_key, api_secret=api_secret,
            api_passphrase=api_passphrase, channels=channels)
        self._asks = SortedDict()
        self._bids = SortedDict()
        self._client = PublicClient()
        self._sequence = -1
        self._log_to = log_to
        if self._log_to:
            assert hasattr(self._log_to, 'write')
        self._current_ticker = None 
Example #14
Source File: recipes.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, iterable=()):
        self._keys = {}
        self._nums = SortedDict()
        self._count = count()
        self |= iterable 
Example #15
Source File: test_splitting.py    From mikado with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_spanning_hit_nocheck(self):
        self.transcript.blast_hits = [self.get_spanning_hit()]
        self.transcript.json_conf["pick"]["chimera_split"]["blast_check"] = False
        cds_boundaries = SortedDict()
        for orf in sorted(self.transcript.loaded_bed12,
                          key=operator.attrgetter("thick_start", "thick_end")):
            cds_boundaries[(orf.thick_start, orf.thick_end)] = [orf]

        self.assertEqual(len(cds_boundaries), 2)
        self.assertEqual(self.transcript.number_internal_orfs, 2)
        self.assertEqual(2, len(list(splitting.split_by_cds(self.transcript))))
        sl = loci.Superlocus(self.transcript, json_conf=self.transcript.json_conf)
        self.assertEqual(len(sl.transcripts), 1)
        sl.load_all_transcript_data(data_dict=dict())
        self.assertEqual(len(sl.transcripts), 2) 
Example #16
Source File: sequence_learner.py    From adaptive with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, function, sequence):
        self._original_function = function
        self.function = _IgnoreFirstArgument(function)
        self._to_do_indices = SortedSet({i for i, _ in enumerate(sequence)})
        self._ntotal = len(sequence)
        self.sequence = copy(sequence)
        self.data = SortedDict()
        self.pending_points = set() 
Example #17
Source File: learner1D.py    From adaptive with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_neighbors_from_list(xs):
    xs = np.sort(xs)
    xs_left = np.roll(xs, 1).tolist()
    xs_right = np.roll(xs, -1).tolist()
    xs_left[0] = None
    xs_right[-1] = None
    neighbors = {x: [x_L, x_R] for x, x_L, x_R in zip(xs, xs_left, xs_right)}
    return sortedcontainers.SortedDict(neighbors) 
Example #18
Source File: learner1D.py    From adaptive with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, function, bounds, loss_per_interval=None):
        self.function = function

        if hasattr(loss_per_interval, "nth_neighbors"):
            self.nth_neighbors = loss_per_interval.nth_neighbors
        else:
            self.nth_neighbors = 0

        self.loss_per_interval = loss_per_interval or default_loss

        # When the scale changes by a factor 2, the losses are
        # recomputed. This is tunable such that we can test
        # the learners behavior in the tests.
        self._recompute_losses_factor = 2

        self.data = {}
        self.pending_points = set()

        # A dict {x_n: [x_{n-1}, x_{n+1}]} for quick checking of local
        # properties.
        self.neighbors = sortedcontainers.SortedDict()
        self.neighbors_combined = sortedcontainers.SortedDict()

        # Bounding box [[minx, maxx], [miny, maxy]].
        self._bbox = [list(bounds), [np.inf, -np.inf]]

        # Data scale (maxx - minx), (maxy - miny)
        self._scale = [bounds[1] - bounds[0], 0]
        self._oldscale = deepcopy(self._scale)

        # A LossManager storing the loss function for each interval x_n.
        self.losses = loss_manager(self._scale[0])
        self.losses_combined = loss_manager(self._scale[0])

        # The precision in 'x' below which we set losses to 0.
        self._dx_eps = 2 * max(np.abs(bounds)) * np.finfo(float).eps

        self.bounds = list(bounds)

        self._vdim = None 
Example #19
Source File: learner1D.py    From adaptive with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __getstate__(self):
        return (
            self.function,
            self.bounds,
            self.loss_per_interval,
            dict(self.losses),  # SortedDict cannot be pickled
            dict(self.losses_combined),  # ItemSortedDict cannot be pickled
            self._get_data(),
        ) 
Example #20
Source File: ordereddict.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self._keys = {}
        self._nums = nums = SortedDict()
        self._count = count()
        self.iloc = SequenceView(nums)
        self.update(*args, **kwargs) 
Example #21
Source File: util.py    From rssit with MIT License 5 votes vote down vote up
def __init__(self, name, timeout, rand=0):
        self.db = {}
        self.name = name
        self.timestamps = sortedcontainers.SortedDict()
        self.timeout = timeout
        self.rand = rand
        self.base_redis_key = "RSSIT:" + str(self.name) + ":" 
Example #22
Source File: memory.py    From biggraphite with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        """Create a new MemoryAccessor."""
        super(_MemoryAccessor, self).__init__("memory")
        self._metric_to_points = collections.defaultdict(sortedcontainers.SortedDict)
        self._name_to_metric = {}
        self._directory_names = sortedcontainers.SortedSet()
        self.__downsampler = _downsampling.Downsampler()
        self.__delayed_writer = _delayed_writer.DelayedWriter(self) 
Example #23
Source File: piecewise.py    From clusterman with Apache License 2.0 5 votes vote down vote up
def __init__(self, initial_value: float = 0) -> None:
        """ Initialize the constant function to a particular value

        :param initial_value: the starting value for the function
        """
        self.breakpoints = SortedDict()
        self._initial_value: float = initial_value 
Example #24
Source File: piecewise.py    From clusterman with Apache License 2.0 5 votes vote down vote up
def values(self, start: XValue[T], stop: XValue[T], step: XValueDiff[T]) -> 'SortedDict[XValue[T], float]':
        """ Compute a sequence of values of the function

        This is more efficient than [self.call(xval) for xval in range(start, stop, step)] because each self.call(..)
        takes O(log n) time due to the binary tree structure of self._breakpoints.  This method can compute the range
        of values in linear time in the range, which is significantly faster for large value ranges.

        :param start: lower bound of value sequence
        :param stop: upper bound of value sequence
        :param step: width between points in the sequence
        :returns: a SortedDict of the values of the function between start and stop, with the x-distance between
            each data-point equal to `step`; like normal "range" functions the right endpoint is not included
        """

        step = step or (stop - start)
        if len(self.breakpoints) == 0:
            num_values = int(math.ceil((stop - start) / step))
            return SortedDict([(start + step * i, self._initial_value) for i in range(num_values)])

        curr_xval = start
        curr_value = self.call(start)
        next_index, next_breakpoint, next_value = self._breakpoint_info(self.breakpoints.bisect(start))

        sequence = SortedDict()
        while curr_xval < stop:
            sequence[curr_xval] = curr_value

            next_xval = min(stop, curr_xval + step)
            while next_breakpoint and next_xval >= next_breakpoint:
                assert next_index is not None  # if next_breakpoint is set, next_index should also be set
                curr_value = next_value
                next_index, next_breakpoint, next_value = self._breakpoint_info(next_index + 1)
            curr_xval = next_xval

        return sequence 
Example #25
Source File: io.py    From clusterman with Apache License 2.0 5 votes vote down vote up
def _register_handlers():
    # These operations are idempotent, it's safe to do more than once
    jsonpickle.handlers.register(arrow.Arrow, ArrowSerializer)
    jsonpickle.handlers.register(SortedDict, SortedDictSerializer) 
Example #26
Source File: orderbook.py    From btc_bot_framework with MIT License 5 votes vote down vote up
def init(self):
        self.sd_bids = SortedDict()
        self.sd_asks = SortedDict() 
Example #27
Source File: orderbook.py    From btc_bot_framework with MIT License 5 votes vote down vote up
def __on_message(self, msg):
        p = msg['params']
        ch = p['channel']
        m = p['message']
        if ch == self.ch_snapshot:
            bids, asks = SortedDict(), SortedDict()
            self.__update(bids, m['bids'], -1)
            self.__update(asks, m['asks'], 1)
            self.sd_bids, self.sd_asks = bids, asks
        elif ch == self.ch_update:
            self.__update(self.sd_bids, m['bids'], -1)
            self.__update(self.sd_asks, m['asks'], 1)

        self._trigger_callback() 
Example #28
Source File: orderbook.py    From btc_bot_framework with MIT License 5 votes vote down vote up
def __on_message(self, msg):
        d = msg['message']['data']
        ch = msg['room_name']

        if ch == self.ch_snapshot:
            bids, asks = SortedDict(), SortedDict()
            self.__update(bids, d['bids'], -1)
            self.__update(asks, d['asks'], 1)
            self.sd_bids, self.sd_asks = bids, asks
        elif ch == self.ch_update:
            self.__update(self.sd_bids, d['b'], -1)
            self.__update(self.sd_asks, d['a'], 1)

        self._trigger_callback() 
Example #29
Source File: qfeature_map.py    From angr-management with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, disasm_view, parent=None):
        super().__init__(parent)

        self.disasm_view = disasm_view
        self.workspace = disasm_view.workspace
        self.instance = self.workspace.instance

        self.orientation = Orientation.Vertical

        # widgets
        self.view = None  # type: QFeatureMapView

        # items
        self._insn_indicators = [ ]

        # data instance
        self.addr = ObjectContainer(None, name='The current address of the Feature Map.')

        # cached values
        self._addr_to_region = SortedDict()
        self._regionaddr_to_offset = SortedDict()
        self._offset_to_regionaddr = SortedDict()
        self._total_size = None
        self._regions_painted = False

        self._init_widgets()
        self._register_events() 
Example #30
Source File: qlinear_viewer.py    From angr-management with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, workspace, disasm_view, parent=None):
        QDisassemblyBaseControl.__init__(self, workspace, disasm_view, QAbstractScrollArea)
        QAbstractScrollArea.__init__(self, parent=parent)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.horizontalScrollBar().setSingleStep(Conf.disasm_font_width)
        self.verticalScrollBar().setSingleStep(16)

        # self.setTransformationAnchor(QGraphicsView.NoAnchor)
        # self.setResizeAnchor(QGraphicsView.NoAnchor)
        # self.setAlignment(Qt.AlignLeft)

        self._viewer = None  # type: QLinearDisassemblyView

        self._line_height = Conf.disasm_font_height

        self._offset_to_region = SortedDict()
        self._addr_to_region_offset = SortedDict()
        # Offset (in bytes) into the entire blanket view
        self._offset = 0
        # The maximum offset (in bytes) of the blanket view
        self._max_offset = None
        # The first line that is rendered of the first object in self.objects. Start from 0.
        self._start_line_in_object = 0

        self._disasms = { }
        self.objects = [ ]

        self.verticalScrollBar().actionTriggered.connect(self._on_vertical_scroll_bar_triggered)

        self._init_widgets()