예제 #1
0
def paul(M, s=1.0, n=4):
    """
	Paul wavelet.

	Parameters
	----------
	M : int
	Length of the wavelet.
	n : int
	Order of the Paul wavelet. Default is 4
	s : float
	Scaling factor . Default is 1.

	Returns
	-------
	Paul : (M,) ndarray


	Notes
	-----

	"""
    x = linspace(-M/2.0, M/2.0, M)
    output = 2**n * math.factorial(n) * (1-1j*(x/s))**-(n+1)
    output /= 2*pi*sqrt(math.factorial(2*n)/2)
    output /= sqrt(s)
 
    return output
예제 #2
0
def multichoose(string):
    tot = sum([int(a) for a in string])
    resid = len(string) - tot
    out = math.factorial(len(string)) / prod(
        [math.factorial(int(a)) for a in string])
    if string == '1' + '0' * (len(string) - 1):
        return out / math.factorial(resid) - 1
    return out / math.factorial(resid) if resid >= 0 else 0
예제 #3
0
def anagram_counter(words):
    return int(
        sum(
            map(
                lambda n: np_math.factorial(n) /
                (np_math.factorial(2) * np_math.factorial(n - 2)), [
                    n
                    for n in Counter([''.join(sorted(word))
                                      for word in words]).values() if n > 1
                ])))
예제 #4
0
def nCx(n, x):
    """Gives the number of combinations with n trials when selecting x successes. (N
    choose x)

    An example.

    Args:
        n (int) : The number of events
        x (int) : The number of outcomes of the event
    Returns:
        int : the number of combinations of that event occurring within the sample space

    """
    return int(math.factorial(n) / (math.factorial(x) * math.factorial(n - x)))
예제 #5
0
    def __init__(self,
                 paths,
                 aug,
                 inch,
                 sample_rate=1,
                 puzzle_num=4,
                 original_img=False):
        self.sample_rate = sample_rate
        self.inch = inch
        self.original_img = original_img
        self.aug = aug
        self.root_path = paths
        self.inputs = []
        self.outputs = []
        self.lens = [0]
        self.len = 0
        for p in paths:
            self.read_data_to_memory(p)
            if sample_rate == 1:
                self.len += read_length(p, 'output')
            else:
                self.len += sample_rate
            self.lens.append(self.len)

        self.ch_out = read_ch(paths[0], 'output')
        self.puzzle_num = int(np.sqrt(puzzle_num))
        self.pnc = PN_converter(puzzle_num,
                                pnumber=min(math.factorial(puzzle_num), 50))
        if aug:
            self.len *= 4
        if inch == 1:
            self.len *= 64
예제 #6
0
 def calculate(self):
     m = self.calculate_m()
     multiplication = self.multiplication()
     expression = (f'{multiplication} * ({m}/({self.order}!))')
     factorial_of_order_plus_one = math.factorial(self.order)
     result = multiplication * m / factorial_of_order_plus_one
     self.result['erro'] = {'expression': expression, 'result': result}
예제 #7
0
def f(n: int) -> int:
    """
    Function takes an integer and give a sum of factorial of the digits
    :param n:
    :return:
    """
    return sum([npm.factorial(int(i)) for i in str(n)])
 def __init__(self, in_ch=3, out_ch=2, ss=True, num_puzzle=9, bench=False):
     super(SUNET, self).__init__()
     self.in_ch = in_ch
     self.extractor = Extractor(in_ch)
     self.regressor = Regressor(out_ch)
     self.num_puzzle = num_puzzle
     self.decoder = Sorter(in_ch,
                           num_perm=min(math.factorial(self.num_puzzle),
                                        50))
     if ss:
         self.criterion = nn.CrossEntropyLoss()
     else:
         self.criterion = nn.MSELoss()
     self.opt_all = optim.Adam(self.parameters(), lr=0.001)
     if ss:
         self.opt_ext = optim.Adam(self.extractor.parameters(), lr=0.001)
         self.opt_dec = optim.Adam(self.decoder.parameters(), lr=0.001)
         self.scheduler_dec = StepLR(self.opt_dec, step_size=1, gamma=0.5)
         self.scheduler_ext = StepLR(self.opt_ext, step_size=1, gamma=0.5)
     elif bench:
         self.opt_ext = optim.Adam(self.extractor.parameters(), lr=0.0001)
         self.opt_reg = optim.Adam(self.regressor.parameters(), lr=0.001)
         self.scheduler_ext = StepLR(self.opt_ext, step_size=1, gamma=0.5)
         self.scheduler_reg = StepLR(self.opt_reg, step_size=1, gamma=0.5)
     else:
         self.opt_ext = optim.Adam(self.extractor.parameters(), lr=0.00001)
         self.opt_reg = optim.Adam(self.regressor.parameters(), lr=0.001)
         self.scheduler_ext = StepLR(self.opt_ext, step_size=1, gamma=0.5)
         self.scheduler_reg = StepLR(self.opt_reg, step_size=1, gamma=0.5)
     self.out_ch = out_ch
     self.imshown = False
