def calculate(self): col = TaxSlabs[self.filling] i = 0 prev = 0.0 current = 0.0 income = utils.sum(self.income) self.taxes['Federal Income Tax'] = 0.0 for rate in TaxSlabs["rates"]: current = col[i] i = i + 1 if (income >= current): residual = current - prev else: residual = income - prev self.nominal = rate self.taxes['Federal Income Tax'] += (rate/100) * residual prev = current if (prev > income): break # Social Security Tax adjusted_income = min(137700, income) self.taxes['Social Security Tax'] = 0.062 * adjusted_income self.taxes['Medicare Tax'] = 0.0145 * income self.total = utils.sum(self.taxes) # adjust the credits self.total -= utils.sum(self.credits)
def castRay(self, origin, direction, recursion=0): material, intersect = self.sceneIntersect(origin, direction) if material is None or recursion >= MAX_RECURSION_DEPTH: return self.currentColor # Si el rayo no golpeo nada o si llego al limite de recursion lightDir = norm(sub(self.light.position, intersect.point)) lightDistance = length(sub(self.light.position, intersect.point)) offsetNormal = mul(intersect.normal, 1.1) shadowOrigin = sub( intersect.point, offsetNormal) if dot(lightDir, intersect.normal) < 0 else sum( intersect.point, offsetNormal) shadowMaterial, shadowIntersect = self.sceneIntersect( shadowOrigin, lightDir) shadowIntensity = 0 if shadowMaterial and length(sub(shadowIntersect.point, shadowOrigin)) < lightDistance: shadowIntensity = 0.9 intensity = self.light.intensity * max( 0, dot(lightDir, intersect.normal)) * (1 - shadowIntensity) reflection = reflect(lightDir, intersect.normal) specularIntensity = self.light.intensity * (max( 0, -dot(reflection, direction))**material.spec) if material.albedo[2] > 0: reflectDir = reflect(direction, intersect.normal) reflectOrigin = sub(intersect.point, offsetNormal) if dot( reflectDir, intersect.normal) < 0 else sum( intersect.point, offsetNormal) reflectedColor = self.castRay(reflectOrigin, reflectDir, recursion + 1) else: reflectedColor = self.currentColor if material.albedo[3] > 0: refractDir = refract(direction, intersect.normal, material.refractionIndex) refractOrigin = sub(intersect.point, offsetNormal) if dot( refractDir, intersect.normal) < 0 else sum( intersect.point, offsetNormal) refractedColor = self.castRay(refractOrigin, refractDir, recursion + 1) else: refractedColor = self.currentColor diffuse = material.diffuse * intensity * material.albedo[0] specular = Color(255, 255, 255) * specularIntensity * material.albedo[1] reflected = reflectedColor * material.albedo[2] refracted = refractedColor * material.albedo[3] return diffuse + specular + reflected + refracted
def get_kl(self, other): a0 = self.logits - U.max(self.logits, axis=-1, keepdims=True) a1 = other.logits - U.max(other.logits, axis=-1, keepdims=True) ea0 = tf.exp(a0) ea1 = tf.exp(a1) z0 = U.sum(ea0, axis=-1, keepdims=True) z1 = U.sum(ea1, axis=-1, keepdims=True) p0 = ea0 / z0 return U.sum(p0 * (a0 - tf.log(z0) - a1 + tf.log(z1)), axis=-1)
def average_best_evals(self, n): """ Return the average of the n last best evaluations of the goal function. This is a fast function which uses the last evaluations already done by the SPSA algorithm to return an approximation of the current goal value (note that we do not call the goal function another time, so the returned value is an upper bound of the true value). """ assert (self.best_count > 0), "not enough evaluations in average_evaluations!" if n <= 0: n = 1 if n > 1000: n = 1000 if n > self.best_count: n = self.best_count sum_eval = 0.0 sum_theta = utils.linear_combinaison(0.0, self.theta0) for i in range(n): j = ((self.best_count - 1) % 1000) - i if j < 0: j += 1000 if j >= 1000: j -= 1000 sum_eval += self.best_eval[j] sum_theta = utils.sum(sum_theta, self.best_theta[j]) # return the average alpha = 1.0 / (1.0 * n) return (alpha * sum_eval, utils.linear_combinaison(alpha, sum_theta))
def summarize(sensor, timeframe, start, end): # prepare the database schema to use if timeframe == "hour": key_to_read = sensor["db_sensor"] key_to_write = sensor["db_sensor"] + ":hour" elif timeframe == "day": key_to_read = sensor["db_sensor"] + ":hour:avg" key_to_write = sensor["db_sensor"] + ":day" # retrieve from the database the data based on the given timeframe data = db.rangebyscore(key_to_read, start, end, withscores=True) # split between values and timestamps values = [] timestamps = [] for i in range(0, len(data)): timestamps.append(data[i][0]) values.append(data[i][1]) # calculate the derived values timestamp = start min = avg = max = rate = sum = count = count_unique = "-" if "avg" in sensor["summarize"] and sensor["summarize"]["avg"]: # calculate avg avg = utils.avg(values) db.deletebyscore(key_to_write + ":avg", start, end) db.set(key_to_write + ":avg", avg, timestamp) if "min_max" in sensor["summarize"] and sensor["summarize"]["min_max"]: # calculate min min = utils.min(values) db.deletebyscore(key_to_write + ":min", start, end) db.set(key_to_write + ":min", min, timestamp) # calculate max max = utils.max(values) db.deletebyscore(key_to_write + ":max", start, end) db.set(key_to_write + ":max", max, timestamp) if "rate" in sensor["summarize"] and sensor["summarize"]["rate"]: # calculate the rate of change rate = utils.velocity(timestamps, values) db.deletebyscore(key_to_write + ":rate", start, end) db.set(key_to_write + ":rate", rate, timestamp) if "sum" in sensor["summarize"] and sensor["summarize"]["sum"]: # calculate the sum sum = utils.sum(values) db.deletebyscore(key_to_write + ":sum", start, end) db.set(key_to_write + ":sum", sum, timestamp) if "count" in sensor["summarize"] and sensor["summarize"]["count"]: # count the values count = utils.count(values) db.deletebyscore(key_to_write + ":count", start, end) db.set(key_to_write + ":count", count, timestamp) if "count_unique" in sensor["summarize"] and sensor["summarize"][ "count_unique"]: # count the unique values count_unique = utils.count_unique(values) db.deletebyscore(key_to_write + ":count_unique", start, end) db.set(key_to_write + ":count_unique", count_unique, timestamp) log.debug("[" + sensor["module_id"] + "][" + sensor["group_id"] + "][" + sensor["sensor_id"] + "] (" + utils.timestamp2date(timestamp) + ") updating summary of the " + timeframe + " (min,avg,max,rate,sum,count,count_unique): (" + str(min) + "," + str(avg) + "," + str(max) + "," + str(rate) + "," + str(sum) + "," + str(count) + "," + str(count_unique) + ")")
def report(self): utils.report("Debt payments (monthly)", self.payment, utils.sum(self.payment)) if (len(self.payment.items()) > 1): utils.piechart("Payments", "Your debt payments", [n for n, v in self.payment.items()], [v for n, v in self.payment.items()])
def side(self, v0, v1, v2, origin, direction): v0v1 = sub(v1, v0) v0v2 = sub(v2, v0) N = cross(v0v1, v0v2) raydirection = dot(N, direction) if abs(raydirection) < 0.0001: return None d = dot(N, v0) t = (dot(N, origin) + d) / raydirection if t < 0: return None P = sum(origin, mul(direction, t)) U, V, W = barycentric(v0, v1, v2, P) if U < 0 or V < 0 or W < 0: return None else: return Intersect(distance = d, point = P, normal = norm(N))
def __init__(self, pattern = "", seeds_dict = {}): self.pattern = pattern self.strlen = len(pattern) self.num_of_seeds = len(seeds_dict) self.seeds_dict = seeds_dict self.max_seed = max(self.seeds_dict.values()) self.avg_seed = utils.divide(utils.sum(self.seeds_dict.values()), self.num_of_seeds)
def rayIntersect(self, orig, dir): # t = (( position - origRayo) dot normal) / (dirRayo dot normal) denom = dot(dir, self.normal) if abs(denom) > 0.0001: t = dot(self.normal, sub(self.position, orig)) / denom if t > 0: # P = O + tD hit = sum(orig, mul(dir, t)) return Intersect(distance = t, point = hit, normal = self.normal) return None
def Gaussian_Diag(mean, logsd): class o(object): log2pi = float(np.log(2 * np.pi)) pass @staticmethod def log_like_i(x): return -0.5 * (o.log2pi + 2.0 * logsd + ((x - mean)**2) / torch.exp(2.0 * logsd)) @staticmethod def sample(eps): if eps is None: eps = torch.zeros_like(mean).normal_() return mean + torch.exp(logsd) * eps o.logp = lambda x: utils.sum(o.log_like_i(x), dims=[1, 2, 3]) return o
def average_best_evals(self, n): ''' Return the average of the n last best evaluation of the goal function. ''' if n <= 0: n = 1 if n > 1000: n = 1000 if n > self.best_count: n = self.best_count sum_eval = 0.0 sum_theta = utils.linear_combinaison(0.0, self.theta0) for i in range(n): j = ((self.best_count - 1) % 1000) - i if j < 0: j += 1000 if j >= 1000: j -= 1000 sum_eval += self.best_eval[j] sum_theta = utils.sum(sum_theta, self.best_theta[j]) #return the average alpha = 1.0 / (1.0 * n) return (alpha * sum_eval, utils.linear_combinaison(alpha, sum_theta))
def rayIntersect(self, origin, direction): L = sub(self.center, origin) tca = dot(L, direction) l = length(L) d2 = l ** 2 - tca ** 2 if d2 > self.radius ** 2: return None thc = (self.radius ** 2 - d2) ** 0.5 t0 = tca - thc t1 = tca + thc if t0 < 0: t0 = t1 if t0 < 0: return None hit = sum(origin, mul(direction, t0)) normal = norm(sub(hit, self.center)) return Intersect( distance=t0, point=hit, normal=normal )
def average_evaluations(self, n): """ Return the average of the n last evaluations of the goal function. This is a fast function which uses the last evaluations already done by the SPSA algorithm to return an approximation of the current goal value (note that we do not call the goal function another time, so the returned value is an upper bound of the true value). """ assert (self.history_count > 0), "not enough evaluations in average_evaluations!" n = max(1, min(1000, n)) n = min(n, self.history_count) # print(f'n = {n}') # print(f'hist_cnt = {self.history_count}') sum_eval = 0.0 sum_theta = utils.linear_combinaison(0.0, self.theta0) for i in range(n): j = ((self.history_count - 1) % 1000) - i if j < 0: j += 1000 if j >= 1000: j -= 1000 # print(f'i={i}, j={j}, hist_cnt: {self.history_count}, hist_eval[{j}] = {self.history_eval[j]}') sum_eval += self.history_eval[j] sum_theta = utils.sum(sum_theta, self.history_theta[j]) # return the average alpha = 1.0 / (1.0 * n) return (alpha * sum_eval, utils.linear_combinaison(alpha, sum_theta))
def __init__(self, position, size, material): self.position = position self.size = size self.material = material self.planes = [] halfSize = size / 2 self.planes.append( Plane(sum(position, V3(halfSize, 0, 0)), V3(1, 0, 0), material)) self.planes.append( Plane(sum(position, V3(-halfSize, 0, 0)), V3(-1, 0, 0), material)) self.planes.append( Plane(sum(position, V3(0, halfSize, 0)), V3(0, 1, 0), material)) self.planes.append( Plane(sum(position, V3(0, -halfSize, 0)), V3(0, -1, 0), material)) self.planes.append( Plane(sum(position, V3(0, 0, halfSize)), V3(0, 0, 1), material)) self.planes.append( Plane(sum(position, V3(0, 0, -halfSize)), V3(0, 0, -1), material))
def __init__(self, sess, args, x_BO, y_targ_B, y_pred_BC, weights, new_weights_v, update_wts_op, loss, num_train, data_mb_list): """ The updater for Hamiltonian Monte Carlo. Formulas, where `pos` are the (neural network) model parameters: > H(pos,mom) = U(pos) + K(mom) > U(pos) = - log P(pos,data) = - log P(pos) - log P(x1,...,xn|pos) = - (log P(pos1) + ... + log P(posk)) - \sum_i log P(xi|pos) with log P(posi) = -0.5 * plambdai * ||posi||_2^2 > K(mom) = 0.5 * ||mom||_2^2 Normal Metropolis test: accept if u < exp(H_old-H_new), otherwise reject. Thus, with equality (or if H_old is larger) we always accept. Reject more often if H_new > H_old. Note: be careful about where I put in the temperature. It should be U(theta)/T = U(pos)/T but I sometimes compute the components separately in later code. """ self.sess = sess self.args = args self.weights = weights self.update_wts_op = update_wts_op self.loss = loss self.y_pred_BC = y_pred_BC self.num_train = num_train self.data_mb_list = data_mb_list self.num_train_mbs = len(self.data_mb_list['X_train']) T = args.temperature # Placeholders self.x_BO = x_BO self.y_targ_B = y_targ_B self.new_weights_v = new_weights_v self.hparams = tf.placeholder(shape=[None], name='hparams', dtype=tf.float32) # Hyperparameters for HMC self.h_updaters = [] for w in self.weights: hp = HyperParams(alpha=args.gamma_alpha, beta=args.gamma_beta) self.h_updaters.append( HyperUpdater(w, args, hp, self.sess, self.num_train)) # HMC: define U(pos) as that's what we use for gradients. prior_l = [] # Obviously depends on our Gaussian assumptions. for idx, w in enumerate(self.weights): prior_l.append(self.hparams[idx] * U.sum(tf.square(w))) self.neg_logprior = (0.5 * U.sum(prior_l)) / T self.nb = tf.shape(self.x_BO)[0] self.logprob_BC = tf.nn.log_softmax(self.y_pred_BC) self.logprob_B = U.fancy_slice_2d(self.logprob_BC, tf.range(self.nb), self.y_targ_B) self.logprob_B /= T # temperature here self.logprob_sum = U.sum(self.logprob_B) # *Negation* as we want the negative log probs. Multiply by N later. self.neg_logprob = -U.mean(self.logprob_B) self.U = self.neg_logprior + (self.num_train * self.neg_logprob) self.U_grads = tf.gradients(self.U, self.weights) # Finally, the Metropolis test. params = { 'sess': self.sess, 'args': self.args, 'weights': self.weights, 'data_mb_list': self.data_mb_list, 'x_BO': self.x_BO, 'y_targ_B': self.y_targ_B, 'new_weights_v': self.new_weights_v, 'hparams': self.hparams, 'neg_logprior': self.neg_logprior, 'logprob_sum': self.logprob_sum, 'update_wts_op': self.update_wts_op } if args.algo_mh == 'mhnormal': self.mhtest = MHNormal(params) elif args.algo_mh == 'mhminibatch': self.mhtest = MHMinibatch(params) elif args.algo_mh == 'mhsublhd': self.mhtest = MHSubLhd(params) elif args.algo_mh == 'austeremh-c': self.mhtest = AustereMH(params, conservative=True) elif args.algo_mh == 'austeremh-nc': self.mhtest = AusteremH(params, conservative=False) else: raise ValueError()
def get_entropy(self): return U.sum(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.logits, labels=self.ps), axis=-1)
def test_ab(self): a = 5 b = 2 self.assertEquals(utils.sum(a,b), a + b)
def get_neglogp(self, x): return U.sum(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.logits, labels=tf.to_float(x)), axis=-1)
def get_kl(self, other): return U.sum(tf.nn.sigmoid_cross_entropy_with_logits(logits=other.logits, labels=self.ps), axis=-1) - U.sum(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.logits, labels=self.ps), axis=-1)
def test_ab0(self): self.assertEquals(utils.sum(0,0), 0)
def maxdiff(indices, values, size): evals = values.exp() sums = utils.sum(indices, evals, size) diff = (1.0 - sums).abs() return diff.max()
def get_entropy(self): a0 = self.logits - U.max(self.logits, axis=-1, keepdims=True) ea0 = tf.exp(a0) z0 = U.sum(ea0, axis=-1, keepdims=True) p0 = ea0 / z0 return U.sum(p0 * (tf.log(z0) - a0), axis=-1)
def get_neglogp(self, x): return 0.5 * U.sum(tf.square((x - self.mean) / self.std), axis=-1) \ + 0.5 * np.log(2.0 * np.pi) * tf.to_float(tf.shape(x)[-1]) \ + U.sum(self.logstd, axis=-1)
import utils utils.hello() print(utils.constant) print(utils.sum(1, 2)) # print(utils.div()) # работает через командную строку
def calculate(self): for n, v in self.fixed.items(): self.payment[n] = utils.payment(v[0], v[1], v[2]) for n, v in self.unknown.items(): self.payment[n] = utils.payment(v[0], v[1], v[2]) return utils.sum(self.payment)
''' ***************** Date: 2020-04-16 Author: Allen ***************** ''' import utils print(utils.name) result = utils.sum(10, 20) print(result) p = utils.Person('张三', 30) from utils import name, sum print(name) result = sum(10, 20) from utils import * print(name) result = sum(10, 20) p = Person('林青霞', 60) from hello import name from hi import name print(name) from hello import name as hello_name
def get_monthly(self): return utils.sum(self.payment)
def softmax_naive(indices, values, size): evals = values.exp() sums = utils.sum(indices, evals, size) return evals / sums
def add(self, i, t, d, e): self.data["income"] = i.get_monthly() self.data["tax"] = -(t.get_monthly()) self.data["debt payment"] = -(d.get_monthly()) self.data["expenses"] = -(e.get_monthly()) self.surplus = utils.sum(self.data)
def get_kl(self, other): assert isinstance(other, DiagGaussianPd) return U.sum(other.logstd - self.logstd + (tf.square(self.std) + tf.square(self.mean - other.mean)) / (2.0 * tf.square(other.std)) - 0.5, axis=-1)
def add_expense(self, name, value): self.data[name] = -(value) self.surplus = utils.sum(self.data)
def get_entropy(self): return U.sum(self.logstd + .5 * np.log(2.0 * np.pi * np.e), axis=-1)
def count_cooc_over_freq(self, list, cache=False): cooc, frequencies = self.count_cooc_and_freq(list, cache) return utils.count_num_over_denom(cooc, utils.sum(frequencies))
def report(self): utils.report("Taxes", self.taxes, self.total) if (len(self.credits.items()) != 0): utils.report("Tax credits", self.credits, utils.sum(self.credits))