How to use by_operation method in localstack

Best Python code snippet using localstack_python

main.py

Source:main.py Github

copy

Full Screen

1import numpy as np2import matplotlib.pyplot as plt3import scipy.interpolate as interpolate4from scipy.optimize import curve_fit5import sys6class AsymmetricData:7 def __init__(self, mu=10.0, sigma_n=1.0, sigma_p=1.0, N=10000, confidence=1.0, creation_type='by_constructor', data=[]):8 """9 :param mu: Mode of the distribution, the most probable value10 :param sigma_n: Pegative sigma11 :param sigma_p: Positive sigma12 :param N: Sample size13 """14 self.mu = mu15 self.confidence = confidence # sigma16 self.sigma_n, self.sigma_p = sigma_n, sigma_p17 self.sigma2_n, self.sigma2_p = None, None18 self.sigma3_n, self.sigma3_p = None, None19 self.N = int(N)20 self.creation_type = creation_type21 if not any(data):22 self.data = np.asarray([])23 else:24 self.data = np.asarray(data)25 #self.creation_type = 'by_operation'26 self.bin_value = 5027 if str(self.creation_type) == 'by_constructor':28 if confidence == 1.0:29 self.sigma_n, self.sigma_p = sigma_n, sigma_p30 self.sigma2_n, self.sigma2_p = self.convert_from_1_sigma(self.mu, sigma_n, sigma_p, 2.0)31 self.sigma3_n, self.sigma3_p = self.convert_from_1_sigma(self.mu, sigma_n, sigma_p, 3.0)32 elif confidence == 2.0:33 self.sigma_n, self.sigma_p = self.convert_to_1_sigma(self.mu, sigma_n, sigma_p, 2.0)34 self.sigma2_n, self.sigma2_p = sigma_n, sigma_p35 self.sigma3_n, self.sigma3_p = self.convert_from_1_sigma(self.mu, self.sigma_n, self.sigma_p, 3.0)36 elif confidence == 3.0:37 self.sigma_n, self.sigma_p = self.convert_to_1_sigma(self.mu, sigma_n, sigma_p, 3.0)38 self.sigma2_n, self.sigma2_p = self.convert_from_1_sigma(self.mu, self.sigma_n, self.sigma_p, 2.0)39 self.sigma3_n, self.sigma3_p = sigma_n, sigma_p40 else:41 raise ValueError42 self.x_limits = [self.mu - 5.0*self.sigma_n, self.mu + 5.0*self.sigma_p]43 self.x_values = np.linspace(self.x_limits[0], self.x_limits[1], self.N)44 self.norm = 1.045 self.norm = self.calculate_norm()46 self.pdf_values = np.asarray(self.pdf(self.x_values))47 self.cdf_values = self.calculate_cdf_values()48 self.cdf = self.calculate_cdf()49 self.inverse_cdf = self.calculate_inverse_cdf()50 self.log_likelihood_values = self.log_likelihood(self.x_values)51 self.generate()52 elif str(self.creation_type) == 'by_operation':53 self.N = self.data.size54 self.fit()55 #self.sigma_n, self.sigma_p = self.estimate()56 self.sigma2_n, self.sigma2_p = self.convert_from_1_sigma(self.mu, self.sigma_n, self.sigma_p, 2.0)57 self.sigma3_n, self.sigma3_p = self.convert_from_1_sigma(self.mu, self.sigma_n, self.sigma_p, 3.0)58 self.x_limits = [self.mu - 5.0*self.sigma_n, self.mu + 5.0*self.sigma_p]59 self.x_values = np.linspace(self.x_limits[0], self.x_limits[1], self.N)60 self.norm = 1.061 self.norm = self.calculate_norm()62 self.pdf_values = np.asarray(self.pdf(self.x_values))63 self.cdf_values = self.calculate_cdf_values()64 self.cdf = self.calculate_cdf()65 self.inverse_cdf = self.calculate_inverse_cdf()66 def __str__(self):67 output = f"Value = {self.mu:.4f} (-{self.sigma_n:.4f}, +{self.sigma_p:.4f}) (1 sigma)"68 output2 = f"Value = {self.mu:.4f} (-{self.sigma2_n:.4f}, +{self.sigma2_p:.4f}) (2 sigma)"69 output3 = f"Value = {self.mu:.4f} (-{self.sigma3_n:.4f}, +{self.sigma3_p:.4f}) (3 sigma)"70 result = "{}\n{}\n{}".format(output, output2, output3)71 return result72 @classmethod73 def new(cls, mu=10.0, sigma_n=1.0, sigma_p=1.0, N=10000):74 return cls(mu, sigma_n, sigma_p, N)75 def integrate(self):76 delta_x = self.x_limits[1] - self.x_limits[0]77 c = delta_x / (self.N - 1)78 # x_values = np.linspace(self.x_limits[0], self.x_limits[1], self.N, dtype=float)79 area = np.sum(c * self.pdf(self.x_values))80 return area81 def calculate_norm(self):82 area = self.integrate()83 norm = 1/area84 return norm85 def pdf(self, x):86 par_1 = (2.0 * self.sigma_p * self.sigma_n) / (self.sigma_p + self.sigma_n)87 par_2 = (self.sigma_p - self.sigma_n) / (self.sigma_p + self.sigma_n)88 par_3 = (-1.0/2.0) * ((self.mu - x)/(par_1 + par_2*(x - self.mu)))**2.089 par_4 = self.norm / (2.0 * np.pi)**0.590 value = par_4 * np.exp(par_3)91 return value92 def log_likelihood(self, x):93 par_1 = (2.0 * self.sigma_p * self.sigma_n) / (self.sigma_p + self.sigma_n)94 par_2 = (self.sigma_p - self.sigma_n) / (self.sigma_p + self.sigma_n)95 value = (-1.0/2.0) * ((self.mu - x)/(par_1 + par_2*(x - self.mu)))**2.096 return value97 def calculate_cdf_values(self):98 delta_x = self.x_limits[1] - self.x_limits[0]99 c = delta_x / (self.N - 1)100 area = 0.0101 cdf_values = np.asarray([])102 for i in range(self.N):103 area += self.pdf_values[i] * c104 cdf_values = np.append(cdf_values, area)105 return cdf_values106 def calculate_cdf(self):107 cdf = interpolate.interp1d(self.x_values, self.cdf_values, kind='nearest')108 return cdf109 def calculate_inverse_cdf(self):110 inverse_cdf = interpolate.interp1d(self.cdf_values, self.x_values, kind='nearest')111 return inverse_cdf112 def generate(self):113 rnd_prob = np.random.uniform(0, 1, self.N)114 self.data = self.inverse_cdf(rnd_prob)115 @staticmethod116 def fit_func(x, norm, mu, sigma_n, sigma_p):117 par_1 = (2.0 * sigma_p * sigma_n) / (sigma_p + sigma_n)118 par_2 = (sigma_p - sigma_n) / (sigma_p + sigma_n)119 par_3 = (-1.0 / 2.0) * ((mu - x) / (par_1 + par_2 * (x - mu))) ** 2.0120 par_4 = norm / (2.0 * np.pi) ** 0.5121 value = par_4 * np.exp(par_3)122 return value123 def fit(self, expected_values=None):124 y, x, _ = plt.hist(self.data, bins=int(self.N/250))125 plt.clf()126 x = (x[1:] + x[:-1]) / 2 # for len(x)==len(y)127 mod = None128 max_y = max(y)129 for i in range(len(y)):130 if y[i] == max_y:131 mod = x[i]132 #print("mod", mod)133 #print(len(self.data))134 min_data = min(self.data)135 max_data = max(self.data)136 norm = 1000.0137 if not expected_values:138 expected_values = norm, mod, (mod - min_data) * 0.1, (max_data - mod) * 0.1139 expected = (expected_values[0], expected_values[1], expected_values[2], expected_values[3])140 params, cov = curve_fit(self.fit_func, x, y, expected, method='trf')141 self.norm = params[0]142 self.mu = params[1]143 #print("params", params)144 if params[2] > 0.0:145 self.sigma_n = (params[2])146 self.sigma_p = (params[3])147 else:148 self.sigma_n = (params[3])149 self.sigma_p = (params[2])150 def estimate(self, confidence=1.0):151 target_likelihood = -0.5 * float(confidence)152 delta_steps = 1e-5153 current_value = self.mu154 delta = abs(self.mu - self.sigma_p) * delta_steps155 current_likelihood = self.log_likelihood(current_value)156 while abs(current_likelihood) < abs(target_likelihood):157 current_value += delta158 current_likelihood = self.log_likelihood(current_value)159 positive_limit = current_value160 current_value = self.mu161 delta = abs(self.mu - self.sigma_n) * delta_steps162 current_likelihood = self.log_likelihood(current_value)163 while abs(current_likelihood) < abs(target_likelihood):164 current_value -= delta165 current_likelihood = self.log_likelihood(current_value)166 negative_limit = current_value167 print("interval found")168 return [self.mu - negative_limit, positive_limit - self.mu]169 def plot_pdf(self, show=True, save=False):170 plt.clf()171 plt.plot(self.x_values, self.pdf_values, color="blue")172 plt.xlabel("x")173 plt.ylabel("prob")174 if save:175 plt.savefig("plot_pdf.png", dpi=300)176 if show:177 plt.show()178 def plot_log_likelihood(self, show=True, save=False):179 plt.clf()180 plt.plot(self.x_values, self.log_likelihood(self.x_values))181 plt.ylim([-5, 1.5])182 plt.xlabel("x")183 plt.ylabel("ln L")184 plt.axhline(y=-0.5, color="black", ls="--", lw="2.0", label=f"Value = {self.mu:.4f} (-{self.sigma_n:.4f}, +{self.sigma_p:.4f}) (1 sigma)")185 plt.axhline(y=-2.0, color="black", ls="--", lw="1.5", label=f"Value = {self.mu:.4f} (-{self.sigma2_n:.4f}, +{self.sigma2_p:.4f}) (2 sigma)")186 plt.axhline(y=-4.5, color="black", ls="--", lw="1.0", label=f"Value = {self.mu:.4f} (-{self.sigma3_n:.4f}, +{self.sigma3_p:.4f}) (3 sigma)")187 plt.legend()188 if save:189 plt.savefig("plot_log_likelihood.png", dpi=300)190 if show:191 plt.show()192 def plot_cdf(self, show=True, save=False):193 plt.plot(self.x_values, self.cdf(self.x_values))194 if save:195 plt.savefig("plot_cdf.png", dpi=300)196 if show:197 plt.show()198 def plot_data(self, bins=None, show=True, save=False):199 if not bins:200 bins = self.bin_value201 plt.clf()202 plt.hist(self.data, bins=bins, density=True, color="green", alpha=0.7)203 if save:204 plt.savefig("plot_data.png", dpi=300)205 if show:206 plt.show()207 def plot_data_and_pdf(self, bins=None, show=True, save=False):208 if not bins:209 bins = self.bin_value210 plt.clf()211 plt.hist(self.data, bins=bins, density=True, color="green", alpha=0.6)212 plt.plot(self.x_values, self.pdf_values, color="blue")213 plt.xlabel("x")214 plt.ylabel("Prob.")215 plt.axvline(x=self.mu - self.sigma_n, color="black", ls="--", lw="1.5",216 label=f"Value = {self.mu:.4f} (-{self.sigma_n:.4f}, +{self.sigma_p:.4f}) (1 sigma)")217 plt.axvline(x=self.mu + self.sigma_p, color="black", ls="--", lw="1.5")218 plt.axvline(x=self.mu - self.sigma2_n, color="black", ls="--", lw="1.0",219 label=f"Value = {self.mu:.4f} (-{self.sigma2_n:.4f}, +{self.sigma2_p:.4f}) (2 sigma)")220 plt.axvline(x=self.mu + self.sigma2_p, color="black", ls="--", lw="1.0")221 plt.axvline(x=self.mu - self.sigma3_n, color="black", ls="--", lw="0.5",222 label=f"Value = {self.mu:.4f} (-{self.sigma3_n:.4f}, +{self.sigma3_p:.4f}) (3 sigma)")223 plt.axvline(x=self.mu + self.sigma3_p, color="black", ls="--", lw="0.5")224 plt.legend()225 if save:226 plt.savefig("plot_data_and_pdf.png", dpi=300)227 if show:228 plt.show()229 def plot_pdf_cdf(self, show=True, save=False):230 plt.plot(self.x_values, self.cdf_values)231 plt.plot(self.x_values, self.pdf_values)232 if save:233 plt.savefig("plot_pdf_cdf.png", dpi=300)234 if show:235 plt.show()236 def __add__(self, other):237 if isinstance(other, self.__class__):238 add = self.data + other.data239 print(len(add))240 elif isinstance(other, (int, float)):241 add = self.data + float(other)242 else:243 print("Unindentified input type! ({}, {})".format(other, type(other)))244 sys.exit()245 temp_obj = AsymmetricData(creation_type='by_operation', data=add)246 return temp_obj247 def __radd__(self, other):248 if isinstance(other, self.__class__):249 add = other.data + self.data250 elif isinstance(other, (int, float)):251 add = float(other) + self.data252 else:253 print("Unindentified input type! ({}, {})".format(other, type(other)))254 sys.exit()255 temp_obj = AsymmetricData(creation_type='by_operation', data=add)256 return temp_obj257 def __sub__(self, other):258 if isinstance(other, self.__class__):259 add = self.data - other.data260 elif isinstance(other, (int, float)):261 add = self.data - float(other)262 else:263 print("Unindentified input type! ({}, {})".format(other, type(other)))264 sys.exit()265 temp_obj = AsymmetricData(creation_type='by_operation', data=add)266 return temp_obj267 def __rsub__(self, other):268 if isinstance(other, self.__class__):269 add = other.data - self.data270 elif isinstance(other, (int, float)):271 add = float(other) - self.data272 else:273 print("Unindentified input type! ({}, {})".format(other, type(other)))274 sys.exit()275 temp_obj = AsymmetricData(creation_type='by_operation', data=add)276 return temp_obj277 def __mul__(self, other):278 if isinstance(other, self.__class__):279 add = self.data * other.data280 elif isinstance(other, (int, float)):281 add = self.data * float(other)282 else:283 print("Unindentified input type! ({}, {})".format(other, type(other)))284 sys.exit()285 temp_obj = AsymmetricData(creation_type='by_operation', data=add)286 return temp_obj287 def __rmul__(self, other):288 if isinstance(other, self.__class__):289 add = other.data * self.data290 elif isinstance(other, (int, float)):291 add = float(other) * self.data292 else:293 print("Unindentified input type! ({}, {})".format(other, type(other)))294 sys.exit()295 temp_obj = AsymmetricData(creation_type='by_operation', data=add)296 return temp_obj297 def __truediv__(self, other):298 if isinstance(other, self.__class__):299 add = self.data / other.data300 elif isinstance(other, (int, float)):301 add = self.data / float(other)302 else:303 print("Unindentified input type! ({}, {})".format(other, type(other)))304 sys.exit()305 temp_obj = AsymmetricData(creation_type='by_operation', data=add)306 return temp_obj307 def __rtruediv__(self, other):308 if isinstance(other, self.__class__):309 add = other.data / self.data310 elif isinstance(other, (int, float)):311 add = float(other) / self.data312 else:313 print("Unindentified input type! ({}, {})".format(other, type(other)))314 sys.exit()315 temp_obj = AsymmetricData(creation_type='by_operation', data=add)316 return temp_obj317 def __pow__(self, other):318 if isinstance(other, self.__class__):319 add = self.data ** other.data320 elif isinstance(other, (int, float)):321 add = self.data ** float(other)322 else:323 print("Unindentified input type! ({}, {})".format(other, type(other)))324 sys.exit()325 temp_obj = AsymmetricData(creation_type='by_operation', data=add)326 return temp_obj327 def __rpow__(self, other):328 if isinstance(other, self.__class__):329 add = other.data ** self.data330 elif isinstance(other, (int, float)):331 add = float(other) ** self.data332 else:333 print("Unindentified input type! ({}, {})".format(other, type(other)))334 sys.exit()335 temp_obj = AsymmetricData(creation_type='by_operation', data=add)336 return temp_obj337 @staticmethod338 def lnL(x, mu, sigma_n, sigma_p):339 par_1 = (2.0 * sigma_p * sigma_n) / (sigma_p + sigma_n)340 par_2 = (sigma_p - sigma_n) / (sigma_p + sigma_n)341 value = (-1.0 / 2.0) * ((mu - x) / (par_1 + par_2 * (x - mu))) ** 2.0342 return value343 @staticmethod344 def residual(params1, mu, n3, p3, confidence):345 n1, p1 = params1346 if confidence == 1.0:347 target_likelihood = -0.5348 elif confidence == 2.0:349 target_likelihood = -2.0350 elif confidence == 3.0:351 target_likelihood = -4.5352 else:353 target_likelihood = -0.5354 print("Something went wrong!")355 resid = (AsymmetricData.lnL(mu - n3, mu, n1, p1) - target_likelihood) ** 2.0 + (356 AsymmetricData.lnL(mu + p3, mu, n1, p1) - target_likelihood) ** 2.0357 return resid358 @staticmethod359 def convert_to_1_sigma(mu, n, p, confidence):360 N = 500361 n_range = np.linspace(1e-5, n, N)362 p_range = np.linspace(1e-5, p, N)363 np_matrix = np.zeros([n_range.shape[0], p_range.shape[0]])364 for i in range(n_range.shape[0]):365 for j in range(p_range.shape[0]):366 np_matrix[i, j] = np.log(AsymmetricData.residual([n_range[i], p_range[j]], mu, n, p, confidence))367 min_val = np_matrix.min()368 index_n, index_p = np.where(np_matrix == min_val)369 n_new, p_new = n_range[index_n[0]], p_range[index_p[0]]370 #print("")371 #print("# Converting to 1 sigma")372 #print("# {} (-{},+{}) ({} sigma) -> {} (-{},+{}) ({} sigma)".format(mu, n, p, confidence, mu, n_new, p_new, 1.0))373 return [n_new, p_new]374 @staticmethod375 def convert_from_1_sigma(mu, sigma_n, sigma_p, confidence):376 if confidence == 1.0:377 target_likelihood = -0.5378 elif confidence == 2.0:379 target_likelihood = -2.0380 elif confidence == 3.0:381 target_likelihood = -4.5382 else:383 target_likelihood = -0.5384 delta_steps = 1e-4385 current_value = mu386 delta = abs(mu - sigma_p) * delta_steps387 current_likelihood = AsymmetricData.lnL(current_value, mu, sigma_n, sigma_p)388 while abs(current_likelihood) < abs(target_likelihood):389 current_value += delta390 current_likelihood = AsymmetricData.lnL(current_value, mu, sigma_n, sigma_p)391 positive_limit = current_value392 current_value = mu393 delta = abs(mu - sigma_n) * delta_steps394 current_likelihood = AsymmetricData.lnL(current_value, mu, sigma_n, sigma_p)395 while abs(current_likelihood) < abs(target_likelihood):396 current_value -= delta397 current_likelihood = AsymmetricData.lnL(current_value, mu, sigma_n, sigma_p)398 negative_limit = current_value399 n_new, p_new = mu - negative_limit, positive_limit - mu400 #print("")401 #print("# Converting from 1 sigma")402 #print("# {} (-{},+{}) ({} sigma) -> {} (-{},+{}) ({} sigma)".format(mu, sigma_n, sigma_p, 1.0, mu, n_new, p_new, confidence))...

