INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Return QMED estimate based on annual maximum flow records. :return: QMED in m³/s :rtype: float
def _qmed_from_amax_records(self): """ Return QMED estimate based on annual maximum flow records. :return: QMED in m³/s :rtype: float """ valid_flows = valid_flows_array(self.catchment) n = len(valid_flows) if n < 2: raise InsufficientDataErro...
Return QMED estimate based on peaks-over-threshold (POT) records. Methodology source: FEH, Vol. 3, pp. 77-78 :return: QMED in m³/s :rtype: float
def _qmed_from_pot_records(self): """ Return QMED estimate based on peaks-over-threshold (POT) records. Methodology source: FEH, Vol. 3, pp. 77-78 :return: QMED in m³/s :rtype: float """ pot_dataset = self.catchment.pot_dataset if not pot_dataset: ...
Return a list of 12 sets. Each sets contains the years included in the POT record period. :param pot_dataset: POT dataset (records and meta data) :type pot_dataset: :class:`floodestimation.entities.PotDataset`
def _pot_month_counts(self, pot_dataset): """ Return a list of 12 sets. Each sets contains the years included in the POT record period. :param pot_dataset: POT dataset (records and meta data) :type pot_dataset: :class:`floodestimation.entities.PotDataset` """ periods = p...
Return a tuple of a list of :class:`PotRecord`s filtering out part-complete years; and the number of complete years. This method creates complete years by ensuring there is an equal number of each month in the entire record, taking into account data gaps. A month is considered to be covered by ...
def _complete_pot_years(self, pot_dataset): """ Return a tuple of a list of :class:`PotRecord`s filtering out part-complete years; and the number of complete years. This method creates complete years by ensuring there is an equal number of each month in the entire record, taking...
Methodology source: FEH, Vol. 3, p. 14
def _residual_soil(self): """ Methodology source: FEH, Vol. 3, p. 14 """ return self.catchment.descriptors.bfihost \ + 1.3 * (0.01 * self.catchment.descriptors.sprhost) \ - 0.987
Return QMED estimate based on catchment area. TODO: add source of method :return: QMED in m³/s :rtype: float
def _qmed_from_area(self): """ Return QMED estimate based on catchment area. TODO: add source of method :return: QMED in m³/s :rtype: float """ try: return 1.172 * self.catchment.descriptors.dtm_area ** self._area_exponent() # Area in km² ex...
Return QMED estimation based on FEH catchment descriptors, 1999 methodology. Methodology source: FEH, Vol. 3, p. 14 :param as_rural: assume catchment is fully rural. Default: false. :type as_rural: bool :return: QMED in m³/s :rtype: float
def _qmed_from_descriptors_1999(self, as_rural=False): """ Return QMED estimation based on FEH catchment descriptors, 1999 methodology. Methodology source: FEH, Vol. 3, p. 14 :param as_rural: assume catchment is fully rural. Default: false. :type as_rural: bool :return:...
Return QMED estimation based on FEH catchment descriptors, 2008 methodology. Methodology source: Science Report SC050050, p. 36 :param as_rural: assume catchment is fully rural. Default: false. :type as rural: bool :param donor_catchments: override donor catchment to improve QMED catch...
def _qmed_from_descriptors_2008(self, as_rural=False, donor_catchments=None): """ Return QMED estimation based on FEH catchment descriptors, 2008 methodology. Methodology source: Science Report SC050050, p. 36 :param as_rural: assume catchment is fully rural. Default: false. :t...
Return percentage runoff urban adjustment factor. Methodology source: eqn. 6, Kjeldsen 2010
def _pruaf(self): """ Return percentage runoff urban adjustment factor. Methodology source: eqn. 6, Kjeldsen 2010 """ return 1 + 0.47 * self.catchment.descriptors.urbext(self.year) \ * self.catchment.descriptors.bfihost / (1 - self.catchment.descriptors.bfihos...
Return urban adjustment factor (UAF) used to adjust QMED and growth curves. Methodology source: eqn. 8, Kjeldsen 2010 :return: urban adjustment factor :rtype: float
def urban_adj_factor(self): """ Return urban adjustment factor (UAF) used to adjust QMED and growth curves. Methodology source: eqn. 8, Kjeldsen 2010 :return: urban adjustment factor :rtype: float """ urbext = self.catchment.descriptors.urbext(self.year) ...
Generic distance-decaying correlation function :param dist: Distance between catchment centrolds in km :type dist: float :param phi1: Decay function parameters 1 :type phi1: float :param phi2: Decay function parameters 2 :type phi2: float :param phi3: Decay funct...
def _dist_corr(dist, phi1, phi2, phi3): """ Generic distance-decaying correlation function :param dist: Distance between catchment centrolds in km :type dist: float :param phi1: Decay function parameters 1 :type phi1: float :param phi2: Decay function parameters ...
Return model error correlation between subject catchment and other catchment. Methodology source: Kjeldsen & Jones, 2009, table 3 :param catchment1: catchment to calculate error correlation with :type catchment1: :class:`Catchment` :param catchment2: catchment to calculate error correl...
def _model_error_corr(self, catchment1, catchment2): """ Return model error correlation between subject catchment and other catchment. Methodology source: Kjeldsen & Jones, 2009, table 3 :param catchment1: catchment to calculate error correlation with :type catchment1: :class:`...
Return model error correlation between subject catchment and other catchment. Methodology source: Kjeldsen & Jones, 2009, fig 3 :param catchment1: catchment to calculate correlation with :type catchment1: :class:`Catchment` :param catchment2: catchment to calculate correlation with ...
def _lnqmed_corr(self, catchment1, catchment2): """ Return model error correlation between subject catchment and other catchment. Methodology source: Kjeldsen & Jones, 2009, fig 3 :param catchment1: catchment to calculate correlation with :type catchment1: :class:`Catchment` ...
Return vector ``b`` of model error covariances to estimate weights Methodology source: Kjeldsen, Jones and Morris, 2009, eqs 3 and 10 :param donor_catchments: Catchments to use as donors :type donor_catchments: list of :class:`Catchment` :return: Model error covariance vector :...
def _vec_b(self, donor_catchments): """ Return vector ``b`` of model error covariances to estimate weights Methodology source: Kjeldsen, Jones and Morris, 2009, eqs 3 and 10 :param donor_catchments: Catchments to use as donors :type donor_catchments: list of :class:`Catchment` ...
Return beta, the GLO scale parameter divided by loc parameter estimated using simple regression model Methodology source: Kjeldsen & Jones, 2009, table 2 :param catchment: Catchment to estimate beta for :type catchment: :class:`Catchment` :return: beta :rtype: float
def _beta(catchment): """ Return beta, the GLO scale parameter divided by loc parameter estimated using simple regression model Methodology source: Kjeldsen & Jones, 2009, table 2 :param catchment: Catchment to estimate beta for :type catchment: :class:`Catchment` :retu...
Return model error coveriance matrix Sigma eta Methodology source: Kjelsen, Jones & Morris 2014, eqs 2 and 3 :param donor_catchments: Catchments to use as donors :type donor_catchments: list of :class:`Catchment` :return: 2-Dimensional, symmetric covariance matrix :rtype: :clas...
def _matrix_sigma_eta(self, donor_catchments): """ Return model error coveriance matrix Sigma eta Methodology source: Kjelsen, Jones & Morris 2014, eqs 2 and 3 :param donor_catchments: Catchments to use as donors :type donor_catchments: list of :class:`Catchment` :retur...
Return sampling error coveriance matrix Sigma eta Methodology source: Kjeldsen & Jones 2009, eq 9 :param donor_catchments: Catchments to use as donors :type donor_catchments: list of :class:`Catchment` :return: 2-Dimensional, symmetric covariance matrix :rtype: :class:`numpy.nd...
def _matrix_sigma_eps(self, donor_catchments): """ Return sampling error coveriance matrix Sigma eta Methodology source: Kjeldsen & Jones 2009, eq 9 :param donor_catchments: Catchments to use as donors :type donor_catchments: list of :class:`Catchment` :return: 2-Dimens...
Return vector alpha which is the weights for donor model errors Methodology source: Kjeldsen, Jones & Morris 2014, eq 10 :param donor_catchments: Catchments to use as donors :type donor_catchments: list of :class:`Catchment` :return: Vector of donor weights :rtype: :class:`nump...
def _vec_alpha(self, donor_catchments): """ Return vector alpha which is the weights for donor model errors Methodology source: Kjeldsen, Jones & Morris 2014, eq 10 :param donor_catchments: Catchments to use as donors :type donor_catchments: list of :class:`Catchment` :...
Return ln(QMED) model error at a gauged catchment :param catchment: Gauged catchment :type catchment: :class:`Catchment` :return: Model error :rtype: float
def _lnqmed_residual(catchment): """ Return ln(QMED) model error at a gauged catchment :param catchment: Gauged catchment :type catchment: :class:`Catchment` :return: Model error :rtype: float """ analysis = QmedAnalysis(catchment, year=2000) # Probably ...
Return ln(QMED) model errors for a list of catchments :param catchments: List of gauged catchments :type catchments: list of :class:`Catchment` :return: Model errors :rtype: list of float
def _vec_lnqmed_residuals(self, catchments): """ Return ln(QMED) model errors for a list of catchments :param catchments: List of gauged catchments :type catchments: list of :class:`Catchment` :return: Model errors :rtype: list of float """ result = np.em...
Return a suitable donor catchment to improve a QMED estimate based on catchment descriptors alone. :param limit: maximum number of catchments to return. Default: 6. Set to `None` to return all available catchments. :type limit: int :param dist_limit: maximum distance in km...
def find_donor_catchments(self, limit=6, dist_limit=500): """ Return a suitable donor catchment to improve a QMED estimate based on catchment descriptors alone. :param limit: maximum number of catchments to return. Default: 6. Set to `None` to return all available catchmen...
Return QMED estimate using best available methodology depending on what catchment attributes are available. ====================== ====================== ================================================================== `method` `method_options` notes ======================...
def growth_curve(self, method='best', **method_options): """ Return QMED estimate using best available methodology depending on what catchment attributes are available. ====================== ====================== ================================================================== `meth...
Calculate L-CV and L-SKEW from a single catchment or a pooled group of catchments. Methodology source: Science Report SC050050, para. 6.4.1-6.4.2
def _var_and_skew(self, catchments, as_rural=False): """ Calculate L-CV and L-SKEW from a single catchment or a pooled group of catchments. Methodology source: Science Report SC050050, para. 6.4.1-6.4.2 """ if not hasattr(catchments, '__getitem__'): # In case of a single catchm...
Calculate L-CV and L-SKEW for a gauged catchment. Uses `lmoments3` library. Methodology source: Science Report SC050050, para. 6.7.5
def _l_cv_and_skew(self, catchment): """ Calculate L-CV and L-SKEW for a gauged catchment. Uses `lmoments3` library. Methodology source: Science Report SC050050, para. 6.7.5 """ z = self._dimensionless_flows(catchment) l1, l2, t3 = lm.lmom_ratios(z, nmom=3) retur...
Return L-CV weighting for a donor catchment. Methodology source: Science Report SC050050, eqn. 6.18 and 6.22a
def _l_cv_weight(self, donor_catchment): """ Return L-CV weighting for a donor catchment. Methodology source: Science Report SC050050, eqn. 6.18 and 6.22a """ try: dist = donor_catchment.similarity_dist except AttributeError: dist = self._similari...
Return multiplier for L-CV weightings in case of enhanced single site analysis. Methodology source: Science Report SC050050, eqn. 6.15a and 6.15b
def _l_cv_weight_factor(self): """ Return multiplier for L-CV weightings in case of enhanced single site analysis. Methodology source: Science Report SC050050, eqn. 6.15a and 6.15b """ b = 0.0047 * sqrt(0) + 0.0023 / 2 c = 0.02609 / (self.catchment.record_length - 1) ...
Return L-SKEW weighting for donor catchment. Methodology source: Science Report SC050050, eqn. 6.19 and 6.22b
def _l_skew_weight(self, donor_catchment): """ Return L-SKEW weighting for donor catchment. Methodology source: Science Report SC050050, eqn. 6.19 and 6.22b """ try: dist = donor_catchment.similarity_dist except AttributeError: dist = self._simila...
Return flood growth curve function based on `amax_records` from the subject catchment only. :return: Inverse cumulative distribution function with one parameter `aep` (annual exceedance probability) :type: :class:`.GrowthCurve`
def _growth_curve_single_site(self, distr='glo'): """ Return flood growth curve function based on `amax_records` from the subject catchment only. :return: Inverse cumulative distribution function with one parameter `aep` (annual exceedance probability) :type: :class:`.GrowthCurve` ...
Return flood growth curve function based on `amax_records` from a pooling group. :return: Inverse cumulative distribution function with one parameter `aep` (annual exceedance probability) :type: :class:`.GrowthCurve` :param as_rural: assume catchment is fully rural. Default: false. :typ...
def _growth_curve_pooling_group(self, distr='glo', as_rural=False): """ Return flood growth curve function based on `amax_records` from a pooling group. :return: Inverse cumulative distribution function with one parameter `aep` (annual exceedance probability) :type: :class:`.GrowthCurve...
We're lazy here and simply iterate to find the location parameter such that growth_curve(0.5)=1.
def _solve_location_param(self): """ We're lazy here and simply iterate to find the location parameter such that growth_curve(0.5)=1. """ params = copy.copy(self.params) del params['loc'] f = lambda location: self.distr_f.ppf(0.5, loc=location, **params) - 1 retu...
Logging versions of required tools.
def process(self, document): """Logging versions of required tools.""" content = json.dumps(document) versions = {} versions.update({'Spline': Version(VERSION)}) versions.update(self.get_version("Bash", self.BASH_VERSION)) if content.find('"docker(container)":') >= 0 or...
Get name and version of a tool defined by given command. Args: tool_name (str): name of the tool. tool_command (str): Bash one line command to get the version of the tool. Returns: dict: tool name and version or empty when no line has been found
def get_version(tool_name, tool_command): """ Get name and version of a tool defined by given command. Args: tool_name (str): name of the tool. tool_command (str): Bash one line command to get the version of the tool. Returns: dict: tool name and ver...
Logging version sorted ascending by tool name.
def process(self, versions): """Logging version sorted ascending by tool name.""" for tool_name in sorted(versions.keys()): version = versions[tool_name] self._log("Using tool '%s', %s" % (tool_name, version))
Registers new events after instance creation Args: *names (str): Name or names of the events to register
def register_event(self, *names): """Registers new events after instance creation Args: *names (str): Name or names of the events to register """ for name in names: if name in self.__events: continue self.__events[name] = Event(name)
Subscribes to events or to :class:`~pydispatch.properties.Property` updates Keyword arguments are used with the Event or Property names as keys and the callbacks as values:: class Foo(Dispatcher): name = Property() foo = Foo() foo.bind(name=my_list...
def bind(self, **kwargs): """Subscribes to events or to :class:`~pydispatch.properties.Property` updates Keyword arguments are used with the Event or Property names as keys and the callbacks as values:: class Foo(Dispatcher): name = Property() foo = Foo...
Unsubscribes from events or :class:`~pydispatch.properties.Property` updates Multiple arguments can be given. Each of which can be either the method that was used for the original call to :meth:`bind` or an instance object. If an instance of an object is supplied, any previously bound ...
def unbind(self, *args): """Unsubscribes from events or :class:`~pydispatch.properties.Property` updates Multiple arguments can be given. Each of which can be either the method that was used for the original call to :meth:`bind` or an instance object. If an instance of an objec...
Dispatches an event to any subscribed listeners Note: If a listener returns :obj:`False`, the event will stop dispatching to other listeners. Any other return value is ignored. Args: name (str): The name of the :class:`Event` to dispatch *args (Optional)...
def emit(self, name, *args, **kwargs): """Dispatches an event to any subscribed listeners Note: If a listener returns :obj:`False`, the event will stop dispatching to other listeners. Any other return value is ignored. Args: name (str): The name of the :clas...
Retrieves an Event object by name Args: name (str): The name of the :class:`Event` or :class:`~pydispatch.properties.Property` object to retrieve Returns: The :class:`Event` instance for the event or property definition .. versionadded:: 0.1.0
def get_dispatcher_event(self, name): """Retrieves an Event object by name Args: name (str): The name of the :class:`Event` or :class:`~pydispatch.properties.Property` object to retrieve Returns: The :class:`Event` instance for the event or property defi...
Holds emission of events and dispatches the last event on release The context manager returned will store the last event data called by :meth:`emit` and prevent callbacks until it exits. On exit, it will dispatch the last event captured (if any):: class Foo(Dispatcher): ...
def emission_lock(self, name): """Holds emission of events and dispatches the last event on release The context manager returned will store the last event data called by :meth:`emit` and prevent callbacks until it exits. On exit, it will dispatch the last event captured (if any):: ...
Test function to step through all functions in order to try and identify all features on a map This test function should be placed in a main section later
def TEST(fname): """ Test function to step through all functions in order to try and identify all features on a map This test function should be placed in a main section later """ #fname = os.path.join(os.getcwd(), '..','..', # os.path.join(os.path.getcwd(), ' m = MapObject(fname, os.p...
describes various contents of data table
def describe_contents(self): """ describes various contents of data table """ print('======================================================================') print(self) print('Table = ', str(len(self.header)) + ' cols x ' + str(len(self.arr)) + ' rows') print('HEADER = ', self...
returns the list of distinct combinations in a dataset based on the columns in the list. Note that this is currently implemented as MAX permutations of the combo so it is not guarenteed to have values in each case.
def get_distinct_values_from_cols(self, l_col_list): """ returns the list of distinct combinations in a dataset based on the columns in the list. Note that this is currently implemented as MAX permutations of the combo so it is not guarenteed to have values in each case. ...
selects rows from the array where col_list == val_list
def select_where(self, where_col_list, where_value_list, col_name=''): """ selects rows from the array where col_list == val_list """ res = [] # list of rows to be returned col_ids = [] # ids of the columns to check #print('select_where : arr = ', len(self.ar...
updates the array to set cell = value where col_list == val_list
def update_where(self, col, value, where_col_list, where_value_list): """ updates the array to set cell = value where col_list == val_list """ if type(col) is str: col_ndx = self.get_col_by_name(col) else: col_ndx = col #print('col_ndx = ', col_nd...
calculates the percentiles of col_name WHERE [where_col_list] = [where_value_list]
def calc_percentiles(self, col_name, where_col_list, where_value_list): """ calculates the percentiles of col_name WHERE [where_col_list] = [where_value_list] """ #col_data = self.get_col_data_by_name(col_name) col_data = self.select_where(where_col_list, where_value_li...
calculates the 'num' percentile of the items in the list
def percentile(self, lst_data, percent , key=lambda x:x): """ calculates the 'num' percentile of the items in the list """ new_list = sorted(lst_data) #print('new list = ' , new_list) #n = float(len(lst_data)) k = (len(new_list)-1) * percent f = math.floor(k) c = ...
default is to save a file from list of lines
def save(self, filename, content): """ default is to save a file from list of lines """ with open(filename, "w") as f: if hasattr(content, '__iter__'): f.write('\n'.join([row for row in content])) else: print('WRINGI CONTWETESWREWR'...
save the default array as a CSV file
def save_csv(self, filename, write_header_separately=True): """ save the default array as a CSV file """ txt = '' #print("SAVING arr = ", self.arr) with open(filename, "w") as f: if write_header_separately: f.write(','.join([c for c in...
drop the table, view or delete the file
def drop(self, fname): """ drop the table, view or delete the file """ if self.dataset_type == 'file': import os try: os.remove(fname) except Exception as ex: print('cant drop file "' + fname + '" : ' + str(ex))
returns the values of col_name according to where
def get_col_data_by_name(self, col_name, WHERE_Clause=''): """ returns the values of col_name according to where """ #print('get_col_data_by_name: col_name = ', col_name, ' WHERE = ', WHERE_Clause) col_key = self.get_col_by_name(col_name) if col_key is None: print('get_col_da...
return table in RST format
def format_rst(self): """ return table in RST format """ res = '' num_cols = len(self.header) col_width = 25 for _ in range(num_cols): res += ''.join(['=' for _ in range(col_width - 1)]) + ' ' res += '\n' for c in self.header: ...
Read perseus network collection folder format >>> network_table, networks = read_networks(folder) :param folder: Path to network collection :returns: Network table and dictionary with 'name', 'edge_table', and 'node_table' keys.
def read_networks(folder): """ Read perseus network collection folder format >>> network_table, networks = read_networks(folder) :param folder: Path to network collection :returns: Network table and dictionary with 'name', 'edge_table', and 'node_table' keys. """ network_table = re...
Create networkx graph from network tables >>> from perseuspy import read_networks, nx >>> network_table, networks = read_networks(folder) >>> graphs = nx.from_perseus(network_table, networks)
def from_perseus(network_table, networks): """ Create networkx graph from network tables >>> from perseuspy import read_networks, nx >>> network_table, networks = read_networks(folder) >>> graphs = nx.from_perseus(network_table, networks) """ graphs = [] for guid, graph_attr in zip(...
Create a network table and the network dictionary for export to Perseus. :param graphs: Collection of networkx graphs >>> from perseuspy import nx >>> G = nx.random_graphs.barabasi_albert_graph(10, 3) >>> network_table, networks = nx.to_perseus([G])
def to_perseus(graphs): """ Create a network table and the network dictionary for export to Perseus. :param graphs: Collection of networkx graphs >>> from perseuspy import nx >>> G = nx.random_graphs.barabasi_albert_graph(10, 3) >>> network_table, networks = nx.to_perseus([G]) """ ...
Writing networkTable, nodes and edges to Perseus readable format. :param folder: Path to output directory. :param network_table: Network table. :param networks: Dictionary with node and edge tables, indexed by network guid.
def write_networks(folder, network_table, networks): """ Writing networkTable, nodes and edges to Perseus readable format. :param folder: Path to output directory. :param network_table: Network table. :param networks: Dictionary with node and edge tables, indexed by network guid. """ ma...
Returns NBCI's Homolog Gene tables. :param taxfile: path to local file or to baseURL/taxfile :param genefile: path to local file or to baseURL/genefile :param proteinsfile: path to local file or to baseURL/proteinsfile :param proteinsclusterfile: path to local file or to baseURL/proteinsclusterfile ...
def getHomoloGene(taxfile="build_inputs/taxid_taxname",\ genefile="homologene.data",\ proteinsfile="build_inputs/all_proteins.data",\ proteinsclusterfile="build_inputs/proteins_for_clustering.data",\ baseURL="http://ftp.ncbi.nih.gov/pub/HomoloGene/...
Retrieves a sequence from an opened multifasta file :param opened_file: an opened multifasta file eg. opened_file=open("/path/to/file.fa",'r+') :param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome chromosome:GRCm38:2:1:182113224:1 REF' use: sequence_name=str(2) returns...
def getFasta(opened_file, sequence_name): """ Retrieves a sequence from an opened multifasta file :param opened_file: an opened multifasta file eg. opened_file=open("/path/to/file.fa",'r+') :param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome chromosome:GRCm38:2:1:1...
Writes a fasta sequence into a file. :param sequence: a string with the sequence to be written :param sequence_name: name of the the fasta sequence :param output_file: /path/to/file.fa to be written :returns: nothing
def writeFasta(sequence, sequence_name, output_file): """ Writes a fasta sequence into a file. :param sequence: a string with the sequence to be written :param sequence_name: name of the the fasta sequence :param output_file: /path/to/file.fa to be written :returns: nothing """ i=0 ...
Rewrites a specific sequence in a multifasta file while keeping the sequence header. :param sequence: a string with the sequence to be written :param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome chromosome:GRCm38:2:1:182113224:1 REF' use: sequence_name=str(2) :param fa...
def rewriteFasta(sequence, sequence_name, fasta_in, fasta_out): """ Rewrites a specific sequence in a multifasta file while keeping the sequence header. :param sequence: a string with the sequence to be written :param sequence_name: the name of the sequence to be retrieved eg. for '>2 dna:chromosome ch...
get a string representation of the tool
def _get_tool_str(self, tool): """ get a string representation of the tool """ res = tool['file'] try: res += '.' + tool['function'] except Exception as ex: print('Warning - no function defined for tool ' + str(tool)) res += '\n' r...
get the tool object by name or file
def get_tool_by_name(self, nme): """ get the tool object by name or file """ for t in self.lstTools: if 'name' in t: if t['name'] == nme: return t if 'file' in t: if t['file'] == nme: return t...
Adds a Tool to the list, logs the reference and TODO
def add(self, tool): """ Adds a Tool to the list, logs the reference and TODO """ self.lstTools.append(tool) self.lg.record_process(self._get_tool_str(tool))
Save the list of tools to AIKIF core and optionally to local file fname
def save(self, fname=''): """ Save the list of tools to AIKIF core and optionally to local file fname """ if fname != '': with open(fname, 'w') as f: for t in self.lstTools: self.verify(t) f.write(self.tool_as_string(t))
check that the tool exists
def verify(self, tool): """ check that the tool exists """ if os.path.isfile(tool['file']): print('Toolbox: program exists = TOK :: ' + tool['file']) return True else: print('Toolbox: program exists = FAIL :: ' + tool['file']) retu...
import the tool and call the function, passing the args.
def run(self, tool, args, new_import_path=''): """ import the tool and call the function, passing the args. """ if new_import_path != '': #print('APPENDING PATH = ', new_import_path) sys.path.append(new_import_path) #if silent == 'N': prin...
The Pipeline tool.
def main(**kwargs): """The Pipeline tool.""" options = ApplicationOptions(**kwargs) Event.configure(is_logging_enabled=options.event_logging) application = Application(options) application.run(options.definition)
Setup of application logging.
def setup_logging(self): """Setup of application logging.""" is_custom_logging = len(self.options.logging_config) > 0 is_custom_logging = is_custom_logging and os.path.isfile(self.options.logging_config) is_custom_logging = is_custom_logging and not self.options.dry_run if is_cu...
Validate given pipeline document. The method is trying to load, parse and validate the spline document. The validator verifies the Python structure B{not} the file format. Args: definition (str): path and filename of a yaml file containing a valid spline definition. Return...
def validate_document(self, definition): """ Validate given pipeline document. The method is trying to load, parse and validate the spline document. The validator verifies the Python structure B{not} the file format. Args: definition (str): path and filename of a ya...
Running pipeline via a matrix. Args: matrix_definition (dict): one concrete matrix item. document (dict): spline document (complete) as loaded from yaml file.
def run_matrix(self, matrix_definition, document): """ Running pipeline via a matrix. Args: matrix_definition (dict): one concrete matrix item. document (dict): spline document (complete) as loaded from yaml file. """ matrix = Matrix(matrix_definition, 'm...
Shutdown of the application.
def shutdown(self, collector, success): """Shutdown of the application.""" self.event.delegate(success) if collector is not None: collector.queue.put(None) collector.join() if not success: sys.exit(1)
Processing the pipeline.
def run(self, definition): """Processing the pipeline.""" self.logger.info("Running with Python %s", sys.version.replace("\n", "")) self.logger.info("Running on platform %s", platform.platform()) self.logger.info("Current cpu count is %d", multiprocessing.cpu_count()) self.logger...
When configured trying to ensure that path does exist.
def provide_temporary_scripts_path(self): """When configured trying to ensure that path does exist.""" if len(self.options.temporary_scripts_path) > 0: if os.path.isfile(self.options.temporary_scripts_path): self.logger.error("Error: configured script path seems to be a file!...
Create and run collector process for report data.
def create_and_run_collector(document, options): """Create and run collector process for report data.""" collector = None if not options.report == 'off': collector = Collector() collector.store.configure(document) Event.configure(collector_queue=collector.queu...
Use Jinja2 rendering for given text an key key/values. Args: value (str): the template to be rendered. kwargs (dict): named parameters representing available variables inside the template. >>> model = {"message": "hello world 1!"} >>> rendered_text = render("{{model....
def render(value, **kwargs): """ Use Jinja2 rendering for given text an key key/values. Args: value (str): the template to be rendered. kwargs (dict): named parameters representing available variables inside the template. >>> model = {"message": "hello world 1!"}...
Transform dictionary of environment variables into Docker -e parameters. >>> result = docker_environment({'param1': 'val1', 'param2': 'val2'}) >>> result in ['-e "param1=val1" -e "param2=val2"', '-e "param2=val2" -e "param1=val1"'] True
def docker_environment(env): """ Transform dictionary of environment variables into Docker -e parameters. >>> result = docker_environment({'param1': 'val1', 'param2': 'val2'}) >>> result in ['-e "param1=val1" -e "param2=val2"', '-e "param2=val2" -e "param1=val1"'] True """ return ' '.join( ...
Find **stages** in document. Args: document (dict): validated spline document loaded from a yaml file. Returns: list: stages as a part of the spline document or an empty list if not given. >>> find_stages({'pipeline': [{'stage(Prepare)':1}, {'stage(Build)':1}, {'stage(Deploy)':2}]}) ...
def find_stages(document): """ Find **stages** in document. Args: document (dict): validated spline document loaded from a yaml file. Returns: list: stages as a part of the spline document or an empty list if not given. >>> find_stages({'pipeline': [{'stage(Prepare)':1}, {'stage(...
Retrieves download location for FEH data zip file from hosted json configuration file. :return: URL for FEH data file :rtype: str
def _retrieve_download_url(): """ Retrieves download location for FEH data zip file from hosted json configuration file. :return: URL for FEH data file :rtype: str """ try: # Try to obtain the url from the Open Hydrology json config file. with urlopen(config['nrfa']['oh_json_url...
Check whether updated NRFA data is available. :param after_days: Only check if not checked previously since a certain number of days ago :type after_days: float :return: `True` if update available, `False` if not, `None` if remote location cannot be reached. :rtype: bool or None
def update_available(after_days=1): """ Check whether updated NRFA data is available. :param after_days: Only check if not checked previously since a certain number of days ago :type after_days: float :return: `True` if update available, `False` if not, `None` if remote location cannot be reached. ...
Downloads complete station dataset including catchment descriptors and amax records. And saves it into a cache folder.
def download_data(): """ Downloads complete station dataset including catchment descriptors and amax records. And saves it into a cache folder. """ with urlopen(_retrieve_download_url()) as f: with open(os.path.join(CACHE_FOLDER, CACHE_ZIP), "wb") as local_file: local_file.write(...
Save NRFA metadata to local config file using retrieved config data :param remote_config: Downloaded JSON data, not a ConfigParser object!
def _update_nrfa_metadata(remote_config): """ Save NRFA metadata to local config file using retrieved config data :param remote_config: Downloaded JSON data, not a ConfigParser object! """ config['nrfa']['oh_json_url'] = remote_config['nrfa_oh_json_url'] config['nrfa']['version'] = remote_confi...
Return metadata on the NRFA data. Returned metadata is a dict with the following elements: - `url`: string with NRFA data download URL - `version`: string with NRFA version number, e.g. '3.3.4' - `published_on`: datetime of data release/publication (only month and year are accurate, rest should be ign...
def nrfa_metadata(): """ Return metadata on the NRFA data. Returned metadata is a dict with the following elements: - `url`: string with NRFA data download URL - `version`: string with NRFA version number, e.g. '3.3.4' - `published_on`: datetime of data release/publication (only month and year...
Extract all files from downloaded FEH data zip file.
def unzip_data(): """ Extract all files from downloaded FEH data zip file. """ with ZipFile(os.path.join(CACHE_FOLDER, CACHE_ZIP), 'r') as zf: zf.extractall(path=CACHE_FOLDER)
Return all annual maximum flow (`*.am`) files in cache folder and sub folders. :return: List of file paths :rtype: list
def amax_files(): """ Return all annual maximum flow (`*.am`) files in cache folder and sub folders. :return: List of file paths :rtype: list """ return [os.path.join(dp, f) for dp, dn, filenames in os.walk(CACHE_FOLDER) for f in filenames if os.path.splitext(f)[1].lower() == '.am']
return a dictionary of statistics about an XML file including size in bytes, num lines, number of elements, count by elements
def get_xml_stats(fname): """ return a dictionary of statistics about an XML file including size in bytes, num lines, number of elements, count by elements """ f = mod_file.TextFile(fname) res = {} res['shortname'] = f.name res['folder'] = f.path res['filesize'] = str(f.size) + ...
makes a random xml file mainly for testing the xml_split
def make_random_xml_file(fname, num_elements=200, depth=3): """ makes a random xml file mainly for testing the xml_split """ with open(fname, 'w') as f: f.write('<?xml version="1.0" ?>\n<random>\n') for dep_num, _ in enumerate(range(1,depth)): f.write(' <depth>\n <content>\n...
returns (511, 35082) for ANC__WhereToHongKong.xml
def count_elements(fname, element): """ returns (511, 35082) for ANC__WhereToHongKong.xml """ num = 0 tot = 0 for event, elem in iterparse(fname): tot += 1 if elem.text != '': #print(' tag = ', elem.tag) #print(' event = ', event # always end ...
Lists all organisms present in the KEGG database. :returns: a dataframe containing one organism per row.
def organismsKEGG(): """ Lists all organisms present in the KEGG database. :returns: a dataframe containing one organism per row. """ organisms=urlopen("http://rest.kegg.jp/list/organism").read() organisms=organisms.split("\n") #for o in organisms: # print o # sys.stdout.flus...
Finds KEGG database identifiers for a respective organism given example ensembl ids. :param organism: an organism as listed in organismsKEGG() :param ens_ids: a list of ensenbl ids of the respective organism :returns: nothing if no database was found, or a string if a database was found
def databasesKEGG(organism,ens_ids): """ Finds KEGG database identifiers for a respective organism given example ensembl ids. :param organism: an organism as listed in organismsKEGG() :param ens_ids: a list of ensenbl ids of the respective organism :returns: nothing if no database was found, or a...
Looks up KEGG mappings of KEGG ids to ensembl ids :param organism: an organisms as listed in organismsKEGG() :param kegg_db: a matching KEGG db as reported in databasesKEGG :returns: a Pandas dataframe of with 'KEGGid' and 'ENSid'.
def ensembl_to_kegg(organism,kegg_db): """ Looks up KEGG mappings of KEGG ids to ensembl ids :param organism: an organisms as listed in organismsKEGG() :param kegg_db: a matching KEGG db as reported in databasesKEGG :returns: a Pandas dataframe of with 'KEGGid' and 'ENSid'. """ print("KEG...
Uses KEGG to retrieve all ids and respective ecs for a given KEGG organism :param organism: an organisms as listed in organismsKEGG() :returns: a Pandas dataframe of with 'ec' and 'KEGGid'.
def ecs_idsKEGG(organism): """ Uses KEGG to retrieve all ids and respective ecs for a given KEGG organism :param organism: an organisms as listed in organismsKEGG() :returns: a Pandas dataframe of with 'ec' and 'KEGGid'. """ kegg_ec=urlopen("http://rest.kegg.jp/link/"+organism+"/enzyme").read...
Uses KEGG to retrieve all ids for a given KEGG organism :param organism: an organism as listed in organismsKEGG() :returns: a Pandas dataframe of with 'gene_name' and 'KEGGid'.
def idsKEGG(organism): """ Uses KEGG to retrieve all ids for a given KEGG organism :param organism: an organism as listed in organismsKEGG() :returns: a Pandas dataframe of with 'gene_name' and 'KEGGid'. """ ORG=urlopen("http://rest.kegg.jp/list/"+organism).read() ORG=ORG.split("\n") ...
Retrieves all pathways for a given organism. :param organism: an organism as listed in organismsKEGG() :returns df: a Pandas dataframe with the columns 'KEGGid','pathIDs', and 'pathName'. :returns df_: a Pandas dataframe with a columns for 'KEGGid', and one column for each pathway with the corresponding gen...
def pathwaysKEGG(organism): """ Retrieves all pathways for a given organism. :param organism: an organism as listed in organismsKEGG() :returns df: a Pandas dataframe with the columns 'KEGGid','pathIDs', and 'pathName'. :returns df_: a Pandas dataframe with a columns for 'KEGGid', and one column for...
Transforms a pandas dataframe with the columns 'ensembl_gene_id','kegg_enzyme' to dataframe ready for use in ... :param df: a pandas dataframe with the following columns: 'ensembl_gene_id','kegg_enzyme' :returns: a pandas dataframe with the following columns: 'ensembl_gene_id','kegg_enzyme'
def biomaRtTOkegg(df): """ Transforms a pandas dataframe with the columns 'ensembl_gene_id','kegg_enzyme' to dataframe ready for use in ... :param df: a pandas dataframe with the following columns: 'ensembl_gene_id','kegg_enzyme' :returns: a pandas dataframe with the following columns: 'ensembl_ge...
Gets all KEGG pathways for an organism :param organism: an organism as listed in organismsKEGG() :param names_KEGGids: a Pandas dataframe with the columns 'gene_name': and 'KEGGid' as reported from idsKEGG(organism) (or a subset of it). :returns df: a Pandas dataframe with 'KEGGid','pathID(1):pathNAME(1)...
def expKEGG(organism,names_KEGGids): """ Gets all KEGG pathways for an organism :param organism: an organism as listed in organismsKEGG() :param names_KEGGids: a Pandas dataframe with the columns 'gene_name': and 'KEGGid' as reported from idsKEGG(organism) (or a subset of it). :returns df: a Pand...
Looks for all KEGG annotatios of an organism in biomart and the respective pathways in KEGG. It can also retrieve links to pathways figures with red labeled genes provided in a dataframe. :param organism: a KEGG organism identifier :param dataset: a biomaRt dataset :param query_attributes: biomaRt query at...
def KEGGmatrix(organism, dataset, query_attributes=['ensembl_gene_id','kegg_enzyme'], host=biomart_host,links=True,dfexp=None,kegg_db=None, database=None ): """ Looks for all KEGG annotatios of an organism in biomart and the respective pathways in KEGG. It can also retrieve links to pathways figures with red la...
Lists BioMart databases through a RPY2 connection. :param host: address of the host server, default='www.ensembl.org' :returns: nothing
def RdatabasesBM(host=rbiomart_host): """ Lists BioMart databases through a RPY2 connection. :param host: address of the host server, default='www.ensembl.org' :returns: nothing """ biomaRt = importr("biomaRt") print(biomaRt.listMarts(host=host))
Lists BioMart datasets through a RPY2 connection. :param database: a database listed in RdatabasesBM() :param host: address of the host server, default='www.ensembl.org' :returns: nothing
def RdatasetsBM(database,host=rbiomart_host): """ Lists BioMart datasets through a RPY2 connection. :param database: a database listed in RdatabasesBM() :param host: address of the host server, default='www.ensembl.org' :returns: nothing """ biomaRt = importr("biomaRt") ensemblMart=bi...
Lists BioMart filters through a RPY2 connection. :param dataset: a dataset listed in RdatasetsBM() :param database: a database listed in RdatabasesBM() :param host: address of the host server, default='www.ensembl.org' :returns: nothing
def RfiltersBM(dataset,database,host=rbiomart_host): """ Lists BioMart filters through a RPY2 connection. :param dataset: a dataset listed in RdatasetsBM() :param database: a database listed in RdatabasesBM() :param host: address of the host server, default='www.ensembl.org' :returns: nothing ...
Lists BioMart attributes through a RPY2 connection. :param dataset: a dataset listed in RdatasetsBM() :param database: a database listed in RdatabasesBM() :param host: address of the host server, default='www.ensembl.org' :returns: nothing
def RattributesBM(dataset,database,host=rbiomart_host): """ Lists BioMart attributes through a RPY2 connection. :param dataset: a dataset listed in RdatasetsBM() :param database: a database listed in RdatabasesBM() :param host: address of the host server, default='www.ensembl.org' :returns: no...
Queries BioMart. :param query_filtery: one BioMart filter associated with the items being queried :param query_items: list of items to be queried (must assoiate with given filter) :param query_attributes: list of attributes to recover from BioMart :param dataset: dataset to query :param database: d...
def RqueryBM(query_filter,query_items,query_attributes,dataset,database,host=rbiomart_host): """ Queries BioMart. :param query_filtery: one BioMart filter associated with the items being queried :param query_items: list of items to be queried (must assoiate with given filter) :param query_attribute...