def generate_weibull(size): k1 = 0.5 scale1 = 0.3 dat1 = exponweib.rvs(a=1, c=k1, scale=scale1, size=size) k2 = 1.1 scale2 = 0.1 dat2 = exponweib.rvs(a=1, c=k2, scale=scale2, size=size) dat = np.concatenate([dat1, dat2]) return dat
def samples(self, size=1000): ''' Generates samples from current Weibull distribution. args: size: The number of samples to be generated. ''' return exponweib.rvs(a=1, c=self.k, scale=self.lmb, size=size)
def time_to_failure(): """Return time until next failure for a machine.""" if not useWeibull: nextFailure = int(random.expovariate(BREAK_MEAN)) else: # The Weibull distr. generates many errors. #nextFailure = int(np.random.weibull(WEIBULL_K)*98.0) # Gives MTBF to be 200 nextFailure = int(exponweib.rvs(1.0, WEIBULL_SHAPE, scale=WEIBULL_SCALE)) return nextFailure
def fit_weib2(): # 生成韦伯分布数据 sample = exponweib.rvs(a=10, c=1, scale=3, loc=0, size=1000) x = np.linspace(0, np.max(sample), 100) #拟合 a, c, loc, scale = exponweib.fit(sample, floc=0, fa=1) print(a, c, loc, scale) y = exponweib.pdf(x, a, c, loc, scale) for x1, y1 in zip(x, y): print(x1, y1) plt.plot(x, y) plt.show()
def example_4(): a, c = 3, 1 data = exponweib.rvs(a, c, size=1000) pf = lambda ah, ch=c, d=data: -np.sum(np.log(exponweib.pdf(data, ah, ch))) x0 = 2 sols = {} methods = ["nelder-mead", "powell", "Anneal", "BFGS", "TNC", "L-BFGS-B", "SLSQP"] for method in sorted(methods): th = {'success': False} while not th['success']: th = minimizer(x0, pf, method) print '{0} ({1}): {2}'.format(method, x0, th['message']) x0 = np.random.uniform(0, 10) sols[method] = th['x'] for i, (method, sol) in enumerate(sols.iteritems()): print '{0}: {1}'.format(method, sol)
def example_2(): a, c = 3, 1 data = exponweib.rvs(a, c, size=1000) l = round(max(data) - min(data)) pf = lambda ah, ch=c, d=data: np.sum(np.log(exponweib.pdf(data, ah, ch))) e = 1 # step size of random-walk qrf = lambda x, e=e: norm.rvs(x, e) x0 = 2 ahs0 = metropolis_hastings(x0, 100000, pf, qrf) # ahs = ahs0 ahs = prune(ahs0, l, e) print 'Generated {0} samples after pruning from {1}.'.format(len(ahs), len(ahs0)) print min(ahs), max(ahs) plt.axvline(a, label='theta', color='b', linestyle='--') plt.hist(ahs, 100, normed=True, label='pruned m-h samples') plt.legend() # plt.savefig('../img/example-2.png') plt.show()
def example_3(): a, c = 3, 1 data = exponweib.rvs(a, c, size=1000) l = round(max(data) - min(data)) pf = lambda ah, ch=c, d=data: np.sum(np.log(exponweib.pdf(data, ah, ch))) d = 1.0 Tf = lambda i: d/np.log(i+2) # cooling function e = 1 # step size of random-walk qrf = lambda x, e=e: norm.rvs(x, e) x0 = 2 ahs0 = simulated_annealing(x0, 100000, pf, qrf, Tf) print 'Generated {0} samples. MAP estimate is {1}'.format(len(ahs0), ahs0[-1]) plt.hist(ahs0, 100, normed=True, label='samples') plt.axvline(a, label='theta', color='b', linestyle='--') plt.axvline(ahs0[-1], label='theta-hat', color='c', linestyle='--') plt.xlim([2.8, 3.4]) plt.legend() # plt.savefig('../img/example-3.png') plt.show()
def next_ttr(final_downtime_model, CRN=None): dist = final_downtime_model[0] params = final_downtime_model[1] if dist == "uniform": return uniform.rvs(*params, random_state=CRN) elif dist == "expon": return expon.rvs(*params, random_state=CRN) elif dist == "rayleigh": return rayleigh.rvs(*params, random_state=CRN) elif dist == "weibull_min": return weibull_min.rvs(*params, random_state=CRN) elif dist == "gamma": return gamma.rvs(*params, random_state=CRN) elif dist == "gengamma": return gengamma.rvs(*params, random_state=CRN) elif dist == "invgamma": return invgamma.rvs(*params, random_state=CRN) elif dist == "gompertz": return gompertz.rvs(*params, random_state=CRN) elif dist == "lognorm": return lognorm.rvs(*params, random_state=CRN) elif dist == "exponweib": return exponweib.rvs(*params, random_state=CRN)
# # # # plt.matshow(upper); # plt.colorbar(); # plt.show() # plt.matshow(lower); # plt.colorbar(); # plt.show(); # plt.matshow(median); # plt.colorbar(); # plt.show(); exit(); r = exponweib.rvs(1.0,2.0,loc=0.0,scale=1.0,size=10); interv = exponweib.interval(0.99,1.0,2.0,loc=0.0,scale=1.0) print(interv); binned,edges = np.histogram(r,bins, normed=True); fit = exponweib.fit(r); DF = bins - len(fit); print(DF) x = np.linspace(np.min(r),np.max(r),bins); y = exponweib.pdf(x,*fit); kern = scipy.stats.gaussian_kde(r)
def adult(frame, tpgroup, weibull, day): # empexclude = False; # if frame['empcode'] > -1: # empexclude = True; #revisit later actlist = [] t = np.floor(exponweib.rvs(1.0, 1.8, scale=90)) + 120 act = 10101 locx = frame['addrx'] locy = frame['addry'] actlist += [(t, act, locx, locy)] ct = t while ct < 1440.0: hour = np.floor(ct / 60.0) g = tpgroup.get_group((day, hour)) #act = np.random.choice(g['dest'],p=(g['count']/np.sum(g['count'])) ); act = np.random.choice(g['dest'], p=g['prob']) #handle movement if act <= 189999 and act >= 180000: #if we're travelling, we know we start at the current location #so locx and locy remain the same #but then we have to pick the next item wb = weibull.ix[act] t = np.floor(exponweib.rvs(1.0, wb['c'], scale=wb['scale'])) + 1 ct += t actlist += [(t, act, locx, locy)] #pick based on the type of travel and consider where we currently are #determine maximum range based on travel time #we assume an average speed of 60 kph using taxicab movement #60 kph is 1000 m/min dist = np.floor(800.0 * t) #if we are working and we are NOT at work, go to work #if we are at work, go home if frame['empcode'] > -1 and act >= 180501 and act <= 180599: if locx != frame['empx'] and locy != frame['empy']: locx = frame['empx'] locy = frame['empy'] else: locx = frame['addrx'] locy = frame['addry'] #if we are not travelling related to work, then #we we are travelling somewhere else #but, we might not travel directly home else: if locx == frame['addrx'] and locy == frame['addry']: locx = np.random.randint(-dist, dist) + locx locy = np.random.randint(-dist, dist) + locy #after 4 PM 50% probability of going home elif t > 720 and (np.random.rand() > 0.5): locx = frame['addrx'] locy = frame['addry'] #after 8 PM 75% probability of going home elif t > 960 and (np.random.rand() > 0.25): locx = frame['addrx'] locy = frame['addry'] else: locx = np.random.randint(-dist, dist) + frame['addrx'] locy = np.random.randint(-dist, dist) + frame['addry'] g = tpgroup.get_group((day, hour)) #act = np.random.choice(g['dest'],p=(g['count']/np.sum(g['count']))); act = np.random.choice(g['dest'], p=g['prob']) #teleport home if its after midnight if t > 1200 and locx != frame['addrx'] and locy != frame['addry']: locx = frame['addrx'] locy = frame['addry'] wb = weibull.ix[act] t = np.floor(exponweib.rvs(1.0, wb['c'], scale=wb['scale'])) + 1 ct += t actlist += [(t, act, locx, locy)] return actlist
def rollweibull(act, tab): wb = tab.ix[act] return np.floor(exponweib.rvs(1.0, wb['c'], scale=wb['scale'])) + 1
def indchild(frame, tpgroup, weibull, day): #we assume that school happens around 8:30 on a weekday for 6.5 hours school = False if day > 1 and day < 7: school = True if school: if frame['age'] > 12: grid = 4000.0 elif frame['age'] > 10: grid = 2000.0 else: grid = 1000.0 actlist = [] t = np.floor(exponweib.rvs(1.0, 1.8, scale=90)) + 120 act = 10101 locx = frame['addrx'] locy = frame['addry'] actlist += [(t, act, locx, locy)] ct = t while ct < 1440.0: #force school time if school and t > (4.5 * 60.0 - 15) and t < (11.0 * 60.0 + 15) and act != 60101: act = 180601 t = np.floor(exponweib.rvs(1.0, 1.5, scale=15)) + 1 ct += t locx = frame['addrx'] locy = frame['addry'] actlist += [(t, act, locx, locy)] t = (11.0 * 60.0) - ct ct += t act = 60101 locx = np.round(frame['addrx'] / grid, 0) * grid locy = np.round(frame['addry'] / grid, 0) * grid actlist += [(t, act, locx, locy)] else: hour = np.floor(ct / 60.0) g = tpgroup.get_group((day, hour)) #act = np.random.choice(g['dest'],p=(g['count']/np.sum(g['count']))); act = np.random.choice(g['dest'], p=g['prob']) #handle movement if act <= 189999 and act >= 180000: #if we're travelling, we know we start at the current location #so locx and locy remain the same #but then we have to pick the next item wb = weibull.ix[act] t = np.floor(exponweib.rvs(1.0, wb['c'], scale=wb['scale'])) + 1 ct += t actlist += [(t, act, locx, locy)] #pick based on the type of travel and consider where we currently are #determine maximum range based on travel time #we assume an average speed of 60 kph using taxicab movement #30 mph is 800 m/min dist = np.floor(800.0 * t) #if we are working and we are NOT at work, go to work #if we are at work, go home if frame['empcode'] > -1 and act >= 180501 and act <= 180599: if locx != frame['empx'] and locy != frame['empy']: locx = frame['empx'] locy = frame['empy'] else: locx = frame['addrx'] locy = frame['addry'] #if we are not travelling related to work, then #we we are travelling somewhere else #but, we might not travel directly home else: if locx == frame['addrx'] and locy == frame['addry']: locx = np.random.randint(-dist, dist) + locx locy = np.random.randint(-dist, dist) + locy #after 4 PM 50% probability of going home elif t > 720 and (np.random.rand() > 0.5): locx = frame['addrx'] locy = frame['addry'] #after 8 PM 75% probability of going home elif t > 960 and (np.random.rand() > 0.25): locx = frame['addrx'] locy = frame['addry'] else: locx = np.random.randint(-dist, dist) + frame['addrx'] locy = np.random.randint(-dist, dist) + frame['addry'] g = tpgroup.get_group((day, hour)) #act = np.random.choice(g['dest'],p=(g['count']/np.sum(g['count']))); act = np.random.choice(g['dest'], p=g['prob']) #teleport home if its after midnight if t > 1200 and locx != frame['addrx'] and locy != frame['addry']: locx = frame['addrx'] locy = frame['addry'] wb = weibull.ix[act] t = np.floor(exponweib.rvs(1.0, wb['c'], scale=wb['scale'])) + 1 ct += t actlist += [(t, act, locx, locy)] return actlist
def samples(self, size = 1000): return exponweib.rvs(a=1,c=self.k,scale=self.lmb,size=size)
exponweib.pdf(x, a, c), 'r-', lw=5, alpha=0.6, label='exponweib pdf') # Alternatively, the distribution object can be called (as a function) # to fix the shape, location and scale parameters. This returns a "frozen" # RV object holding the given parameters fixed. # Freeze the distribution and display the frozen ``pdf``: rv = exponweib(a, c) ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') # Check accuracy of ``cdf`` and ``ppf``: vals = exponweib.ppf([0.001, 0.5, 0.999], a, c) np.allclose([0.001, 0.5, 0.999], exponweib.cdf(vals, a, c)) # True # Generate random numbers: r = exponweib.rvs(a, c, size=1000) # And compare the histogram: ax.hist(r, density=True, histtype='stepfilled', alpha=0.2) ax.legend(loc='best', frameon=False) plt.show()
def samples_(k, lmb, size=1000): return exponweib.rvs(a=1, c=k, scale=lmb, size=size)