Computes the error magnitudes. Works also with erasures and errors+erasures beyond the (n-k)//2 bound, here the bound is 2*e+v <= (n-k-1) with e the number of errors and v the number of erasures.
484438
def _forney(self, omega, X):
        ''''''
        # XXX Is floor division okay here? Should this be ceiling?

        Y = [] # the final result, the error/erasures polynomial (contain the values that we should minus on the received message to get the repaired message)
        Xlength = len(X)
        for l, Xl in enumerate(X):

            Xl_inv = Xl.inverse()

            # Compute the formal derivative of the error locator polynomial (see Blahut, Algebraic codes for data transmission, pp 196-197).
            # the formal derivative of the errata locator is used as the denominator of the Forney Algorithm, which simply says that the ith error value is given by error_evaluator(gf_inverse(Xi)) / error_locator_derivative(gf_inverse(Xi)). See Blahut, Algebraic codes for data transmission, pp 196-197.
            sigma_prime_tmp = [1 - Xl_inv * X[j] for j in _range(Xlength) if j != l] # TODO? maybe a faster way would be to precompute sigma_prime = sigma[len(sigma) & 1:len(sigma):2] and then just do sigma_prime.evaluate(X[j]) ? (like in reedsolo.py)
            # compute the product
            sigma_prime = 1
            for coef in sigma_prime_tmp:
                sigma_prime = sigma_prime * coef
            # equivalent to: sigma_prime = functools.reduce(mul, sigma_prime, 1)

            # Compute Yl
            # This is a more faithful translation of the theoretical equation contrary to the old forney method. Here it is exactly copy/pasted from the included presentation decoding_rs.pdf: Yl = omega(Xl.inverse()) / prod(1 - Xj*Xl.inverse()) for j in len(X) (in the paper it's for j in s, but it's useless when len(X) < s because we compute neutral terms 1 for nothing, and wrong when correcting more than s erasures or erasures+errors since it prevents computing all required terms).
            # Thus here this method works with erasures too because firstly we fixed the equation to be like the theoretical one (don't know why it was modified in _old_forney(), if it's an optimization, it doesn't enhance anything), and secondly because we removed the product bound on s, which prevented computing errors and erasures above the s=(n-k)//2 bound.
            # The best resource I have found for the correct equation is https://en.wikipedia.org/wiki/Forney_algorithm -- note that in the article, fcr is defined as c.
            Yl = - (Xl**(1-self.fcr)  * omega.evaluate(Xl_inv) / sigma_prime) # sigma_prime is the denominator of the Forney algorithm

            Y.append(Yl)
        return Y
