def test_integrate_polyn_good_degree(self): """ Check quadrature errors for polynomials of max. degree N+1 which should be zero. The integral values on the given domain are of magnitue 1e90 for n=13, so if this relative error is machine precision, it must be exact. """ for number in self.orders: cc = clenshawcurtis.ClenshawCurtis(number, self.ndim, self.ilbds) random_poly = np.random.randint(1, 11, (number + 1, number + 1)) integrated_poly = npoly.polyint(npoly.polyint(random_poly).T).T # pylint: disable=cell-var-from-loop def testpoly(val): return npoly.polyval2d(val[:, 0], val[:, 1], c=random_poly) truesol = ( npoly.polyval2d( self.ilbds[0, 1], self.ilbds[1, 1], c=integrated_poly) - npoly.polyval2d( self.ilbds[0, 1], self.ilbds[1, 0], c=integrated_poly) - npoly.polyval2d( self.ilbds[0, 0], self.ilbds[1, 1], c=integrated_poly) + npoly.polyval2d( self.ilbds[0, 0], self.ilbds[1, 0], c=integrated_poly)) abserror = np.abs( cc.integrate(testpoly, isvectorized=True) - truesol) relerror = abserror / np.abs(truesol) self.assertLess(relerror, 1e-14)
def test_integ(self) : p = self.p2.integ() assert_almost_equal(p.coef, poly.polyint([1,2,3], 1, 0, scl=.5)) p = self.p2.integ(1, 1) assert_almost_equal(p.coef, poly.polyint([1,2,3], 1, 1, scl=.5)) p = self.p2.integ(2, [1, 2]) assert_almost_equal(p.coef, poly.polyint([1,2,3], 2, [1, 2], scl=.5))
def test_integ(self): p = self.p2.integ() assert_almost_equal(p.coef, poly.polyint([1, 2, 3], 1, 0, scl=.5)) p = self.p2.integ(lbnd=0) assert_almost_equal(p(0), 0) p = self.p2.integ(1, 1) assert_almost_equal(p.coef, poly.polyint([1, 2, 3], 1, 1, scl=.5)) p = self.p2.integ(2, [1, 2]) assert_almost_equal(p.coef, poly.polyint([1, 2, 3], 2, [1, 2], scl=.5))
def _set_sicd(self, the_sicd): # type : (SICDType) -> None if the_sicd is None: self._sicd = None return if not isinstance(the_sicd, SICDType): raise TypeError( 'the_sicd must be an insatnce of SICDType, got type {}'.format( type(the_sicd))) self._sicd = the_sicd row_delta_kcoa_poly, self._row_fft_sgn = _get_deskew_params( the_sicd, 0) col_delta_kcoa_poly, self._col_fft_sgn = _get_deskew_params( the_sicd, 1) if self.dimension == 0: self._delta_kcoa_poly_axis = row_delta_kcoa_poly delta_kcoa_poly_int = polynomial.polyint(row_delta_kcoa_poly, axis=0) self._delta_kcoa_poly_off_axis = _add_poly( -polynomial.polyder(delta_kcoa_poly_int, axis=1), col_delta_kcoa_poly) else: self._delta_kcoa_poly_axis = col_delta_kcoa_poly delta_kcoa_poly_int = polynomial.polyint(col_delta_kcoa_poly, axis=1) self._delta_kcoa_poly_off_axis = _add_poly( -polynomial.polyder(delta_kcoa_poly_int, axis=0), row_delta_kcoa_poly) self._row_shift = the_sicd.ImageData.SCPPixel.Row - the_sicd.ImageData.FirstRow self._row_mult = the_sicd.Grid.Row.SS self._col_shift = the_sicd.ImageData.SCPPixel.Col - the_sicd.ImageData.FirstCol self._col_mult = the_sicd.Grid.Col.SS self._row_pad = max( 1., 1. / (the_sicd.Grid.Row.SS * the_sicd.Grid.Row.ImpRespBW)) self._row_weight = the_sicd.Grid.Row.WgtFunct.copy( ) if the_sicd.Grid.Row.WgtFunct is not None else None self._col_pad = max( 1., 1. / (the_sicd.Grid.Col.SS * the_sicd.Grid.Col.ImpRespBW)) self._col_weight = the_sicd.Grid.Col.WgtFunct.copy( ) if the_sicd.Grid.Col.WgtFunct is not None else None self._is_normalized = is_normalized(the_sicd, self.dimension) self._is_not_skewed_row = is_not_skewed(the_sicd, 0) self._is_not_skewed_col = is_not_skewed(the_sicd, 1) self._is_uniform_weight_row = is_uniform_weight(the_sicd, 0) self._is_uniform_weight_col = is_uniform_weight(the_sicd, 1)
def get_immigration2(S, starting_age, ending_age, E): ''' Parameters: S - Number of age cohorts starting age - initial age of cohorts Returns: im_array - S x 1 array of immigration rates for each age cohort child_imm_rate - starting_age x 1 array of immigration rates for children ''' imm_rate_condensed1 = get_immigration1( S, starting_age, ending_age, pop_2010, pop_2011, E) imm_rate_condensed2 = get_immigration1( S, starting_age, ending_age, pop_2011, pop_2012, E) imm_rate_condensed3 = get_immigration1( S, starting_age, ending_age, pop_2012, pop_2013, E) im_array = ( imm_rate_condensed1 + imm_rate_condensed2 + imm_rate_condensed3) / 3.0 poly_imm = poly.polyfit(np.linspace( 1, ending_age, ending_age-1), im_array[:-1], deg=18) poly_imm_int = poly.polyint(poly_imm) child_imm_rate = poly.polyval(np.linspace( 0, starting_age, E+1), poly_imm_int) imm_rate = poly.polyval(np.linspace( starting_age, ending_age, S+1), poly_imm_int) child_imm_rate = np.diff(child_imm_rate) imm_rate = np.diff(imm_rate) imm_rate[-1] = 0.0 return imm_rate, child_imm_rate
def get_fert(S, starting_age, ending_age, E): ''' Parameters: S - Number of age cohorts starting age - initial age of cohorts Returns: fert_rate - Sx1 array of fertility rates for each age cohort children_fertrate - starting_age x 1 array of zeros, to be used in get_omega() ''' # Fit a polynomial to the fertility rates poly_fert = poly.polyfit(age_midpoint, fert_data, deg=4) fert_rate = integrate(poly_fert, np.linspace( starting_age, ending_age, S+1)) fert_rate /= 2.0 children_fertrate_int = poly.polyint(poly_fert) children_fertrate_int = poly.polyval(np.linspace( 0, starting_age, E + 1), children_fertrate_int) children_fertrate = np.diff(children_fertrate_int) children_fertrate /= 2.0 children_fertrate[children_fertrate < 0] = 0 children_fertrate[:int(10*S/float(ending_age-starting_age))] = 0 return fert_rate, children_fertrate
def __init__(self, inertia, datafile, options={}): ''' AVAILABLE OPTIONS : 'angle unit': 'rad', 'deg' 'data type': 'moment', 'potential' 'delimiter': any character 'polynomial degree': any positive integer ''' self.options = { 'angle unit': 'rad', \ 'delimiter': None, \ 'polynomial degree': 9, \ 'data type': 'moment' } for key in options: self.options[key] = options[key] self.inertia = inertia data = np.loadtxt(datafile, delimiter=self.options['delimiter']) if self.options['angle unit'] == 'deg': data[:,0] *= np.pi / 180. self.deg = self.options['polynomial degree'] if self.options['data type'] == 'moment': temp = Poly.polyfit(data[:,0], data[:,1], self.deg-1) self.VPoly = Poly.polyint(temp) elif self.options['data type'] == 'potential': self.VPoly = Poly.polyfit(data[:,0], data[:,1], self.deg) self.VPoly[0] = 0 self.VPoly[1] = 0 self.frequency = np.vectorize(self.frequency1)
def smoothing_poly_lnprior(poly, degree, xmin, xmax, gamma=1): """ A smoothing prior that suppresses higher order derivatives of a polynomial, poly = a + b x + c x*x + ..., described by a vector of its coefficients, [a, b, c, ...]. Functional form is: ln p(poly coeffs) = -gamma * integrate( (diff(poly(x), x, degree))^2, x, xmin, xmax) So it takes the `degree`th derivative of the polynomial, squares it, integrates that from xmin to xmax, and scales by -gamma. """ # Take the `degree`th derivative of the polynomial. poly_diff = P.polyder(poly, m=degree) # Square the polynomial. poly_diff_sq = P.polypow(poly_diff, 2) # Take the indefinite integral of the polynomial. poly_int_indef = P.polyint(poly_diff_sq) # Evaluate the integral at xmin and xmax to get the definite integral. poly_int_def = (P.polyval(xmax, poly_int_indef) - P.polyval(xmin, poly_int_indef)) # Scale by -gamma to get the log prior lnp = -gamma * poly_int_def return lnp
def smoothing_poly_lnprior(poly, degree, xmin, xmax, gamma=1): """ A smoothing prior that suppresses higher order derivatives of a polynomial, poly = a + b x + c x*x + ..., described by a vector of its coefficients, [a, b, c, ...]. Functional form is: ln p(poly coeffs) = -gamma * integrate( (diff(poly(x), x, degree))^2, x, xmin, xmax) So it takes the `degree`th derivative of the polynomial, squares it, integrates that from xmin to xmax, and scales by -gamma. """ # Take the `degree`th derivative of the polynomial. poly_diff = P.polyder(poly, m=degree) # Square the polynomial. poly_diff_sq = P.polypow(poly_diff, 2) # Take the indefinite integral of the polynomial. poly_int_indef = P.polyint(poly_diff_sq) # Evaluate the integral at xmin and xmax to get the definite integral. poly_int_def = ( P.polyval(xmax, poly_int_indef) - P.polyval(xmin, poly_int_indef) ) # Scale by -gamma to get the log prior lnp = -gamma * poly_int_def return lnp
def rmnGreen_Taylor_Mmn_vec(n, k, R, rmnRgM, rnImM, rmnvecM): """ act on wave with radial representation Cpol(kr) by spherical Green's function this is for Arnoldi process with the regular M waves the leading asymptotice for vecM is r^n so rmnv_vecM stores Taylor series representation of (kr)^(-n) * vecM rmnRgM stores (kr)^(-n) * RgM, rnImM stores (kr)^(n+1) * ImM """ kR = mp.mpf(k * R) Mfact_prefactpow, Mfact = rmnMpol_dot(2 * n, rmnRgM, rmnvecM) Mfact = po.Polynomial(Mfact) RgMfact_intgd = rnImM * rmnvecM RgMfact_intgd = [0] + RgMfact_intgd.coef.tolist() RgMfact = po.polyint(RgMfact_intgd, lbnd=kR) RgMfact = po.Polynomial(RgMfact) ###first add on Asym(G) part MfactkR = kR**Mfact_prefactpow * po.polyval(kR, Mfact.coef) newrmnvecM = 1j * MfactkR * rmnRgM #newimag_rmnv_vecM = MfactkR * rmnRgM ###then deal with (kr)^(n+2*vecnum+2) part### newrmnvecM = newrmnvecM - rnImM * Mfact * po.Polynomial( [0, 0, 1]) + rmnRgM * RgMfact #return newreal_rmnv_vecM, newimag_rmnv_vecM #return the real and imaginary part separately return newrmnvecM
def deskewmem(input_data, DeltaKCOAPoly, dim0_coords_m, dim1_coords_m, dim, fft_sgn=-1): """ Performs deskew (centering of the spectrum on zero frequency) on a complex dataset. Parameters ---------- input_data : numpy.ndarray Complex FFT Data DeltaKCOAPoly : numpy.ndarray Polynomial that describes center of frequency support of data. dim0_coords_m : numpy.ndarray dim1_coords_m : numpy.ndarray dim : int fft_sgn : int|float Returns ------- Tuple[numpy.ndarray, numpy.ndarray] * `output_data` - Deskewed data * `new_DeltaKCOAPoly` - Frequency support shift in the non-deskew dimension caused by the deskew. """ # Integrate DeltaKCOA polynomial (in meters) to form new polynomial DeltaKCOAPoly_int DeltaKCOAPoly_int = polynomial.polyint(DeltaKCOAPoly, axis=dim) # New DeltaKCOAPoly in other dimension will be negative of the derivative of # DeltaKCOAPoly_int in other dimension (assuming it was zero before). new_DeltaKCOAPoly = - polynomial.polyder(DeltaKCOAPoly_int, axis=dim-1) # Apply phase adjustment from polynomial dim1_coords_m_2d, dim0_coords_m_2d = np.meshgrid(dim1_coords_m, dim0_coords_m) output_data = np.multiply(input_data, np.exp(1j * fft_sgn * 2 * np.pi * polynomial.polyval2d( dim0_coords_m_2d, dim1_coords_m_2d, DeltaKCOAPoly_int))) return output_data, new_DeltaKCOAPoly
def rmnMpol_dot(prefactpow, Cpol1, Cpol2): #compute unconjugated inner product of two M-type waves represented by A_1mn*Cpol(kr) #prefactpow is extra multiplicative factor of (kr)^prefactpow intweight = np.zeros(prefactpow + 2, dtype=np.complex).tolist() intgd = Cpol1 * Cpol2 intpol = po.polyint(intweight + intgd.coef.tolist()) return prefactpow + 3, intpol[prefactpow + 3:]
def deskewmem(input_data, DeltaKCOAPoly, dim0_coords_m, dim1_coords_m, dim, fft_sgn=-1): """Performs deskew (centering of the spectrum on zero frequency) on a complex dataset. INPUTS: input_data: Complex FFT Data DeltaKCOAPoly: Polynomial that describes center of frequency support of data. dim0_coords_m: Coordinate of each "row" in dimension 0 dim1_coords_m: Coordinate of each "column" in dimension 1 dim: Dimension over which to perform deskew fft_sgn: FFT sign required to transform data to spatial frequency domain OUTPUTS: output_data: Deskewed data new_DeltaKCOAPoly: Frequency support shift in the non-deskew dimension caused by the deskew. """ # Integrate DeltaKCOA polynomial (in meters) to form new polynomial DeltaKCOAPoly_int DeltaKCOAPoly_int = polynomial.polyint(DeltaKCOAPoly, axis=dim) # New DeltaKCOAPoly in other dimension will be negative of the derivative of # DeltaKCOAPoly_int in other dimension (assuming it was zero before). new_DeltaKCOAPoly = -polynomial.polyder(DeltaKCOAPoly_int, axis=dim - 1) # Apply phase adjustment from polynomial [dim1_coords_m_2d, dim0_coords_m_2d] = np.meshgrid(dim1_coords_m, dim0_coords_m) output_data = np.multiply( input_data, np.exp(1j * fft_sgn * 2 * np.pi * polynomial.polyval2d( dim0_coords_m_2d, dim1_coords_m_2d, DeltaKCOAPoly_int))) return output_data, new_DeltaKCOAPoly
def integrate(func, points): params_guess = [1, 1] a, b = opt.fsolve(fit_exp_right, params_guess, args=([40, poly.polyval(40, func)], [49.5, .0007])) func_int = poly.polyint(func) integral = np.empty(points.shape) integral[points <= 40] = poly.polyval(points[points <= 40], func_int) integral[points > 40] = poly.polyval(40, func_int) + exp_int(points[points > 40], a, b) return np.diff(integral)
def integrate(func, points): params_guess = [1, 1] a, b = opt.fsolve(fit_exp_right, params_guess, args=( [40, poly.polyval(40, func)], [49.5, .0007])) func_int = poly.polyint(func) integral = np.empty(points.shape) integral[points <= 40] = poly.polyval(points[points <= 40], func_int) integral[points > 40] = poly.polyval(40, func_int) + exp_int( points[points > 40], a, b) return np.diff(integral)
def rmnNpol_dot(prefactpow, Bpol1, Ppol1, Bpol2, Ppol2): #compute unconjugated dot product of two N-type waves represented by A_2mn * Bpol(r) + A_3mn * Ppol(r) #prefactpow is an extra multiplicative factor of (kr)^prefactpow #over spherical domain, returns polynomial coefficients intweight = np.zeros(prefactpow + 2, dtype=np.complex).tolist( ) #the +2 represents the radial integral weight function (kr)^2 intgd = Bpol1 * Bpol2 + Ppol1 * Ppol2 intpol = po.polyint(intweight + intgd.coef.tolist()) return prefactpow + 3, intpol[ prefactpow + 3:] #return an updated prefactor and polynomial coeffs for (kr)^{-prefactor} * integrationresult
def _set_sicd(self, the_sicd): # type : (SICDType) -> None self._sicd = the_sicd row_delta_kcoa_poly, self._row_fft_sgn = _get_deskew_params( the_sicd, 0) col_delta_kcoa_poly, self._col_fft_sgn = _get_deskew_params( the_sicd, 1) if self.dimension == 0: self._delta_kcoa_poly_axis = row_delta_kcoa_poly delta_kcoa_poly_int = polynomial.polyint(row_delta_kcoa_poly, axis=0) self._delta_kcoa_poly_off_axis = _add_poly( -polynomial.polyder(delta_kcoa_poly_int, axis=1), col_delta_kcoa_poly) else: self._delta_kcoa_poly_axis = col_delta_kcoa_poly delta_kcoa_poly_int = polynomial.polyint(col_delta_kcoa_poly, axis=1) self._delta_kcoa_poly_off_axis = _add_poly( -polynomial.polyder(delta_kcoa_poly_int, axis=0), row_delta_kcoa_poly) self._row_shift = the_sicd.ImageData.SCPPixel.Row - the_sicd.ImageData.FirstRow self._row_mult = the_sicd.Grid.Row.SS self._col_shift = the_sicd.ImageData.SCPPixel.Col - the_sicd.ImageData.FirstCol self._col_mult = the_sicd.Grid.Col.SS self._row_pad = max( 1, 1 / (the_sicd.Grid.Row.SS * the_sicd.Grid.Row.ImpRespBW)) self._row_weight = the_sicd.Grid.Row.WgtFunct.copy( ) if the_sicd.Grid.Row.WgtFunct is not None else None self._col_pad = max( 1, 1 / (the_sicd.Grid.Col.SS * the_sicd.Grid.Col.ImpRespBW)) self._col_weight = the_sicd.Grid.Col.WgtFunct.copy( ) if the_sicd.Grid.Col.WgtFunct is not None else None self._is_normalized = is_normalized(the_sicd, self.dimension) self._is_not_skewed_row = _is_not_skewed(the_sicd, 0) self._is_not_skewed_col = _is_not_skewed(the_sicd, 1) self._is_uniform_weight_row = _is_uniform_weight(the_sicd, 0) self._is_uniform_weight_col = _is_uniform_weight(the_sicd, 1)
def test_for_normalization(polycoeffs, xrange): ''' Test to check if a polynomial integrates to one with a small error. :param polycoeffs: single polynomial coeffecient array or list of polynomial coefficients. :param xrange: the range of x-axis to integrate. :return: Nothing, raises exceptions in case there is no element to go with. ''' polycoeffs_list = polycoeffs.tolist() epsilon = .001 if isinstance(polycoeffs_list, list): ele = polycoeffs_list[0] if isinstance(ele, list): #list of polynomials. results = [] for polynomial in polycoeffs: integral = poly.polyint(polynomial) sum = np.diff(poly.polyval(xrange, integral))[0] diff_from_one = np.abs(sum - 1) if np.abs(sum - 1) > epsilon: results.append([False, diff_from_one]) else: results.append([True, diff_from_one]) assert False not in results, 'Not normalized polynomial at indices {}'.format( results.index(False)) else: integral = poly.polyint(polycoeffs) sum = np.diff(poly.polyval(xrange, integral))[0] diff_from_one = np.abs(sum - 1) # ndivs = 100000 # x = np.linspace(xrange[0],xrange[1],ndivs) # sum2 = np.sum(poly.polyval(x,polycoeffs))*(xrange[1]-xrange[0])/ndivs # diff_from_one_2 = np.abs(sum2-1) # assert diff_from_one_2<epsilon, 'Not normalized polynomial with error 2 {}, {}'.format(diff_from_one_2, diff_from_one) assert diff_from_one < epsilon, 'Not normalized polynomial with error {} and actual sum {}'.format( diff_from_one, sum) return
def test_polyder(self) : # check exceptions assert_raises(ValueError, poly.polyder, [0], -1) # check that zeroth deriviative does nothing for i in range(5) : tgt = [1] + [0]*i res = poly.polyder(tgt, m=0) assert_equal(trim(res), trim(tgt)) # check that derivation is the inverse of integration for i in range(5) : for j in range(2,5) : tgt = [1] + [0]*i res = poly.polyder(poly.polyint(tgt, m=j), m=j) assert_almost_equal(trim(res), trim(tgt)) # check derivation with scaling for i in range(5) : for j in range(2,5) : tgt = [1] + [0]*i res = poly.polyder(poly.polyint(tgt, m=j, scl=2), m=j, scl=.5) assert_almost_equal(trim(res), trim(tgt))
def collocation_to_butcher(ci): polynomials = lagrange_polynomials(ci) integrated_polynomials = [polyint(p) for p in polynomials] A = np.zeros((len(ci), len(ci))) for i, j in itertools.product(range(len(ci)), range(len(ci))): A[i, j] = np.polynomial.polynomial.polyval( ci[i], integrated_polynomials[j]) - integrated_polynomials[j][0] b = np.zeros((len(ci))) for i in range(len(ci)): b[i] = polyval( 1, integrated_polynomials[i]) - integrated_polynomials[i][0] return A, b
def integrate(func, points, j): params_guess = [1, 1] # fit_to = j/2.0 fit_to = poly.polyval(70, func) * .5 a, b = opt.fsolve(fit_exp_right, params_guess, args=( [70, poly.polyval(70, func)], [100, fit_to])) func_int = poly.polyint(func) integral = np.empty(points.shape) integral[points <= 70] = poly.polyval(points[points <= 70], func_int) integral[points > 70] = poly.polyval(70, func_int) + exp_int( points[points > 70], a, b) vals = np.diff(integral) # vals[50:] = np.ones(30) * vals[50] return vals
def rmnGreen_Taylor_Nmn_vec(n, k, R, rmnRgN_Bpol, rmnRgN_Ppol, rnImN_Bpol, rnImN_Ppol, rmnvecBpol, rmnvecPpol): """ act on the wave with radial representation Bpol(kr), Ppol(kr) by the spherical Green's fcn central subroutine for Arnoldi iteration starting from RgN rmnRgN_Bpol, rmnRgN_Ppol stores Taylor series representation of (kr)^{-(n-1)}*RgN(kr) with np polynomials rnImN_Bpol, rnImN_Ppol stores Taylor series representation of (kr)^{n+2} * Im{N(kr)} the real part of N(kr) is just RgN(kr) rmnvecBpol, rmnvecPpol store Taylor series representations of (kr)^{-(n-1)}*vec(kr), where vec is the current Arnoldi iterate the prefactors are there to efficiently use the numpy polynomial package, avoiding carrying a long list of zeros leading to large polynomials and slow running time N has radial dependence with negative powers so the prefactor lets use np polynomials just need to divide results after multiplication of N by (kr)^{n+2} """ kR = mp.mpf(k * R) ti = time.time() Nfact_prefactpow, Nfact = rmnNpol_dot(2 * n - 2, rmnRgN_Bpol, rmnRgN_Ppol, rmnvecBpol, rmnvecPpol) #Nfact_prefactpow should be 2*n+1 Nfact = po.Polynomial(Nfact) #Nfact = po.Polynomial(1j*Npol_dot(RgN_Bpol,RgN_Ppol, vecBpol,vecPpol)) RgNfact_intgd = rnImN_Bpol * rmnvecBpol + rnImN_Ppol * rmnvecPpol RgNfact_intgd = [0, 0] + RgNfact_intgd.coef.tolist() #print('1/r term size',RgNfact_intgd[2]) #check that the 1/r term of integrand is indeed 0 up to floating point error #print('r term size',RgNfact_intgd[4]) RgNfact_intgd = po.Polynomial( RgNfact_intgd[3:]) #n+2-(n-1) divide by (kr)^{3} to get true intgd #print(time.time()-ti,'in GTNv, 1') # print(len(RgNfact_intgd)) RgNfact = po.Polynomial(po.polyint(RgNfact_intgd.coef, lbnd=kR)) #print(time.time()-ti,'in GTNv, 2') ######first add on the Asym(G) part NfactkR = kR**Nfact_prefactpow * po.polyval(kR, Nfact.coef) newrmnBpol = 1j * NfactkR * rmnRgN_Bpol newrmnPpol = 1j * NfactkR * rmnRgN_Ppol #print(time.time()-ti,'in GTNv, 3') ######then add on the Sym(G) part newrmnBpol = newrmnBpol - Nfact * rnImN_Bpol newrmnPpol = newrmnPpol - Nfact * rnImN_Ppol newrmnBpol = newrmnBpol + RgNfact * rmnRgN_Bpol newrmnPpol = newrmnPpol + RgNfact * rmnRgN_Ppol - rmnvecPpol #the subtraction at end is delta fcn contribution #print(time.time()-ti,'in GTNv, 4') #print(len(newrmnBpol),len(newrmnPpol),len(RgNfact),len(Nfact),len(rmnRgN_Bpol),len(rmnRgN_Ppol),len(rnImN_Bpol), len(rnImN_Ppol)) return newrmnBpol, newrmnPpol
def polynomial_normalize(polycoeffs, xrange): ''' :param polycoeffs: polynomial co-efficients to normalize. (according to numpy.polynomial.polynomial.polynomial convention) :param xrange: The [beginning, ending] point to evaluate around on the normalization on x-axis :return: normailzed polynomial and the normalization scale. ''' integral = poly.polyint(polycoeffs) sum = np.diff(poly.polyval(xrange, integral)) / 1.0 if not np.isnan(sum): normalized_polynomial = polycoeffs / sum # print(sum) # polynomial_normalize(normalized_polynomial,xrange) test_for_normalization(normalized_polynomial, xrange) return normalized_polynomial, sum
def apply_skew_poly(input_data, delta_kcoa_poly, row_array, col_array, fft_sgn, dimension, forward=False): """ Performs the skew operation on the complex array, according to the provided delta kcoa polynomial. Parameters ---------- input_data : numpy.ndarray The input data. delta_kcoa_poly : numpy.ndarray The delta kcoa polynomial to use. row_array : numpy.ndarray The row array, should agree with input_data first dimension definition. col_array : numpy.ndarray The column array, should agree with input_data second dimension definition. fft_sgn : int The fft sign to use. dimension : int The dimension to apply along. forward : bool If True, this shifts forward (i.e. skews), otherwise applies in inverse (i.e. deskew) direction. Returns ------- numpy.ndarray """ if numpy.all(delta_kcoa_poly == 0): return input_data delta_kcoa_poly_int = polynomial.polyint(delta_kcoa_poly, axis=dimension) if forward: fft_sgn *= -1 return input_data * numpy.exp( 1j * fft_sgn * 2 * numpy.pi * polynomial.polygrid2d(row_array, col_array, delta_kcoa_poly_int))
def _deskew_array(input_data, delta_kcoa_poly, row_array, col_array, fft_sgn, dimension): """ Performs deskew (centering of the spectrum on zero frequency) on a complex array. Parameters ---------- input_data : numpy.ndarray delta_kcoa_poly : numpy.ndarray row_array : numpy.ndarray col_array : numpy.ndarray fft_sgn : int Returns ------- numpy.ndarray """ delta_kcoa_poly_int = polynomial.polyint(delta_kcoa_poly, axis=dimension) return input_data*numpy.exp(1j*fft_sgn*2*numpy.pi*polynomial.polygrid2d( row_array, col_array, delta_kcoa_poly_int))
def test_polyint_axis(self): # check that axis keyword works c2d = np.random.random((3, 4)) tgt = np.vstack([poly.polyint(c) for c in c2d.T]).T res = poly.polyint(c2d, axis=0) assert_almost_equal(res, tgt) tgt = np.vstack([poly.polyint(c) for c in c2d]) res = poly.polyint(c2d, axis=1) assert_almost_equal(res, tgt) tgt = np.vstack([poly.polyint(c, k=3) for c in c2d]) res = poly.polyint(c2d, k=3, axis=1) assert_almost_equal(res, tgt)
def get_survival(S, starting_age, ending_age, E): """ Parameters: S - Number of age cohorts starting age - initial age of cohorts Returns: surv_array - S x 1 array of survival rates for each age cohort children_rate_condensed - starting_age x 1 array of surrvival rates for children """ mort_rate = np.array(mort_data.mort_rate) mort_poly = poly.polyfit(np.arange(mort_rate.shape[0]), mort_rate, deg=18) mort_int = poly.polyint(mort_poly) child_rate = poly.polyval(np.linspace(0, starting_age, E + 1), mort_int) child_rate = np.diff(child_rate) mort_rate = poly.polyval(np.linspace(starting_age, ending_age, S + 1), mort_int) mort_rate = np.diff(mort_rate) child_rate[child_rate < 0] = 0.0 mort_rate[mort_rate < 0] = 0.0 return 1.0 - mort_rate, 1.0 - child_rate
def get_survival(S, starting_age, ending_age, E): ''' Parameters: S - Number of age cohorts starting age - initial age of cohorts Returns: surv_array - S x 1 array of survival rates for each age cohort children_rate_condensed - starting_age x 1 array of surrvival rates for children ''' mort_rate = np.array(mort_data.mort_rate) mort_poly = poly.polyfit(np.arange(mort_rate.shape[0]), mort_rate, deg=18) mort_int = poly.polyint(mort_poly) child_rate = poly.polyval(np.linspace(0, starting_age, E+1), mort_int) child_rate = np.diff(child_rate) mort_rate = poly.polyval( np.linspace(starting_age, ending_age, S+1), mort_int) mort_rate = np.diff(mort_rate) child_rate[child_rate < 0] = 0.0 mort_rate[mort_rate < 0] = 0.0 return 1.0 - mort_rate, 1.0 - child_rate
def evaluate(self, nodes, interval=None): """Computes weights for stored polynomial and given nodes. The weights are calculated with help of the Lagrange polynomials .. math:: \\alpha_i = \\int_a^b\\omega (x) \\prod_{j=1,j \\neq i}^{n} \\frac{x-x_j}{x_i-x_j} \\mathrm{d}x See Also -------- :py:meth:`.IWeightFunction.evaluate` : overridden method """ super(PolynomialWeightFunction, self).evaluate(nodes, interval) a = self._interval[0] b = self._interval[1] n_nodes = nodes.size alpha = np.zeros(n_nodes) for j in range(n_nodes): selection = list(range(j)) selection.extend(list(range(j + 1, n_nodes))) poly = [1.0] for ais in nodes[selection]: # builds Lagrange polynomial p_i poly = pol.polymul(poly, [ais / (ais - nodes[j]), 1 / (nodes[j] - ais)]) # computes \int w(x)p_i dx poly = pol.polyint(pol.polymul(poly, self._coefficients)) alpha[j] = pol.polyval(b, poly) - pol.polyval(a, poly) #LOG.debug("Computed polynomial weights for nodes {:s} in {:s}." # .format(nodes, self._interval)) del self._interval self._weights = alpha
def test_polyint(self) : # check exceptions assert_raises(ValueError, poly.polyint, [0], .5) assert_raises(ValueError, poly.polyint, [0], -1) assert_raises(ValueError, poly.polyint, [0], 1, [0,0]) # test integration of zero polynomial for i in range(2, 5): k = [0]*(i - 2) + [1] res = poly.polyint([0], m=i, k=k) assert_almost_equal(res, [0, 1]) # check single integration with integration constant for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [1/scl] res = poly.polyint(pol, m=1, k=[i]) assert_almost_equal(trim(res), trim(tgt)) # check single integration with integration constant and lbnd for i in range(5) : scl = i + 1 pol = [0]*i + [1] res = poly.polyint(pol, m=1, k=[i], lbnd=-1) assert_almost_equal(poly.polyval(-1, res), i) # check single integration with integration constant and scaling for i in range(5) : scl = i + 1 pol = [0]*i + [1] tgt = [i] + [0]*i + [2/scl] res = poly.polyint(pol, m=1, k=[i], scl=2) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with default k for i in range(5) : for j in range(2,5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = poly.polyint(tgt, m=1) res = poly.polyint(pol, m=j) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with defined k for i in range(5) : for j in range(2,5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = poly.polyint(tgt, m=1, k=[k]) res = poly.polyint(pol, m=j, k=range(j)) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd for i in range(5) : for j in range(2,5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = poly.polyint(tgt, m=1, k=[k], lbnd=-1) res = poly.polyint(pol, m=j, k=range(j), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling for i in range(5) : for j in range(2,5) : pol = [0]*i + [1] tgt = pol[:] for k in range(j) : tgt = poly.polyint(tgt, m=1, k=[k], scl=2) res = poly.polyint(pol, m=j, k=range(j), scl=2) assert_almost_equal(trim(res), trim(tgt))
def test_polyint(self): # check exceptions assert_raises(TypeError, poly.polyint, [0], .5) assert_raises(ValueError, poly.polyint, [0], -1) assert_raises(ValueError, poly.polyint, [0], 1, [0, 0]) assert_raises(ValueError, poly.polyint, [0], lbnd=[0]) assert_raises(ValueError, poly.polyint, [0], scl=[0]) assert_raises(TypeError, poly.polyint, [0], axis=.5) with assert_warns(DeprecationWarning): poly.polyint([1, 1], 1.) # test integration of zero polynomial for i in range(2, 5): k = [0] * (i - 2) + [1] res = poly.polyint([0], m=i, k=k) assert_almost_equal(res, [0, 1]) # check single integration with integration constant for i in range(5): scl = i + 1 pol = [0] * i + [1] tgt = [i] + [0] * i + [1 / scl] res = poly.polyint(pol, m=1, k=[i]) assert_almost_equal(trim(res), trim(tgt)) # check single integration with integration constant and lbnd for i in range(5): scl = i + 1 pol = [0] * i + [1] res = poly.polyint(pol, m=1, k=[i], lbnd=-1) assert_almost_equal(poly.polyval(-1, res), i) # check single integration with integration constant and scaling for i in range(5): scl = i + 1 pol = [0] * i + [1] tgt = [i] + [0] * i + [2 / scl] res = poly.polyint(pol, m=1, k=[i], scl=2) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with default k for i in range(5): for j in range(2, 5): pol = [0] * i + [1] tgt = pol[:] for k in range(j): tgt = poly.polyint(tgt, m=1) res = poly.polyint(pol, m=j) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with defined k for i in range(5): for j in range(2, 5): pol = [0] * i + [1] tgt = pol[:] for k in range(j): tgt = poly.polyint(tgt, m=1, k=[k]) res = poly.polyint(pol, m=j, k=list(range(j))) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd for i in range(5): for j in range(2, 5): pol = [0] * i + [1] tgt = pol[:] for k in range(j): tgt = poly.polyint(tgt, m=1, k=[k], lbnd=-1) res = poly.polyint(pol, m=j, k=list(range(j)), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling for i in range(5): for j in range(2, 5): pol = [0] * i + [1] tgt = pol[:] for k in range(j): tgt = poly.polyint(tgt, m=1, k=[k], scl=2) res = poly.polyint(pol, m=j, k=list(range(j)), scl=2) assert_almost_equal(trim(res), trim(tgt))
def polyint(cs, m=1, k=[], lbnd=0, scl=1): from numpy.polynomial.polynomial import polyint return polyint(cs, m, k, lbnd, scl)
def get_omega(S, T, starting_age, ending_age, E, flag_graphs): ''' Inputs: S - Number of age cohorts (scalar) T - number of time periods in TPI (scalar) starting_age - initial age of cohorts (scalar) ending_age = ending age of cohorts (scalar) E = number of children (scalar) flag_graphs = graph variables or not (bool) Outputs: omega_big = array of all population weights over time ((T+S)x1 array) g_n_SS = steady state growth rate (scalar) omega_SS = steady state population weights (Sx1 array) surv_array = survival rates (Sx1 array) rho = mortality rates (Sx1 array) g_n_vec = population growth rate over time ((T+S)x1 array) ''' data1 = data pop_data = np.array(data1['2010']) poly_pop = poly.polyfit(np.linspace( 0, pop_data.shape[0]-1, pop_data.shape[0]), pop_data, deg=11) poly_int_pop = poly.polyint(poly_pop) pop_int = poly.polyval(np.linspace( starting_age, ending_age, S+1), poly_int_pop) new_omega = pop_int[1:]-pop_int[:-1] surv_array, children_rate = get_survival(S, starting_age, ending_age, E) surv_array[-1] = 0.0 imm_array, children_im = get_immigration2(S, starting_age, ending_age, E) #imm_array *= 0.0 #children_im *= 0.0 fert_rate, children_fertrate = get_fert(S, starting_age, ending_age, E) cum_surv_rate = np.cumprod(surv_array) if flag_graphs: rate_graphs(S, starting_age, ending_age, imm_array, fert_rate, surv_array, children_im, children_fertrate, children_rate) children_int = poly.polyval(np.linspace(0, starting_age, E + 1), poly_int_pop) sum2010 = pop_int[-1] - children_int[0] new_omega /= sum2010 children = np.diff(children_int) children /= sum2010 children = np.tile(children.reshape(1, E), (T + S, 1)) omega_big = np.tile(new_omega.reshape(1, S), (T + S, 1)) # Generate the time path for each age group for t in range(1, T + S): # Children are born and then have to wait 20 years to enter the model omega_big[t, 0] = children[t-1, -1] * (children_rate[-1] + children_im[-1]) omega_big[t, 1:] = omega_big[t-1, :-1] * (surv_array[:-1] + imm_array[:-1]) children[t, 1:] = children[t-1, :-1] * (children_rate[:-1] + children_im[:-1]) children[t, 0] = (omega_big[t-1, :] * fert_rate).sum(0) + (children[t-1] * children_fertrate).sum(0) OMEGA = np.zeros(((S + E), (S + E))) OMEGA[0, :] = np.array(list(children_fertrate) + list(fert_rate)) OMEGA += np.diag(np.array(list(children_rate) + list(surv_array[:-1])) + np.array(list(children_im) + list(imm_array[:-1])), -1) eigvalues, eigvectors = np.linalg.eig(OMEGA) mask = eigvalues.real != 0 eigvalues = eigvalues[mask] mask2 = eigvalues.imag == 0 eigvalues = eigvalues[mask2].real g_n_SS = eigvalues - 1 eigvectors = np.abs(eigvectors.T) eigvectors = eigvectors[mask] omega_SS = eigvectors[mask2].real if eigvalues.shape[0] != 1: ind = ((abs(omega_SS.T/omega_SS.T.sum(0) - np.array(list(children[-1, :]) + list(omega_big[-1, :])).reshape(S+E, 1)).sum(0))).argmin() omega_SS = omega_SS[ind] g_n_SS = [g_n_SS[ind]] omega_SS = omega_SS[E:] omega_SS /= omega_SS.sum() # Creating the different ability level bins if flag_graphs: pop_graphs(S, T, starting_age, ending_age, children, g_n_SS[0], omega_big) N_vector = omega_big.sum(1) g_n_vec = N_vector[1:] / N_vector[:-1] -1.0 g_n_vec = np.append(g_n_vec, g_n_SS[0]) rho = 1.0 - surv_array imm_rates_mat = np.hstack(( np.tile(np.reshape(imm_array[:],(S,1)), (1, 120)), np.tile(np.reshape(imm_array[:],(S,1)), (1, T+S-120)))) return omega_big, g_n_SS[0], omega_SS, surv_array, rho, g_n_vec, imm_rates_mat
def get_omega(S, J, T, bin_weights, starting_age, ending_age, E): ''' Parameters: S - Number of age cohorts J - Number of ability types T - number of time periods in TPI starting age - initial age of cohorts bin_weights - weights for each ability type in each age cohort Returns: ''' data1 = data pop_data = np.array(data1['2010']) poly_pop = poly.polyfit(np.linspace( 0, pop_data.shape[0]-1, pop_data.shape[0]), pop_data, deg=11) poly_int_pop = poly.polyint(poly_pop) pop_int = poly.polyval(np.linspace( starting_age, ending_age, S+1), poly_int_pop) new_omega = np.zeros(S) for s in xrange(S): new_omega[s] = pop_int[s+1] - pop_int[s] surv_array, children_rate = get_survival(S, starting_age, ending_age, E) imm_array, children_im = get_immigration2(S, starting_age, ending_age, E) fert_rate, children_fertrate = get_fert(S, starting_age, ending_age, E) cum_surv_rate = np.zeros(S) for i in xrange(S): cum_surv_rate[i] = np.prod(surv_array[:i]) rate_graphs(S, starting_age, ending_age, imm_array, fert_rate, surv_array, children_im, children_fertrate, children_rate) children_int = poly.polyval( np.linspace( 0, starting_age, E + 1), poly_int_pop) sum2010 = pop_int[-1] - children_int[0] new_omega /= sum2010 children = np.diff(children_int) children /= sum2010 children = np.tile(children.reshape(1, E), (T + S, 1)) omega_big = np.tile(new_omega.reshape(1, S), (T + S, 1)) # Generate the time path for each age group for t in xrange(1, T + S): # Children are born and then have to wait 20 years to enter the model omega_big[t, 0] = children[t-1, -1] * ( children_rate[-1] + children_im[-1]) omega_big[t, 1:] = omega_big[t-1, :-1] * ( surv_array[:-1] + imm_array[ :-1]) children[t, 1:] = children[t-1, :-1] * ( children_rate[:-1] + children_im[:-1]) children[t, 0] = ((omega_big[t-1, :] * fert_rate).sum(0) + ( children[t-1] * children_fertrate).sum(0)) * (1 + children_im[0]) OMEGA = np.zeros(((S + E), (S + E))) OMEGA[0, :] = np.array(list(children_fertrate) + list( fert_rate)) * (1 + children_im[0]) OMEGA += np.diag(np.array(list(children_rate[:]) + list( surv_array[:-1])) + np.array(list(children_im) + list( imm_array[:-1])), -1) eigvalues, eigvectors = np.linalg.eig(OMEGA) mask = eigvalues.real != 0 eigvalues = eigvalues[mask] mask2 = eigvalues.imag == 0 eigvalues = eigvalues[mask2].real g_n_SS = eigvalues - 1 eigvectors = np.abs(eigvectors.T) eigvectors = eigvectors[mask] omega_SS = eigvectors[mask2].real if eigvalues.shape[0] != 1: ind = ((abs(omega_SS.T/omega_SS.T.sum(0) - np.array( list(children[-1, :]) + list(omega_big[-1, :])).reshape( S+E, 1)).sum(0))).argmin() omega_SS = omega_SS[ind] g_n_SS = [g_n_SS[ind]] omega_SS = omega_SS.reshape(S+E, 1)[E:, :] omega_SS /= omega_SS.sum() # Creating the different ability level bins omega_SS = np.tile( omega_SS.reshape(S, 1), (1, J)) * bin_weights.reshape(1, J) omega_big = np.tile( omega_big.reshape(T+S, S, 1), (1, 1, J)) * bin_weights.reshape(1, 1, J) children = np.tile(children.reshape( T+S, E, 1), (1, 1, J)) * bin_weights.reshape(1, 1, J) pop_graphs(S, T, starting_age, ending_age, children, g_n_SS[0], omega_big) return omega_big, g_n_SS[0], omega_SS, children, surv_array
def get_omega(S, J, T, bin_weights, starting_age, ending_age, E): ''' Parameters: S - Number of age cohorts J - Number of ability types T - number of time periods in TPI starting age - initial age of cohorts bin_weights - weights for each ability type in each age cohort Returns: ''' data1 = data pop_data = np.array(data1['2010']) poly_pop = poly.polyfit(np.linspace( 0, pop_data.shape[0]-1, pop_data.shape[0]), pop_data, deg=11) poly_int_pop = poly.polyint(poly_pop) pop_int = poly.polyval(np.linspace( starting_age, ending_age, S+1), poly_int_pop) new_omega = pop_int[1:]-pop_int[:-1] surv_array, children_rate = get_survival(S, starting_age, ending_age, E) imm_array, children_im = get_immigration2(S, starting_age, ending_age, E) fert_rate, children_fertrate = get_fert(S, starting_age, ending_age, E) cum_surv_rate = np.cumprod(surv_array) rate_graphs(S, starting_age, ending_age, imm_array, fert_rate, surv_array, children_im, children_fertrate, children_rate) children_int = poly.polyval(np.linspace(0, starting_age, E + 1), poly_int_pop) sum2010 = pop_int[-1] - children_int[0] new_omega /= sum2010 children = np.diff(children_int) children /= sum2010 children = np.tile(children.reshape(1, E), (T + S, 1)) omega_big = np.tile(new_omega.reshape(1, S), (T + S, 1)) # Generate the time path for each age group for t in xrange(1, T + S): # Children are born and then have to wait 20 years to enter the model omega_big[t, 0] = children[t-1, -1] * ( children_rate[-1] + children_im[-1]) omega_big[t, 1:] = omega_big[t-1, :-1] * ( surv_array[:-1] + imm_array[ :-1]) children[t, 1:] = children[t-1, :-1] * ( children_rate[:-1] + children_im[:-1]) children[t, 0] = ((omega_big[t-1, :] * fert_rate).sum(0) + ( children[t-1] * children_fertrate).sum(0)) * (1 + children_im[0]) OMEGA = np.zeros(((S + E), (S + E))) OMEGA[0, :] = np.array(list(children_fertrate) + list( fert_rate)) * (1 + children_im[0]) OMEGA += np.diag(np.array(list(children_rate[:]) + list( surv_array[:-1])) + np.array(list(children_im) + list( imm_array[:-1])), -1) eigvalues, eigvectors = np.linalg.eig(OMEGA) mask = eigvalues.real != 0 eigvalues = eigvalues[mask] mask2 = eigvalues.imag == 0 eigvalues = eigvalues[mask2].real g_n_SS = eigvalues - 1 eigvectors = np.abs(eigvectors.T) eigvectors = eigvectors[mask] omega_SS = eigvectors[mask2].real if eigvalues.shape[0] != 1: ind = ((abs(omega_SS.T/omega_SS.T.sum(0) - np.array( list(children[-1, :]) + list(omega_big[-1, :])).reshape( S+E, 1)).sum(0))).argmin() omega_SS = omega_SS[ind] g_n_SS = [g_n_SS[ind]] omega_SS = omega_SS.reshape(S+E, 1)[E:, :] omega_SS /= omega_SS.sum() # Creating the different ability level bins omega_SS = np.tile( omega_SS.reshape(S, 1), (1, J)) * bin_weights.reshape(1, J) omega_big = np.tile( omega_big.reshape(T+S, S, 1), (1, 1, J)) * bin_weights.reshape(1, 1, J) children = np.tile(children.reshape( T+S, E, 1), (1, 1, J)) * bin_weights.reshape(1, 1, J) pop_graphs(S, T, starting_age, ending_age, children, g_n_SS[0], omega_big) return omega_big, g_n_SS[0], omega_SS, surv_array
def test_polyint(self): # check exceptions assert_raises(ValueError, poly.polyint, [0], .5) assert_raises(ValueError, poly.polyint, [0], -1) assert_raises(ValueError, poly.polyint, [0], 1, [0, 0]) assert_raises(ValueError, poly.polyint, [0], 1, lbnd=[0, 0]) assert_raises(ValueError, poly.polyint, [0], 1, scl=[0, 0]) # check single integration with integration constant for i in range(5): scl = i + 1 pol = [0] * i + [1] tgt = [i] + [0] * i + [1 / scl] res = poly.polyint(pol, m=1, k=[i]) assert_almost_equal(trim(res), trim(tgt)) # check single integration with integration constant and lbnd for i in range(5): scl = i + 1 pol = [0] * i + [1] res = poly.polyint(pol, m=1, k=[i], lbnd=-1) assert_almost_equal(poly.polyval(-1, res), i) # check single integration with integration constant and scaling for i in range(5): scl = i + 1 pol = [0] * i + [1] tgt = [i] + [0] * i + [2 / scl] res = poly.polyint(pol, m=1, k=[i], scl=2) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with default k for i in range(5): for j in range(2, 5): pol = [0] * i + [1] tgt = pol[:] for k in range(j): tgt = poly.polyint(tgt, m=1) res = poly.polyint(pol, m=j) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with defined k for i in range(5): for j in range(2, 5): pol = [0] * i + [1] tgt = pol[:] for k in range(j): tgt = poly.polyint(tgt, m=1, k=[k]) res = poly.polyint(pol, m=j, k=range(j)) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with lbnd for i in range(5): for j in range(2, 5): pol = [0] * i + [1] tgt = pol[:] for k in range(j): tgt = poly.polyint(tgt, m=1, k=[k], lbnd=-1) res = poly.polyint(pol, m=j, k=range(j), lbnd=-1) assert_almost_equal(trim(res), trim(tgt)) # check multiple integrations with scaling for i in range(5): for j in range(2, 5): pol = [0] * i + [1] tgt = pol[:] for k in range(j): tgt = poly.polyint(tgt, m=1, k=[k], scl=2) res = poly.polyint(pol, m=j, k=range(j), scl=2) assert_almost_equal(trim(res), trim(tgt))
def product(a, b): c = polymul2d(a, b) c = P.polyint(c, lbnd=dom[0], axis=0) c = P.polyint(c, lbnd=dom[2], axis=1) v = P.polyval2d(dom[1], dom[3], c) return v
def get_omega(S, T, starting_age, ending_age, E, flag_graphs): ''' Inputs: S - Number of age cohorts (scalar) T - number of time periods in TPI (scalar) starting_age - initial age of cohorts (scalar) ending_age = ending age of cohorts (scalar) E = number of children (scalar) flag_graphs = graph variables or not (bool) Outputs: omega_big = array of all population weights over time ((T+S)x1 array) g_n_SS = steady state growth rate (scalar) omega_SS = steady state population weights (Sx1 array) surv_array = survival rates (Sx1 array) rho = mortality rates (Sx1 array) g_n_vec = population growth rate over time ((T+S)x1 array) ''' data1 = data pop_data = np.array(data1['2010']) poly_pop = poly.polyfit(np.linspace( 0, pop_data.shape[0]-1, pop_data.shape[0]), pop_data, deg=11) poly_int_pop = poly.polyint(poly_pop) pop_int = poly.polyval(np.linspace( starting_age, ending_age, S+1), poly_int_pop) new_omega = pop_int[1:]-pop_int[:-1] surv_array, children_rate = get_survival(S, starting_age, ending_age, E) surv_array[-1] = 0.0 imm_array, children_im = get_immigration2(S, starting_age, ending_age, E) imm_array *= 0.0 fert_rate, children_fertrate = get_fert(S, starting_age, ending_age, E) cum_surv_rate = np.cumprod(surv_array) if flag_graphs: rate_graphs(S, starting_age, ending_age, imm_array, fert_rate, surv_array, children_im, children_fertrate, children_rate) children_int = poly.polyval(np.linspace(0, starting_age, E + 1), poly_int_pop) sum2010 = pop_int[-1] - children_int[0] new_omega /= sum2010 children = np.diff(children_int) children /= sum2010 children = np.tile(children.reshape(1, E), (T + S, 1)) omega_big = np.tile(new_omega.reshape(1, S), (T + S, 1)) # Generate the time path for each age group for t in xrange(1, T + S): # Children are born and then have to wait 20 years to enter the model omega_big[t, 0] = children[t-1, -1] * (children_rate[-1] + children_im[-1]) omega_big[t, 1:] = omega_big[t-1, :-1] * (surv_array[:-1] + imm_array[:-1]) children[t, 1:] = children[t-1, :-1] * (children_rate[:-1] + children_im[:-1]) children[t, 0] = (omega_big[t-1, :] * fert_rate).sum(0) + (children[t-1] * children_fertrate).sum(0) OMEGA = np.zeros(((S + E), (S + E))) OMEGA[0, :] = np.array(list(children_fertrate) + list(fert_rate)) OMEGA += np.diag(np.array(list(children_rate) + list(surv_array[:-1])) + np.array(list(children_im) + list(imm_array[:-1])), -1) eigvalues, eigvectors = np.linalg.eig(OMEGA) mask = eigvalues.real != 0 eigvalues = eigvalues[mask] mask2 = eigvalues.imag == 0 eigvalues = eigvalues[mask2].real g_n_SS = eigvalues - 1 eigvectors = np.abs(eigvectors.T) eigvectors = eigvectors[mask] omega_SS = eigvectors[mask2].real if eigvalues.shape[0] != 1: ind = ((abs(omega_SS.T/omega_SS.T.sum(0) - np.array(list(children[-1, :]) + list(omega_big[-1, :])).reshape(S+E, 1)).sum(0))).argmin() omega_SS = omega_SS[ind] g_n_SS = [g_n_SS[ind]] omega_SS = omega_SS[E:] omega_SS /= omega_SS.sum() # Creating the different ability level bins if flag_graphs: pop_graphs(S, T, starting_age, ending_age, children, g_n_SS[0], omega_big) N_vector = omega_big.sum(1) g_n_vec = N_vector[1:] / N_vector[:-1] -1.0 g_n_vec = np.append(g_n_vec, g_n_SS[0]) rho = 1.0 - surv_array return omega_big, g_n_SS[0], omega_SS, surv_array, rho, g_n_vec