docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Start a subscription for profit and loss events for single positions. Returns a :class:`.PnLSingle` object that is kept live updated. The result can also be queried from :meth:`.pnlSingle`. https://interactivebrokers.github.io/tws-api/pnl.html Args: account: Subscribe to t...
def reqPnLSingle( self, account: str, modelCode: str, conId: int) -> PnLSingle: key = (account, modelCode, conId) assert key not in self.wrapper.pnlSingleKey2ReqId reqId = self.client.getReqId() self.wrapper.pnlSingleKey2ReqId[key] = reqId pnlSingle = PnLSing...
104,845
Cancel PnLSingle subscription for the given account, modelCode and conId. Args: account: Cancel for this account name. modelCode: Cancel for this account model. conId: Cancel for this contract ID.
def cancelPnLSingle( self, account: str, modelCode: str, conId: int): key = (account, modelCode, conId) reqId = self.wrapper.pnlSingleKey2ReqId.pop(key, None) if reqId: self.client.cancelPnLSingle(reqId) self.wrapper.pnlSingles.pop(reqId, None) ...
104,846
Get a list of contract details that match the given contract. If the returned list is empty then the contract is not known; If the list has multiple values then the contract is ambiguous. The fully qualified contract is available in the the ContractDetails.contract attribute. T...
def reqContractDetails(self, contract: Contract) -> List[ContractDetails]: return self._run(self.reqContractDetailsAsync(contract))
104,847
Request contract descriptions of contracts that match a pattern. This method is blocking. https://interactivebrokers.github.io/tws-api/matching_symbols.html Args: pattern: The first few letters of the ticker symbol, or for longer strings a character sequence matchi...
def reqMatchingSymbols(self, pattern: str) -> List[ContractDescription]: return self._run(self.reqMatchingSymbolsAsync(pattern))
104,848
Request price increments rule. https://interactivebrokers.github.io/tws-api/minimum_increment.html Args: marketRuleId: ID of market rule. The market rule IDs for a contract can be obtained via :meth:`.reqContractDetails` from :class:`.Contrac...
def reqMarketRule(self, marketRuleId: int) -> PriceIncrement: return self._run(self.reqMarketRuleAsync(marketRuleId))
104,849
Request realtime 5 second bars. https://interactivebrokers.github.io/tws-api/realtime_bars.html Args: contract: Contract of interest. barSize: Must be 5. whatToShow: Specifies the source for constructing bars. Can be 'TRADES', 'MIDPOINT', 'BID' or 'A...
def reqRealTimeBars( self, contract: Contract, barSize: int, whatToShow: str, useRTH: bool, realTimeBarsOptions: List[TagValue] = None) -> RealTimeBarList: reqId = self.client.getReqId() bars = RealTimeBarList() bars.reqId = reqId bars.contrac...
104,850
Cancel the realtime bars subscription. Args: bars: The bar list that was obtained from ``reqRealTimeBars``.
def cancelRealTimeBars(self, bars: RealTimeBarList): self.client.cancelRealTimeBars(bars.reqId) self.wrapper.endSubscription(bars)
104,851
Cancel the update subscription for the historical bars. Args: bars: The bar list that was obtained from ``reqHistoricalData`` with a keepUpToDate subscription.
def cancelHistoricalData(self, bars: BarDataList): self.client.cancelHistoricalData(bars.reqId) self.wrapper.endSubscription(bars)
104,853
Get the datetime of earliest available historical data for the contract. Args: contract: Contract of interest. useRTH: If True then only show data from within Regular Trading Hours, if False then show all data. formatDate: If set to 2 then the result ...
def reqHeadTimeStamp( self, contract: Contract, whatToShow: str, useRTH: bool, formatDate: int = 1) -> datetime.datetime: return self._run( self.reqHeadTimeStampAsync( contract, whatToShow, useRTH, formatDate))
104,855
Unsubscribe from realtime streaming tick data. Args: contract: The exact contract object that was used to subscribe with.
def cancelMktData(self, contract: Contract): ticker = self.ticker(contract) reqId = self.wrapper.endTicker(ticker, 'mktData') if reqId: self.client.cancelMktData(reqId) else: self._logger.error( 'cancelMktData: ' f'No reqId found for contr...
104,857
Subscribe to tick-by-tick data and return the Ticker that holds the ticks in ticker.tickByTicks. https://interactivebrokers.github.io/tws-api/tick_data.html Args: contract: Contract of interest. tickType: One of 'Last', 'AllLast', 'BidAsk' or 'MidPoint'. nu...
def reqTickByTickData( self, contract: Contract, tickType: str, numberOfTicks: int = 0, ignoreSize: bool = False) -> Ticker: reqId = self.client.getReqId() ticker = self.wrapper.startTicker(reqId, contract, tickType) self.client.reqTickByTickData( req...
104,858
Unsubscribe from tick-by-tick data Args: contract: The exact contract object that was used to subscribe with.
def cancelTickByTickData(self, contract: Contract, tickType: str): ticker = self.ticker(contract) reqId = self.wrapper.endTicker(ticker, tickType) if reqId: self.client.cancelTickByTickData(reqId) else: self._logger.error( f'cancelMktData:...
104,859
Unsubscribe from market depth data. Args: contract: The exact contract object that was used to subscribe with.
def cancelMktDepth(self, contract: Contract, isSmartDepth=False): ticker = self.ticker(contract) reqId = self.wrapper.endTicker(ticker, 'mktDepth') if reqId: self.client.cancelMktDepth(reqId, isSmartDepth) else: self._logger.error( f'cance...
104,861
Request histogram data. This method is blocking. https://interactivebrokers.github.io/tws-api/histograms.html Args: contract: Contract to query. useRTH: If True then only show data from within Regular Trading Hours, if False then show all data. ...
def reqHistogramData( self, contract: Contract, useRTH: bool, period: str) -> List[HistogramData]: return self._run( self.reqHistogramDataAsync(contract, useRTH, period))
104,862
Do a blocking market scan by starting a subscription and canceling it after the initial list of results are in. This method is blocking. https://interactivebrokers.github.io/tws-api/market_scanners.html Args: subscription: Basic filters. scannerSubscriptionOpti...
def reqScannerData( self, subscription: ScannerSubscription, scannerSubscriptionOptions: List[TagValue] = None, scannerSubscriptionFilterOptions: List[TagValue] = None) -> ScanDataList: return self._run( self.reqScannerDataAsync( ...
104,864
Subscribe to market scan data. https://interactivebrokers.github.io/tws-api/market_scanners.html Args: subscription: What to scan for. scannerSubscriptionOptions: Unknown. scannerSubscriptionFilterOptions: Unknown.
def reqScannerSubscription( self, subscription: ScannerSubscription, scannerSubscriptionOptions: List[TagValue] = None, scannerSubscriptionFilterOptions: List[TagValue] = None) -> ScanDataList: reqId = self.client.getReqId() dataList = ScanDataLis...
104,865
Cancel market data subscription. https://interactivebrokers.github.io/tws-api/market_scanners.html Args: dataList: The scan data list that was obtained from :meth:`.reqScannerSubscription`.
def cancelScannerSubscription(self, dataList: ScanDataList): self.client.cancelScannerSubscription(dataList.reqId) self.wrapper.endSubscription(dataList)
104,866
Calculate the volatility given the option price. This method is blocking. https://interactivebrokers.github.io/tws-api/option_computations.html Args: contract: Option contract. optionPrice: Option price to use in calculation. underPrice: Price of the underl...
def calculateImpliedVolatility( self, contract: Contract, optionPrice: float, underPrice: float, implVolOptions: List[TagValue] = None) -> OptionComputation: return self._run( self.calculateImpliedVolatilityAsync( contract, optionPrice, un...
104,867
Calculate the option price given the volatility. This method is blocking. https://interactivebrokers.github.io/tws-api/option_computations.html Args: contract: Option contract. volatility: Option volatility to use in calculation. underPrice: Price of the un...
def calculateOptionPrice( self, contract: Contract, volatility: float, underPrice: float, optPrcOptions=None) -> OptionComputation: return self._run( self.calculateOptionPriceAsync( contract, volatility, underPrice, optPrcOptions))
104,868
Get the option chain. This method is blocking. https://interactivebrokers.github.io/tws-api/options.html Args: underlyingSymbol: Symbol of underlier contract. futFopExchange: Exchange (only for ``FuturesOption``, otherwise leave blank). unde...
def reqSecDefOptParams( self, underlyingSymbol: str, futFopExchange: str, underlyingSecType: str, underlyingConId: int) -> List[OptionChain]: return self._run( self.reqSecDefOptParamsAsync( underlyingSymbol, futFopExchange, ...
104,869
Get the body of a news article. This method is blocking. https://interactivebrokers.github.io/tws-api/news.html Args: providerCode: Code indicating news provider, like 'BZ' or 'FLY'. articleId: ID of the specific article. newsArticleOptions: Unknown.
def reqNewsArticle( self, providerCode: str, articleId: str, newsArticleOptions: List[TagValue] = None) -> NewsArticle: return self._run( self.reqNewsArticleAsync( providerCode, articleId, newsArticleOptions))
104,871
Replaces Financial Advisor's settings. Args: faDataType: See :meth:`.requestFA`. xml: The XML-formatted configuration string.
def replaceFA(self, faDataType: int, xml: str): self.client.replaceFA(faDataType, xml)
104,873
Schedule the callback to be run at the given time with the given arguments. Args: time: Time to run callback. If given as :py:class:`datetime.time` then use today as date. callback: Callable scheduled to run. args: Arguments for to call callback with.
def schedule( time: Union[datetime.time, datetime.datetime], callback: Callable, *args): dt = _fillDate(time) now = datetime.datetime.now(dt.tzinfo) delay = (dt - now).total_seconds() loop = asyncio.get_event_loop() loop.call_later(delay, callback, *args)
104,912
Iterator that waits periodically until certain time points are reached while yielding those time points. Args: start: Start time, can be specified as datetime.datetime, or as datetime.time in which case today is used as the date end: End time, can be specified as datetime.datetime, ...
def timeRange( start: datetime.time, end: datetime.time, step: float) -> Iterator[datetime.datetime]: assert step > 0 start = _fillDate(start) end = _fillDate(end) delta = datetime.timedelta(seconds=step) t = start while t < datetime.datetime.now(): t += delta wh...
104,913
Run combined Qt5/asyncio event loop. Args: qtLib: Name of Qt library to use, can be 'PyQt5' or 'PySide2'. period: Period in seconds to poll Qt.
def useQt(qtLib: str = 'PyQt5', period: float = 0.01): def qt_step(): loop.call_later(period, qt_step) if not stack: qloop = QEventLoop() timer = QTimer() timer.timeout.connect(qloop.quit) stack.append((qloop, timer)) qloop, timer = stack....
104,917
Stock contract. Args: symbol: Symbol name. exchange: Destination exchange. currency: Underlying currency.
def __init__( self, symbol: str = '', exchange: str = '', currency: str = '', **kwargs): Contract.__init__( self, secType='STK', symbol=symbol, exchange=exchange, currency=currency, **kwargs)
105,081
Foreign exchange currency pair. Args: pair: Shortcut for specifying symbol and currency, like 'EURUSD'. exchange: Destination exchange. symbol: Base currency. currency: Quote currency.
def __init__( self, pair: str = '', exchange: str = 'IDEALPRO', symbol: str = '', currency: str = '', **kwargs): if pair: assert len(pair) == 6 symbol = symbol or pair[:3] currency = currency or pair[3:] Contract.__init__( ...
105,083
To check if word is present in the keyword_trie_dict Args: word : string word that you want to check Returns: status : bool If word is present as it is in keyword_trie_dict then we return True, else False Examples: >>> keywor...
def __contains__(self, word): if not self.case_sensitive: word = word.lower() current_dict = self.keyword_trie_dict len_covered = 0 for char in word: if char in current_dict: current_dict = current_dict[char] len_covered +=...
105,111
To add keyword to the dictionary pass the keyword and the clean name it maps to. Args: keyword : string keyword that you want to identify clean_name : string clean term for that keyword that you would want to get back in return or replace ...
def __setitem__(self, keyword, clean_name=None): status = False if not clean_name and keyword: clean_name = keyword if keyword and clean_name: if not self.case_sensitive: keyword = keyword.lower() current_dict = self.keyword_trie_dict...
105,112
To remove keyword from the dictionary pass the keyword and the clean name it maps to. Args: keyword : string keyword that you want to remove if it's present Examples: >>> keyword_processor.add_keyword('Big Apple') >>> del keyword_processor['B...
def __delitem__(self, keyword): status = False if keyword: if not self.case_sensitive: keyword = keyword.lower() current_dict = self.keyword_trie_dict character_trie_list = [] for letter in keyword: if letter in cur...
105,113
To add keywords from a list Args: keyword_list (list(str)): List of keywords to add Examples: >>> keyword_processor.add_keywords_from_list(["java", "python"]}) Raises: AttributeError: If `keyword_list` is not a list.
def add_keywords_from_list(self, keyword_list): if not isinstance(keyword_list, list): raise AttributeError("keyword_list should be a list") for keyword in keyword_list: self.add_keyword(keyword)
105,117
To remove keywords present in list Args: keyword_list (list(str)): List of keywords to remove Examples: >>> keyword_processor.remove_keywords_from_list(["java", "python"]}) Raises: AttributeError: If `keyword_list` is not a list.
def remove_keywords_from_list(self, keyword_list): if not isinstance(keyword_list, list): raise AttributeError("keyword_list should be a list") for keyword in keyword_list: self.remove_keyword(keyword)
105,118
Normalize datetime intervals. Given a pair of datetime.date or datetime.datetime objects, returns a 2-tuple of tz-aware UTC datetimes spanning the same interval. For datetime.date objects, the returned interval starts at 00:00:00.0 on the first date and ends at 00:00:00.0 on the second. Naive dat...
def _normalize_interval(start, end, value): if not isinstance(start, datetime): start = datetime.combine(start, START_OF_DAY) end = datetime.combine(end, START_OF_DAY) if start.tzinfo is None: start = pytz.UTC.localize(start) end = pytz.UTC.localize(end) else: s...
106,213
Performs a keyboard key press without the release. This will put that key in a held down state. NOTE: For some reason, this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field. Args: key (str): The key to be pressed down. The valid names are liste...
def _keyDown(key): if key not in keyboardMapping or keyboardMapping[key] is None: return if type(key) == int: fake_input(_display, X.KeyPress, key) _display.sync() return needsShift = pyautogui.isShiftCharacter(key) if needsShift: fake_input(_display, X.Key...
106,250
Performs a keyboard key release (without the press down beforehand). Args: key (str): The key to be released up. The valid names are listed in pyautogui.KEY_NAMES. Returns: None
def _keyUp(key): if key not in keyboardMapping or keyboardMapping[key] is None: return if type(key) == int: keycode = key else: keycode = keyboardMapping[key] fake_input(_display, X.KeyRelease, keycode) _display.sync()
106,251
Return Window object if 'title' or its part found in visible windows titles, else return None Return only 1 window found first Args: title: unicode string exact (bool): True if search only exact match
def getWindow(title, exact=False): titles = getWindows() hwnd = titles.get(title, None) if not hwnd and not exact: for k, v in titles.items(): if title in k: hwnd = v break if hwnd: return Window(hwnd) else: return None
106,253
Returns the current xy coordinates of the mouse cursor as a two-integer tuple. Args: x (int, None, optional) - If not None, this argument overrides the x in the return value. y (int, None, optional) - If not None, this argument overrides the y in the return value. Returns: ...
def position(x=None, y=None): posx, posy = platformModule._position() posx = int(posx) posy = int(posy) if x is not None: # If set, the x parameter overrides the return value. posx = int(x) if y is not None: # If set, the y parameter overrides the return value. posy = int(y) ...
106,261
Returns whether the given xy coordinates are on the screen or not. Args: Either the arguments are two separate values, first arg for x and second for y, or there is a single argument of a sequence with two values, the first x and the second y. Example: onScreen(x, y) or onScreen([x, y...
def onScreen(x, y=None): x, y = _unpackXY(x, y) x = int(x) y = int(y) width, height = platformModule._size() return 0 <= x < width and 0 <= y < height
106,262
Performs a keyboard key press without the release. This will put that key in a held down state. NOTE: For some reason, this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field. Args: key (str): The key to be pressed down. The valid names are liste...
def keyDown(key, pause=None, _pause=True): if len(key) > 1: key = key.lower() _failSafeCheck() platformModule._keyDown(key) _autoPause(pause, _pause)
106,275
Performs a keyboard key release (without the press down beforehand). Args: key (str): The key to be released up. The valid names are listed in KEYBOARD_KEYS. Returns: None
def keyUp(key, pause=None, _pause=True): if len(key) > 1: key = key.lower() _failSafeCheck() platformModule._keyUp(key) _autoPause(pause, _pause)
106,276
Performs a keyboard key press without the release. This will put that key in a held down state. NOTE: For some reason, this does not seem to cause key repeats like would happen if a keyboard key was held down on a text field. Args: key (str): The key to be pressed down. The valid names are liste...
def _keyDown(key): if key not in keyboardMapping or keyboardMapping[key] is None: return needsShift = pyautogui.isShiftCharacter(key) mods, vkCode = divmod(keyboardMapping[key], 0x100) for apply_mod, vk_mod in [(mods & 4, 0x12), (mods & 2, 0x11), (mods & 1 or needsShift, 0x1...
106,282
Send the mouse down event to Windows by calling the mouse_event() win32 function. Args: x (int): The x position of the mouse event. y (int): The y position of the mouse event. button (str): The mouse button, either 'left', 'middle', or 'right' Returns: None
def _mouseDown(x, y, button): if button == 'left': try: _sendMouseEvent(MOUSEEVENTF_LEFTDOWN, x, y) except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60 pass elif button == ...
106,284
Send the mouse up event to Windows by calling the mouse_event() win32 function. Args: x (int): The x position of the mouse event. y (int): The y position of the mouse event. button (str): The mouse button, either 'left', 'middle', or 'right' Returns: None
def _mouseUp(x, y, button): if button == 'left': try: _sendMouseEvent(MOUSEEVENTF_LEFTUP, x, y) except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60 pass elif button == 'mid...
106,285
Send the mouse click event to Windows by calling the mouse_event() win32 function. Args: button (str): The mouse button, either 'left', 'middle', or 'right' x (int): The x position of the mouse event. y (int): The y position of the mouse event. Returns: None
def _click(x, y, button): if button == 'left': try: _sendMouseEvent(MOUSEEVENTF_LEFTCLICK, x, y) except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60 pass elif button == 'mi...
106,286
The helper function that actually makes the call to the mouse_event() win32 function. Args: ev (int): The win32 code for the mouse event. Use one of the MOUSEEVENTF_* constants for this argument. x (int): The x position of the mouse event. y (int): The y position of the mouse event. ...
def _sendMouseEvent(ev, x, y, dwData=0): assert x != None and y != None, 'x and y cannot be set to None' # TODO: ARG! For some reason, SendInput isn't working for mouse events. I'm switching to using the older mouse_event win32 function. #mouseStruct = MOUSEINPUT() #mouseStruct.dx = x #mouseStr...
106,287
Send the mouse vertical scroll event to Windows by calling the mouse_event() win32 function. Args: clicks (int): The amount of scrolling to do. A positive value is the mouse wheel moving forward (scrolling up), a negative value is backwards (down). x (int): The x position of the mouse event. ...
def _scroll(clicks, x=None, y=None): startx, starty = _position() width, height = _size() if x is None: x = startx else: if x < 0: x = 0 elif x >= width: x = width - 1 if y is None: y = starty else: if y < 0: y = 0...
106,288
Helper function for creating `FunctionCall`s with `Arguments`. Args: function: The value to store for the action function. arguments: The values to store for the arguments of the action. Can either be an `Arguments` object, a `dict`, or an iterable. If a `dict` or an iterable is provide...
def all_arguments(cls, function, arguments): if isinstance(arguments, dict): arguments = Arguments(**arguments) elif not isinstance(arguments, Arguments): arguments = Arguments(*arguments) return cls(function, arguments)
106,478
Initialize the runconfig with the various directories needed. Args: replay_dir: Where to find replays. Might not be accessible to SC2. data_dir: Where SC2 should find the data and battle.net cache. tmp_dir: The temporary directory. None is system default. cwd: Where to set the current worki...
def __init__(self, replay_dir, data_dir, tmp_dir, cwd=None, env=None): self.replay_dir = replay_dir self.data_dir = data_dir self.tmp_dir = tmp_dir self.cwd = cwd self.env = env
106,505
Save a replay to a directory, returning the path to the replay. Args: replay_data: The result of controller.save_replay(), ie the binary data. replay_dir: Where to save the replay. This can be absolute or relative. prefix: Optional prefix for the replay filename. Returns: The full path...
def save_replay(self, replay_data, replay_dir, prefix=None): if not prefix: replay_filename = "" elif os.path.sep in prefix: raise ValueError("Prefix '%s' contains '%s', use replay_dir instead." % ( prefix, os.path.sep)) else: replay_filename = prefix + "_" now = datetim...
106,509
Create a game for the agents to join. Args: map_name: The map to use.
def create_game(self, map_name): map_inst = maps.get(map_name) map_data = map_inst.data(self._run_config) if map_name not in self._saved_maps: for controller in self._controllers: controller.save_map(map_inst.path, map_data) self._saved_maps.add(map_name) # Form the create game...
106,549
Create a game, one remote agent vs the specified bot. Args: map_name: The map to use. bot_difficulty: The difficulty of the bot to play against. bot_race: The race for the bot. bot_first: Whether the bot should be player 1 (else is player 2).
def create_game( self, map_name, bot_difficulty=sc_pb.VeryEasy, bot_race=sc_common.Random, bot_first=False): self._controller.ping() # Form the create game message. map_inst = maps.get(map_name) map_data = map_inst.data(self._run_config) if map_name not in self._s...
106,552
Apply actions, step the world forward, and return observations. Args: actions: A list of actions meeting the action spec, one per agent. step_mul: If specified, use this rather than the environment's default. Returns: A tuple of TimeStep namedtuples, one per agent.
def step(self, actions, step_mul=None): if self._state == environment.StepType.LAST: return self.reset() skip = not self._ensure_available_actions self._parallel.run( (c.act, f.transform_action(o.observation, a, skip_available=skip)) for c, f, o, a in zip( self._contr...
106,570
Forwards ports such that multiplayer works between machines. Args: remote_host: Where to ssh to. local_host: "127.0.0.1" or "::1". local_listen_ports: Which ports to listen on locally to forward remotely. remote_listen_ports: Which ports to listen on remotely to forward locally. Returns: The s...
def forward_ports(remote_host, local_host, local_listen_ports, remote_listen_ports): if ":" in local_host and not local_host.startswith("["): local_host = "[%s]" % local_host ssh = whichcraft.which("ssh") or whichcraft.which("plink") if not ssh: raise ValueError("Couldn't find an ssh...
106,602
Initializes the TestEnvironment. The `next_observation` is initialized to be reward = 0., discount = 1., and an appropriately sized observation of all zeros. `episode_length` is set to `float('inf')`. Args: num_agents: The number of agents. observation_spec: The observation specs for each ...
def __init__(self, num_agents, observation_spec, action_spec): self._num_agents = num_agents self._observation_spec = observation_spec self._action_spec = action_spec self._episode_steps = 0 self.next_timestep = [ environment.TimeStep( step_type=environment.StepType.MID, ...
106,607
A surface to display on screen. Args: surf: The actual pygame.Surface (or subsurface). surf_type: A SurfType, used to tell how to treat clicks in that area. surf_rect: Rect of the surface relative to the window. world_to_surf: Convert a world point to a pixel on the surface. world_to_...
def __init__(self, surf, surf_type, surf_rect, world_to_surf, world_to_obs, draw): self.surf = surf self.surf_type = surf_type self.surf_rect = surf_rect self.world_to_surf = world_to_surf self.world_to_obs = world_to_obs self.draw = draw
106,632
Take the game info and the static data needed to set up the game. This must be called before render or get_actions for each game or restart. Args: game_info: A `sc_pb.ResponseGameInfo` object for this game. static_data: A `StaticData` object for this game. Raises: ValueError: if there i...
def init(self, game_info, static_data): self._game_info = game_info self._static_data = static_data if not game_info.HasField("start_raw"): raise ValueError("Raw observations are required for the renderer.") self._map_size = point.Point.build(game_info.start_raw.map_size) if game_info....
106,641
Create and send a specific request, and return the response. For example: send(ping=sc_pb.RequestPing()) => sc_pb.ResponsePing Args: **kwargs: A single kwarg with the name and value to fill in to Request. Returns: The Response corresponding to your request.
def send(self, **kwargs): assert len(kwargs) == 1, "Must make a single request." res = self.send_req(sc_pb.Request(**kwargs)) return getattr(res, list(kwargs.keys())[0])
106,688
Initialize a Features instance matching the specified interface format. Args: agent_interface_format: See the documentation for `AgentInterfaceFormat`. map_size: The size of the map in world units, needed for feature_units. Raises: ValueError: if agent_interface_format isn't specified. ...
def __init__(self, agent_interface_format=None, map_size=None): if not agent_interface_format: raise ValueError("Please specify agent_interface_format") self._agent_interface_format = agent_interface_format aif = self._agent_interface_format if (aif.use_feature_units or aif.use_came...
106,709
Transform an SC2-style action into an agent-style action. This should be the inverse of `transform_action`. Args: action: a `sc_pb.Action` to be transformed. Returns: A corresponding `actions.FunctionCall`. Raises: ValueError: if it doesn't know how to transform this action.
def reverse_action(self, action): FUNCTIONS = actions.FUNCTIONS # pylint: disable=invalid-name aif = self._agent_interface_format def func_call_ability(ability_id, cmd_type, *args): if ability_id not in actions.ABILITY_IDS: logging.warning("Unknown ability_id: %s. This is probab...
106,716
Decorate a function/method to check its timings. To use the function's name: @sw.decorate def func(): pass To name it explicitly: @sw.decorate("name") def random_func_name(): pass Args: name_or_func: the name or the function to decorate. Returns: I...
def decorate(self, name_or_func): if os.environ.get("SC2_NO_STOPWATCH"): return name_or_func if callable(name_or_func) else lambda func: func def decorator(name, func): @functools.wraps(func) def _stopwatch(*args, **kwargs): with self(name): return func(*args, **kwargs)...
106,758
Wrapper for _log_counter_per_token. Args: token: The token for which to look up the count. Returns: The number of times this function has been called with *token* as an argument (starting at 0)
def _GetNextLogCountPerToken(token): global _log_counter_per_token # pylint: disable=global-variable-not-assigned _log_counter_per_token[token] = 1 + _log_counter_per_token.get(token, -1) return _log_counter_per_token[token]
107,664
Log 'msg % args' at level 'level' once per 'n' times. Logs the 1st call, (N+1)st call, (2N+1)st call, etc. Not threadsafe. Args: level: The level at which to log. msg: The message to be logged. n: The number of times this should be called before it is logged. *args: The args to be substit...
def log_every_n(level, msg, n, *args): count = _GetNextLogCountPerToken(_GetFileAndLine()) log_if(level, msg, not (count % n), *args)
107,665
A generic function to load mnist-like dataset. Parameters: ---------- shape : tuple The shape of digit images. path : str The path that the data is downloaded to. name : str The dataset name you want to use(the default is 'mnist'). url : str The url of dataset(th...
def _load_mnist_dataset(shape, path, name='mnist', url='http://yann.lecun.com/exdb/mnist/'): path = os.path.join(path, name) # Define functions for loading mnist-like data's images and labels. # For convenience, they also download the requested files if needed. def load_mnist_images(path, filename...
107,679
Return zero-filled state tensor(s). Args: batch_size: int, float, or unit Tensor representing the batch size. Returns: tensor of shape '[batch_size x shape[0] x shape[1] x num_features] filled with zeros
def zero_state(self, batch_size, dtype=LayersConfig.tf_dtype): shape = self.shape num_features = self.num_features # TODO : TypeError: 'NoneType' object is not subscriptable zeros = tf.zeros([batch_size, shape[0], shape[1], num_features * 2], dtype=dtype) return zeros
107,872
Perform random distortions on an image. Args: image: A float32 Tensor of shape [height, width, 3] with values in [0, 1). thread_id: Preprocessing thread id used to select the ordering of color distortions. There should be a multiple of 2 preprocessing threads. Returns:```` distor...
def distort_image(image, thread_id): # Randomly flip horizontally. with tf.name_scope("flip_horizontal"): # , values=[image]): # DH MOdify # with tf.name_scope("flip_horizontal", values=[image]): image = tf.image.random_flip_left_right(image) # Randomly distort the colors based on thre...
108,001
Uses RMSProp to compute step from gradients. Args: grads: numpy array of gradients. cache: numpy array of same shape as `grads` as RMSProp cache decay_rate: How fast to decay cache Returns: A tuple of step: numpy array of the same shape a...
def _rmsprop(self, grads, cache=None, decay_rate=0.95): if cache is None: cache = np.zeros_like(grads) cache = decay_rate * cache + (1 - decay_rate) * grads ** 2 step = -grads / np.sqrt(cache + K.epsilon()) return step, cache
108,259
Import a module path and create an api doc from it Args: string (str): string with line breaks to write to file. filename (str): filename without the .md out_path (str): The output directory
def to_md_file(string, filename, out_path="."): md_file = "%s.md" % filename with open(os.path.join(out_path, md_file), "w") as f: f.write(string) print("wrote {}.".format(md_file))
108,266
Initializes the markdown api generator. Args: src_root: The root folder name containing all the sources. Ex: src github_link: The base github link. Should include branch name. Ex: https://github.com/raghakot/keras-vis/tree/master All sourc...
def __init__(self, src_root, github_link): self.src_root = src_root self.github_link = github_link
108,267
Takes a function (or method) and documents it. Args: clsname (str, optional): class name to prepend to funcname. depth (int, optional): number of ### to append to function name
def func2md(self, func, clsname=None, names=None, depth=3): section = "#" * depth if names is None: names = [func.__name__] funcname = ", ".join(names) escfuncname = ", ".join(["`%s`" % funcname if funcname.startswith("_") else funcname for funcname in names]) ...
108,270
Searches for the nearest penultimate `Conv` or `Pooling` layer. Args: model: The `keras.models.Model` instance. layer_idx: The layer index within `model.layers`. penultimate_layer_idx: The pre-layer to `layer_idx`. If set to None, the nearest penultimate `Conv` or `Pooling` laye...
def _find_penultimate_layer(model, layer_idx, penultimate_layer_idx): if penultimate_layer_idx is None: for idx, layer in utils.reverse_enumerate(model.layers[:layer_idx - 1]): if isinstance(layer, Wrapper): layer = layer.layer if isinstance(layer, (_Conv, _Pooli...
108,273
Creates a copy of model by modifying all activations to use a custom op to modify the backprop behavior. Args: model: The `keras.models.Model` instance. backprop_modifier: One of `{'guided', 'rectified'}` Returns: A copy of model with modified activations for backwards pass.
def modify_model_backprop(model, backprop_modifier): # The general strategy is as follows: # - Save original model so that upstream callers don't see unexpected results with their models. # - Call backend specific function that registers the custom op and loads the model under modified context manager....
108,280
Normalizes the `output_tensor` with respect to `input_tensor` dimensions. This makes regularizer weight factor more or less uniform across various input image dimensions. Args: input_tensor: An tensor of shape: `(samples, channels, image_dims...)` if `image_data_format= channels_first` ...
def normalize(input_tensor, output_tensor): image_dims = utils.get_img_shape(input_tensor)[1:] return output_tensor / np.prod(image_dims)
108,284
Builds a L-p norm function. This regularizer encourages the intensity of pixels to stay bounded. i.e., prevents pixels from taking on very large values. Args: img_input: 4D image input tensor to the model of shape: `(samples, channels, rows, cols)` if data_format='channe...
def __init__(self, img_input, p=6.): super(LPNorm, self).__init__() if p < 1: raise ValueError('p value should range between [1, inf)') self.name = "L-{} Norm Loss".format(p) self.p = p self.img = img_input
108,287
Updates `kwargs` with dict of `defaults` Args: defaults: A dictionary of keys and values **kwargs: The kwargs to update. Returns: The updated kwargs.
def add_defaults_to_kwargs(defaults, **kwargs): defaults = dict(defaults) defaults.update(kwargs) return defaults
108,291
Helper utility to retrieve the callable function associated with a string identifier. Args: identifier: The identifier. Could be a string or function. module_globals: The global objects of the module. module_name: The module name Returns: The callable associated with the identi...
def get_identifier(identifier, module_globals, module_name): if isinstance(identifier, six.string_types): fn = module_globals.get(identifier) if fn is None: raise ValueError('Unknown {}: {}'.format(module_name, identifier)) return fn elif callable(identifier): re...
108,292
Applies modifications to the model layers to create a new Graph. For example, simply changing `model.layers[idx].activation = new activation` does not change the graph. The entire graph needs to be updated with modified inbound and outbound tensors because of change in layer building function. Args: ...
def apply_modifications(model, custom_objects=None): # The strategy is to save the modified model and load it back. This is done because setting the activation # in a Keras layer doesnt actually change the graph. We have to iterate the entire graph and change the # layer inbound and outbound nodes with...
108,293
Creates a uniformly distributed random array with the given `mean` and `std`. Args: shape: The desired shape mean: The desired mean (Default value = 128) std: The desired std (Default value = 20) Returns: Random numpy array of given `shape` uniformly distributed with desired `mean` and...
def random_array(shape, mean=128., std=20.): x = np.random.random(shape) # normalize around mean=0, std=1 x = (x - np.mean(x)) / (np.std(x) + K.epsilon()) # and then around the desired mean/std x = (x * std) + mean return x
108,294
Looks up the layer index corresponding to `layer_name` from `model`. Args: model: The `keras.models.Model` instance. layer_name: The name of the layer to lookup. Returns: The layer index if found. Raises an exception otherwise.
def find_layer_idx(model, layer_name): layer_idx = None for idx, layer in enumerate(model.layers): if layer.name == layer_name: layer_idx = idx break if layer_idx is None: raise ValueError("No layer with name '{}' within the model".format(layer_name)) return...
108,295
Utility function to scale the `input_array` to `input_range` throwing away high frequency artifacts. Args: input_array: An N-dim numpy array. input_range: Specifies the input range as a `(min, max)` tuple to rescale the `input_array`. Returns: The rescaled `input_array`.
def deprocess_input(input_array, input_range=(0, 255)): # normalize tensor: center on 0., ensure std is 0.1 input_array = input_array.copy() input_array -= input_array.mean() input_array /= (input_array.std() + K.epsilon()) input_array *= 0.1 # clip to [0, 1] input_array += 0.5 inp...
108,296
Utility function to stitch images together with a `margin`. Args: images: The array of 2D images to stitch. margin: The black border margin size between images (Default value = 5) cols: Max number of image cols. New row is created when number of images exceed the column size. (D...
def stitch_images(images, margin=5, cols=5): if len(images) == 0: return None h, w, c = images[0].shape n_rows = int(math.ceil(len(images) / cols)) n_cols = min(len(images), cols) out_w = n_cols * w + (n_cols - 1) * margin out_h = n_rows * h + (n_rows - 1) * margin stitched_im...
108,297
Returns image shape in a backend agnostic manner. Args: img: An image tensor of shape: `(channels, image_dims...)` if data_format='channels_first' or `(image_dims..., channels)` if data_format='channels_last'. Returns: Tuple containing image shape information in `(samples, channels...
def get_img_shape(img): if isinstance(img, np.ndarray): shape = img.shape else: shape = K.int_shape(img) if K.image_data_format() == 'channels_last': shape = list(shape) shape.insert(1, shape[-1]) shape = tuple(shape[:-1]) return shape
108,298
Utility function to load an image from disk. Args: path: The image file path. grayscale: True to convert to grayscale image (Default value = False) target_size: (w, h) to resize. (Default value = None) Returns: The loaded numpy image.
def load_img(path, grayscale=False, target_size=None): img = io.imread(path, grayscale) if target_size: img = transform.resize(img, target_size, preserve_range=True).astype('uint8') return img
108,299
Utility function to return the image net label for the final `dense` layer output index. Args: indices: Could be a single value or an array of indices whose labels should be looked up. Returns: Image net label corresponding to the image category.
def lookup_imagenet_labels(indices): global _CLASS_INDEX if _CLASS_INDEX is None: with open(os.path.join(os.path.dirname(__file__), '../../resources/imagenet_class_index.json')) as f: _CLASS_INDEX = json.load(f) indices = listify(indices) return [_CLASS_INDEX[str(idx)][1] for i...
108,300
Draws text over the image. Requires PIL. Args: img: The image to use. text: The text string to overlay. position: The text (x, y) position. (Default value = (10, 10)) font: The ttf or open type font to use. (Default value = 'FreeSans.ttf') font_size: The text font size. (Def...
def draw_text(img, text, position=(10, 10), font='FreeSans.ttf', font_size=14, color=(0, 0, 0)): _check_pil() font_files = _find_font_file(font) if len(font_files) == 0: logger.warn("Failed to lookup font '{}', falling back to default".format(font)) font = ImageFont.load_default() ...
108,301
Normalizes the numpy array to (min_value, max_value) Args: array: The numpy array min_value: The min value in normalized array (Default value = 0) max_value: The max value in normalized array (Default value = 1) Returns: The array normalized to range between (min_value, max_val...
def normalize(array, min_value=0., max_value=1.): arr_min = np.min(array) arr_max = np.max(array) normalized = (array - arr_min) / (arr_max - arr_min + K.epsilon()) return (max_value - min_value) * normalized + min_value
108,302
Determines the number of filters within the given `layer`. Args: layer: The keras layer to use. Returns: Total number of filters within `layer`. For `keras.layers.Dense` layer, this is the total number of outputs.
def get_num_filters(layer): # Handle layers with no channels. if K.ndim(layer.output) == 2: return K.int_shape(layer.output)[-1] channel_idx = 1 if K.image_data_format() == 'channels_first' else -1 return K.int_shape(layer.output)[channel_idx]
108,304
Overlays `array1` onto `array2` with `alpha` blending. Args: array1: The first numpy array. array2: The second numpy array. alpha: The alpha value of `array1` as overlayed onto `array2`. This value needs to be between [0, 1], with 0 being `array2` only to 1 being `array1` only (...
def overlay(array1, array2, alpha=0.5): if alpha < 0. or alpha > 1.: raise ValueError("`alpha` needs to be between [0, 1]") if array1.shape != array2.shape: raise ValueError('`array1` and `array2` must have the same shapes') return (array1 * alpha + array2 * (1. - alpha)).astype(array1...
108,305
Retrieve the Engine-level model params from a Swarm model Args: modelID - Engine-level model ID of the Swarm model Returns: JSON-encoded string containing Model Params
def getSwarmModelParams(modelID): # TODO: the use of nupic.frameworks.opf.helpers.loadExperimentDescriptionScriptFromDir when # retrieving module params results in a leakage of pf_base_descriptionNN and # pf_descriptionNN module imports for every call to getSwarmModelParams, so # the leakage is unlimited...
108,310
[private] Create the default database connection policy instance Parameters: ---------------------------------------------------------------- retval: The default database connection policy instance
def _createDefaultPolicy(cls): logger = _getLogger(cls) logger.debug( "Creating database connection policy: platform=%r; pymysql.VERSION=%r", platform.system(), pymysql.VERSION) if platform.system() == "Java": # NOTE: PooledDB doesn't seem to work under Jython # NOTE: not appr...
108,315
Get a Connection instance. Parameters: ---------------------------------------------------------------- retval: A ConnectionWrapper instance. NOTE: Caller is responsible for calling the ConnectionWrapper instance's release() method or use it in a context manag...
def acquireConnection(self): self._logger.debug("Acquiring connection") # Check connection and attempt to re-establish it if it died (this is # what PooledDB does) self._conn._ping_check() connWrap = ConnectionWrapper(dbConn=self._conn, cursor=self._conn.curs...
108,322
Get a connection from the pool. Parameters: ---------------------------------------------------------------- retval: A ConnectionWrapper instance. NOTE: Caller is responsible for calling the ConnectionWrapper instance's release() method or use it in a context ...
def acquireConnection(self): self._logger.debug("Acquiring connection") dbConn = self._pool.connection(shareable=False) connWrap = ConnectionWrapper(dbConn=dbConn, cursor=dbConn.cursor(), releaser=self._releaseConnection, ...
108,325
Create a Connection instance. Parameters: ---------------------------------------------------------------- retval: A ConnectionWrapper instance. NOTE: Caller is responsible for calling the ConnectionWrapper instance's release() method or use it in a context ma...
def acquireConnection(self): self._logger.debug("Acquiring connection") dbConn = SteadyDB.connect(** _getCommonSteadyDBArgsDict()) connWrap = ConnectionWrapper(dbConn=dbConn, cursor=dbConn.cursor(), releaser=self._releaseConnection, ...
108,328
The range of connected synapses for column. This is used to calculate the inhibition radius. This variation of the function only supports a 1 dimensional column topology. Parameters: ---------------------------- :param columnIndex: The index identifying a column in the permanence, ...
def _avgConnectedSpanForColumn1D(self, columnIndex): assert(self._inputDimensions.size == 1) connected = self._connectedSynapses[columnIndex].nonzero()[0] if connected.size == 0: return 0 else: return max(connected) - min(connected) + 1
108,372
The range of connectedSynapses per column, averaged for each dimension. This value is used to calculate the inhibition radius. This variation of the function only supports a 2 dimensional column topology. Parameters: ---------------------------- :param columnIndex: The index identifying a column...
def _avgConnectedSpanForColumn2D(self, columnIndex): assert(self._inputDimensions.size == 2) connected = self._connectedSynapses[columnIndex] (rows, cols) = connected.reshape(self._inputDimensions).nonzero() if rows.size == 0 and cols.size == 0: return 0 rowSpan = rows.max() - rows.min()...
108,373
Runs the OPF Model Parameters: ------------------------------------------------------------------------- retval: (completionReason, completionMsg) where completionReason is one of the ClientJobsDAO.CMPL_REASON_XXX equates.
def run(self): # ----------------------------------------------------------------------- # Load the experiment's description.py module descriptionPyModule = helpers.loadExperimentDescriptionScriptFromDir( self._experimentDir) expIface = helpers.getExperimentDescriptionInterfaceFromModule( ...
108,445
Main loop of the OPF Model Runner. Parameters: ----------------------------------------------------------------------- recordIterator: Iterator for counting number of records (see _runTask) learningOffAt: If not None, learning is turned off when we reach this iteration n...
def __runTaskMainLoop(self, numIters, learningOffAt=None): ## Reset sequence states in the model, so it starts looking for a new ## sequence self._model.resetSequenceStates() self._currentRecordIndex = -1 while True: # If killed by a terminator, stop running if self._isKilled: ...
108,446
Delete the stored checkpoint for the specified modelID. This function is called if the current model is now the best model, making the old model's checkpoint obsolete Parameters: ----------------------------------------------------------------------- modelID: The modelID for the checkpoint to ...
def __deleteModelCheckpoint(self, modelID): checkpointID = \ self._jobsDAO.modelsGetFields(modelID, ['modelCheckpointId'])[0] if checkpointID is None: return try: shutil.rmtree(os.path.join(self._experimentDir, str(self._modelCheckpointGUID))) except: self._logger.warn(...
108,449
Get the label for the metric being optimized. This function also caches the label in the instance variable self._optimizedMetricLabel Parameters: ----------------------------------------------------------------------- metricLabels: A sequence of all the labels being computed for this model Retur...
def __getOptimizedMetricLabel(self): matchingKeys = matchPatterns([self._optimizeKeyPattern], self._getMetricLabels()) if len(matchingKeys) == 0: raise Exception("None of the generated metrics match the specified " "optimization pattern: %s. Av...
108,451
Delete's the output cache associated with the given modelID. This actually clears up the resources associated with the cache, rather than deleting al the records in the cache Parameters: ----------------------------------------------------------------------- modelID: The id of the model whose ...
def __deleteOutputCache(self, modelID): # If this is our output, we should close the connection if modelID == self._modelID and self._predictionLogger is not None: self._predictionLogger.close() del self.__predictionCache self._predictionLogger = None self.__predictionCache = None
108,459
Creates and returns a PeriodicActivityMgr instance initialized with our periodic activities Parameters: ------------------------------------------------------------------------- retval: a PeriodicActivityMgr instance
def _initPeriodicActivities(self): # Activity to update the metrics for this model # in the models table updateModelDBResults = PeriodicActivityRequest(repeating=True, period=100, cb=self._updateModelDBRe...
108,460