45329
def rs_find_error_locator(synd, nsym, erase_loc=None, erase_count=0):
    ''''''
    # The idea is that BM will iteratively estimate the error locator polynomial.
    # To do this, it will compute a Discrepancy term called Delta, which will tell us if the error locator polynomial needs an update or not
    # (hence why it's called discrepancy: it tells us when we are getting off board from the correct value).

    # Init the polynomials
    if erase_loc: # if the erasure locator polynomial is supplied, we init with its value, so that we include erasures in the final locator polynomial
        err_loc = bytearray(erase_loc)
        old_loc = bytearray(erase_loc)
    else:
        err_loc = bytearray([1]) # This is the main variable we want to fill, also called Sigma in other notations or more formally the errors/errata locator polynomial.
        old_loc = bytearray([1]) # BM is an iterative algorithm, and we need the errata locator polynomial of the previous iteration in order to update other necessary variables.
    #L = 0 # update flag variable, not needed here because we use an alternative equivalent way of checking if update is needed (but using the flag could potentially be faster depending on if using length(list) is taking linear time in your language, here in Python it's constant so it's as fast.

    # Fix the syndrome shifting: when computing the syndrome, some implementations may prepend a 0 coefficient for the lowest degree term (the constant). This is a case of syndrome shifting, thus the syndrome will be bigger than the number of ecc symbols (I don't know what purpose serves this shifting). If that's the case, then we need to account for the syndrome shifting when we use the syndrome such as inside BM, by skipping those prepended coefficients.
    # Another way to detect the shifting is to detect the 0 coefficients: by definition, a syndrome does not contain any 0 coefficient (except if there are no errors/erasures, in this case they are all 0). This however doesn't work with the modified Forney syndrome, which set to 0 the coefficients corresponding to erasures, leaving only the coefficients corresponding to errors.
    synd_shift = 0
    if len(synd) > nsym: synd_shift = len(synd) - nsym

    for i in xrange(nsym-erase_count): # generally: nsym-erase_count == len(synd), except when you input a partial erase_loc and using the full syndrome instead of the Forney syndrome, in which case nsym-erase_count is more correct (len(synd) will fail badly with IndexError).
        if erase_loc: # if an erasures locator polynomial was provided to init the errors locator polynomial, then we must skip the FIRST erase_count iterations (not the last iterations, this is very important!)
            K = erase_count+i+synd_shift
        else: # if erasures locator is not provided, then either there's no erasures to account or we use the Forney syndromes, so we don't need to use erase_count nor erase_loc (the erasures have been trimmed out of the Forney syndromes).
            K = i+synd_shift

        # Compute the discrepancy Delta
        # Here is the close-to-the-books operation to compute the discrepancy Delta: it's a simple polynomial multiplication of error locator with the syndromes, and then we get the Kth element.
        #delta = gf_poly_mul(err_loc[::-1], synd)[K] # theoretically it should be gf_poly_add(synd[::-1], [1])[::-1] instead of just synd, but it seems it's not absolutely necessary to correctly decode.
        # But this can be optimized: since we only need the Kth element, we don't need to compute the polynomial multiplication for any other element but the Kth. Thus to optimize, we compute the polymul only at the item we need, skipping the rest (avoiding a nested loop, thus we are linear time instead of quadratic).
        # This optimization is actually described in several figures of the book "Algebraic codes for data transmission", Blahut, Richard E., 2003, Cambridge university press.
        delta = synd[K]
        for j in xrange(1, len(err_loc)):
            delta ^= gf_mul(err_loc[-(j+1)], synd[K - j]) # delta is also called discrepancy. Here we do a partial polynomial multiplication (ie, we compute the polynomial multiplication only for the term of degree K). Should be equivalent to brownanrs.polynomial.mul_at().
        #print "delta", K, delta, list(gf_poly_mul(err_loc[::-1], synd)) # debugline

        # Shift polynomials to compute the next degree
        old_loc = old_loc + bytearray([0])

        # Iteratively estimate the errata locator and evaluator polynomials
        if delta != 0: # Update only if there's a discrepancy
            if len(old_loc) > len(err_loc): # Rule B (rule A is implicitly defined because rule A just says that we skip any modification for this iteration)
            #if 2*L <= K+erase_count: # equivalent to len(old_loc) > len(err_loc), as long as L is correctly computed
                # Computing errata locator polynomial Sigma
                new_loc = gf_poly_scale(old_loc, delta)
                old_loc = gf_poly_scale(err_loc, gf_inverse(delta)) # effectively we are doing err_loc * 1/delta = err_loc // delta
                err_loc = new_loc
                # Update the update flag
                #L = K - L # the update flag L is tricky: in Blahut's schema, it's mandatory to use `L = K - L - erase_count` (and indeed in a previous draft of this function, if you forgot to do `- erase_count` it would lead to correcting only 2*(errors+erasures) <= (n-k) instead of 2*errors+erasures <= (n-k)), but in this latest draft, this will lead to a wrong decoding in some cases where it should correctly decode! Thus you should try with and without `- erase_count` to update L on your own implementation and see which one works OK without producing wrong decoding failures.

            # Update with the discrepancy
            err_loc = gf_poly_add(err_loc, gf_poly_scale(old_loc, delta))

    # Check if the result is correct, that there's not too many errors to correct
    err_loc = list(itertools.dropwhile(lambda x: x == 0, err_loc)) # drop leading 0s, else errs will not be of the correct size
    errs = len(err_loc) - 1
    if (errs-erase_count) * 2 + erase_count > nsym:
        raise ReedSolomonError("Too many errors to correct")

    return err_loc
