INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Plots the histogram with Poisson ( sqrt ( n )) error bars - scale_errors_by multiplies the error bars by its argument - scale_histogram_by multiplies the histogram AND the error bars by its argument - plt thing to call. errorbar on ( pylab figure axes whatever the matplotlib guys come up with next )
def plot(self, normed=False, scale_errors_by=1.0, scale_histogram_by=1.0, plt=plt, errors=False, **kwargs): """Plots the histogram with Poisson (sqrt(n)) error bars - scale_errors_by multiplies the error bars by its argument - scale_histogram_by multiplies the histogram AND the error bars by...
Return bin center nearest to percentile
def percentile(self, percentile): """Return bin center nearest to percentile""" return self.bin_centers[np.argmin(np.abs(self.cumulative_density * 100 - percentile))]
Lookup values at coordinates. coordinates: arraylike of coordinates.
def lookup(self, coordinates): """Lookup values at coordinates. coordinates: arraylike of coordinates. Clips if out of range!! TODO: option to throw exception instead. TODO: Needs tests!! """ # Convert coordinates to indices index_array = np.clip(np.searchsorted(...
Make a HistdD from numpy histogram + bin edges: param histogram: Initial histogram: param bin_edges: x bin edges of histogram y bin edges...: return: Histnd instance
def from_histogram(cls, histogram, bin_edges, axis_names=None): """Make a HistdD from numpy histogram + bin edges :param histogram: Initial histogram :param bin_edges: x bin edges of histogram, y bin edges, ... :return: Histnd instance """ bin_edges = np.array(bin_edges) ...
Return bin_edges histogram array
def _data_to_hist(self, data, **kwargs): """Return bin_edges, histogram array""" if hasattr(self, 'bin_edges'): kwargs.setdefault('bins', self.bin_edges) if len(data) == 1 and isinstance(data[0], COLUMNAR_DATA_SOURCES): data = data[0] if self.axis_names is N...
Return axis names without axis or None if axis_names is None
def axis_names_without(self, axis): """Return axis names without axis, or None if axis_names is None""" if self.axis_names is None: return None return itemgetter(*self.other_axes(axis))(self.axis_names)
Return bin centers along an axis or if axis = None list of bin_centers along each axis
def bin_centers(self, axis=None): """Return bin centers along an axis, or if axis=None, list of bin_centers along each axis""" if axis is None: return np.array([self.bin_centers(axis=i) for i in range(self.dimensions)]) axis = self.get_axis_number(axis) return 0.5 * (self.bin...
Returns index along axis of bin in histogram which contains value Inclusive on both endpoints
def get_axis_bin_index(self, value, axis): """Returns index along axis of bin in histogram which contains value Inclusive on both endpoints """ axis = self.get_axis_number(axis) bin_edges = self.bin_edges[axis] # The right bin edge of np.histogram is inclusive: if...
Returns index tuple in histogram of bin which contains value
def get_bin_indices(self, values): """Returns index tuple in histogram of bin which contains value""" return tuple([self.get_axis_bin_index(values[ax_i], ax_i) for ax_i in range(self.dimensions)])
Return ndarray of same shape as histogram containing bin center value along axis at each point
def all_axis_bin_centers(self, axis): """Return ndarray of same shape as histogram containing bin center value along axis at each point""" # Arcane hack that seems to work, at least in 3d... hope axis = self.get_axis_number(axis) return np.meshgrid(*self.bin_centers(), indexing='ij')[axi...
Sums all data along axis returns d - 1 dimensional histogram
def sum(self, axis): """Sums all data along axis, returns d-1 dimensional histogram""" axis = self.get_axis_number(axis) if self.dimensions == 2: new_hist = Hist1d else: new_hist = Histdd return new_hist.from_histogram(np.sum(self.histogram, axis=axis), ...
Restrict histogram to bins whose data values ( not bin numbers ) along axis are between start and stop ( both inclusive ). Returns d dimensional histogram.
def slice(self, start, stop=None, axis=0): """Restrict histogram to bins whose data values (not bin numbers) along axis are between start and stop (both inclusive). Returns d dimensional histogram.""" if stop is None: # Make a 1=bin slice stop = start axis = self....
Slices the histogram along axis then sums over that slice returning a d - 1 dimensional histogram
def slicesum(self, start, stop=None, axis=0): """Slices the histogram along axis, then sums over that slice, returning a d-1 dimensional histogram""" return self.slice(start, stop, axis).sum(axis)
Sums all data along all other axes then return Hist1D
def projection(self, axis): """Sums all data along all other axes, then return Hist1D""" axis = self.get_axis_number(axis) projected_hist = np.sum(self.histogram, axis=self.other_axes(axis)) return Hist1d.from_histogram(projected_hist, bin_edges=self.bin_edges[axis])
Returns new histogram with all data cumulated along axis.
def cumulate(self, axis): """Returns new histogram with all data cumulated along axis.""" axis = self.get_axis_number(axis) return Histdd.from_histogram(np.cumsum(self.histogram, axis=axis), bin_edges=self.bin_edges, axis_...
Returns new histogram where all values along axis ( in one bin of the other axes ) sum to 1
def normalize(self, axis): """Returns new histogram where all values along axis (in one bin of the other axes) sum to 1""" axis = self.get_axis_number(axis) sum_along_axis = np.sum(self.histogram, axis=axis) # Don't do anything for subspaces without any entries -- this avoids nans everyw...
Returns new histogram with all values replaced by their central likelihoods along axis.
def central_likelihood(self, axis): """Returns new histogram with all values replaced by their central likelihoods along axis.""" result = self.cumulative_density(axis) result.histogram = 1 - 2 * np.abs(result.histogram - 0.5) return result
Returns d - 1 dimensional histogram containing percentile of values along axis if inclusive = True will report bin center of first bin for which percentile% of data lies in or below the bin = False... data lies strictly below the bin 10% percentile is calculated as: value at least 10% data is LOWER than
def percentile(self, percentile, axis, inclusive=True): """Returns d-1 dimensional histogram containing percentile of values along axis if inclusive=True, will report bin center of first bin for which percentile% of data lies in or below the bin =False, ... data lies strictly below t...
Returns d - 1 dimensional histogram of ( estimated ) mean value of axis NB this is very different from averaging over the axis!!!
def average(self, axis): """Returns d-1 dimensional histogram of (estimated) mean value of axis NB this is very different from averaging over the axis!!! """ axis = self.get_axis_number(axis) avg_hist = np.ma.average(self.all_axis_bin_centers(axis), ...
Returns d - 1 dimensional histogram of ( estimated ) std value along axis NB this is very different from just std of the histogram values ( which describe bin counts )
def std(self, axis): """Returns d-1 dimensional histogram of (estimated) std value along axis NB this is very different from just std of the histogram values (which describe bin counts) """ def weighted_std(values, weights, axis): # Stolen from http://stackoverflow.com/questi...
Return a new histogram that is rebinned ( zoomed ) by factors ( tuple of floats ) along each dimensions factors: tuple with zoom factors along each axis. e. g. 2 = double number of bins 0. 5 = halve them. order: Order for spline interpolation in scipy. ndimage. zoom. Defaults to linear interpolation ( order = 1 ).
def rebin(self, *factors, **kwargs): """Return a new histogram that is 'rebinned' (zoomed) by factors (tuple of floats) along each dimensions factors: tuple with zoom factors along each axis. e.g. 2 = double number of bins, 0.5 = halve them. order: Order for spline interpolation in scipy.ndi...
Returns ( size n_dim ) array of random variates from the histogram. Inside the bins a uniform distribution is assumed Note this assumes the histogram is an events per bin not a pdf. TODO: test more.
def get_random(self, size=10): """Returns (size, n_dim) array of random variates from the histogram. Inside the bins, a uniform distribution is assumed Note this assumes the histogram is an 'events per bin', not a pdf. TODO: test more. """ # Sample random bin centers ...
Lookup values at specific points. coordinate_arrays: numpy arrays of coordinates one for each dimension e. g. lookup ( np. array ( [ 0 2 ] ) np. array ( [ 1 3 ] )) looks up ( x = 0 y = 1 ) and ( x = 2 y3 ).
def lookup(self, *coordinate_arrays): """Lookup values at specific points. coordinate_arrays: numpy arrays of coordinates, one for each dimension e.g. lookup(np.array([0, 2]), np.array([1, 3])) looks up (x=0, y=1) and (x=2, y3). Clips if out of range!! TODO: option to throw exception in...
Return histogram within binning of Histdd mh with values looked up in this histogram.
def lookup_hist(self, mh): """Return histogram within binning of Histdd mh, with values looked up in this histogram. This is not rebinning: no interpolation /renormalization is performed. It's just a lookup. """ result = mh.similar_blank_histogram() points = np.stack([mh...
takes a dictionary read from a yaml file and converts it to the roadmap documentation
def create_roadmap_doc(dat, opFile): """ takes a dictionary read from a yaml file and converts it to the roadmap documentation """ op = format_title('Roadmap for AIKIF') for h1 in dat['projects']: op += format_h1(h1) if dat[h1] is None: op += '(No details)\n' ...
Reset the game so the grid is zeros ( or default items )
def reset(self): """ Reset the game so the grid is zeros (or default items) """ self.grid = [[0 for dummy_l in range(self.grid_width)] for dummy_l in range(self.grid_height)]
Clears grid to be EMPTY
def clear(self): """ Clears grid to be EMPTY """ self.grid = [[EMPTY for dummy_col in range(self.grid_width)] for dummy_row in range(self.grid_height)]
saves a grid to file as ASCII text
def save(self, fname): """ saves a grid to file as ASCII text """ try: with open(fname, "w") as f: f.write(str(self)) except Exception as ex: print('ERROR = cant save grid results to ' + fname + str(ex))
loads a ASCII text file grid to self
def load(self, fname): """ loads a ASCII text file grid to self """ # get height and width of grid from file self.grid_width = 4 self.grid_height = 4 # re-read the file and load it self.grid = [[0 for dummy_l in range(self.grid_width)] for dummy_l in ra...
get column number col
def extract_col(self, col): """ get column number 'col' """ new_col = [row[col] for row in self.grid] return new_col
get row number row
def extract_row(self, row): """ get row number 'row' """ new_row = [] for col in range(self.get_grid_width()): new_row.append(self.get_tile(row, col)) return new_row
replace a grids row at index ndx with line
def replace_row(self, line, ndx): """ replace a grids row at index 'ndx' with 'line' """ for col in range(len(line)): self.set_tile(ndx, col, line[col])
replace a grids column at index ndx with line
def replace_col(self, line, ndx): """ replace a grids column at index 'ndx' with 'line' """ for row in range(len(line)): self.set_tile(row, ndx, line[row])
Create a new tile in a randomly selected empty square. The tile should be 2 90% of the time and 4 10% of the time.
def new_tile(self, num=1): """ Create a new tile in a randomly selected empty square. The tile should be 2 90% of the time and 4 10% of the time. """ for _ in range(num): if random.random() > .5: new_tile = self.pieces[0] ...
return a count of blank cells
def count_blank_positions(self): """ return a count of blank cells """ blanks = 0 for row_ndx in range(self.grid_height - 0): for col_ndx in range(self.grid_width - 0): if self.get_tile(row_ndx, col_ndx) == EMPTY: blanks += 1 ...
return a count of blank cells
def count_filled_positions(self): """ return a count of blank cells """ filled = 0 for row_ndx in range(self.grid_height - 0): for col_ndx in range(self.grid_width - 0): if self.get_tile(row_ndx, col_ndx) != EMPTY: filled += 1 ...
Set the tile at position row col to have the given value.
def set_tile(self, row, col, value): """ Set the tile at position row, col to have the given value. """ #print('set_tile: y=', row, 'x=', col) if col < 0: print("ERROR - x less than zero", col) col = 0 #return if col > s...
Returns horiz/ vert neighbors of cell ( row col )
def four_neighbors(self, row, col): """ Returns horiz/vert neighbors of cell (row, col) """ ans = [] if row > 0: ans.append((row - 1, col)) if row < self.grid_height - 1: ans.append((row + 1, col)) if col > 0: ans.append((row, c...
Returns horiz/ vert neighbors of cell ( row col ) as well as diagonal neighbors
def eight_neighbors(self, row, col): """ Returns horiz/vert neighbors of cell (row, col) as well as diagonal neighbors """ ans = [] if row > 0: ans.append((row - 1, col)) if row < self.grid_height - 1: ans.append((row + 1, col)) if ...
replace all cells in current grid with updated grid
def replace_grid(self, updated_grid): """ replace all cells in current grid with updated grid """ for col in range(self.get_grid_width()): for row in range(self.get_grid_height()): if updated_grid[row][col] == EMPTY: self.set_empty(row, col...
finds a place on the grid which is clear on all sides to avoid starting in the middle of a blockage
def find_safe_starting_point(self): """ finds a place on the grid which is clear on all sides to avoid starting in the middle of a blockage """ y = random.randint(2,self.grid_height-4) x = random.randint(2,self.grid_width-4) return y, x
takes a screenshot of the users desktop ( Currently Win only )
def screenshot(fname): """ takes a screenshot of the users desktop (Currently Win only) """ try: im = ImageGrab.grab() im.save(fname) except Exception as ex: print('image_tools.screenshot:cant create screenshot ' + str(ex))
resize an image to basewidth
def resize(fname, basewidth, opFilename): """ resize an image to basewidth """ if basewidth == 0: basewidth = 300 img = Image.open(fname) wpercent = (basewidth/float(img.size[0])) hsize = int((float(img.size[1])*float(wpercent))) img = img.resize((basewidth,hsize), Image.ANTIALIAS) i...
prints stats remember that img should already have been loaded
def print_stats(img): """ prints stats, remember that img should already have been loaded """ stat = ImageStat.Stat(img) print("extrema : ", stat.extrema) print("count : ", stat.count) print("sum : ", stat.sum) print("sum2 : ", stat.sum2) print("mean : ", stat.mean...
high level that prints all as long list
def print_all_metadata(fname): """ high level that prints all as long list """ print("Filename :", fname ) print("Basename :", os.path.basename(fname)) print("Path :", os.path.dirname(fname)) print("Size :", os.path.getsize(fname)) img = Image.open(fname) # get the image's wi...
Gets all metadata and puts into dictionary
def get_metadata_as_dict(fname): """ Gets all metadata and puts into dictionary """ imgdict = {} try: imgdict['filename'] = fname imgdict['size'] = str(os.path.getsize(fname)) imgdict['basename'] = os.path.basename(fname) imgdict['path'] = os.path.dirname(fname) img ...
Gets all metadata and puts into CSV format
def get_metadata_as_csv(fname): """ Gets all metadata and puts into CSV format """ q = chr(34) d = "," res = q + fname + q + d res = res + q + os.path.basename(fname) + q + d res = res + q + os.path.dirname(fname) + q + d try: res = res + q + str(os.path.getsize(fname)) + q + d ...
convert an image by adding text
def add_text_to_image(fname, txt, opFilename): """ convert an image by adding text """ ft = ImageFont.load("T://user//dev//src//python//_AS_LIB//timR24.pil") #wh = ft.getsize(txt) print("Adding text ", txt, " to ", fname, " pixels wide to file " , opFilename) im = Image.open(fname) draw = ImageD...
convert an image by adding a cross hair
def add_crosshair_to_image(fname, opFilename): """ convert an image by adding a cross hair """ im = Image.open(fname) draw = ImageDraw.Draw(im) draw.line((0, 0) + im.size, fill=(255, 255, 255)) draw.line((0, im.size[1], im.size[0], 0), fill=(255, 255, 255)) del draw im.save(opFilename)
convert an image by applying a contour
def filter_contour(imageFile, opFile): """ convert an image by applying a contour """ im = Image.open(imageFile) im1 = im.filter(ImageFilter.CONTOUR) im1.save(opFile)
Checking Images for duplicates ( despite resizing colours etc )
def check_image_duplicates(file_list): """ Checking Images for duplicates (despite resizing, colours, etc) """ master_hash = '' ham_dist = 0 results = [] print("Checking Images for duplicates (despite resizing, colours, etc) " ) for ndx, fname in enumerate(file_list): #img = Image.open(f...
Return the Hamming distance between equal - length sequences ( http:// en. wikipedia. org/ wiki/ Hamming_distance )
def hamming_distance(s1, s2): """ Return the Hamming distance between equal-length sequences (http://en.wikipedia.org/wiki/Hamming_distance ) """ if len(s1) != len(s2): raise ValueError("Undefined for sequences of unequal length") return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))
Grayscale and shrink the image in one step
def get_img_hash(image, hash_size = 8): """ Grayscale and shrink the image in one step """ image = image.resize((hash_size + 1, hash_size), Image.ANTIALIAS, ) pixels = list(image.getdata()) #print('get_img_hash: pixels=', pixels) # Compare adjacent pixels. difference = [] for row in range...
read an image from file - PIL doesnt close nicely
def load_image(fname): """ read an image from file - PIL doesnt close nicely """ with open(fname, "rb") as f: i = Image.open(fname) #i.load() return i
output the image as text
def dump_img(fname): """ output the image as text """ img = Image.open(fname) width, _ = img.size txt = '' pixels = list(img.getdata()) for col in range(width): txt += str(pixels[col:col+width]) return txt
Python implementation of the CellPlot from the CellPlot package for R. - inf or inf enrichments will come out as min found float or max found float respectively.
def CellPlot(df, output_file=None, gene_expression="log2FC", figure_title="CellPlot", pvalCol="elimFisher", lowerLimit=None, upperLimit=None, colorBarType='Spectral'): """ Python implementation of the CellPlot from the CellPlot package for R. -inf or inf enrichments will come out as min found float or max f...
Python implementation of the SymPlot from the CellPlot package for R. - inf or inf enrichments will come out as min found float or max found float respectively.
def SymPlot(df,output_file=None,figure_title="SymPlot",pvalCol="elimFisher"): """ Python implementation of the SymPlot from the CellPlot package for R. -inf or inf enrichments will come out as min found float or max found float, respectively. :param df: pandas dataframe with the following columns - 'En...
Normalizes intensities of a gene in two samples
def NormInt(df,sampleA,sampleB): """ Normalizes intensities of a gene in two samples :param df: dataframe output of GetData() :param sampleA: column header of sample A :param sampleB: column header of sample B :returns: normalized intensities """ c1=df[sampleA] c2=df[sampleB] ...
Plots an MA like plot GetData () outputs.
def MA(df,title,figName,c, daType="counts",nbins=10,perc=.5,deg=3,eq=True,splines=True,spec=None,Targets=None,ylim=None,sizeRed=8): """ Plots an MA like plot GetData() outputs. :param df: dataframe output of GetData() :param title: plot title, 'Genes' or 'Transcripts' :param figName: /path/to/saved...
Testing given number to be a prime.
def is_prime(number): """ Testing given number to be a prime. >>> [n for n in range(100+1) if is_prime(n)] [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] """ if number < 2: return False if number % 2 == 0: return number == 2 ...
Return array of valid flows ( i. e. excluding rejected years etc )
def valid_flows_array(catchment): """ Return array of valid flows (i.e. excluding rejected years etc) :param catchment: gauged catchment with amax_records set :type catchment: :class:`floodestimation.entities.Catchment` :return: 1D array of flow values :rtype: :class:`numpy.ndarray` """ ...
Return QMED estimate using best available methodology depending on what catchment attributes are available.
def qmed(self, method='best', **method_options): """ Return QMED estimate using best available methodology depending on what catchment attributes are available. The preferred/best order of methods is defined by :attr:`qmed_methods`. Alternatively, a method can be supplied e.g. `method='...
Returns a dict of QMED methods using all available methods.
def qmed_all_methods(self): """ Returns a dict of QMED methods using all available methods. Available methods are defined in :attr:`qmed_methods`. The returned dict keys contain the method name, e.g. `amax_record` with value representing the corresponding QMED estimate in m³/s. ...
Return QMED estimate based on annual maximum flow records.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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
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
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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...
Find list of suitable donor cachments ranked by hydrological similarity distance measure. This method is implicitly called when calling the: meth:. growth_curve method unless the attribute: attr:. donor_catchments is set manually.
def find_donor_catchments(self, include_subject_catchment='auto'): """ Find list of suitable donor cachments, ranked by hydrological similarity distance measure. This method is implicitly called when calling the :meth:`.growth_curve` method unless the attribute :attr:`.donor_catchments` ...
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.
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
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
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
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...