def __call__(self, u, v, du_dv=None): p = self.order # make sure that u and v are of type float64 and ordered in # fortran fashion u = numpy.array(u, dtype="float64", order="fortran") v = numpy.array(v, dtype="float64", order="fortran") # allocate memory space for the result array result = numpy.zeros_like(u) # check if du_dv was given if du_dv != None: # check the size of du_dv, it must be vector of length 2 try: if len(du_dv) != 2: print "du_dy should be a vector of size 2: [du dv]" return except TypeError: print "du_dv must be a vector of size 2: [du dv]" return # try to convert both values to int try: du_dv[0] = int(du_dv[0]) du_dv[1] = int(du_dv[1]) except ValueError: print "du_dv must be a vector with two integers" return # check if they are bigger or equal to zero if (du_dv[0] < 0) or (du_dv[1] < 0): print "du_dv must be a vector with two positive values" if (du_dv == None) or (du_dv == [0, 0]): result = _math_tools.polyeval_2d(u, v, self.coeffs[0], self.coeffs[1], result) return result elif du_dv == [1, 0]: result = _math_tools.polyeval_2d(u, v, self.d_coeffs[0], self.coeffs[1], result) return result elif du_dv == [0, 1]: result = _math_tools.polyeval_2d(u, v, self.coeffs[0], self.d_coeffs[1], result) return result else: # compute the coefficients of the derivatives du_coeffs = scipy.polyder(self.coeffs[0], m=du_dv[0]) dv_coeffs = scipy.polyder(self.coeffs[1], m=du_dv[1]) result = _math_tools.polyeval_2d(u, v, du_coeffs, dv_coeffs, result) return result
def LGR(self,figura): """ Função para traçado do Lugar Geométrico das Raízes kvect: Vetor dos ganhos; figura: referência a uma figura do Matplotlib. O LGR é traçado sempre com ganho K = 1. """ num = self.polyDnum den = self.polyDden # Criando vetor de ganhos (sem os pontos críticos). # Kmin, Kmax e numero de pontos são atributos desta classe. delta_k = (self.Kmax-self.Kmin) / self.Kpontos kvect = numpy.arange(self.Kmin,self.Kmax,delta_k) # Geracao dos pontos de separacao # Fazendo d(-1/G(s))/ds = 0 deriv = scipy.polyder(den)*num - scipy.polyder(num)*den cpss = scipy.roots(deriv) # candidatos a ponto de separacao # Verificacao de quais os candidatos pertinentes for raiz in cpss: aux = num(raiz) if aux != 0: Kc = -den(raiz) / num(raiz) if (numpy.isreal(Kc)) and (Kc <= self.Kmax) and (Kc >= self.Kmin): kvect = numpy.append(kvect,Kc) # Reordena o kvect: kvect = numpy.sort(kvect); # Calculate the roots: root_vector = MyRootLocus(num,den,kvect) # Ploting: figura.clf() ax = figura.add_subplot(111) # Open loop poles: poles = numpy.array(den.r) ax.plot(numpy.real(poles), numpy.imag(poles), 'x') # Open loop zeros: zeros = numpy.array(num.r) if zeros.any(): ax.plot(numpy.real(zeros), numpy.imag(zeros), 'o') for col in root_vector.T: # Ploting the root locus. ax.plot(numpy.real(col), numpy.imag(col), '-') return root_vector
def polyint(lowerLimit, upperLimit, x, y): import scipy from scipy.optimize import leastsq y = y[lowerLimit:upperLimit] x = x[lowerLimit:upperLimit] maxY = max(y) p0 = array([-276025,1051,-1,1,100]) plsq = leastsq(polyresiduals, p0, args=(y, x), maxfev=2000) rplsq = [] i=1 while i <= len(plsq[0]): rplsq.append(plsq[0][-i]) i = i+1 diff = scipy.polyder(rplsq,1) roots = scipy.roots(diff) peak = 0 for root in roots: if root < x[-1] and root > x[0]: peak = root peakIntensity = polyfunction(peak,plsq[0]) return float(real(peakIntensity))
def quadfit(lowerLimit, upperLimit, x,y): import scipy from scipy.optimize import leastsq y = y[lowerLimit:upperLimit] x = x[lowerLimit:upperLimit] maxY = max(y) p0 = array([-276025.,1051.,1.]) plsq = leastsq(quadresiduals, p0, args=(y, x), maxfev=2000) rplsq = [] i=1 while i <= len(plsq[0]): rplsq.append(plsq[0][-i]) i = i+1 diff = scipy.polyder(rplsq,1) roots = scipy.roots(diff) peak = 0 for root in roots: if root < x[-1] and root > x[0]: peak = root fit = [] for i in x: fit.append((i,quadfunction(i,plsq[0]))) return float(real(peak))
def poly2deval_fortran(x, y, polyXY, dx_dy=None): # make sure that x, y and polyXY are float64 and ordered in fortran mode x = numpy.array(x, dtype="float64", order="fortran") y = numpy.array(y, dtype="float64", order="fortran") polyXY = numpy.array(polyXY, dtype="float64", order="fortran") # check if dx_dy was given if dx_dy != None: # check the size of dx_dy, it must be vector of length 2 try: if len(dx_dy) != 2: print "dx_dy should be a vector of size 2: [dx dy]" return except TypeError: print "dx_dy must be a vector of size 2: [dx dy]" return # try to convert both values to int try: dx_dv[0] = int(dx_dy[0]) dx_dy[1] = int(dx_dy[1]) except ValueError: print "dx_dy must be a vector with two integers" return # check if they are bigger or equal to zero if (dx_dy[0] < 0) or (dx_dy[1] < 0): print "dx_dy must be a vector with two positive values" # allocate memory space for the result array result = numpy.zeros_like(x) if (dx_dy == None) or (dx_dy == [0, 0]): result = _math_tools.polyeval_2d(x, y, polyXY, result) return result else: # compute the coefficients of the derivative polynomial in x polyXY[0, :] = scipy.polyder(polyXY[0], m=dx_dy[0]) # compute the coefficients of the derivative polynomial in y polyXY[1, :] = scipy.polyder(polyXY[1], m=dx_dy[1]) # evaluate the 2d polynomial in x and y result = _math_tools.polyeval_2d(x, y, polyXY, result) return resultcipy.polyder(polyXY[1], m=dx_dy[1]) # evaluate the 2d polynomial in x and y result = _math_tools.polyeval_2d(x, y, polyXY, result) return result
def spl3(x, y, x2, s=3): polycoeffs = array(scipy.polyfit(x, y, s)).flatten() y2 = scipy.polyval(polycoeffs, x2) dercoeffs = scipy.polyder(polycoeffs, 1) dy2 = scipy.polyval(dercoeffs, x2) return y2, dy2
def estimate_rate_func(t, T, N, plot_flag=False, method='central diff'): t_est_pts = scipy.linspace(t.min(), t.max(), N + 2) interp_func = scipy.interpolate.interp1d(t, T, 'linear') T_est_pts = interp_func(t_est_pts) if plot_flag == True: pylab.figure() pylab.subplot(211) pylab.plot(t_est_pts, T_est_pts, 'or') # Estimate slopes slope_pts = scipy.zeros((N, )) T_slope_pts = scipy.zeros((N, )) if method == 'local fit': for i in range(1, (N + 1)): mask0 = t > 0.5 * (t_est_pts[i - 1] + t_est_pts[i]) mask1 = t < 0.5 * (t_est_pts[i + 1] + t_est_pts[i]) mask = scipy.logical_and(mask0, mask1) t_slope_est = t[mask] T_slope_est = T[mask] local_fit = scipy.polyfit(t_slope_est, T_slope_est, 2) dlocal_fit = scipy.polyder(local_fit) slope_pts[i - 1] = scipy.polyval(dlocal_fit, t_est_pts[i]) T_slope_pts[i - 1] = scipy.polyval(local_fit, t_est_pts[i]) if plot_flag == True: t_slope_fit = scipy.linspace(t_slope_est[0], t_slope_est[-1], 100) T_slope_fit = scipy.polyval(local_fit, t_slope_fit) pylab.plot(t_slope_fit, T_slope_fit, 'g') elif method == 'central diff': dt = t_est_pts[1] - t_est_pts[0] slope_pts = (T_est_pts[2:] - T_est_pts[:-2]) / (2.0 * dt) T_slope_pts = T_est_pts[1:-1] else: raise ValueError, 'unkown method %s' % (method, ) # Fit line to slope estimates fit = scipy.polyfit(T_slope_pts, slope_pts, 1) if plot_flag == True: T_slope_fit = scipy.linspace(T_slope_pts.min(), T_slope_pts.max(), 100) slope_fit = scipy.polyval(fit, T_slope_fit) pylab.subplot(212) pylab.plot(T_slope_fit, slope_fit, 'r') pylab.plot(T_slope_pts, slope_pts, 'o') pylab.show() rate_slope = fit[0] rate_offset = fit[1] return rate_slope, rate_offset
def estimate_rate_func(t, T, N, plot_flag=False, method='central diff'): t_est_pts = scipy.linspace(t.min(), t.max(), N+2) interp_func = scipy.interpolate.interp1d(t,T,'linear') T_est_pts = interp_func(t_est_pts) if plot_flag == True: pylab.figure() pylab.subplot(211) pylab.plot(t_est_pts, T_est_pts,'or') # Estimate slopes slope_pts = scipy.zeros((N,)) T_slope_pts = scipy.zeros((N,)) if method == 'local fit': for i in range(1,(N+1)): mask0 = t > 0.5*(t_est_pts[i-1] + t_est_pts[i]) mask1 = t < 0.5*(t_est_pts[i+1] + t_est_pts[i]) mask = scipy.logical_and(mask0, mask1) t_slope_est = t[mask] T_slope_est = T[mask] local_fit = scipy.polyfit(t_slope_est,T_slope_est,2) dlocal_fit = scipy.polyder(local_fit) slope_pts[i-1] = scipy.polyval(dlocal_fit,t_est_pts[i]) T_slope_pts[i-1] = scipy.polyval(local_fit,t_est_pts[i]) if plot_flag == True: t_slope_fit = scipy.linspace(t_slope_est[0], t_slope_est[-1], 100) T_slope_fit = scipy.polyval(local_fit,t_slope_fit) pylab.plot(t_slope_fit, T_slope_fit,'g') elif method == 'central diff': dt = t_est_pts[1] - t_est_pts[0] slope_pts = (T_est_pts[2:] - T_est_pts[:-2])/(2.0*dt) T_slope_pts = T_est_pts[1:-1] else: raise ValueError, 'unkown method %s'%(method,) # Fit line to slope estimates fit = scipy.polyfit(T_slope_pts, slope_pts,1) if plot_flag == True: T_slope_fit = scipy.linspace(T_slope_pts.min(), T_slope_pts.max(),100) slope_fit = scipy.polyval(fit,T_slope_fit) pylab.subplot(212) pylab.plot(T_slope_fit, slope_fit,'r') pylab.plot(T_slope_pts, slope_pts,'o') pylab.show() rate_slope = fit[0] rate_offset = fit[1] return rate_slope, rate_offset
def _BOpntsLoc(sys): """Breakout point locater This returns the location of breakout points on the root locus and the associated gains at those locations. Parameters ---------- sys: StateSpace or TransferFunction Linear system Returns ------- KatBO: list of gains at which a breakout point occurs BOpnts: list of breakout points """ (nump, denp) = _systopoly1d(sys) # Breakout points potentially occur where N*D' - N'*D = 0 numpD = polyder(nump) denpD = polyder(denp) BOpnts = roots((nump*denpD) - (numpD*denp)) # Selects only the Breakout points on the real line BOpnts = BOpnts[imag(BOpnts) == 0] # Finds gains from breakout points fgain = vectorize(lambda s: polyval(-denp,s)/polyval(nump,s)) KatBO = fgain(BOpnts) # Selects only the positive gains at the Breakout points KatBO = KatBO[KatBO >= 0] return KatBO, BOpnts
def PontosSeparacao(self): """ Calcula os pontos de separação e retorna só os pertinentes. """ num = self.polyDnum den = self.polyDden pontos = [] ganhos = [] # Geracao dos pontos de separacao # Fazendo d(-1/G(s))/ds = 0 deriv = scipy.polyder(den)*num - scipy.polyder(num)*den cpss = scipy.roots(deriv) # candidatos a ponto de separacao # Verificacao de quais os candidatos pertinentes for raiz in cpss: aux = num(raiz) if aux != 0: Kc = -den(raiz) / num(raiz) if (numpy.isreal(Kc)):# and (Kc <= self.Kmax) and (Kc >= self.Kmin): pontos.append(raiz) ganhos.append(Kc) return pontos, ganhos
def _offbid(self, markups, withholds): """ Converts arrays of percentage price markups and capacity withholds into offers/bids and submits them to the marketplace. """ for i, g in enumerate(self.generators): ratedPMin = self._g0[g]["p_min"] ratedPMax = self._g0[g]["p_max"] margPCost = self._g0[g]["p_cost"] margPCostModel = self._g0[g]["pcost_model"] # Index of the first markup in 'markups' for generator 'i'. k = i * (len(markups) / len(self.generators)) # Index of the first withhold in 'withholds' for generator 'i'. kk = i * (len(withholds) / len(self.generators)) # Determine the cost at zero output. if margPCostModel == POLYNOMIAL: costNoLoad = margPCost[-1] else: costNoLoad = 0.0 # Divide available capacity equally among the offers/bids. if g.is_load: qty = ratedPMin / self.numOffbids else: qty = ratedPMax / self.numOffbids # Track the total quantity offered/bid for by the generator. totQty = 0.0 # p0 = 0.0 # c0 = costNoLoad for j in range(self.numOffbids): wh = withholds[kk+j] qty = qty * ((100.0 - wh) / 100.0) totQty += qty # The markups are cumulative to ensure cost function convexity. mk = sum(markups[k:k + j + 1]) # Marginal cost (cost function gradient). if margPCostModel == POLYNOMIAL: cmarg = polyval(polyder(margPCost), totQty) elif margPCostModel == PW_LINEAR: n_segments = len(margPCost) - 1 for i in range(n_segments): x1, y1 = margPCost[i] x2, y2 = margPCost[i + 1] if x1 <= totQty <= x2: cmarg = (y2 - y1) / (x2 - x1) else: raise ValueError, "Invalid bid quantity [%f]." % totQty else: raise ValueError # Markup the marginal cost of the generator. if not g.is_load: prc = cmarg * ((100.0 + mk) / 100.0) else: prc = cmarg * ((100.0 + mk) / 100.0) if not g.is_load: offer = Offer(g, qty, prc, costNoLoad) self.market.offers.append(offer) self._lastAction.append(offer) logger.info( "%.2fMW offered at %.2f$/MWh for %s (%.1f%%, %.1f%%)." % (qty, prc, g.name, mk, wh)) else: bid = Bid(g, -qty, prc, costNoLoad) self.market.bids.append(bid) self._lastAction.append(bid) logger.info( "%.2f$/MWh bid for %.2fMW for %s (%.1f%%, %.1f%%)." % (prc, -qty, g.name, mk, wh)) return self._lastAction
from numpy.polynomial.polynomial import polyfit from scipy.optimize import fmin import numpy as np import scipy import numpy import pylab import scipy.optimize as optimize c, stats = polyfit(range(1, len(data) + 1), data, 120, full=True) x, stats = polyfit(range(1, len(show_data) + 1), show_data, 120, full=True) l = c.tolist() g = x.tolist() f = scipy.poly1d(l[::-1]) f1 = scipy.poly1d(scipy.polyder(f)) f2 = scipy.poly1d(scipy.polyder(f1)) f3 = scipy.poly1d(scipy.polyder(f2)) g = scipy.poly1d(g[::-1]) g1 = scipy.poly1d(scipy.polyder(g)) g2 = scipy.poly1d(scipy.polyder(g1)) g3 = scipy.poly1d(scipy.polyder(g2)) t = numpy.arange(0.0, 40, 0.01) #s = map(f,t) #s1 = map(f1,t) #s2 = map(f2,t) #s3 = map(f3,t) #pylab.plot(t, s,'#000000')
def _offbid(self, markups, withholds): """ Converts arrays of percentage price markups and capacity withholds into offers/bids and submits them to the marketplace. """ for i, g in enumerate(self.generators): ratedPMin = self._g0[g]["p_min"] ratedPMax = self._g0[g]["p_max"] margPCost = self._g0[g]["p_cost"] margPCostModel = self._g0[g]["pcost_model"] # Index of the first markup in 'markups' for generator 'i'. k = i * (len(markups) / len(self.generators)) # Index of the first withhold in 'withholds' for generator 'i'. kk = i * (len(withholds) / len(self.generators)) # Determine the cost at zero output. if margPCostModel == POLYNOMIAL: costNoLoad = margPCost[-1] else: costNoLoad = 0.0 # Divide available capacity equally among the offers/bids. if g.is_load: qty = ratedPMin / self.numOffbids else: qty = ratedPMax / self.numOffbids # Track the total quantity offered/bid for by the generator. totQty = 0.0 # p0 = 0.0 # c0 = costNoLoad for j in range(self.numOffbids): wh = withholds[kk + j] qty = qty * ((100.0 - wh) / 100.0) totQty += qty # The markups are cumulative to ensure cost function convexity. mk = sum(markups[k:k + j + 1]) # Marginal cost (cost function gradient). if margPCostModel == POLYNOMIAL: cmarg = polyval(polyder(margPCost), totQty) elif margPCostModel == PW_LINEAR: n_segments = len(margPCost) - 1 for i in range(n_segments): x1, y1 = margPCost[i] x2, y2 = margPCost[i + 1] if x1 <= totQty <= x2: cmarg = (y2 - y1) / (x2 - x1) else: raise ValueError, "Invalid bid quantity [%f]." % totQty else: raise ValueError # Markup the marginal cost of the generator. if not g.is_load: prc = cmarg * ((100.0 + mk) / 100.0) else: prc = cmarg * ((100.0 + mk) / 100.0) if not g.is_load: offer = Offer(g, qty, prc, costNoLoad) self.market.offers.append(offer) self._lastAction.append(offer) logger.info( "%.2fMW offered at %.2f$/MWh for %s (%.1f%%, %.1f%%)." % (qty, prc, g.name, mk, wh)) else: bid = Bid(g, -qty, prc, costNoLoad) self.market.bids.append(bid) self._lastAction.append(bid) logger.info( "%.2f$/MWh bid for %.2fMW for %s (%.1f%%, %.1f%%)." % (prc, -qty, g.name, mk, wh)) return self._lastAction