Full Screen

Full Screen

histogram-input.py

Source:histogram-input.py Github

copy

Full Screen

1from soad import AsymmetricData as asyd2import numpy as np3N=500004data_input = list(np.random.normal(10,1,N))5a = asyd(creation_type='by_operation', data=data_input)6print(a)7a.plot_data_and_pdf(show=True, save=False)8a.plot_pdf()9#******* Ignore this part **********10#c=a**0.111#print("print c", c)12#c.plot_data_and_pdf()13#plt.hist(a.data, bins=80, density=True, color='red', alpha=0.5)14#plt.hist(b.data, bins=80, density=True, color='blue', alpha=0.5)15#plt.hist(c.data, bins=100, density=True, color='cyan', alpha=0.5)16#plt.show()17#a = asyd(10,1,1.2,N=N)18#b = asyd(10,1,1.2,N=N)19"""20c = asyd(10,1,1.2,N=N)21d = asyd(10,1,1.2,N=N)22e = asyd(10,1,1.2,N=N)23f = asyd(10,1,1.2,N=N)24g = asyd(10,1,1.2,N=N)25h = asyd(10,1,1.2,N=N)26print(a,b,c,d,e,f,g,h,sep="\n")27data_input = np.concatenate((a.data, b.data, c.data, d.data, e.data, f.data, g.data, h.data))28"""29#data_input = np.concatenate((a.data, b.data))30#x = asyd(creation_type='by_operation', data=data_input)31#x = (a+b+c+d+e+f+g+h+a+b+c+d+e+f+g+h+a+b+c+d+e+f+g+h+a+b+c+d+e+f+g+h)/32.032#x = (a+b)/2.033#print(x)34#print("asym a: {}".format((a.sigma_p-a.sigma_n)/(a.sigma_p+a.sigma_n)))35#print("asym x: {}".format((x.sigma_p-x.sigma_n)/(x.sigma_p+x.sigma_n)))36#x.plot_data_and_pdf()37#means = []38#for i in range(5000):39# temp = asyd(10,1.0,1.5,500)40# temp_mean = np.sum(temp.data)/temp.N41# means.append(temp_mean)42#plt.hist(means, bins=30)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful