INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Execute `func(*args)` in an asynchronous parallel process. :param funcs: Functions to be executed. :type funcs: list[callable] :param args: Arguments to be passed to first function call. :type args: tuple :param executor: Pool executor to run the function. :type execut...
def async_process(funcs, *args, executor=False, sol=None, callback=None, **kw): """ Execute `func(*args)` in an asynchronous parallel process. :param funcs: Functions to be executed. :type funcs: list[callable] :param args: Arguments to be passed to first function call. :type a...
Execute `sol._evaluate_node` in an asynchronous thread. :param sol: Solution to be updated. :type sol: schedula.utils.sol.Solution :param args: Arguments to be passed to node calls. :type args: tuple :param node_attr: Dictionary of node attributes. :type node_attr: dic...
def async_thread(sol, args, node_attr, node_id, *a, **kw): """ Execute `sol._evaluate_node` in an asynchronous thread. :param sol: Solution to be updated. :type sol: schedula.utils.sol.Solution :param args: Arguments to be passed to node calls. :type args: tuple :param nod...
Return the result of a `Future` object. :param obj: Value object. :type obj: concurrent.futures.Future | object :param timeout: The number of seconds to wait for the result if the future isn't done. If None, then there is no limit on the wait time. :type timeout: int :retu...
def await_result(obj, timeout=None): """ Return the result of a `Future` object. :param obj: Value object. :type obj: concurrent.futures.Future | object :param timeout: The number of seconds to wait for the result if the future isn't done. If None, then there is no limit on...
Return a dictionary of values derived directly from the VCS. This is the third attempt to find information by get_versions().
def git_versions_from_vcs(tag_prefix, root, verbose=False): """Return a dictionary of values derived directly from the VCS. This is the third attempt to find information by get_versions(). """ # this runs 'git' from the root of the source tree. This only gets called # if the git-archive 'subst' key...
This variation of get_versions() will be used in _version.py .
def get_versions(default={"version": "unknown", "full": ""}, verbose=False): """This variation of get_versions() will be used in _version.py .""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/no...
Creates a cross-tab or pivot table from a normalised input table. Use this function to 'denormalize' a table of normalized records. * The table argument can be a list of dictionaries or a Table object. (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/334621) * The left argument is a tuple of he...
def pivot(table, left, top, value): """ Creates a cross-tab or pivot table from a normalised input table. Use this function to 'denormalize' a table of normalized records. * The table argument can be a list of dictionaries or a Table object. (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/...
Function to download HRRR data for GSSHA URL: http://nomads.ncep.noaa.gov/cgi-bin/filter_hrrr_2d.pl Args: main_directory(str): Location of the output for the forecast data. forecast_start_date_string(str): String for day of forecast. Ex. '20160913' forecast_start_hour_string(st...
def download_hrrr_for_gssha(main_directory, forecast_start_date_string, #EX. '20160913' forecast_start_hour_string, #EX. '00' to '23' leftlon=-180, rightlon=180, toplat=90,bottomlat=-90): """ Function...
Patch the current RAML ResourceNode by the resource with the correct method if it exists If the resource with the specified method does not exist an exception is raised. :param str method: the method of the resource :raises UnsupportedResourceMethodError: i...
def _patch_resource(self, method): """ Patch the current RAML ResourceNode by the resource with the correct method if it exists If the resource with the specified method does not exist an exception is raised. :param str method: the method of the reso...
Parse RAML file
def parse_raml(self): """ Parse RAML file """ if utils.is_url(self.ramlfile): raml = utils.download_file(self.ramlfile) else: with codecs.open(self.ramlfile, "rb", encoding="utf-8") as raml_f: raml = raml_f.read() loader = raml...
Gets a resource by it's path and optional by it's method This method does not care about the supported resource methods unless it is specified. :param str resource_path: The path of the resource :param str method: The method of the path. :returns: the resou...
def get_resource(self, base_resource_path, resource_path, method=None): """ Gets a resource by it's path and optional by it's method This method does not care about the supported resource methods unless it is specified. :param str resource_path: The path of the ...
Returns the highest whole-number unit.
def auto(self): """Returns the highest whole-number unit.""" if self._value >= 1000000000000: return self.tb, 'tb' if self._value >= 1000000000: return self.gb, 'gb' if self._value >= 1000000: return self.mb, 'mb' if self._value >= 1000: ...
Returns the highest whole-number unit.
def auto(self): """Returns the highest whole-number unit.""" if self._value >= 1099511627776: return self.TiB, 'TiB' if self._value >= 1073741824: return self.GiB, 'GiB' if self._value >= 1048576: return self.MiB, 'MiB' if self._value >= 1024: ...
Like self.auto but calculates the next unit if >999.99.
def auto_no_thousands(self): """Like self.auto but calculates the next unit if >999.99.""" if self._value >= 1000000000000: return self.TiB, 'TiB' if self._value >= 1000000000: return self.GiB, 'GiB' if self._value >= 1000000: return self.MiB, 'MiB' ...
Prints an error message to stderr and exits with a status of 1 by default.
def error(message, code=1): """Prints an error message to stderr and exits with a status of 1 by default.""" if message: print('ERROR: {0}'.format(message), file=sys.stderr) else: print(file=sys.stderr) sys.exit(code)
This function updates the paths in the HMET card file to the new location of the HMET data. This is necessary because the file paths are absolute and will need to be updated if moved. Args: hmet_card_file_path(str): Location of the file used for the HMET_ASCII card. new_hmet_data_path(str):...
def update_hmet_card_file(hmet_card_file_path, new_hmet_data_path): """This function updates the paths in the HMET card file to the new location of the HMET data. This is necessary because the file paths are absolute and will need to be updated if moved. Args: hmet_card_file_path(str): Location...
get xarray dataset file handle to LSM files
def xd(self): """get xarray dataset file handle to LSM files""" if self._xd is None: path_to_lsm_files = path.join(self.lsm_input_folder_path, self.lsm_search_card) self._xd = pa.open_mfdataset(path_to_lsm_files, ...
load subset based on extent
def _set_subset_indices(self, y_min, y_max, x_min, x_max): """ load subset based on extent """ y_coords, x_coords = self.xd.lsm.coords dx = self.xd.lsm.dx dy = self.xd.lsm.dy lsm_y_indices_from_y, lsm_x_indices_from_y = \ np.where((y_coords >= (y_min ...
# Get extent from GSSHA Grid in LSM coordinates # Determine range within LSM Grid
def _load_modeling_extent(self): """ # Get extent from GSSHA Grid in LSM coordinates # Determine range within LSM Grid """ #### # STEP 1: Get extent from GSSHA Grid in LSM coordinates #### # reproject GSSHA grid and get bounds min_x, max_x, min_y, ...
This converts a UTC time integer to a string
def _time_to_string(self, dt, conversion_string="%Y %m %d %H %M"): """ This converts a UTC time integer to a string """ if self.output_timezone is not None: dt = dt.replace(tzinfo=utc) \ .astimezone(self.output_timezone) return dt.strftime(conversio...
This extracts the LSM data from a folder of netcdf files
def _load_lsm_data(self, data_var, conversion_factor=1, calc_4d_method=None, calc_4d_dim=None, time_step=None): """ This extracts the LSM data from a folder of netcdf files """ data = self.xd.lsm....
This function loads data from LSM and converts to GSSHA format
def _load_converted_gssha_data_from_lsm(self, gssha_var, lsm_var, load_type, time_step=None): """ This function loads data from LSM and converts to GSSHA format """ if 'radiation' in gssha_var: conversion_factor = self.netcdf_attributes[gssha_var]['conversion_factor'][load_ty...
This function checks the input var map array to ensure the required input variables exist
def _check_lsm_input(self, data_var_map_array): """ This function checks the input var map array to ensure the required input variables exist """ REQUIRED_HMET_VAR_LIST = ['Prcp', 'Pres', 'Temp', 'Clod', 'RlHm', 'Drad', 'Grad', 'WndS'] #...
This function resamples the data to match the GSSHA grid IN TESTING MODE
def _resample_data(self, gssha_var): """ This function resamples the data to match the GSSHA grid IN TESTING MODE """ self.data = self.data.lsm.resample(gssha_var, self.gssha_grid)
This function converts the data to hourly data and then puts it into the data_np_array USED WHEN GENERATING HMET DATA ONLY
def _convert_data_to_hourly(self, gssha_data_var): """ This function converts the data to hourly data and then puts it into the data_np_array USED WHEN GENERATING HMET DATA ONLY """ time_step_hours = np.diff(self.data.time)[0]/np.timedelta64(1, 'h') calc_function ...
This function takes array data and writes out a GSSHA ascii grid. Parameters: out_grid_file(str): Location of ASCII file to generate. lsm_data_var(str or list): This is the variable name for precipitation in the LSM files. gssha_convert_var(str): This is the name of the vari...
def lsm_var_to_grid(self, out_grid_file, lsm_data_var, gssha_convert_var, time_step=0, ascii_format='grass'): """This function takes array data and writes out a GSSHA ascii grid. Parameters: out_grid_file(str): Location of ASCII file to generate. lsm_data_var(str or list): This ...
This function takes array data and writes out a GSSHA precip gage file. See: http://www.gsshawiki.com/Precipitation:Spatially_and_Temporally_Varied_Precipitation .. note:: GSSHA CARDS: * PRECIP_FILE card with path to gage file * RAIN_INV_DISTANCE or RAIN_THIE...
def lsm_precip_to_gssha_precip_gage(self, out_gage_file, lsm_data_var, precip_type="RADAR"): """This function takes array data and writes out a GSSHA precip gage file. See: http://www.gsshawiki.com/Precipitation:Spatially_and_Temporally_Varied_Precipitation .. note:: GSSHA CARDS: ...
This function writes the HMET_ASCII card file with ASCII file list for input to GSSHA
def _write_hmet_card_file(self, hmet_card_file_path, main_output_folder): """ This function writes the HMET_ASCII card file with ASCII file list for input to GSSHA """ with io_open(hmet_card_file_path, 'w') as out_hmet_list_file: for hour_time in self.data.lsm.datetim...
Writes extracted data to Arc ASCII file format into folder to be read in by GSSHA. Also generates the HMET_ASCII card file for GSSHA in the folder named 'hmet_file_list.txt'. .. warning:: For GSSHA 6 Versions, for GSSHA 7 or greater, use lsm_data_to_subset_netcdf. .. note:: ...
def lsm_data_to_arc_ascii(self, data_var_map_array, main_output_folder=""): """Writes extracted data to Arc ASCII file format into folder to be read in by GSSHA. Also generates the HMET_ASCII card file for GSSHA in the folder named 'hmet_file_list.txt'. ...
Writes extracted data to the NetCDF file format .. todo:: NetCDF output data time is always in UTC time. Need to convert to local timezone for GSSHA. .. warning:: The NetCDF GSSHA file is only supported in GSSHA 7 or greater. .. note:: GSSHA CARDS: * HMET_NETCDF po...
def lsm_data_to_subset_netcdf(self, netcdf_file_path, data_var_map_array, resample_method=None): """Writes extracted data to the NetCDF file format .. todo:: NetCDF output data time is always in UTC time. Need to convert to...
Creates a csv file from a query of devices and attributes over a time range. Authentication: The client must be configured with a valid api access token to call this action. The token must include at least one of the following scopes: all.Application, all.Application.read, all.D...
def export(self, **kwargs): """ Creates a csv file from a query of devices and attributes over a time range. Authentication: The client must be configured with a valid api access token to call this action. The token must include at least one of the following scopes: ...
Retrieve the geometry in KML format. This method is a veneer for an SQL query that calls the ``ST_AsKml()`` function on the geometry column. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database. Returns: str...
def getAsKml(self, session): """ Retrieve the geometry in KML format. This method is a veneer for an SQL query that calls the ``ST_AsKml()`` function on the geometry column. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS en...
Retrieve the geometry in Well Known Text format. This method is a veneer for an SQL query that calls the ``ST_AsText()`` function on the geometry column. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database. Returns: ...
def getAsWkt(self, session): """ Retrieve the geometry in Well Known Text format. This method is a veneer for an SQL query that calls the ``ST_AsText()`` function on the geometry column. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound ...
Retrieve the geometry in GeoJSON format. This method is a veneer for an SQL query that calls the ``ST_AsGeoJSON()`` function on the geometry column. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database. Returns: ...
def getAsGeoJson(self, session): """ Retrieve the geometry in GeoJSON format. This method is a veneer for an SQL query that calls the ``ST_AsGeoJSON()`` function on the geometry column. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound t...
Retrieve the spatial reference id by which the geometry column is registered. This method is a veneer for an SQL query that calls the ``ST_SRID()`` function on the geometry column. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled dat...
def getSpatialReferenceId(self, session): """ Retrieve the spatial reference id by which the geometry column is registered. This method is a veneer for an SQL query that calls the ``ST_SRID()`` function on the geometry column. Args: session (:mod:`sqlalchemy.orm.session.Ses...
Given a message in message, return a response in the appropriate format.
def _generate(self, message): """Given a message in message, return a response in the appropriate format.""" raw_params = {"INPUT_TEXT" : message.encode('UTF8'), "INPUT_TYPE" : self.input_type, "OUTPUT_TYPE" : self.output_type, ...
The message received from the queue specify a method of the class the actor represents. This invokes it. If the communication is an ASK, sends the result back to the channel included in the message as an ASKRESPONSE. If it is a FUTURE, generates a FUTURERESPONSE to send ...
def receive(self, msg): ''' The message received from the queue specify a method of the class the actor represents. This invokes it. If the communication is an ASK, sends the result back to the channel included in the message as an ASKRESPONSE. If it is a FUTURE,...
Creates the actor thread wich will process the channel queue while the actor :meth:`is_alive`, making it able to receive queries.
def run(self): ''' Creates the actor thread wich will process the channel queue while the actor :meth:`is_alive`, making it able to receive queries. ''' self.thread = Thread(target=self.__processQueue) self.thread.start()
RA of prime meridian
def right_ascension_at_time(self,t): '''RA of prime meridian''' α0 = self.right_ascension_at_epoch t0 = self.epoch ω = self.rotational_speed return (α0 + ω * (t - t0)) % (2*π)
Hack: blit per-pixel alpha source onto dest with surface opacity.
def blit_alpha(dest, source, pos, opacity): """Hack: blit per-pixel alpha source onto dest with surface opacity.""" # http://www.nerdparadise.com/tech/python/pygame/blitopacity/ (x, y) = pos temp = pygame.Surface((source.get_width(), source.get_height())).convert() temp.bl...
Downloads a file from the specified URL. :param str url: The URL to the file to be downloaded :returns: the downloaded file's content :rtype: str
def download_file(url): """ Downloads a file from the specified URL. :param str url: The URL to the file to be downloaded :returns: the downloaded file's content :rtype: str """ response = requests.get(url) if response.status_code is not 200: return None ret...
Add a single data node to the dispatcher. :param data_id: Data node id. If None will be assigned automatically ('unknown<%d>') not in dmap. :type data_id: str, optional :param default_value: Data node default value. This will be used as input if it is not ...
def add_data(self, data_id=None, default_value=EMPTY, initial_dist=0.0, wait_inputs=False, wildcard=None, function=None, callback=None, description=None, filters=None, await_result=None, **kwargs): """ Add a single data node to the dispatcher. :param data_id: ...
Add a single function node to dispatcher. :param function_id: Function node id. If None will be assigned as <fun.__name__>. :type function_id: str, optional :param function: Data node estimation function. :type function: callable, optional :...
def add_function(self, function_id=None, function=None, inputs=None, outputs=None, input_domain=None, weight=None, inp_weight=None, out_weight=None, description=None, filters=None, await_domain=None, await_result=None, **kwargs): ...
Add a single function node to dispatcher. :param inputs_kwargs: Do you want to include kwargs as inputs? :type inputs_kwargs: bool :param inputs_defaults: Do you want to set default values? :type inputs_defaults: bool :param function_id: Fun...
def add_func(self, function, outputs=None, weight=None, inputs_defaults=False, inputs_kwargs=False, filters=None, input_domain=None, await_domain=None, await_result=None, inp_weight=None, out_weight=None, description=None, inputs=None, function_id=None...
Add a single sub-dispatcher node to dispatcher. :param dsp: Child dispatcher that is added as sub-dispatcher node to the parent dispatcher. :type dsp: Dispatcher | dict[str, list] :param inputs: Inputs mapping. Data node ids from parent dispatcher to child ...
def add_dispatcher(self, dsp, inputs, outputs, dsp_id=None, input_domain=None, weight=None, inp_weight=None, description=None, include_defaults=False, await_domain=None, **kwargs): """ Add a single sub-dispatcher node to dispatcher. ...
Add multiple function and data nodes to dispatcher. :param data_list: It is a list of data node kwargs to be loaded. :type data_list: list[dict], optional :param fun_list: It is a list of function node kwargs to be loaded. :type fun_list: list[dict], optional ...
def add_from_lists(self, data_list=None, fun_list=None, dsp_list=None): """ Add multiple function and data nodes to dispatcher. :param data_list: It is a list of data node kwargs to be loaded. :type data_list: list[dict], optional :param fun_list: It is ...
Set the default value of a data node in the dispatcher. :param data_id: Data node id. :type data_id: str :param value: Data node default value. .. note:: If `EMPTY` the previous default value is removed. :type value: T, optional :param init...
def set_default_value(self, data_id, value=EMPTY, initial_dist=0.0): """ Set the default value of a data node in the dispatcher. :param data_id: Data node id. :type data_id: str :param value: Data node default value. .. note:: If `EMPTY` the...
Returns the sub-dispatcher induced by given node and edge bunches. The induced sub-dispatcher contains the available nodes in nodes_bunch and edges between those nodes, excluding those that are in edges_bunch. The available nodes are non isolated nodes and function nodes that have all ...
def get_sub_dsp(self, nodes_bunch, edges_bunch=None): """ Returns the sub-dispatcher induced by given node and edge bunches. The induced sub-dispatcher contains the available nodes in nodes_bunch and edges between those nodes, excluding those that are in edges_bunch. The availa...
Returns the sub-dispatcher induced by the workflow from sources. The induced sub-dispatcher of the dsp contains the reachable nodes and edges evaluated with breadth-first-search on the workflow graph from source nodes. :param sources: Source nodes for the breadth-first-sear...
def get_sub_dsp_from_workflow( self, sources, graph=None, reverse=False, add_missing=False, check_inputs=True, blockers=None, wildcard=False, _update_links=True): """ Returns the sub-dispatcher induced by the workflow from sources. The induced sub-dispatcher ...
Returns all data nodes of the dispatcher. :return: All data nodes of the dispatcher. :rtype: dict[str, dict]
def data_nodes(self): """ Returns all data nodes of the dispatcher. :return: All data nodes of the dispatcher. :rtype: dict[str, dict] """ return {k: v for k, v in self.nodes.items() if v['type'] == 'data'}
Returns all function nodes of the dispatcher. :return: All data function of the dispatcher. :rtype: dict[str, dict]
def function_nodes(self): """ Returns all function nodes of the dispatcher. :return: All data function of the dispatcher. :rtype: dict[str, dict] """ return {k: v for k, v in self.nodes.items() if v['type'] == 'function'}
Returns all sub-dispatcher nodes of the dispatcher. :return: All sub-dispatcher nodes of the dispatcher. :rtype: dict[str, dict]
def sub_dsp_nodes(self): """ Returns all sub-dispatcher nodes of the dispatcher. :return: All sub-dispatcher nodes of the dispatcher. :rtype: dict[str, dict] """ return {k: v for k, v in self.nodes.items() if v['type'] == 'dispatcher'}
Constructs a BlueDispatcher out of the current object. :param memo: A dictionary to cache Blueprints. :type memo: dict[T,schedula.utils.blue.Blueprint] :return: A BlueDispatcher of the current object. :rtype: schedula.utils.blue.BlueDispatcher
def blue(self, memo=None): """ Constructs a BlueDispatcher out of the current object. :param memo: A dictionary to cache Blueprints. :type memo: dict[T,schedula.utils.blue.Blueprint] :return: A BlueDispatcher of the current object. :rtype: schedu...
Extends Dispatcher calling each deferred operation of given Blueprints. :param blues: Blueprints or Dispatchers to extend deferred operations. :type blues: Blueprint | schedula.dispatcher.Dispatcher :param memo: A dictionary to cache Blueprints and Dispatchers. ...
def extend(self, *blues, memo=None): """ Extends Dispatcher calling each deferred operation of given Blueprints. :param blues: Blueprints or Dispatchers to extend deferred operations. :type blues: Blueprint | schedula.dispatcher.Dispatcher :param memo: A...
Evaluates the minimum workflow and data outputs of the dispatcher model from given inputs. :param inputs: Input data values. :type inputs: dict[str, T], list[str], iterable, optional :param outputs: Ending data nodes. :type outputs: list[str], iterable, ...
def dispatch(self, inputs=None, outputs=None, cutoff=None, inputs_dist=None, wildcard=False, no_call=False, shrink=False, rm_unused_nds=False, select_output_kw=None, _wait_in=None, stopper=None, executor=False, sol_name=()): """ Evaluates the minimum wo...
Returns a reduced dispatcher. :param inputs: Input data nodes. :type inputs: list[str], iterable, optional :param outputs: Ending data nodes. :type outputs: list[str], iterable, optional :param cutoff: Depth to stop the search. :type...
def shrink_dsp(self, inputs=None, outputs=None, cutoff=None, inputs_dist=None, wildcard=True): """ Returns a reduced dispatcher. :param inputs: Input data nodes. :type inputs: list[str], iterable, optional :param outputs: Ending data n...
Returns the sub-dispatcher induced by the workflow from outputs. :param outputs: Ending data nodes. :type outputs: list[str], iterable, optional :param bfs_graphs: A dictionary with directed graphs where evaluate the breadth-first-search. :type bfs_g...
def _get_dsp_from_bfs(self, outputs, bfs_graphs=None): """ Returns the sub-dispatcher induced by the workflow from outputs. :param outputs: Ending data nodes. :type outputs: list[str], iterable, optional :param bfs_graphs: A dictionary with directed grap...
Set `wait_inputs` flags for data nodes that: - are estimated from functions with a domain function, and - are waiting inputs. :param flag: Value to be set. If None `wait_inputs` are just cleaned. :type flag: bool, None, optional :param all_domain: ...
def _get_wait_in(self, flag=True, all_domain=True): """ Set `wait_inputs` flags for data nodes that: - are estimated from functions with a domain function, and - are waiting inputs. :param flag: Value to be set. If None `wait_inputs` are just cleaned. ...
Attaches a mehtod that will be called when the future finishes. :param method: A callable from an actor that will be called when the future completes. The only argument for that method must be the future itself from wich you can get the result though `future.:meth:`result()`...
def add_callback(self, method): """ Attaches a mehtod that will be called when the future finishes. :param method: A callable from an actor that will be called when the future completes. The only argument for that method must be the future itself from wich you can get th...
Returns the result of the call that the future represents. :param timeout: The number of seconds to wait for the result if the future has not been completed. None, the default, sets no limit. :returns: The result of the call that the future represents. :raises: TimeoutEr...
def result(self, timeout=None): """Returns the result of the call that the future represents. :param timeout: The number of seconds to wait for the result if the future has not been completed. None, the default, sets no limit. :returns: The result of the call that the fu...
Return a exception raised by the call that the future represents. :param timeout: The number of seconds to wait for the exception if the future has not been completed. None, the default, sets no limit. :returns: The exception raised by the call that the future ...
def exception(self, timeout=None): """Return a exception raised by the call that the future represents. :param timeout: The number of seconds to wait for the exception if the future has not been completed. None, the default, sets no limit. :returns: The exception ...
Sends the query to the actor for it to start executing the work. It is possible to execute once again a future that has finished if necessary (overwriting the results), but only one execution at a time.
def send_work(self): '''Sends the query to the actor for it to start executing the work. It is possible to execute once again a future that has finished if necessary (overwriting the results), but only one execution at a time. ''' if self.__set_running(): ...
Sets the return value of work associated with the future. Only called internally.
def set_result(self, result): """Sets the return value of work associated with the future. Only called internally. """ with self.__condition: self.__result = result self.__state = FINISHED self.__condition.notify_all() self._invoke_callbacks()
Sets the result of the future as being the given exception. Only called internally.
def set_exception(self, exception): """Sets the result of the future as being the given exception. Only called internally. """ with self.__condition: self.__exception = exception self.__state = FINISHED self.__condition.notify_all() self._invok...
Returns the result of the call that the future represents. :param timeout: The number of seconds to wait for the result if the future has not been completed. None, the default, sets no limit. :returns: The result of the call that the future represents. :raises: TimeoutEr...
def result(self, timeout=None): """Returns the result of the call that the future represents. :param timeout: The number of seconds to wait for the result if the future has not been completed. None, the default, sets no limit. :returns: The result of the call that the fu...
Compute the angle between vector x and y
def angle_between_vectors(x, y): """ Compute the angle between vector x and y """ dp = dot_product(x, y) if dp == 0: return 0 xm = magnitude(x) ym = magnitude(y) return math.acos(dp / (xm*ym)) * (180. / math.pi)
Sets a timer that will call the *f* function past *timeout* seconds. See example in :ref:`sample_inter` :return: :class:`Timer`
def later(timeout, f, *args, **kwargs): ''' Sets a timer that will call the *f* function past *timeout* seconds. See example in :ref:`sample_inter` :return: :class:`Timer` ''' t = Timer(timeout, f, args, kwargs) t.start() return t
Creates an Event attached to the *host* that will execute the *f* function every *time* seconds. See example in :ref:`sample_inter` :param Proxy host: proxy of the host. Can be obtained from inside a class with ``self.host``. :param int time: seconds for the intervals. :param func f: funct...
def interval_host(host, time, f, *args, **kwargs): ''' Creates an Event attached to the *host* that will execute the *f* function every *time* seconds. See example in :ref:`sample_inter` :param Proxy host: proxy of the host. Can be obtained from inside a class with ``self.host``. :para...
Waiting for an incoming connection from a reverse forwarded port. Note that this results in a kernel block until a connection is received.
def _ssh_forward_accept(ssh_session, timeout_ms): """Waiting for an incoming connection from a reverse forwarded port. Note that this results in a kernel block until a connection is received. """ ssh_channel = c_ssh_forward_accept(c_void_p(ssh_session), c_int(tim...
Execute a remote command. This functionality does not support more than one command to be executed on the same channel, so we create a dedicated channel at the session level than allowing direct access at the channel level.
def execute(self, cmd, block_size=DEFAULT_EXECUTE_READ_BLOCK_SIZE): """Execute a remote command. This functionality does not support more than one command to be executed on the same channel, so we create a dedicated channel at the session level than allowing direct access at the channe...
Project File Read from File Method
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile, force_relative=True): """ Project File Read from File Method """ self.project_directory = directory with tmp_chdir(directory): ...
Project File Write to File Method
def _write(self, session, openFile, replaceParamFile): """ Project File Write to File Method """ # Enforce cards that must be written in certain order PRIORITY_CARDS = ('WMS', 'MASK_WATERSHED', 'REPLACE_LINE', 'REPLACE_PARAMS', 'REPLACE_VALS', 'REPLACE_F...
Append directory to relative paths in project file. By default, the project file paths are read and written as relative paths. Use this method to prepend a directory to all the paths in the project file. Args: directory (str): Directory path to prepend to file paths in project file. ...
def appendDirectory(self, directory, projectFilePath): """ Append directory to relative paths in project file. By default, the project file paths are read and written as relative paths. Use this method to prepend a directory to all the paths in the project file. Args: direct...
Read all files for a GSSHA project into the database. This method will read all the files, both input and output files, that are supported by GsshaPy into a database. To use GsshaPy more efficiently, it is recommended that you use the readInput method when performing pre-processing tasks and re...
def readProject(self, directory, projectFileName, session, spatial=False, spatialReferenceID=None): """ Read all files for a GSSHA project into the database. This method will read all the files, both input and output files, that are supported by GsshaPy into a database. To use GsshaPy m...
Read only input files for a GSSHA project into the database. Use this method to read a project when only pre-processing tasks need to be performed. Args: directory (str): Directory containing all GSSHA model files. This method assumes that all files are located in the same ...
def readInput(self, directory, projectFileName, session, spatial=False, spatialReferenceID=None): """ Read only input files for a GSSHA project into the database. Use this method to read a project when only pre-processing tasks need to be performed. Args: directory (str): D...
Read only output files for a GSSHA project to the database. Use this method to read a project when only post-processing tasks need to be performed. Args: directory (str): Directory containing all GSSHA model files. This method assumes that all files are located in the same ...
def readOutput(self, directory, projectFileName, session, spatial=False, spatialReferenceID=None): """ Read only output files for a GSSHA project to the database. Use this method to read a project when only post-processing tasks need to be performed. Args: directory (str): ...
Read specific IO file for a GSSHA project to the database.
def _readXputFile(self, file_cards, card_name, directory, session, spatial=False, spatialReferenceID=None, replaceParamFile=None, **kwargs): """ Read specific IO file for a GSSHA project to the database. """ # Automatically derive the spatial r...
Read specific input file for a GSSHA project to the database. Args: card_name(str): Name of GSSHA project card. directory (str): Directory containing all GSSHA model files. This method assumes that all files are located in the same directory. session (:mod:`s...
def readInputFile(self, card_name, directory, session, spatial=False, spatialReferenceID=None, **kwargs): """ Read specific input file for a GSSHA project to the database. Args: card_name(str): Name of GSSHA project card. directory (str): Directory ...
Read specific input file for a GSSHA project to the database. Args: card_name(str): Name of GSSHA project card. directory (str): Directory containing all GSSHA model files. This method assumes that all files are located in the same directory. session (:mod:`s...
def readOutputFile(self, card_name, directory, session, spatial=False, spatialReferenceID=None, **kwargs): """ Read specific input file for a GSSHA project to the database. Args: card_name(str): Name of GSSHA project card. directory (str): Directory...
Write all files for a project from the database to file. Use this method to write all GsshaPy supported files back into their native file formats. If writing to execute the model, increase efficiency by using the writeInput method to write only the file needed to run the model. Args: ...
def writeProject(self, session, directory, name): """ Write all files for a project from the database to file. Use this method to write all GsshaPy supported files back into their native file formats. If writing to execute the model, increase efficiency by using the writeInput method to...
Write only input files for a GSSHA project from the database to file. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database directory (str): Directory where the files will be written. name (str): Name that will be ...
def writeInput(self, session, directory, name): """ Write only input files for a GSSHA project from the database to file. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database directory (str): Directory where t...
Write only output files for a GSSHA project from the database to file. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database directory (str): Directory where the files will be written. name (str): Name that will be...
def writeOutput(self, session, directory, name): """ Write only output files for a GSSHA project from the database to file. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database directory (str): Directory where...
Retrieve a list of file keys that have been read into the database. This is a utility method that can be used to programmatically access the GsshaPy file objects. Use these keys in conjunction with the dictionary returned by the getFileObjects method. Returns: list: List of keys re...
def getFileKeys(self): """ Retrieve a list of file keys that have been read into the database. This is a utility method that can be used to programmatically access the GsshaPy file objects. Use these keys in conjunction with the dictionary returned by the getFileObjects method. ...
Retrieve a dictionary of file objects. This is a utility method that can be used to programmatically access the GsshaPy file objects. Use this method in conjunction with the getFileKeys method to access only files that have been read into the database. Returns: dict: Dictionary wit...
def getFileObjects(self): """ Retrieve a dictionary of file objects. This is a utility method that can be used to programmatically access the GsshaPy file objects. Use this method in conjunction with the getFileKeys method to access only files that have been read into the database. ...
Retrieve card object for given card name. Args: name (str): Name of card to be retrieved. Returns: :class:`.ProjectCard` or None: Project card object. Will return None if the card is not available.
def getCard(self, name): """ Retrieve card object for given card name. Args: name (str): Name of card to be retrieved. Returns: :class:`.ProjectCard` or None: Project card object. Will return None if the card is not available. """ cards = self.pr...
Adds/updates card for gssha project file Args: name (str): Name of card to be updated/added. value (str): Value to attach to the card. add_quotes (Optional[bool]): If True, will add quotes around string. Default is False.
def setCard(self, name, value, add_quotes=False): """ Adds/updates card for gssha project file Args: name (str): Name of card to be updated/added. value (str): Value to attach to the card. add_quotes (Optional[bool]): If True, will add quotes around string. D...
Removes card from gssha project file
def deleteCard(self, card_name, db_session): """ Removes card from gssha project file """ card_name = card_name.upper() gssha_card = self.getCard(card_name) if gssha_card is not None: db_session.delete(gssha_card) db_session.commit()
Retrieve a KML representation of the model. Includes polygonized mask map and vector stream network. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database path (str, optional): Path to file where KML file will be written. Defa...
def getModelSummaryAsKml(self, session, path=None, documentName=None, withStreamNetwork=True, withNodes=False, styles={}): """ Retrieve a KML representation of the model. Includes polygonized mask map and vector stream network. Args: session (:mod:`sqlalchemy.orm.session.Session`): ...
Retrieve a Well Known Text representation of the model. Includes polygonized mask map and vector stream network. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database withStreamNetwork (bool, optional): Include stream network....
def getModelSummaryAsWkt(self, session, withStreamNetwork=True, withNodes=False): """ Retrieve a Well Known Text representation of the model. Includes polygonized mask map and vector stream network. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bou...
Retrieve a GeoJSON representation of the model. Includes vectorized mask map and stream network. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database withStreamNetwork (bool, optional): Include stream network. Defaults to Tru...
def getModelSummaryAsGeoJson(self, session, withStreamNetwork=True, withNodes=False): """ Retrieve a GeoJSON representation of the model. Includes vectorized mask map and stream network. Args: session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGI...
Returns GDALGrid object of GSSHA grid Paramters: gssha_card_name(str): Name of GSSHA project card for grid. Returns: GDALGrid
def getGridByCard(self, gssha_card_name): """ Returns GDALGrid object of GSSHA grid Paramters: gssha_card_name(str): Name of GSSHA project card for grid. Returns: GDALGrid """ with tmp_chdir(self.project_directory): if gssha_card_name...
Returns GDALGrid object of GSSHA model bounds Paramters: use_mask(bool): If True, uses watershed mask. Otherwise, it uses the elevaiton grid. Returns: GDALGrid
def getGrid(self, use_mask=True): """ Returns GDALGrid object of GSSHA model bounds Paramters: use_mask(bool): If True, uses watershed mask. Otherwise, it uses the elevaiton grid. Returns: GDALGrid """ grid_card_name = "WATERSHED_MASK" i...
Returns GDALGrid object of index map Paramters: name(str): Name of index map in 'cmt' file. Returns: GDALGrid
def getIndexGrid(self, name): """ Returns GDALGrid object of index map Paramters: name(str): Name of index map in 'cmt' file. Returns: GDALGrid """ index_map = self.mapTableFile.indexMaps.filter_by(name=name).one() gssha_pro_card = self....
Returns GSSHA projection WKT string
def getWkt(self): """ Returns GSSHA projection WKT string """ gssha_pro_card = self.getCard("#PROJECTION_FILE") if gssha_pro_card is None: raise ValueError("#PROJECTION_FILE card not found ...") with tmp_chdir(self.project_directory): gssha_prj_fi...
Gets the outlet latitude and longitude. Returns: latitude(float): Latitude of grid cell center. longitude(float): Longitude of grid cell center.
def getOutlet(self): """ Gets the outlet latitude and longitude. Returns: latitude(float): Latitude of grid cell center. longitude(float): Longitude of grid cell center. """ # OUTROW, OUTCOL outrow = int(self.getCard(name='OUTROW').value)-1 ...
Sets the outlet grid cell information in the project file. Parameters: col(float): 1-based column index. row(float): 1-based row index. outslope(Optional[float]): River slope at outlet.
def setOutlet(self, col, row, outslope=None): """ Sets the outlet grid cell information in the project file. Parameters: col(float): 1-based column index. row(float): 1-based row index. outslope(Optional[float]): River slope at outlet. """ #OU...
Calculate outlet location
def findOutlet(self, shapefile_path): """ Calculate outlet location """ # determine outlet from shapefile # by getting outlet from first point in polygon # make sure the boundary geometry is valid check_watershed_boundary_geometry(shapefile_path) shapefi...
Attempt to determine the slope at the OUTLET
def calculateOutletSlope(self): """ Attempt to determine the slope at the OUTLET """ try: mask_grid = self.getGrid() elevation_grid = self.getGrid(use_mask=False) outrow = int(self.getCard("OUTROW").value)-1 outcol = int(self.getCard("OUTC...
timezone of GSSHA model
def timezone(self): """ timezone of GSSHA model """ if self._tz is None: # GET CENTROID FROM GSSHA GRID cen_lat, cen_lon = self.centerLatLon() # update time zone tf = TimezoneFinder() tz_name = tf.timezone_at(lng=cen_lon, lat=ce...
Get the center lat/lon of model
def centerLatLon(self): """ Get the center lat/lon of model """ # GET CENTROID FROM GSSHA GRID gssha_grid = self.getGrid() min_x, max_x, min_y, max_y = gssha_grid.bounds() x_ext, y_ext = transform(gssha_grid.proj, Proj(init='epsg:...
This method is used to automatically lookup the spatial reference ID of the GSSHA project. This method is a wrapper for the ProjectionFile class method lookupSpatialReferenceID(). It requires an internet connection (the lookup uses a web service) and the projection file to be present and the appropriate...
def _automaticallyDeriveSpatialReferenceId(self, directory): """ This method is used to automatically lookup the spatial reference ID of the GSSHA project. This method is a wrapper for the ProjectionFile class method lookupSpatialReferenceID(). It requires an internet connection (the loo...