412702
def demo_err():
    
    max_order = 7
    n = 20
    l = 0.25
    fmt1 = '{0: <5s}\t{1: <21s}\t{2: >21s}\t{3: >21s}\t{4: >21s}'
    fmt2 = '{0: <5d}\t{1:20.18f}\t{2: >21.18f}\t{3: >21.18f}\t{4: >21.18f}'
    x = np.cumsum(np.random.rand(n)*l)
    x = np.concatenate((x[::-1]*-1, x))
    lst = []
    derivs = np.zeros(n)
    for order in range(max_order+1):
        print('Order', order)
        for m in range(1+order//2, n+1):
            sub_x = x[n-m:n+m]
            derivs[m-1] = derivatives_at_point_by_finite_diff(
                sub_x, np.exp(sub_x), 0, order)[order]
        print(fmt1.format('m', 'val', 'diff', 'analytical error',
                          'diff/analytical'))
        for m in range(1, n):
            print(fmt2.format(
                (m+1)*2, derivs[m], derivs[m]-derivs[m-1],
                derivs[m]-1, (derivs[m]-derivs[m-1])/(derivs[m]-1)))
        lst.append((derivs[-1], abs(derivs[-1]-derivs[-2])))
    print(np.array(lst))
593423
public void compute() 
	{
		if (!computable) {
			throw new RuntimeException("can't re-'compute' experiment results after a 'restore'");
		}
		expt = new MatchExpt[blockers.size()][learners.size()][datasets.size()];
		for (int i=0; i<blockers.size(); i++) {
			Blocker blocker = (Blocker)blockers.get(i);
			for (int j=0; j<learners.size(); j++) {
				StringDistanceLearner distance = (StringDistanceLearner)learners.get(j);
				for (int k=0; k<datasets.size(); k++) {
					MatchData dataset = (MatchData)datasets.get(k);
					expt[i][j][k] = new MatchExpt(dataset,distance,blocker);
				}
			}
		}
	}
370574
def rs_correct_errata(msg_in, synd, err_pos, fcr=0, generator=2): # err_pos is a list of the positions of the errors/erasures/errata
    ''''''
    global field_charac
    msg = bytearray(msg_in)
    # calculate errata locator polynomial to correct both errors and erasures (by combining the errors positions given by the error locator polynomial found by BM with the erasures positions given by caller)
    coef_pos = [len(msg) - 1 - p for p in err_pos] # need to convert the positions to coefficients degrees for the errata locator algo to work (eg: instead of [0, 1, 2] it will become [len(msg)-1, len(msg)-2, len(msg) -3])
    err_loc = rs_find_errata_locator(coef_pos, generator)
    # calculate errata evaluator polynomial (often called Omega or Gamma in academic papers)
    err_eval = rs_find_error_evaluator(synd[::-1], err_loc, len(err_loc)-1)[::-1]

    # Second part of Chien search to get the error location polynomial X from the error positions in err_pos (the roots of the error locator polynomial, ie, where it evaluates to 0)
    X = [] # will store the position of the errors
    for i in xrange(len(coef_pos)):
        l = field_charac - coef_pos[i]
        X.append( gf_pow(generator, -l) )

    # Forney algorithm: compute the magnitudes
    E = bytearray(len(msg)) # will store the values that need to be corrected (substracted) to the message containing errors. This is sometimes called the error magnitude polynomial.
    Xlength = len(X)
    for i, Xi in enumerate(X):

        Xi_inv = gf_inverse(Xi)

        # Compute the formal derivative of the error locator polynomial (see Blahut, Algebraic codes for data transmission, pp 196-197).
        # the formal derivative of the errata locator is used as the denominator of the Forney Algorithm, which simply says that the ith error value is given by error_evaluator(gf_inverse(Xi)) / error_locator_derivative(gf_inverse(Xi)). See Blahut, Algebraic codes for data transmission, pp 196-197.
        err_loc_prime_tmp = []
        for j in xrange(Xlength):
            if j != i:
                err_loc_prime_tmp.append( gf_sub(1, gf_mul(Xi_inv, X[j])) )
        # compute the product, which is the denominator of the Forney algorithm (errata locator derivative)
        err_loc_prime = 1
        for coef in err_loc_prime_tmp:
            err_loc_prime = gf_mul(err_loc_prime, coef)
        # equivalent to: err_loc_prime = functools.reduce(gf_mul, err_loc_prime_tmp, 1)

        # Compute y (evaluation of the errata evaluator polynomial)
        # This is a more faithful translation of the theoretical equation contrary to the old forney method. Here it is exactly copy/pasted from the included presentation decoding_rs.pdf: Yl = omega(Xl.inverse()) / prod(1 - Xj*Xl.inverse()) for j in len(X) (in the paper it's for j in s, but it's useless when len(X) < s because we compute neutral terms 1 for nothing, and wrong when correcting more than s erasures or erasures+errors since it prevents computing all required terms).
        # Thus here this method works with erasures too because firstly we fixed the equation to be like the theoretical one (don't know why it was modified in _old_forney(), if it's an optimization, it doesn't enhance anything), and secondly because we removed the product bound on s, which prevented computing errors and erasures above the s=(n-k)//2 bound.
        y = gf_poly_eval(err_eval[::-1], Xi_inv) # numerator of the Forney algorithm (errata evaluator evaluated)
        y = gf_mul(gf_pow(Xi, 1-fcr), y) # adjust to fcr parameter
        
        # Compute the magnitude
        magnitude = gf_div(y, err_loc_prime) # magnitude value of the error, calculated by the Forney algorithm (an equation in fact): dividing the errata evaluator with the errata locator derivative gives us the errata magnitude (ie, value to repair) the ith symbol
        E[err_pos[i]] = magnitude # store the magnitude for this error into the magnitude polynomial

    # Apply the correction of values to get our message corrected! (note that the ecc bytes also gets corrected!)
    # (this isn't the Forney algorithm, we just apply the result of decoding here)
    msg = gf_poly_add(msg, E) # equivalent to Ci = Ri - Ei where Ci is the correct message, Ri the received (senseword) message, and Ei the errata magnitudes (minus is replaced by XOR since it's equivalent in GF(2^p)). So in fact here we substract from the received message the errors magnitude, which logically corrects the value to what it should be.
    return msg
331303
def compute_absolute_error(self, predicted_data, record, dataframe_record):
        ''''''
        absolute_error = abs(record['DDG'] - predicted_data[self.ddg_analysis_type])
        dataframe_record['AbsoluteError'] = absolute_error
666690
@Override
	public void computeDistance(List<Point2D> obs, double[] distance) {
		for( int i = 0; i < obs.size(); i++ ) {
			distance[i] = computeDistance(obs.get(i));
		}
	}
219480
def total_errors(self):
        

        child_errors = sum(len(tree) for _, tree in iteritems(self._contents))
        return len(self.errors) + child_errors
806600
int besterror(float[] a, int step, int addmul) {
        int best = best(a, step);
        switch (addmul) {
            case 0:
                for (int i = 0, o = 0; i < dim; i++, o += step) {
                    a[o] -= valuelist[best * dim + i];
                }
                break;
            case 1:
                for (int i = 0, o = 0; i < dim; i++, o += step) {
                    float val = valuelist[best * dim + i];
                    if (val == 0) {
                        a[o] = 0;
                    } else {
                        a[o] /= val;
                    }
                }
                break;
        }
        return (best);
    }
711048
function calcPrice(err, transactions) {
      // flatten array
      transactions = transactions.reduce(function(a, b) { return a.concat(b) }, [])

      // leave only the gasprice
      // FIXME: convert number using a bignum library
      transactions = transactions.map(function(a) { return parseInt(a.gasPrice, 16) }, [])

      // order ascending
      transactions.sort(function(a, b) { return a - b })

      // ze median
      var half = Math.floor(transactions.length / 2)

      var median
      if (transactions.length % 2)
        median = transactions[half]
      else
        median = Math.floor((transactions[half - 1] + transactions[half]) / 2.0)

      end(null, median)
    }
536089
def _error_dm(self, m, dm, s):
        
        pred = self.fmodel.predict_given_context(np.hstack((m, dm)), s, range(len(s)))
        err_v  = pred - self.goal
        error = sum(e*e for e in err_v)
        return error
646925
def _compute_magnitude(self, rup, C):
        
        m_h = 6.75
        b_3 = 0.0
        if rup.mag <= m_h:
            return C["e1"] + (C['b1'] * (rup.mag - m_h)) +\
                (C['b2'] * (rup.mag - m_h) ** 2)
        else:
            return C["e1"] + (b_3 * (rup.mag - m_h))
365361
public static void magnitude(ZMatrixD1 input , DMatrixD1 output ) {
        if( input.numCols != output.numCols || input.numRows != output.numRows ) {
            throw new IllegalArgumentException("The matrices are not all the same dimension.");
        }

        final int length = input.getDataLength();

        for( int i = 0; i < length; i += 2 ) {
            double real = input.data[i];
            double imaginary = input.data[i+1];

            output.data[i/2] = Math.sqrt(real*real + imaginary*imaginary);
        }
    }
1239796
private int trMedian5(int ISAd, int v1, int v2, int v3, int v4, int v5) {
        int t;
        if (SA[ISAd + SA[v2]] > SA[ISAd + SA[v3]]) {
            t = v2;
            v2 = v3;
            v3 = t;
        }
        if (SA[ISAd + SA[v4]] > SA[ISAd + SA[v5]]) {
            t = v4;
            v4 = v5;
            v5 = t;
        }
        if (SA[ISAd + SA[v2]] > SA[ISAd + SA[v4]]) {
            t = v2;
            v2 = v4;
            v4 = t;
            t = v3;
            v3 = v5;
            v5 = t;
        }
        if (SA[ISAd + SA[v1]] > SA[ISAd + SA[v3]]) {
            t = v1;
            v1 = v3;
            v3 = t;
        }
        if (SA[ISAd + SA[v1]] > SA[ISAd + SA[v4]]) {
            t = v1;
            v1 = v4;
            v4 = t;
            t = v3;
            v3 = v5;
            v5 = t;
        }
        if (SA[ISAd + SA[v3]] > SA[ISAd + SA[v4]]) {
            return v4;
        }
        return v3;
    }
1207910
def k_bn(self, n, Re):
        
        bn = self.b_n(n)
        k = bn*Re**(-1./n)
        return k, bn
1199665
def mean_absolute_error(seq, correct):
    
    assert len(seq) == len(correct)
    diffs = [abs(a-b) for a, b in zip(seq, correct)]
    return sum(diffs)/float(len(diffs))
1288855
def get_valid_error(x1, x2=-1):
    
    # just error
    if type(x2) == int and x2 == -1:
        try:    
            e = np.array(x1)
        except:
            raise ValueError('Impossible to convert series to a numpy array')        
    # two series
    else:
        try:
            x1 = np.array(x1)
            x2 = np.array(x2)
        except:
            raise ValueError('Impossible to convert one of series to a numpy array')
        if not len(x1) == len(x2):
            raise ValueError('The length of both series must agree.')
        e = x1 - x2
    return e