def atan2(column1,column2): i = 0 column1= mt.convert_num_col(column1) column2= mt.convert_num_col(column2) result = list() while i < len(column1): result.insert(i+1,math.atan2(column1[i],column2[i])) i+=1 return result
def isCircularPrime(number): length = len(str(number)) if (length==1): return MathFunctions.checkIfPrime(number) else: for variation in list_of_variations(number): if not MathFunctions.checkIfPrime(variation): return False return True
def find_error2(H_t, H_e, Y_lstm, tsteps): H_t = numpy.reshape(H_t, (H_t.shape[0] * tsteps, 1)) H_e = numpy.reshape(H_e, (H_e.shape[0] * tsteps, 1)) Y_lstm = numpy.reshape(Y_lstm, (Y_lstm.shape[0] * tsteps, 1)) e_deep = (MathFunctions.rms_flat(Y_lstm - H_e)) / (MathFunctions.rms_flat(H_e)) e_deep2 = (MathFunctions.rms_flat(Y_lstm - H_e)) / (MathFunctions.rms_flat(H_t)) return e_deep, e_deep2
def interpolate_calculate_rms(Y_a, Y_p): not_nan = numpy.logical_not(numpy.isnan(Y_a)) not_nan = numpy.squeeze(not_nan) A = Y_a[not_nan] B = Y_p[not_nan] e_interp = (MathFunctions.rms_flat(A - B)) / (MathFunctions.rms_flat(A)) return e_interp
def p_expression_solve(p): '''expression : SOLVE expression''' if s.find('^') != -1: eq = MathFunctions.formateq(p[2]) else: eq = str(p[2]) if p[2] is not None: eq = (str(MathFunctions.msolve(eq, MathFunctions.symbols('x')))) eq = MathFunctions.reformateq(eq) p[0] = eq else: pass
def NN_optimizeNN_v2(t, X, Y, params): row_max, col_max = t.shape t_cv1, real_cv1 = OptimizeRealSchedule_conv_PSB(col_max, params['real_num'], params['real_units']) t_cv2, bin_cv1 = OptimizeBinSchedule_conv_PSB(col_max, params['bin_num'], params['bin_units']) #weather_input = Input(shape=(weather_idxMax,), name='weather_input') x = merge([real_cv1, bin_cv1], mode='concat') #x = Dense(params['layer2_units'], activation='hard_sigmoid')(x) main_cv = Dense(1, activation='linear')(x) cv_model = Model(input=[t_cv1, t_cv2], output=main_cv) cv_model.compile(loss='mse', optimizer='adam') # cv error cvscores = [] kfold = KFold(n=len(Y), n_folds=3) iter_max = 3 for train_index, test_index in kfold: t_train, t_test = t[train_index], t[test_index] #x_train, x_test = X[train_index], X[test_index] y_train, y_test = Y[train_index], Y[test_index] e_t = numpy.zeros((iter_max, 1)) e_select = 1 for i in range(0, iter_max): cv_model.fit([t_train, t_train], y_train, nb_epoch=50, batch_size=1, verbose=0) y_cv = numpy.squeeze(cv_model.predict([t_test, t_test])) e_t[i] = (MathFunctions.rms_flat(y_cv - numpy.squeeze(y_test))) / ( MathFunctions.rms_flat(numpy.squeeze(y_test))) if i > 0: if e_t[i] < e_t[i - 1]: e_select = e_t[i] else: e_select = e_t[i] e_temp = e_select print e_select cvscores.append(e_temp) cvscores = numpy.asanyarray(cvscores) return cvscores
def startProgram(param): """Start this method will generate examples. Args: param: Gets info from user Returns: Result of user """ points = 0 i = 0 times = list() repetition = 5 while i < repetition: start = perf_counter() pc = randomExample() if param == 'user': user = input("Enter answer: ") else: user = param stop = perf_counter() times.append(stop - start) if MathFunctions.points(pc, user): points += 1 else: print(f"Your answer is wrong! Right answer is {pc}") i += 1 print(f"\nYou got {points} of {repetition} points") print(f"Average time is {MathFunctions.average(times)} seconds")
def create_immediate_children(self): assert self.mydataframe is not None, "create_child_nodes called with no dataframe" assert self.target_attribute is not None, "create child nodes called with no target_attribute" # TODO keeping track of columns still available to be split on subsequent nodes would allow us to feed the column list into # TODO determine best split. This would cut back on checks therein (depending on how expensive pandas.unique is) split_column, split_values, score = MathFunctions.determine_best_split( self.mydataframe, self.target_attribute) # if no available split, then this is a leaf. if not split_column: target_classes = self.mydataframe[self.target_attribute].unique() assert len(target_classes) == 1 self.leaf_class = target_classes[0] # otherwise, make more nodes else: self.score = score self.decision_attribute = split_column for single_split in split_values: new_child = Node(parent_node=self) new_child.depth = self.depth + 1 new_child.target_attribute = self.target_attribute child_dataframe = self.mydataframe.loc[ self.mydataframe[split_column].isin(single_split)] new_child.mydataframe = child_dataframe new_child_edge = self.child_edge() new_child_edge.node_ptr = new_child new_child_edge.split_portion = single_split self.child_edges.append(new_child_edge)
def test_areaCircle_for_10radius(self): #Capture the result of the function: result = MathFunctions.areaCircle(10) #Check for expected output: expected = 314.1592653589793 self.assertEqual(expected, result)
def test_factorial_returns_correct_value_for_an_integer(self): math_object = MathFunctions.MathFunction() self.assertEqual(1, math_object.factorial(1)) self.assertEqual(2, math_object.factorial(2)) self.assertEqual(120, math_object.factorial(5)) self.assertEqual(3628800, math_object.factorial(10)) self.assertEqual(1, math_object.factorial(0))
def mouse_down_move_graph(self, position): for node in self.nodes: if MF.distance(position, node.circle.position) <= node.circle.radius: self.selected_node = node self.state = "move_graph" break
def mouse_down_add_edge(self, position): for node in self.nodes: if MF.distance(position, node.circle.position) <= node.circle.radius: self.selected_node = node self.state = "add_edge" break
def mouse_up_add_edge(self, position): self.state = "idle" for node in self.nodes: if MF.distance(position, node.circle.position) <= node.circle.radius: self.add_edge(self.selected_node, node) break
def p_expression_integral(p): '''expression : INTEGRAL OF expression''' if s.find('^') != -1: eq = MathFunctions.formateq(p[3]) else: eq = str(p[3]) if p[3] is not None: eq = (str(MathFunctions.integration(eq, MathFunctions.symbols('x')))) eq = MathFunctions.reformateq(eq) p[0] = eq y = tostring(asciimathml.parse("int" + str(p[3]))) x = tostring(asciimathml.parse(str(p[0]))) print(str(y, "utf-8") + "=" + str(x, "utf-8")) else: pass
def fit_model(model, t, X, Y): # cv error kfold = KFold(n=len(Y), n_folds=3) iter_max = 10 model_init = model save_model = model e_t = numpy.zeros((iter_max, 1)) e_select = 1 for i in range(0, iter_max): cvscores = [] model = model_init for train_index, test_index in kfold: t_train, t_test = t[train_index], t[test_index] x_train, x_test = X[train_index], X[test_index] y_train, y_test = Y[train_index], Y[test_index] model.fit([t_train, t_train, x_train], y_train, nb_epoch=200, batch_size=20, verbose=0) y_cv = numpy.squeeze(model.predict([t_test, t_test, x_test])) e_temp = (MathFunctions.rms_flat(y_cv - numpy.squeeze(y_test))) / ( MathFunctions.rms_flat(numpy.squeeze(y_test))) cvscores.append(e_temp) cvscores = numpy.asanyarray(cvscores) print cvscores e_t[i] = cvscores.mean() if i > 0: if e_t[i] < e_t[i - 1]: e_select = e_t[i] save_model = model else: e_select = e_t[i] print e_t print e_select return save_model, e_select
def p_expression_derivative(p): '''expression : DERIVATIVE OF expression''' if s.find('^') != -1: eq = MathFunctions.formateq(p[3]) else: eq = str(p[3]) if p[3] is not None: eq = (str(MathFunctions.derivative(eq, MathFunctions.symbols('x')))) eq = MathFunctions.reformateq(eq) p[0] = eq w = tostring(asciimathml.parse('frac{d}{dx}')) y = tostring(asciimathml.parse(str(p[3]))) x = tostring(asciimathml.parse(str(p[0]))) print(str(w, "utf-8") + str(y, "utf-8") + "=" + str(x, "utf-8")) else: pass
def cot(column): i = 0 column= mt.convert_num_col(column) result = list() while i < len(column): result.insert(i+1,(math.cos(column[i])/math.sen(column[i]))) i+=1 return result
def sin(column): i = 0 column= mt.convert_num_col(column) result = list() while i < len(column): result.insert(i+1,math.sin(column[i])) i+=1 return result
def mouse_down_add_node(self, position): touching_node = False for node in self.nodes: if MF.distance(position, node.circle.position) <= node.circle.radius: touching_node = True break if touching_node == False: self.add_node(position)
def diagonal_members(size): diagonals = set() for i in range(size, 0,-2): # print("Layer ", i) for j in range(0,4): # print(i, j, i*i - (i-1)*j) diagonals.add(i*i - (i-1)*j) number_of_primes = sum(1 for x in diagonals if MathFunctions.miller_is_prime(x)) # print(number_of_primes,len(diagonals)) return (number_of_primes/len(diagonals))
def forward_propagate(network, inputs): new_inputs = inputs for layer in network: output = [] for neuron in layer: neuron.inputs = new_inputs activate = mf.NeuronPassFail(neuron.weights, neuron.inputs) neuron.output = activate output.append(neuron.output) new_inputs = output
def p_expression_sum(p): '''expression : SUM FROM expression TO expression OF expression''' lowerBound = p[3] highBound = p[5] eq1 = str(p[7]) if s.find('^') != -1: eq = MathFunctions.formateq(eq1) else: eq = str(eq1) if lowerBound is not None and highBound is not None and p[7] is not None: p[0] = MathFunctions.summation(eq, lowerBound, highBound, MathFunctions.symbols('x')) y = tostring( asciimathml.parse("sum_" + str(lowerBound) + "^" + str(highBound) + " " + str(p[7]))) x = tostring(asciimathml.parse(str(p[0]))) print(str(y, "utf-8") + "=" + str(x, "utf-8")) else: pass
def prime_counter(order_in_primes): current_num = 2 current_order_in_primes = 0 while True: if MathFunctions.checkIfPrime(current_num): current_order_in_primes += 1 if current_order_in_primes < order_in_primes: current_num += 1 else: break return (current_num)
def compute_peak_metric(y_a, y_p, T): peak_len = int(len(y_a) / T) peak_a = numpy.zeros((peak_len, )) peak_p = numpy.zeros((peak_len, )) tau = numpy.zeros((peak_len, 1)) tau_p = numpy.zeros((peak_len, 1)) for i in range(0, peak_len): peak_a[i] = numpy.amax(y_a[i * T:(i + 1) * T]) peak_p[i] = numpy.amax(y_p[i * T:(i + 1) * T]) tau[i] = numpy.argmax(y_a[i * T:(i + 1) * T]) tau_p[i] = numpy.argmax(y_p[i * T:(i + 1) * T]) epsilon_1 = (MathFunctions.rms_flat(peak_a - peak_p)) / ( MathFunctions.rms_flat(peak_a)) epsilon_2 = numpy.mean(numpy.absolute(tau - tau_p) / T) return epsilon_1, epsilon_2
def p_expression_definite_integral(p): '''expression : INTEGRAL FROM expression TO expression OF expression | INTEGRAL FROM expression TO INFINITY OF expression''' lowerbound = str(p[3]) highbound = str(p[5]) eq1 = str(p[7]) if s.find('^') != -1: eq = MathFunctions.formateq(eq1) else: eq = str(eq1) if lowerbound is not None and highbound is not None and p[7] is not None: eq = (str( MathFunctions.integration( eq, (MathFunctions.symbols('x'), lowerbound, highbound)))) eq = MathFunctions.reformateq(eq) p[0] = eq y = tostring( asciimathml.parse("int_" + lowerbound + "^" + highbound + " " + str(p[7]))) x = tostring(asciimathml.parse(str(p[0]))) print(str(y, "utf-8") + "=" + str(x, "utf-8")) else: pass
def update(self, position): if self.state == "move_graph": self.selected_node.move(position, [self.x, self.y], [self.width, self.height]) elif self.state == "add_edge": touching_node = False for node in self.nodes: if MF.distance(position, node.circle.position) <= node.circle.radius: self.last_pos = node.get_position() touching_node = True break if touching_node == False: self.last_pos = position
def back_propagate(layers, target_value, learning_rate, row): output_layer = layers[1] for index in range(len(output_layer)): if index == target_value: if output_layer[index].output <= .5: output_layer[index].Error = mf.getOutputError( output_layer[index].output, 1) else: if output_layer[index].output > .5: output_layer[index].Error = mf.getOutputError( output_layer[index].output, 0) for layer in reversed(range(len(layers) - 2)): for item in range(len(layers[layer])): layers[layer][item].Error = mf.getHiddenError(layer, item, layers) for layer in range(len(layers)): inputs = row[:-1] if layer != 0: inputs = [neuron.output for neuron in layers[layer - 1]] for neuron in layers[layer]: for j in range(len(inputs)): neuron.weights[j] = mf.weightUpdate(neuron.weights[j], learning_rate, neuron.Error, inputs[j])
def p_expression_limit(p): '''expression : LIMIT WHEN X GOES expression OF expression | LIMIT WHEN X GOES INFINITY OF expression''' limitOf = str(p[3]) tendsTo = str(p[5]) eq1 = str(p[7]) if s.find('^') != -1: eq = MathFunctions.formateq(eq1) else: eq = str(eq1) if limitOf is not None and tendsTo is not None and p[7] is not None: eq = (str(MathFunctions.limits(eq, MathFunctions.symbols('x'), tendsTo))) eq = MathFunctions.reformateq(eq) p[0] = eq y = tostring( asciimathml.parse("lim_(" + str(limitOf) + "->" + str(tendsTo) + ")")) x = tostring(asciimathml.parse(str(p[0]))) print(str(y, "utf-8") + "=" + str(x, "utf-8")) else: pass
def process_XY(X, Y, intv): #normalize Y Y_rms = MathFunctions.rms_flat(Y) # normalizing data #H_min, H_max = DataFunctions.get_normalize_params(Y) #Y= Y / H_max #Reshape X, Y Pair row_seq = int(len(X) / intv) # Reshaping array into (#of days, 24-hour timesteps, #features) train_data = numpy.reshape(X, (row_seq, intv, X.shape[1])) H_out = numpy.reshape(Y, (row_seq, intv)) return train_data, H_out
def find_permutations(self, string): math_object = MathFunctions.MathFunction() array_permutations = [] len_of_string = len(string) if len_of_string >= 3: for char_start in string: end_string = string.replace(char_start, "") end_string_permutations = self.find_permutations(end_string) for i in range(0, math_object.factorial(len(end_string))): array_permutations.append(char_start + end_string_permutations[i]) if len_of_string == 2: array_permutations.append(string[0] + string[1]) array_permutations.append(string[1] + string[0]) if len_of_string == 1: array_permutations.append(string) return sorted(array_permutations)
import MathFunctions, time start_time = time.time() found, i = "", 9999 while found == "": concatenated = "" for n in range(1, 5): current = i * n concatenated += str(current) if int(concatenated) < 123456789: continue elif int(concatenated) > 987654321: break elif MathFunctions.is_pandigital(int(concatenated)): found = concatenated i -= 1 print(found) print("--- %s seconds ---" % (time.time() - start_time))
import MathFunctions, time start_time = time.time() print(sum(i for i in range(1,1000000) if MathFunctions.is_palindrome(i) and MathFunctions.is_palindrome ("{0:b}".format(i)))) print("--- %s seconds ---" % (time.time() - start_time))
def test_square_area_for_5length(self): #capture results of MathFunctions result = MathFunctions.areaSquare(5) #Check for expected output expected = 25 self.assertEqual(expected, result)
''' A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 ? 99. Find the largest palindrome made from the product of two 3-digit numbers. ''' import time, MathFunctions start_time = time.time() largest_parts = [] largest =0 for i in range(100, 999): for j in range(100, 999): product = i * j if MathFunctions.is_palindrome(product): if largest < product: largest = product if(len(largest_parts)>0): largest_parts.pop() largest_parts.pop() largest_parts.append(i) largest_parts.append(j) # print(largest_parts) print(largest) print("--- %s seconds ---" % (time.time() - start_time))
def sumOfPrimesBelow(upperLimit): sum = 2 for i in range(3, upperLimit, 2): if MathFunctions.miller_is_prime(i): sum+=i return sum
def test_shuntingyard(self): self.assertEqual(MathFunctions.shuntingYard("2 + 2"), "2 2 +")
def isDigitFactorial(number): sum = 0 for i in str(number): sum += MathFunctions.factorial(int(i)) # print(number, sum) return sum == number
''' The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another. There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence. What 12-digit number do you form by concatenating the three terms in this sequence? ''' import MathFunctions, itertools def is_permuted(a, b): list_of_permutations =[int(''.join(x)) for x in itertools.permutations(str(a))] return list_of_permutations.__contains__(b) for i in range(1489, 10000): if MathFunctions.miller_is_prime(i) and MathFunctions.miller_is_prime(i+3330) and MathFunctions.miller_is_prime(i+6660)\ and is_permuted(i,i+3330) and is_permuted(i, i+6660): print(i, i+3330, i+6660) break
from scipy.stats import pearsonr seed = 7 numpy.random.seed(seed) #EnergyData #Processing hourly data date_start = '01/01/15 12:00 AM' date_end = '12/31/15 11:59 PM' std_inv1 = 60 #in minutes #Extracting Energy Data folder_path = r'/home/sseslab/PycharmProjects/ElectricLoad_v1/dataport_data/dataport_hour_train3' H_t, H_max1 = DataFunctions.read_multiple_dataport(folder_path, 24*365) H_t = H_t/H_max1 H_rms1 = MathFunctions.rms_flat(H_t) #Computing Entropy S, unique, pk = DataFunctions.calculate_entropy(H_t) print "The entropy value is: ", S #EnergyData Processing 1-min data data std_inv2 = 1 #in minutes folder_path = r'/home/sseslab/PycharmProjects/ElectricLoad_v1/dataport_data/dataport_1min_train3' H_t2, H_max2 = DataFunctions.read_multiple_dataport(folder_path, 24*365*60) H_t2 = H_t2/H_max2 H_rms2 = MathFunctions.rms_flat(H_t2) file_ = r'~/PycharmProjects/ElectricLoad_v1/dataport_data/austin_weather_2015.csv' weather_train = DataFunctions.preprocess_weatherData_101(file_, date_start, date_end)
''' Given that Fk is the first Fibonacci number for which the first nine digits AND the last nine digits are 1-9 pandigital, find k. ''' import time, MathFunctions all_digits=set(['1','2','3','4','5','6','7','8','9']) def first9pandigital(number): global all_digits return len(all_digits.difference(set(str(number)[:9])))==0 def last9pandigital(number): global all_digits return len(all_digits.difference(set(str(number)[-9:])))==0 start_time = time.time() i = 1 while True: print(i) current_fib = MathFunctions.fib(i) # print(i, len(str(current_fib))) if first9pandigital(current_fib) and last9pandigital(current_fib): break i+=1 print(i) print("--- %s seconds ---" % (time.time() - start_time))
# Getting timescale features timescales = numpy.array([346, 321]) #timescales = numpy.array([325, 351]) T_sch_t = TimeScaleFunctions.timescale_101(X_sch_t, date_start, ref_date, timescales) T_sch_t2 = DataFunctions.get_feature_low_res(T_sch_t, std_inv, std_inv2) T_sch_t2 = T_sch_t2[:, 0:2] train_data = numpy.concatenate((weather_train[:, 0:2], X_sch_t, T_sch_t), axis=1) train_data2 = numpy.concatenate((weather_train2[:, 0:2], X_sch_t2, T_sch_t2), axis=1) #train_data = X_sch_t #train_data2 = X_sch_t2 H_rms = MathFunctions.rms_flat(H_t) #normalizing data H_min, H_max = DataFunctions.get_normalize_params(H_t) H_t = H_t / H_max #normalizing H_t2 H_min2, H_max2 = DataFunctions.get_normalize_params(H_t2) H_t2 = H_t2 / H_max2 #Computing Entropy S, unique, pk = DataFunctions.calculate_entropy(H_t) #print "The entropy value is: ", S # Block to interpolate cons_points = 5 s0 = 245
''' We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime. What is the largest n-digit pandigital prime that exists? ''' import MathFunctions, time def is_pandigital(num): str_rep = str(num) string_rep_set = set(i for i in str_rep) if str_rep.__contains__('0'): return False length = len(str_rep) if length!= len(set(str_rep)): return False pan_digits = set(range(1,length+1)) num_digits = set(ord(i) - ord('0') for i in str_rep) return num_digits.difference(pan_digits) == set() start_time = time.time() # cannot have 9 because 1+2+..+9 = 45, divisible always by 3 and 9, thus not a prime. Same for 8, sum is 36. for i in range(7654321, 1, -2): if is_pandigital(i) and MathFunctions.miller_is_prime(i): print(i) break print("--- %s seconds ---" % (time.time() - start_time))
import time, MathFunctions start_time = time.time() n = 1 while len(str(MathFunctions.fast_fib(n))) < 1000: n += 1 print(n) print("--- %s seconds ---" % (time.time() - start_time))
''' ''' import time import MathFunctions start_time = time.time() for i in range(1, 10000): for j in range(10000, 1, -1): first_pentagon = MathFunctions.pentagonal(i) second_pentagon = MathFunctions.pentagonal(j) if (MathFunctions.inverse_pentagonal(abs(first_pentagon-second_pentagon)) and MathFunctions.inverse_pentagonal(first_pentagon+second_pentagon)): print(abs(first_pentagon-second_pentagon)) print("--- %s seconds ---" % (time.time() - start_time))