def find_service_time(self, n, c): """ Finds the service time function """ if self.mu[c][n][0] == 'Uniform': return lambda : uniform(self.mu[c][n][1], self.mu[c][n][2]) if self.mu[c][n][0] == 'Deterministic': return lambda : self.mu[c][n][1] if self.mu[c][n][0] == 'Triangular': return lambda : triangular(self.mu[c][n][1], self.mu[c][n][2], self.mu[c][n][3]) if self.mu[c][n][0] == 'Exponential': return lambda : expovariate(self.mu[c][n][1]) if self.mu[c][n][0] == 'Gamma': return lambda : gammavariate(self.mu[c][n][1], self.mu[c][n][2]) if self.mu[c][n][0] == 'Normal': return lambda : gauss(self.mu[c][n][1], self.mu[c][n][2]) if self.mu[c][n][0] == 'Lognormal': return lambda : lognormvariate(self.mu[c][n][1], self.mu[c][n][2]) if self.mu[c][n][0] == 'Weibull': return lambda : weibullvariate(self.mu[c][n][1], self.mu[c][n][2]) if self.mu[c][n][0] == 'Custom': P, V = zip(*self.parameters[self.mu[c][n][1]]) probs = list(P) cum_probs = [sum(probs[0:i+1]) for i in range(len(probs))] values = list(V) return lambda : self.custom_pdf(cum_probs, values) return False
def random_year(self): s = random.lognormvariate(self.stocks_mean, self.stocks_stddev) - 1 s = Decimal(s) b = random.lognormvariate(self.bonds_mean, self.bonds_stddev) - 1 b = Decimal(b) return AnnualChange(year=self.year, stocks=s, bonds=b, inflation=Decimal(0))
def sample(self): result = self._scale * random.lognormvariate(self._mu, self._sigma) if self._maximum is not None and result > self._maximum: for _ignore in range(10): result = self._scale * random.lognormvariate(self._mu, self._sigma) if result <= self._maximum: break else: raise ValueError("Unable to generate LogNormalDistribution sample within required range") return result
def test_lognormal(self): """Statistics.lognormal test""" import random import Biskit.gnuplot as gnuplot import Biskit.hist as H cr = [] for i in range( 10000 ): ## Some random values drawn from the same lognormal distribution alpha = 1.5 beta = .7 x = 10. R = [ random.lognormvariate( alpha, beta ) for j in range( 10 ) ] cr += [ logConfidence( x, R )[0] ] ca = logArea( x, alpha, beta ) if self.local: gnuplot.plot( H.density( N.array(cr) - ca, 100 ) ) globals().update( locals() ) self.assertAlmostEqual( ca, 0.86877651432955771, 7)
async def create_server(self, worker, protocol_factory, address=None, sockets=None, idx=0): '''Create the Server which will listen for requests. :return: a :class:`.TcpServer`. ''' cfg = self.cfg max_requests = cfg.max_requests if max_requests: max_requests = int(lognormvariate(log(max_requests), 0.2)) server = self.server_factory( protocol_factory, loop=worker._loop, max_requests=max_requests, keep_alive=cfg.keep_alive, name=self.name, logger=self.logger, server_software=cfg.server_software, cfg=cfg, idx=idx ) for event in ('connection_made', 'pre_request', 'post_request', 'connection_lost'): callback = getattr(cfg, event) if callback != pass_through: server.event(event).bind(callback) await server.start_serving( sockets=sockets, address=address, backlog=cfg.backlog, sslcontext=self.sslcontext() ) return server
def produceReads(self,readDensity = 1,read_length = 50): """ Produces uniform reads by walking iteratively over self.regions """ mRNA = self.getTotalmRNA() spanning_length = self.getRegionSpanningLength() n = spanning_length['total'] - read_length + 1 j = 0 k = 0 for i in range(n): # "alpha is playing the role of k and beta is playing the role of theta" dd = max(0,int(round(random.lognormvariate(math.log(readDensity),0.5))))# Notice this is NOT a binomial distribution!! for d in range(dd): sequence = mRNA[i:i+read_length] if(random.randint(0,1) == 0): strand = 0 else: strand = 16 flag = strand + 0 print "read_"+str(j)+"."+str(i)+"."+str(d)+"\t"+str(flag)+"\t"+self.chromosome+"\t"+str(self.regions[j].start + k)+"\t60\t"+self.getMappingString(read_length,j,k)+"\t*\t0\t0\t"+str(sequence.upper())+"\t*" spanning_length['iter'][j] -= 1 if(k >= self.regions[j].getSpanningLength()-1): j += 1 k = 0 else: k += 1
def _get_new_ctd_packet(self, length): rdt = RecordDictionaryTool(stream_definition_id=self.stream_def._id) #Explicitly make these numpy arrays... c = numpy.array([random.uniform(0.0,75.0) for i in xrange(length)]) t = numpy.array([random.uniform(-1.7, 21.0) for i in xrange(length)]) p = numpy.array([random.lognormvariate(1,2) for i in xrange(length)]) lat = numpy.array([random.uniform(-90.0, 90.0) for i in xrange(length)]) lon = numpy.array([random.uniform(0.0, 360.0) for i in xrange(length)]) h = numpy.array([random.uniform(0.0, 360.0) for i in xrange(length)]) start_time = ntplib.system_to_ntp_time(time.time()) - (length + 1) tvar = numpy.array([start_time + i for i in xrange(1,length+1)]) rdt['time'] = tvar rdt['lat'] = lat rdt['lon'] = lon rdt['temp'] = t rdt['conductivity'] = c rdt['pressure'] = p # rdt['coordinates'] = rdt0 # rdt['data'] = rdt1 g = rdt.to_granule(data_producer_id=self.id) return g
def find_distributions(self, n, c, source): """ Finds distribution functions """ if source[c][n] == 'NoArrivals': return lambda : 'Inf' if source[c][n][0] == 'Uniform': return lambda : uniform(source[c][n][1], source[c][n][2]) if source[c][n][0] == 'Deterministic': return lambda : source[c][n][1] if source[c][n][0] == 'Triangular': return lambda : triangular(source[c][n][1], source[c][n][2], source[c][n][3]) if source[c][n][0] == 'Exponential': return lambda : expovariate(source[c][n][1]) if source[c][n][0] == 'Gamma': return lambda : gammavariate(source[c][n][1], source[c][n][2]) if source[c][n][0] == 'Lognormal': return lambda : lognormvariate(source[c][n][1], source[c][n][2]) if source[c][n][0] == 'Weibull': return lambda : weibullvariate(source[c][n][1], source[c][n][2]) if source[c][n][0] == 'Custom': P, V = zip(*self.parameters[source[c][n][1]]) probs = list(P) cum_probs = [sum(probs[0:i+1]) for i in range(len(probs))] values = list(V) return lambda : self.custom_pdf(cum_probs, values) if source[c][n][0] == 'Empirical': if isinstance(source[c][n][1], str): empirical_dist = self.import_empirical_dist(source[c][n][1]) return lambda : choice(empirical_dist) return lambda : choice(source[c][n][1]) return False
def _get_new_ctd_packet(self, stream_id, length): rdt = RecordDictionaryTool(taxonomy=tx) #Explicitly make these numpy arrays... c = numpy.array([random.uniform(0.0,75.0) for i in xrange(length)]) t = numpy.array([random.uniform(-1.7, 21.0) for i in xrange(length)]) p = numpy.array([random.lognormvariate(1,2) for i in xrange(length)]) lat = numpy.array([random.uniform(-90.0, 90.0) for i in xrange(length)]) lon = numpy.array([random.uniform(0.0, 360.0) for i in xrange(length)]) h = numpy.array([random.uniform(0.0, 360.0) for i in xrange(length)]) tvar = numpy.array([self.last_time + i for i in xrange(1,length+1)]) self.last_time = max(tvar) log.warn('Got time: %s' % str(tvar)) log.warn('Got t: %s' % str(t)) rdt['time'] = tvar rdt['lat'] = lat rdt['lon'] = lon rdt['height'] = h rdt['temp'] = t rdt['cond'] = c rdt['pres'] = p # rdt['coordinates'] = rdt0 # rdt['data'] = rdt1 g = build_granule(data_producer_id=stream_id, taxonomy=tx, record_dictionary=rdt) return g
def generateLogNormalRVs(mu, sigma, count, histDelta): rVec = numpy.zeros(count) rMax = 0. for ii in range(count): rVec[ii] = random.lognormvariate(mu, sigma) if (rMax < rVec[ii]): rMax = rVec[ii] # build the histogram ... deltaR = histDelta rMinHist = 0. rMaxHist = rMax + 2. * deltaR numBins = (rMaxHist - rMinHist) / deltaR numBins = int(numBins) + 2 rHist = numpy.zeros(numBins) # print ' making histogram ... ', deltaR, rMaxHist for ii in range(count): iBin = int((rVec[ii] - rMinHist) / deltaR + 0.0001) rHist[iBin] += 1 for iBin in range(numBins): rHist[iBin] /= float(count) return (rVec, rHist)
def next(self): change = random.lognormvariate(0, self.sigma) if self.current + change > 0 and random.choice((True, False)): change = -change self.current += change delay() yield self.current
def visit_medic(self): """ Lognormal with : logarithmic mean: 1.024 logarithmic std dev: 0.788 """ name = 'medic' if self.debug: print self.name, "at ",name, simpy.now() arrive = simpy.now() yield simpy.request, self, self.resources[name] wait = simpy.now() - arrive self.monitors[name].observe(wait) time = random.lognormvariate(mu=1.024, sigma=0.788) tib = self.numberOfForms * time yield simpy.hold,self,tib yield simpy.release, self, self.resources[name] p = random.random() if p < 0.99: for i in self.visit_dispenser(): yield i else: for i in self.visit_exit(): yield i
def lognormal(mean=None, sigma=None, n=1, minimum=None, maximum=None): """ Generate a list with a lognormal distribution. Option - setting mininum and maximum rejects and regenerates any value outside the truncation range. Setting minimum and maximum to None or 'None' makes the range unbounded. """ if minimum is None or minimum is 'None': minimum = None else: minimum = float(minimum) if maximum is None or maximum is 'None': maximum = None else: maximum = float(maximum) mean = float(mean) sigma = float(sigma) answer = [] while len(answer) < n: x = random.lognormvariate(mu=mean, sigma=sigma) if x > minimum and (x < maximum or (maximum is None)): answer.append(x) return answer
def random(self, start, minVal, maxVal, candidate = None): for z in xrange(config.rand_retries): v=int(start*random.lognormvariate(0,1)+.5) #logging.debug("lognorm: start=%d, v=%d", start, v) if v>=minVal and v<=maxVal and start!=v: return v raise MutateFailed("lognorm random gen failed")
def _trigger_func(self, stream_id): point_def = ctd_stream_definition(stream_id=stream_id) point_constructor = PointSupplementConstructor(point_definition=point_def) while True: length = 1 c = [random.uniform(0.0,75.0) for i in xrange(length)] t = [random.uniform(-1.7, 21.0) for i in xrange(length)] p = [random.lognormvariate(1,2) for i in xrange(length)] lat = [random.uniform(-90.0, 90.0) for i in xrange(length)] lon = [random.uniform(0.0, 360.0) for i in xrange(length)] tvar = [self.last_time + i for i in xrange(1,length+1)] self.last_time = max(tvar) point_id = point_constructor.add_point(time=tvar,location=(lon[0],lat[0])) point_constructor.add_point_coverage(point_id=point_id, coverage_id='temperature', values=t) point_constructor.add_point_coverage(point_id=point_id, coverage_id='pressure', values=p) point_constructor.add_point_coverage(point_id=point_id, coverage_id='conductivity', values=c) ctd_packet = point_constructor.get_stream_granule() log.warn('SimpleCtdPublisher sending %d values!' % length) self.publisher.publish(ctd_packet) time.sleep(2.0)
def _trigger_func(self, stream_id): while True: length = random.randint(1,20) c = [random.uniform(0.0,75.0) for i in xrange(length)] t = [random.uniform(-1.7, 21.0) for i in xrange(length)] p = [random.lognormvariate(1,2) for i in xrange(length)] lat = [random.uniform(-90.0, 90.0) for i in xrange(length)] lon = [random.uniform(0.0, 360.0) for i in xrange(length)] tvar = [self.last_time + i for i in xrange(1,length+1)] self.last_time = max(tvar) ctd_packet = ctd_stream_packet(stream_id=stream_id, c=c, t=t, p=p, lat=lat, lon=lon, time=tvar) log.warn('SimpleCtdPublisher sending %d values!' % length) self.publisher.publish(ctd_packet) time.sleep(2.0)
def initRandomParticle(self, systemRadius, maxSize, systemCenter): position = [random.randrange(systemCenter[0],systemRadius),random.randrange(systemCenter[1],systemRadius)] #this creates a square system velocity = [random.randrange(-50,50),random.randrange(-50,50)] mass = random.lognormvariate(1,6) radius = math.pow(mass,0.25) color = (random.randrange(0,255),random.randrange(0,255),random.randrange(0,255),0) return self(position,velocity,radius,mass,color)
def test(): import random data = [random.gauss(3.3, 2) for i in range(10000)] histogram(data) print '\n\n' data = [random.lognormvariate(0, .7) for i in range(10000)] histogram(data) print '\n\n' data = [random.paretovariate(100) for i in range(10000)] histogram(data) print '\n\n' data = [int(random.gauss(0, 2)) for i in range(10000)] histogram(data) print '\n\n'
def nextArrival(self, time): """Create a user object for the next user to arrive""" zone = self.whichTime(time) #print "Time zone",zone,"time",time,"since midnight", \ # float(time%(24*60*60))/(24*60*60) if zone != self.initZone: self.doTimeZoneInit(zone) loc = self.locDemand[self.chooseLocation()].getLocation() arrivalRate = self.totDemand * self.base_arrival_rate delta = random.expovariate(arrivalRate) life = random.lognormvariate(self.mu, self.sigma) #print "rate",arrivalRate,"delta",delta,"life",life thisuser = user.user(loc, time + delta, time + delta + life) return thisuser
def gen_log_entry(outf): x = random.lognormvariate(0, 1) if x < 2: response = 200 elif x < 3: response = 404 else: response = random.choice(httplib.responses.keys()) host = "127.0.0.1" timestamp = time.strftime("%d/%b/%Y %H:%M:%S") resource = "/index.html" method = "GET" logstr = "%(host)s - - [%(timestamp)s] \"%(method)s %(resource)s HTTP/1.1\" %(response)d\n" % locals() outf.write(logstr)
def callback_liveOut_pipe_in(named_count, state_uid, **kwargs): 'Handle something changing the value of the input pipe or the associated state uid' cache_key = _get_cache_key(state_uid) state = cache.get(cache_key) # If nothing in cache, prepopulate if not state: state = {} # Guard against missing input on startup if not named_count: named_count = {} # extract incoming info from the message and update the internal state user = named_count.get('user', None) click_colour = named_count.get('click_colour', None) click_timestamp = named_count.get('click_timestamp', 0) if click_colour: colour_set = state.get(click_colour, None) if not colour_set: colour_set = [(None, 0, 100) for i in range(5)] _, last_ts, prev = colour_set[-1] # Loop over all existing timestamps and find the latest one if not click_timestamp or click_timestamp < 1: click_timestamp = 0 for _, the_colour_set in state.items(): _, lts, _ = the_colour_set[-1] if lts > click_timestamp: click_timestamp = lts click_timestamp = click_timestamp + 1000 if click_timestamp > last_ts: colour_set.append((user, click_timestamp, prev * random.lognormvariate(0.0, 0.1)), ) colour_set = colour_set[-100:] state[click_colour] = colour_set cache.set(cache_key, state, 3600) return "(%s,%s)" % (cache_key, click_timestamp)
def create_txn(p, x, y_lines, boxes): """Create a new transaction, avoiding existing ones.""" x_minmax = x - p.post_radius, x + p.x_txn_offset + p.txn_radius # Filter boxes to the list which might intersect ours on the x axis. blocker_boxes = [] for box in boxes: bx_minmax, _ = box if intersects(x_minmax, bx_minmax): blocker_boxes.append(box) y_selected = None i = 0 while y_selected is None: if i >= p.max_attempts: return None i += 1 # Select a number of postings. num_postings = 0 while not (p.min_postings <= num_postings <= min( p.max_postings, len(y_lines))): num_postings = int(random.lognormvariate(1.0, 0.4)) # Select some subset of lines. Try to keep the lines together. first_line = random.randint(0, len(y_lines) - num_postings) lines = [first_line] probab_select = 0.3 line = first_line while len(lines) < num_postings: for line in range(first_line + 1, len(y_lines)): if random.random() < probab_select: lines.append(line) if len(lines) >= num_postings: break y_selected = [y_lines[line] for line in sorted(lines)] y_minmax = y_selected[0] - p.post_radius, y_selected[-1] + p.post_radius for box in blocker_boxes: _, by_minmax = box if intersects(y_minmax, by_minmax): y_selected = None break box = (x_minmax, y_minmax) return y_selected, box
def size_box_stream(bounds=(-10, -10, 10, 10)): """ Generate a stream of random bounding boxes where the corners are uniformly distributed Parameters: bounds - the bounds to generate in """ # Check our bounds xmin, ymin, xmax, ymax = check_bounds(bounds) # Generate random size distribution from priors while True: xcentre, ycentre = uniform(xmin, xmax), uniform(ymin, ymax) width, height = [lognormvariate(-1, 1) for _ in range(2)] yield (xcentre - width / 2, ycentre - height / 2, xcentre + width / 2, ycentre + height / 2)
def customer(env, number, pumps, line): print("%d arrives at gas station at %d" % (number, env.now)) #have the customer grab a spot in line myLine = line.request() yield myLine #grab an open pump and release the top spot in line myPump = pumps.request() yield myPump line.release(myLine) print("%d left the line and grabbed an open pump at %d" % (number, env.now)) #wait for a random amount of time determined by a log normal distribution of mean=5, shape=0.5, and scale of 1.5 to release the pump t = random.lognormvariate(1.5, 0.5) yield env.timeout(t) pumps.release(myPump) print("%d leaves at gas station at %d" % (number, env.now))
def randomXValue(tag, params): if tag == "normal": mu = number(params.get("mu", 0.0)) sigma = number(params.get("sigma", 1.0)) return XValue(lambda: random.normalvariate(mu, sigma)) if tag == "pnormal": mu = number(params.get("mu", 0.0)) sigma = number(params.get("sigma", 1.0)) return XValue(lambda: max(random.normalvariate(mu, sigma), 0.0)) elif tag == "uniform": mn = number(params.get("min", 0.0)) mx = number(params.get("max", 1.0)) return XValue(lambda: random.uniform(mn, mx)) elif tag == "triangular": low = number(params.get("low", 0.0)) high = number(params.get("high", 1.0)) mode = number(params.get("mode", 1.0)) return XValue(lambda: random.triangular(low, high, mode)) elif tag == "beta": alpha = number(params.get("alpha", 0.0)) beta = number(params.get("beta", 1.0)) return XValue(lambda: random.betavariate(alpha, beta)) elif tag == "gamma": alpha = number(params.get("alpha", 0.0)) beta = number(params.get("beta", 1.0)) return XValue(lambda: random.gammavariate(alpha, beta)) elif tag == "lognormal": mu = number(params.get("mu", 0.0)) sigma = number(params.get("sigma", 1.0)) return XValue(lambda: random.lognormvariate(mu, sigma)) elif tag == "vonmises": mu = number(params.get("mu", 0.0)) kappa = number(params.get("kappa", 1.0)) return XValue(lambda: random.vonmisesvariate(mu, kappa)) elif tag == "pareto": alpha = number(params.get("alpha", 0.0)) return XValue(lambda: random.paretovariate(alpha)) elif tag == "weibull": alpha = number(params.get("alpha", 0.0)) beta = number(params.get("beta", 1.0)) return XValue(lambda: random.weibullvariate(alpha, beta)) elif tag == "exponential": lamda = number(params.get("lambda", 1.0)) return XValue(lambda: random.expovariate(lamda)) else: raise InvalidXMLException("unsupported attribute value")
def run(self, fnprovider: AbstractFilenameProvider): plt.clf() visualize_from_file('../resources/w11/linreg.txt').save( fnprovider.get_filename('.gif', 'linreg', 'Linreg'), writer='imagemagick', fps=1) visualize_generated(lambda: random.uniform(-1, 1), random.random) \ .save(fnprovider.get_filename('.gif', 'even_dist', 'Even distribution'), writer='imagemagick', fps=1) visualize_generated(lambda: random.gauss(0, 1), random.random) \ .save(fnprovider.get_filename('.gif', 'gauss_dist', 'Gaussian distribution'), writer='imagemagick', fps=1) visualize_generated(lambda: random.gauss(0, 1), lambda: random.lognormvariate(0, 1)) \ .save(fnprovider.get_filename('.gif', 'gauss_log-normal_dist', 'Gaussian distribution with log-normal along the line'), writer='imagemagick', fps=1) return fnprovider.format_files()
def find_distributions(self, n, c, kind): """ Finds distribution functions """ if self.source(c, n, kind) == 'NoArrivals': return lambda: float('Inf') if self.source(c, n, kind)[0] == 'Uniform': return lambda: uniform( self.source(c, n, kind)[1], self.source(c, n, kind)[2]) if self.source(c, n, kind)[0] == 'Deterministic': return lambda: self.source(c, n, kind)[1] if self.source(c, n, kind)[0] == 'Triangular': return lambda: triangular( self.source(c, n, kind)[1], self.source(c, n, kind)[2], self.source(c, n, kind)[3]) if self.source(c, n, kind)[0] == 'Exponential': return lambda: expovariate(self.source(c, n, kind)[1]) if self.source(c, n, kind)[0] == 'Gamma': return lambda: gammavariate( self.source(c, n, kind)[1], self.source(c, n, kind)[2]) if self.source(c, n, kind)[0] == 'Lognormal': return lambda: lognormvariate( self.source(c, n, kind)[1], self.source(c, n, kind)[2]) if self.source(c, n, kind)[0] == 'Weibull': return lambda: weibullvariate( self.source(c, n, kind)[1], self.source(c, n, kind)[2]) if self.source(c, n, kind)[0] == 'Custom': P, V = zip(*self.source(c, n, kind)[1]) probs, values = list(P), list(V) return lambda: random_choice(values, probs) if self.source(c, n, kind)[0] == 'UserDefined': return lambda: self.check_userdef_dist(self.source(c, n, kind)[1]) if self.source(c, n, kind)[0] == 'Empirical': if isinstance(self.source(c, n, kind)[1], str): empirical_dist = self.import_empirical( self.source(c, n, kind)[1]) return lambda: random_choice(empirical_dist) return lambda: random_choice(self.source(c, n, kind)[1]) if self.source(c, n, kind)[0] == 'TimeDependent': return lambda t: self.check_timedependent_dist( self.source(c, n, kind)[1], t)
def __init__(self, startpos: list, speed: list, name: str, color: tuple, expect_life: int = 200): Particle.__init__(self, startpos, speed, 3) self.name = name if not name in Cytokine.surface_dict: newcolor = color Cytokine.surface_dict[self.name] = self.image.copy() Cytokine.surface_dict[self.name].fill(newcolor) self.image = Cytokine.surface_dict[self.name] sigma = 0.3 mu = math.log(expect_life) - sigma**2 / 2 self.life = int(random.lognormvariate(mu, sigma)) #of frames until death
def load_gen(load_type='nonuniform', demand_value=(1,0)): """ this function generates load based on the load type specification demand_value = (a,b) """ if load_type == 'nonuniform': mean, std = demand_value load = random.lognormvariate(mean, std)/1000000 #print "LOAD", load #print "LOGNORMAL", load elif load_type == 'nonuniformh': fixed, error = demand_value load1 = fixed + random.random() * error load2 = fixed - random.random() * error load = random.choice([load1, load2]) load = round(load, 10) return load
def addNoise(im, mode, value): ''' 添加噪声 :param im: :param mode: :param value: :return: ''' draw = ImageDraw.Draw(im) for i in range(0, list(im.size)[0]): for j in range(0, list(im.size)[1]): if mode == "uniform": rnd = random.uniform(value[0], value[1]) elif mode == "normal": #UNIFORM噪声 rnd = random.gauss(value[0], value[1]) elif mode == "lognormal": rnd = random.lognormvariate(value[0], value[1]) elif mode == "negexp": rnd = random.expovariate(value[0], value[1]) elif mode == "gamma": rnd = random.gammavariate(value[0], value[1]) elif mode == "beta": rnd = random.betavariate(value[0], value[1]) elif mode == "pareto": rnd = random.paretovariate(value[0]) elif mode == "weibull": rnd = random.weibullvariate(value[0], value[1]) if im.mode == "RGB": color = list(im.getpixel((i, j))) color[0] = color[0] + rnd color[1] = color[1] + rnd color[2] = color[2] + rnd point = [i, j] draw.point(point, tuple(color)) elif im.mode == "L": color = im.getpixel((i, j)) color = color + rnd point = [i, j] draw.point(point, color) else: print "File type not supported!" sys.exit(1) del draw return im
def Serve(self, customer): customer.waitTime = self.env.now - customer.timeOfArrival customer.startTime = self.env.now #customer.serviceTime = random.normalvariate(self.serviceTime,) #customer.serviceTime = random.expovariate(1.0/self.serviceTime) mu = self.serviceTime std = 553.867816 mu2 = math.log(mu) - 0.5 * math.log(math.pow(std / mu, 2) + 1) std2 = 0.716256793 customer.serviceTime = random.lognormvariate(mu2, std2) yield self.env.timeout(customer.serviceTime) self.queueSize -= 1 customer.departureTime = self.env.now self.customers.append(customer)
def main(): mat = [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8], [5, 6, 7, 8, 9]] ans = [[5, 4, 3, 2, 1], [6, 5, 4, 3, 2], [7, 6, 5, 4, 3], [8, 7, 6, 5, 4], [9, 8, 7, 6, 5]] rotate_matrix(mat) assert mat == ans mat = [] for idx in range(4): mat.append([314 * random.lognormvariate(0, 1) for _ in range(4)]) print("Original matrix: ", mat) rotate_matrix(mat) print("Rotated matrix: ", mat)
def create_mix(files): """ Compute a relative abundance of each genome using a log-norm distribution. The distribution is centered on 1 with a standard deviation of 2 (from CAMISIM). A relative abundance of 1 significate that the genome associated must have a coverage equivalent to the average coverage. @args files All the files to compute abundances. @return A dictionnary associating each filename to a relative abundance. """ relative_dist = {} for f in files: relative_dist[f] = random.lognormvariate(1, 1.5) # Normalise to center on 1 vals = relative_dist.values() avg = sum(vals) / len(vals) relative_dist = {k: v / avg for k, v in relative_dist.items()} return relative_dist
def generate_pay_requests(requests_per_second, time, mu=10**6): "time in seconds" muLog = math.log(mu) sigma = math.log(10) a = (int(random.lognormvariate(muLog, sigma)) for i in itertools.count()) def time_generator(): time = 0 while True: time += random.expovariate(requests_per_second) yield time a = map(lambda amount, time: { "amount": amount, "time": time }, a, time_generator()) a = itertools.takewhile(lambda v: v["time"] < time, a) return a
def random(self, oldVal, minVal, maxVal, candidate=None): if (self.nwkdeFlag): if oldVal == [4, 4, 4, 4]: # change initial value to something useful oldVal = [0.3182, 134.3503, 5.0312, 633.3333] newVal = [0] * len(oldVal) for j in xrange(0, len(oldVal)): successFlag = False for z in xrange(config.rand_retries): v = float(oldVal[j] * random.lognormvariate(0, 1)) if v >= minVal[j] and v <= maxVal[j] and oldVal[j] != v: newVal[j] = v successFlag = True break if not successFlag: raise MutateFailed("lognorm random gen failed") return newVal
def start(): while True: try: print('new request is sent') body = { 'data': [], 'dimensions': ["cpu", "traffic", "ram", "kinergy", "io"] } for resource_id in range(5): for _ in range(50): temp_data_point = [] for i in range(len(body['dimensions'])): # i = 10 if i == 0: temp_data_point.append(gauss( randint(0, 5 * i), 35)) elif i == 1: temp_data_point.append(gauss( randint(0, 5 * i), 35)) elif i == 2: temp_data_point.append(gauss( randint(0, 5 * i), 35)) elif i == 3: temp_data_point.append(gauss( randint(0, 5 * i), 35)) elif i == 4: temp_data_point.append(gauss( randint(0, 5 * i), 35)) elif i == 5: temp_data_point.append(gauss( randint(0, 5 * i), 35)) else: temp_data_point.append(lognormvariate(10, 3)) body['data'].append(temp_data_point) post(URL + str(resource_id), data=dumps(body), headers=headers) sleep(1) except Exception as e: print(e) sleep(5) else: pass finally: pass
def attack(self, target): 'Country attacks another country.' print('{0} is attacking {1}!'.format(self.name, target.name)) seed() # Damage mostly 1-3, theoretical range is 0-12 damage = int(lognormvariate(1, 0.5)) # This may change industry_drain = damage * 3 // 2 if industry_drain > self.resources['industry']: industry_drain = self.resources['industry'] self.resources['industry'] = max(0, self.resources['industry'] - industry_drain) target.resources['population'] -= damage if damage == 0: # Randomized statements statement = [ '{0} tried to attack {1}, but failed!'.format(self.name, target.name), '{0} saw it coming a mile away!'.format(target.name), 'A spy warned {0} of the attack!'.format(target.name) ] print(choice(statement), end=' ') print('No one was killed.') elif damage <= 4: print('{0} attacked {1}! {2} thousand were killed!'.format(self.name, target.name, damage)) elif damage <= 8: # Randomized statements statement = [ '{0} launched missiles at {1}!'.format(self.name, target.name), '{0} surprise-attacked {1}!'.format(self.name, target.name), ] print(choice(statement), end=' ') print('{0} thousand were killed!'.format(damage)) else: print('A devastating nuclear attack devastated {0}'.format(target.name)) print('{0} thousand were wiped out!!!'.format(damage)) if self.identity == 'P': print('Your industrial resources are now {0} thousand tons.'.format( self.resources['industry'])) relationship_drain = 5 + damage * 2 self.__relationships__[identity_key(self, target)] -= relationship_drain
def SteadierComSample(community, n=10, growth=None, obj_frac=1, proteome=False, w_e=0.001, w_r=0.5, constraints=None): solver = build_problem(community, proteome=proteome, w_e=w_e, w_r=w_r) objective = {community.merged_model.biomass_reaction: 1} if growth is None: sol = binary_search(solver, objective, constraints=constraints) growth = obj_frac * sol.values[community.merged_model.biomass_reaction] solver.update_growth(growth) sols = [] for _ in range(n): objective = {f"x_{org_id}": lognormvariate(0, 1) for org_id in community.organisms} sol = solver.solve(objective, minimize=False, constraints=constraints) sols.append(CommunitySolution(community, sol.values)) return sols
def _scroll_up_like_human(driver: WebDriver, step=50, wait=0.03, verbose=False): pos = driver.execute_script('return window.pageYOffset;') if verbose: print("pos0: ", pos) prev_yoffset = -1 while True: driver.execute_script(f"window.scrollTo(0,{pos})") pos -= step * random.lognormvariate(0, 0.1) _human_wait(wait) yoffset = driver.execute_script('return window.pageYOffset;') if yoffset == prev_yoffset or should_stop(): break prev_yoffset = yoffset
def _trigger_func(self, stream_id): point_def = ctd_stream_definition(stream_id=stream_id) point_constructor = PointSupplementConstructor( point_definition=point_def) while True: length = 1 c = [random.uniform(0.0, 75.0) for i in xrange(length)] t = [random.uniform(-1.7, 21.0) for i in xrange(length)] p = [random.lognormvariate(1, 2) for i in xrange(length)] lat = [random.uniform(-90.0, 90.0) for i in xrange(length)] lon = [random.uniform(0.0, 360.0) for i in xrange(length)] tvar = [self.last_time + i for i in xrange(1, length + 1)] self.last_time = max(tvar) point_id = point_constructor.add_point(time=tvar, location=(lon[0], lat[0])) point_constructor.add_point_coverage(point_id=point_id, coverage_id='temperature', values=t) point_constructor.add_point_coverage(point_id=point_id, coverage_id='pressure', values=p) point_constructor.add_point_coverage(point_id=point_id, coverage_id='conductivity', values=c) ctd_packet = point_constructor.get_stream_granule() log.info('SimpleCtdPublisher sending %d values!' % length) self.publisher.publish(ctd_packet) time.sleep(2.0)
def funs(): # seed(a=None, version=2) // 初始换生成器的随机数 random.seed() random.getstate() # 获取生成器内部状态 random.setstate(random.getstate()) # 设置生成器内部状态 # 获取随机数 num = random.getrandbits(8) # 获取x位(bit)随机整数 # randrange(stop) / randrange(start, stop[, step]) // 生成随机整数 num = random.randrange(0, 100, 2) # [0,100)产生的随机整数+2 # randint(a, b) == randrange(a, b + 1) // [a, b] num = random.randint(0, 1) fnum = random.random() # 获取浮点随机数 [0.0, 1.0) fnum = random.uniform(1, 2) # 获取指定范围内的浮点随机数 [1.0, 2.0) # triangular(low, high, mode) // 获取随机浮点数, low低边界(默认0),high高边界(默认1),模式(默认边界中点) fnum = random.triangular(0, 1, 1.5) # betavariate(alpha, beta) // Beta分布,[0.0, 1.0] fnum = random.betavariate(1, 1) # expovariate(lambd) // 指数分布, lambd返回整,值[0, +∞]; lanbd返回负,值[-∞, 0] fnum = random.expovariate( (lambda arg1, arg2: arg1 + arg2)(1, 2)) # lambd返回值越小,获得值越大 # gammavariate(alpha, beta) // 伽玛分布 fnum = random.gammavariate(1, 1) # gauss(mu, sigma) // 高斯分布 mu:平均值, sigma:标准偏差 fnum = random.gauss(1, 1) # lognormvariate(mu, sigma) // 对数正态分布,获得平均值mu和标准偏差sigma的正态分布; mu:任何值,sigma:>0。 fnum = random.lognormvariate(1, 1) # normalvariate(mu, sigma) // 正态分布, mu是平均值, sigma是标准偏差 fnum = random.normalvariate(1, 1) # vonmisesvariate(mu, kappa) // 冯米塞斯分布的随机数。mu:平均角度(弧度[0, 2*pi]), kappa:集中程度>=0 fnum = random.vonmisesvariate(1, 1) # paretovariate(alpha) // 帕累托分布, alpha:形状 fnum = random.paretovariate(1) # weibullvariate(alpha, beta) // 韦伯分布, alpha:缩放, beta:形状 fnum = random.weibullvariate(1, 1) elem = random.choice(lists) # 非空序列中取出随机元素, 序列为空抛IndexError elems = random.sample(lists, 3) # 从列表中随机获取3个元素, 范围>列表大小,抛ValueError # 打乱顺序 random.shuffle(lists) # 打乱序列
def random_mutation(mem): action = randrange(3) if action == 0: newptr = 0 elif action == 1: kind = choice([POINTER_BLOCK, DATA_BLOCK]) newsize = 4 + int(100 * lognormvariate(0, 1)) newptr = allocate(mem, kind, newsize, gc=False) if newptr == 0: return False elif action == 2: newptr = random_block(mem) block = random_block(mem, only_pointer_blocks=True) size = block_size(mem, block) which = randrange(block, block + size - size % 4, 4) mem[which] = 0 mem(24)[which + 1] = newptr return True
def generate_learn_rate(): """ Generate learning rate. Edited to capture a wider range of rates around the original 1e-4 Generate a random float between 0.0 and 0.01. We add +1e-5 so that the function can never return a value of 0. """ # choice = random.randrange(4) # if (choice == 0): # return round((random.random() / 1e2) + 1e-6, 6) # elif (choice == 1): # return round((random.random() / 1e3 + 1e-6), 6) # elif (choice == 2): # return round((random.random() / 1e4 + 1e-6), 6) # elif (choice == 3): # return round((random.random() / 1e5 + 1e-6), 6) return round(random.lognormvariate(0, 1) / 1e4, 6)
def generateRandomNumber( distribution, duration ): randomNumber = -1 if distribution == "Lognormal": mu = 4 sigma = 1 randomNumber = random.lognormvariate(mu, sigma) elif distribution == "Exponential": lam = 0.02 randomNumber = random.expovariate(lam) elif distribution == "Poisson": lam = 10 randomNumber = numpy.random.poisson(lam) elif distribution == "Weibull": scale = 4 shape = 0.6 randomNumber = random.weibullvariate(scale, shape) return int(randomNumber)
def get_next(self): """ Pops the next request from the queue and a request/response pair for each url in the request object """ if self.sleep_between: t = lognormvariate(self._mu, self._sigma) / self._div sleep(t) self.active_request = request = self.request_queue.pop(0) for url in request.urls: self.active_response = response = self.sess.get(url) # check for robot detection, alert user if self._check_for_robot(): ans = input( 'Google has detected a robot. Do you want to solve the captcha? ([y]/n):' ) self._input_handler(ans) self.active_response = response = self.sess.current_response # response.html.lxml.url = url yield request, response
def _scroll_to_y(driver: WebDriver, target_y: int, step=70, verbose=False): # print( f'target_t = {target_y}') while True: cur_y = driver.execute_script('return window.pageYOffset') if verbose: print(f'scroll_to_y: cur_y: {cur_y}') if abs(target_y - cur_y) < 50: driver.execute_script(f"window.scrollTo(0, {target_y})") break else: direction = +1.0 if (target_y - cur_y) >= 0 else -1.0 next_y = int(cur_y + direction * step * random.lognormvariate(0, 0.2)) # print(cur_y, next_y) driver.execute_script(f"window.scrollTo(0, {next_y})") if should_stop(): break _human_wait(0.05)
def _add_initial_log_distribution(list_population, mu, sigma): """ Adding a initial distribution @attention: Values for first sample @param list_population: Main list for all distributions @type : list[list[float]] @param mu: Mean @type mu: float @param sigma: standard deviation @type sigma: float @return: Nothing @rtype: None """ assert isinstance(list_population, list) assert isinstance(mu, (float, int, long)) assert isinstance(sigma, (float, int, long)) for index in xrange(len(list_population)): list_population[index][0] = random.lognormvariate(mu, sigma)