예제 #9
0
    def __getitem__(self, item):
        # light = item % self.img_num
        light = item % self.img_num
        item = (item - light) // self.img_num
        light = 27
        if self.aug:
            aug = item % 4
            item = (item - aug) // 4
        else:
            aug = 0


        input = self.input
        input = np.expand_dims(input[item, light, :, :], axis=0)
        input= input/np.max(input)*2-1
        output = self.output[item, :, :, :]

        if aug % 2 == 0:
            input = np.ascontiguousarray(np.flip(input, 1))
            output = np.ascontiguousarray(np.flip(output, 1))
        if aug > 1:
            input = np.ascontiguousarray(np.flip(input, 2))
            output = np.ascontiguousarray(np.flip(output, 2))
        puzzle = np.repeat(input.copy(), 3, axis=0)
        puzzle_num = self.puzzle_num
        puzzle=np.zeros_like(puzzle)  # white back ground
        # idxs_array = np.random.permutation(puzzle_num * puzzle_num)
        self.perm_id = np.random.randint(min(math.factorial(puzzle_num**2), 50))
        idxs = self.pnc.num2perm(self.perm_id)
        #  hard coded for laziness

        if 'Nut' in self.root_path or 'panel' in self.root_path or 'T' in self.root_path:
            edge = 10
        else:
            edge = 10
        stride = (puzzle.shape[1] - edge * 2) // puzzle_num-edge//2
        for i in range(puzzle_num*puzzle_num):
            giggle=int(((np.random.rand()+1)*edge)//8)
            giggle2=int(((np.random.rand()+1)*edge)//8)
            col = i % puzzle_num
            row = (i - col) // puzzle_num
            tcol = idxs[i] % puzzle_num
            trow = (idxs[i] - tcol) // puzzle_num
            # puzzle[:, edge + trow * stride:edge + trow * stride + stride,
            # edge + tcol * stride:edge + tcol * stride + stride] = input[:,
            #                                                       edge + row * stride:edge + row * stride + stride,
            #                                                       edge + col * stride:edge + col * stride + stride]
            puzzle[:, edge//2 + trow * (stride+edge)+giggle:edge//2 + trow * (stride+edge) + stride+giggle,
            edge//2 + tcol * (stride+edge)+giggle2:edge//2 + tcol * (stride+edge) + stride+giggle2] = input[:,
                                                                  edge + row * stride+giggle2:edge + row * stride + stride+giggle2,
                                                                  edge + col * stride+giggle:edge + col * stride + stride+giggle]

        # plt.subplot(2,1,1)
        # plt.imshow(puzzle[0,:,:])
        # plt.subplot(2,1,2)
        # plt.imshow(input.squeeze())
        # plt.show()
        # print(self.perm_id)
        return puzzle, int(self.perm_id)
예제 #10
0
    def __getitem__(self, item):

        if self.inch == 1:
            light = item % 64
            item = (item - light) // 64
        if self.aug:
            aug = item % 4
            item = (item - aug) // 4
        else:
            aug = 0

        if self.inch == 1:
            input = np.expand_dims(self.input[item, light, :, :], axis=0)
        else:
            input = self.input[item, :, :, :]

        if aug % 2 == 1:
            # plt.imshow(input[0,:,:])
            # plt.show()
            input = np.ascontiguousarray(np.flip(input, 1))
            if self.inch == 3:
                input[0, :, :] *= -1
        if aug > 1:
            input = np.ascontiguousarray(np.flip(input, 2))
            if self.inch == 3:
                input[1, :, :] *= -1

        puzzle = input.copy()
        puzzle_num = self.puzzle_num
        puzzle = np.zeros_like(puzzle)  # white back ground
        # idxs_array = np.random.permutation(puzzle_num * puzzle_num)
        self.perm_id = np.random.randint(min(math.factorial(puzzle_num**2),
                                             50))
        idxs = self.pnc.num2perm(self.perm_id)
        #  hard coded for laziness
        if 'Nut' in self.root_path or 'panel' in self.root_path or 'T' in self.root_path:
            edge = 10
        else:
            edge = 10
        stride = (puzzle.shape[1] - edge * 2) // puzzle_num - edge // 2
        for i in range(puzzle_num * puzzle_num):
            giggle = int(((np.random.rand() + 1) * edge) // 8)
            giggle2 = int(((np.random.rand() + 1) * edge) // 8)
            col = i % puzzle_num
            row = (i - col) // puzzle_num
            tcol = idxs[i] % puzzle_num
            trow = (idxs[i] - tcol) // puzzle_num
            puzzle[:, edge // 2 + trow * (stride + edge) + giggle:edge // 2 +
                   trow * (stride + edge) + stride + giggle,
                   edge // 2 + tcol * (stride + edge) + giggle2:edge // 2 +
                   tcol * (stride + edge) + stride +
                   giggle2] = input[:, edge + row * stride + giggle2:edge +
                                    row * stride + stride + giggle2,
                                    edge + col * stride + giggle:edge +
                                    col * stride + stride + giggle]

        return puzzle, self.perm_id
 def __init__(self,
              in_ch=3,
              out_ch=2,
              ss=True,
              num_puzzle=9,
              scale_lr=1,
              multitask=False,
              para_reduce=1):
     super(SUNET, self).__init__()
     self.in_ch = in_ch
     self.out_ch = out_ch
     self.imshown = False
     self.multi = multitask
     self.extractor = Extractor(in_ch, para_reduce=para_reduce)
     if multitask:
         self.classifier = Classifier(bn=False, para_reduce=para_reduce)
         self.opt_c = optim.Adam(self.classifier.parameters(), lr=0.001)
         self.scheduler_cls = StepLR(self.opt_c, step_size=1, gamma=0.5)
     if ss:
         self.disc = Discriminator(para_reduce=para_reduce)
         self.num_puzzle = num_puzzle
         self.decoder = Sorter(in_ch,
                               num_perm=min(math.factorial(self.num_puzzle),
                                            50),
                               para_reduce=para_reduce)
         self.criterion = nn.CrossEntropyLoss()
         self.opt_dics = optim.Adam(self.disc.parameters(), lr=0.001)
         self.opt_ext = optim.Adam(self.extractor.parameters(), lr=0.001)
         self.opt_dec = optim.Adam(self.decoder.parameters(), lr=0.001)
         self.scheduler_dec = StepLR(self.opt_dec, step_size=1, gamma=0.5)
         self.scheduler_ext = StepLR(self.opt_ext, step_size=1, gamma=0.5)
     else:
         self.regressor = Regressor(out_ch, para_reduce=para_reduce)
         self.criterion = nn.MSELoss()
         paras1 = list(self.extractor.parameters())
         # paras1=list(self.extractor.E1.parameters())+list(self.extractor.E2.parameters())+list(self.extractor.E3.parameters())
         # paras2=list(self.extractor.E4.parameters())+list(self.regressor.parameters())
         paras2 = list(self.regressor.parameters())
         # self.opt_ext = optim.Adam(paras, lr=0.00001)
         if not scale_lr == 1:
             self.opt_ext = optim.Adam(paras1, lr=0.001 * scale_lr)
             self.scheduler_ext = StepLR(self.opt_ext,
                                         step_size=1,
                                         gamma=0.5)
             self.opt_reg = optim.Adam(paras2, lr=0.001 * scale_lr)
         else:
             self.opt_ext = optim.Adam(self.extractor.parameters(),
                                       lr=0.001)
             self.scheduler_ext = StepLR(self.opt_ext,
                                         step_size=1,
                                         gamma=0.5)
             self.opt_reg = optim.Adam(self.regressor.parameters(),
                                       lr=0.001)
         self.scheduler_reg = StepLR(self.opt_reg, step_size=1, gamma=0.5)
def fact(nn,exact=True):
	'''
	Implements the factorial
	'''

	if scipy_misc_loaded:
		return sc_m.factorial(nn, exact=exact)

	elif numpy_math_loaded:
		return np_m.factorial(nn)

	else:
		return m.factorial(nn)
예제 #13
0
 def __init__(self, path, aug, inch, sample_rate=1, puzzle_num=4):
     self.root_path = path
     self.sample_rate = sample_rate
     self.inch = inch
     self.aug = aug
     # self.ch_out = read_ch(path, 'output')
     self.read_data_to_memory()
     self.len = read_length(path, 'output')
     self.puzzle_num = int(np.sqrt(puzzle_num))
     self.pnc = PN_converter(puzzle_num,
                             pnumber=min(math.factorial(puzzle_num), 50))
     if aug:
         self.len *= 4
     if inch == 1:
         self.len *= 64
예제 #14
0
 def __init__(self, path, aug, pnc=None, puzzle_num=0, img_number=1):
     self.root_path = path
     self.ch_out = read_ch(path, 'output')
     self.len = read_length(path, 'output')
     self.read_data_to_memory()
     self.puzzle_num = int(np.sqrt(puzzle_num))
     self.img_num=img_number
     if pnc is None:
         self.pnc = PN_converter(puzzle_num,
                             pnumber=min(math.factorial(puzzle_num), 50))
     else:
         self.pnc=pnc
     if aug:
         self.aug = 4
     else:
         self.aug = 1
 def __init__(self,
              paths,
              aug,
              pnc=None,
              puzzle_num=0,
              img_number=1,
              sample_rate=1,
              original_img=False,
              more_ri=False):
     self.root_path = paths
     self.original_img = original_img
     self.inputs = []
     self.outputs = []
     self.lens = [0]
     self.len = 0
     self.more_ri = more_ri
     for p in paths:
         self.read_data_to_memory(p)
         if sample_rate == 1:
             self.len += read_length(p, 'output')
         else:
             self.len += sample_rate
         self.lens.append(self.len)
     self.ch_out = read_ch(paths[0], 'output')
     self.puzzle_num = int(np.sqrt(puzzle_num))
     self.img_num = img_number
     if pnc is None:
         self.pnc = PN_converter(puzzle_num,
                                 pnumber=min(math.factorial(puzzle_num),
                                             50))
     else:
         self.pnc = pnc
     if aug:
         self.aug = 1
         self.len *= 4
     else:
         self.aug = 0
    def __getitem__(self, item):
        # light = item % self.img_num
        # light = item % self.img_num
        # item = (item - light) // self.img_num
        light = 27
        # light = np.random.permutation(range(64))[:3]
        if self.aug:
            aug = item % 4
            item = (item - aug) // 4
        else:
            aug = 0

        for c in range(len(self.lens)):
            if item >= self.lens[c]:
                continue
            else:
                item = item - self.lens[c - 1]
                self.input = self.inputs[c - 1]
                self.output = self.outputs[c - 1]
                type = c - 1
                break

        input = self.input
        input = np.expand_dims(input[item, light, :, :], axis=0)

        # input = self.input[item,light,:,:]

        # input= input/np.max(input)
        input = input - np.mean(input)  # zero centered
        input = input / (np.std(input) + 0.00000001)  # normalize variance

        output = self.output[item, :, :, :]
        # flip to match the normal map
        input = np.ascontiguousarray(np.flip(input, 1))
        output = np.ascontiguousarray(np.flip(output, 1))

        if aug % 2 == 0:
            input = np.ascontiguousarray(np.flip(input, 1))
            output = np.ascontiguousarray(np.flip(output, 1))
        if aug > 1:
            input = np.ascontiguousarray(np.flip(input, 2))
            output = np.ascontiguousarray(np.flip(output, 2))
        puzzle = np.repeat(input.copy(), 3, axis=0)
        puzzle_num = self.puzzle_num
        #puzzle=np.zeros_like(puzzle)  # white back ground
        # idxs_array = np.random.permutation(puzzle_num * puzzle_num)
        self.perm_id = np.random.randint(min(math.factorial(puzzle_num**2),
                                             50))
        idxs = self.pnc.num2perm(self.perm_id)
        #  hard coded for laziness

        if 'Nut' in self.root_path[type] or 'panel' in self.root_path[
                type] or 'T' in self.root_path[type]:
            edge = 10
        else:
            edge = 10
        stride = (puzzle.shape[1] - edge * 2) // puzzle_num - edge // 2
        for i in range(puzzle_num * puzzle_num):
            giggle = int(((np.random.rand() + 1) * edge) // 8)
            giggle2 = int(((np.random.rand() + 1) * edge) // 8)
            col = i % puzzle_num
            row = (i - col) // puzzle_num
            tcol = idxs[i] % puzzle_num
            trow = (idxs[i] - tcol) // puzzle_num
            # puzzle[:, edge + trow * stride:edge + trow * stride + stride,
            # edge + tcol * stride:edge + tcol * stride + stride] = input[:,
            #                                                       edge + row * stride:edge + row * stride + stride,
            #                                                       edge + col * stride:edge + col * stride + stride]
            puzzle[:, edge // 2 + trow * (stride + edge) + giggle:edge // 2 +
                   trow * (stride + edge) + stride + giggle,
                   edge // 2 + tcol * (stride + edge) + giggle2:edge // 2 +
                   tcol * (stride + edge) + stride +
                   giggle2] = input[:, edge + row * stride + giggle2:edge +
                                    row * stride + stride + giggle2,
                                    edge + col * stride + giggle:edge +
                                    col * stride + stride + giggle]

        # plt.subplot(2,1,1)
        # plt.imshow(puzzle[0,:,:])
        # plt.subplot(2,1,2)
        # plt.imshow(input.squeeze())
        # plt.show()
        # print(self.perm_id)
        if self.more_ri:
            idx = np.random.randint(self.len)
            input = np.expand_dims(
                self.input[idx, np.random.randint(self.img_num), :, :], axis=0)
            input = input / np.max(input)
            np.repeat(input, 3, axis=0)
            return puzzle, int(self.perm_id), np.repeat(input, 3,
                                                        axis=0), output
        if self.original_img:
            return puzzle, int(self.perm_id), np.repeat(input, 3,
                                                        axis=0), output
        else:
            return puzzle, int(self.perm_id)
예제 #17
0
def poisson_dist(n_ave, n):
    f = ((n_ave**n) / (math.factorial(n))) * (np.exp(-n_ave))
    return f
예제 #18
0
    def run_overall_ga(self):
        possible_solutions = m.factorial(self.number_of_cities - 1)
        ninitpop = self.initial_pop_size
        ## create an empty dataframe to store the solutions
        all_solutions_generated = pd.DataFrame(columns=["Route", "Cost"])
        """start a for loop and run the whole process for mentioned number
         of times"""
        print("Starting {} iterations of the GA".format(self.noverall))
        # generating initial population
        """We only generate a population initially, after  the first run ,
		we take the best solutions from the previous run and continue with
         the process"""
        if all_solutions_generated.shape[0] == 0:
            initial_pop_cost = self.initial_pop_cost()
            sorted_init_pop = initial_pop_cost.sort_values("Cost")
        else:
            sorted_init_pop = all_solutions_generated.head(
                self.initial_pop_size)

        # selecting the elite few
        elite_few_df = self.the_elite_few()
        best_sol = []
        """Generating a random number based on which we either
         mutate or do a crossover"""
        mating_factor = np.random.uniform(
            0, 1, 1)  # Random pick to decide on Mutation / crossover

        for i in range(self.noverall):
            if mating_factor < 0.2:
                mutated_population_wth_cost = self.mutation_function(
                    all_solutions_generated)
                all_solutions_generated.append(mutated_population_wth_cost)
            else:
                crossover_population = self.routes_after_cross_over()
                all_solutions_generated = all_solutions_generated.append(
                    crossover_population)

            all_solutions_generated.Route = all_solutions_generated.Route.map(
                lambda x: tuple(x))
            unique_sols_generated = (
                all_solutions_generated.drop_duplicates().sort_values("Cost"))
            all_solutions_generated = all_solutions_generated.sort_values(
                "Cost").head(
                    ninitpop)  # only take the top ninitpop number of solutions
            all_solutions_generated.Route = all_solutions_generated.Route.map(
                lambda x: list(x))

        print(
            "-----------------------------------------------------------------"
        )
        print("""Best solution for initial population size of {} and number 
            of runs {} is \n {}""".format(
            self.initial_pop_size,
            self.noverall,
            all_solutions_generated.sort_values("Cost").head(1),
        ))
        print("Generated {}({}%) of the {} solutions".format(
            all_solutions_generated.shape[0],
            np.round((len(all_solutions_generated) / possible_solutions) * 100,
                     3),
            possible_solutions,
        ))
        final_sol = all_solutions_generated.sort_values("Cost").head(1)

        #### Final Solution ( Cities)
        final_route = []
        starting_point = self.dist_mat.index[0]
        for i in final_sol.Route.values[0]:
            final_route.append(self.cities_mapping[i])
        final_route = [starting_point] + final_route + [starting_point]
        total_cost = ray.get(
            self.fitness_function.remote(self,
                                         list(final_sol.Route.values[0])))

        print(
            """Total distance travelled to cover the final route of \n {} is {} KM.
             (Generated from initial population size of {})""".format(
                " => ".join(final_route), total_cost, self.initial_pop_size))
        print(
            "-----------------------------------------------------------------"
        )
        best_sol.append(final_sol)

        return (final_sol, total_cost)
def evaluate_hand(hand):
    # unpack the hand into single lists
    values = [hand[i][1] for i in range(len(hand))]
    suits = [hand[i][2] for i in range(len(hand))]
    checked_values = []
    # set up booleans
    pair = False
    two_pair = False
    three_of_a_kind = False
    four_of_a_kind = False
    full_house = False
    straight = False
    flush = False
    straight_flush = False
    royal_flush = False
    # check for multiples (there's probably a less sloppy way to do this)
    for i in values:
        if values.count(i) == 2 and pair is True and i not in checked_values:
            two_pair = True
        if values.count(i) == 2 and pair is False:
            pair = True
        if values.count(i) == 3:
            three_of_a_kind = True
        if values.count(i) == 4:
            four_of_a_kind = True
        checked_values.append(i)
    # check for a full house
    if pair is True and three_of_a_kind is True:
        pair = False
        three_of_a_kind = False
        full_house = True
    # check for a straight
    if suits.count(suits[0]) == 5:
        straight = True
    # check for flushes
    flush_products = []  # store result of flush values multiplied together
    for i in range(1, 13):
        flush_products.append(math.factorial(i + 4) / math.factorial(i))
    flush_products.append(13 * 12 * 11 * 10 *
                          1)  # royal flush value... duct tape solution
    if np.prod(values) in flush_products:
        flush = True
    if flush is True and straight:
        straight = False
        flush = False
        straight_flush = True
    if np.prod(values) == 13 * 12 * 11 * 10 * 1 and straight_flush:
        straight_flush = False
        royal_flush = True
    # find the high card for tie-breakers
    high_card = max(values)
    # record hand results
    hand_results = [
        pair, two_pair, three_of_a_kind, straight, flush, full_house,
        four_of_a_kind, straight_flush, royal_flush
    ]
    hand_rank = 1
    for i in range(
            len(hand_results)
    ):  # objects in hand_results are in order of rank, so finding the idx in hand_results tells you the rank of the hand
        if hand_results[i]:
            hand_rank = i + 2
    return hand_rank, high_card
예제 #20
0
def normalization(v,α):
    N_v = math.sqrt(α/(2.**v * math.factorial(v) * math.sqrt(math.pi)))
    return N_v
예제 #21
0
 def combination(self, n, m):
     if n == m: return 1
     return math.factorial(n) / (math.factorial(n - m) * math.factorial(m))
예제 #22
0
파일: 53.py 프로젝트: tkmckenzie/pan
def choose(n, r):
    return npm.factorial(n) / (npm.factorial(r) * npm.factorial(n - r))
예제 #23
0
 def fac(self, a):  # a!
     return math.factorial(a)
예제 #24
0
파일: taskn.py 프로젝트: hmvege/Fys2160
def omega(N,Q):
	top = math.factorial(N+Q-1)
	bottom = math.factorial(Q)*math.factorial(N-1)
	return top/bottom
예제 #25
0
from numpy import math

total = 0
for i in range(0, 100000):
    a = str(i)
    current = 0
    for x in a:
        current += math.factorial(int(x))
    if (current == i):
        total += i
        print(i)
        print(current)
print(total)
예제 #26
0
def factorial(n):
    return math.factorial(n)
예제 #27
0
 def fac(self, a):  # a!
     return math.factorial(a)
예제 #28
0
def main(version, *args):
    global n
    global k
    global M

    try:
        config_path = args[0][0]
    except IndexError:
        print(
            'Fatal error: Please specify the path of the configuration file as the first argument.\nExiting'
        )
        quit()

    num_runs = 1
    scalarizer = scalarizers_list[0]
    flag_create_snapshots = False

    ### Read all command-line parameters ###
    try:
        opts, args = getopt.getopt(
            args[0][1:], 'r:s:hv',
            ['runs=', 'scal=', 'snapshots', 'help', 'version'])
        for opt, arg in opts:
            if opt in ('-r', '--runs'):
                try:
                    num_runs = int(arg)
                    print('Executing {0} runs.'.format(num_runs))
                except ValueError:
                    print(
                        '\nInvalid number of runs provided. Defaulting to 1.')

            elif opt in ('-s', '--scal'):
                scalarizer = str(arg).upper()
                if scalarizer not in scalarizers_list:
                    print('\nError: Provided scalarizer name not implemented.')
                    print('Available scalarization functions: {0}'.format(
                        ', '.join(scalarizers_list)))
                    print('Defaulting to {0}.\n'.format(scalarizers_list[0]))
                    scalarizer = scalarizers_list[0]
                else:
                    print('Using {0} scalarizer.'.format(scalarizer))

            elif opt in ('--snapshots'):
                flag_create_snapshots = True
                print('Creating snapshots in the \'snapshots\' folder.')

            elif opt in ('-h', '--help'):
                print(
                    'Usage: python3 iMOACOR.py <path to configuration file> [OPTIONS]\n'
                )
                print('Options:')
                print(' -r N, --runs=N          the number of runs to execute')
                print(
                    ' -s NAME, --scal=NAME    use the scalarization method named NAME'
                )
                print(
                    ' --snapshots             write generational snapshots to the \'snapshots\' folder'
                )
                print(
                    ' -h, --help              display this help page and exit')
                print(
                    ' -v, --version           display version information and exit'
                )
                print('\n')
                quit()

            elif opt in ('-v', '--version'):
                print('iMOACOR version {0}'.format(version))
                print(
                    'License LGPLv3: GNU LGPL version 3 <https://www.gnu.org/licenses/lgpl>.'
                )
                print('Written by Mykel Shumay.')
                print('\n')
                quit()

    except getopt.GetoptError:
        print('\nError: Unrecognized option provided,' +
              ' or an option that requires an argument was given none.')
        print('Call with option \'--help\' for the help page.\n\n')
        quit()

    try:
        # Searches for the appropriate configuration file.
        config = ConfigParser()
        config.read(config_path)
        chosenConfig = config['Parameters']

        # Reads from configuration file.
        obj_function_name = chosenConfig['Function']
        n = int(chosenConfig['n'])
        k = int(chosenConfig['k'])
        Rmin = float(chosenConfig['Rmin'])
        Rmax = float(chosenConfig['Rmax'])
        q = float(chosenConfig['q'])
        xi = float(chosenConfig['xi'])
        Gmax = int(chosenConfig['Gmax'])
        MAX_RECORD_SIZE = int(chosenConfig['MAX_RECORD_SIZE'])
        EPSILON = 1e-4
        var_threshold = float(chosenConfig['varThreshold'])
        tol_threshold = float(chosenConfig['tolThreshold'])
        H = int(chosenConfig['H'])
        M = N = np_math.factorial(H + k - 1) // np_math.factorial(
            k - 1) // np_math.factorial(H)
    except KeyError:
        print('Fatal error: Unable to read configuration file.\n' +
              'Ensure that the provided path is correct.')
        quit()

    print('\nParameters:')
    print('Objective Function:\t{0:5>}'.format(obj_function_name))
    print('\tScalarizer:\t{0:>5}'.format(scalarizer))
    print('\tn:\t\t{0:5}'.format(n))
    print('\tk:\t\t{0:5}'.format(k))
    print('\tRmin:\t\t{0:5}'.format(Rmin))
    print('\tRmax:\t\t{0:5}'.format(Rmax))
    print('\tq:\t\t{0:5}'.format(q))
    print('\txi:\t\t{0:5}'.format(xi))
    print('\tGmax:\t\t{0:5}'.format(Gmax))
    print('\tM:\t\t{0:5}'.format(M))
    print('\tH:\t\t{0:5}'.format(H))
    print('\tN:\t\t{0:5}\n'.format(N))

    return (obj_function_name, n, k, M, Rmin, Rmax, q, xi, Gmax, N, H, EPSILON,
            MAX_RECORD_SIZE, var_threshold, tol_threshold, num_runs,
            scalarizer, flag_create_snapshots)
예제 #29
0
'''
sinsum.py
v. 1 8/27/18
calculate the sine of an angle from the series expansion
'''

# Import factorial from numpy
from numpy import math

# Initialization of variables
# Get the angle from the user
x = input("Enter the angle in degrees: ")
# convert angle to radians
x = x * math.pi / 180
# get the number of terms to compute from user
N = input("Enter number of terms to compute: ")
sum = 0

#create the loop for our calculation
for j in range (0, N+1):
    sum = sum + (-1)**j*x**(2*j+1)/math.factorial(2*j+1)


#print out result
print "sin(x) = ", sum

print "Percent error = ", math.fabs((math.sin(x)) - sum) / (math.sin(x)) * 100