text
stringlengths
0
1.05M
meta
dict
'32x32x32 Enzynet architecture with adapted weights' # Authors: Afshine Amidi <lastname@mit.edu> # Shervine Amidi <firstname@stanford.edu> # MIT License import numpy as np import os.path from enzynet.keras_utils import MetricsHistory, Voting from enzynet.tools import read_dict, get_class_weights from enzynet.volume import VolumeDataGenerator from keras.callbacks import ModelCheckpoint from keras.initializers import RandomNormal from keras.layers import Dense, Dropout, Flatten, Activation from keras.layers import Conv3D, MaxPooling3D from keras.layers.advanced_activations import LeakyReLU from keras.models import Sequential from keras.optimizers import Adam from keras.regularizers import l2 from keras import backend as K mode_run = 'test' mode_dataset = 'full' mode_weights = 'balanced' ##----------------------------- Parameters -----------------------------------## # PDB weights = [] n_classes = 6 n_channels = 1 + len(weights) scaling_weights = True # Volume p = 0 v_size = 32 flips = (0.2, 0.2, 0.2) max_radius = 40 shuffle = True noise_treatment = False # Model batch_size = 32 max_epochs = 200 period_checkpoint = 50 # Testing voting_type = 'probabilities' augmentation = ['None', 'flips', 'weighted_flips'] # Miscellenaous current_file_name = os.path.basename(__file__)[:-3] stddev_conv3d = np.sqrt(2.0/(n_channels)) ##------------------------------ Dataset -------------------------------------## # Load dictionary of labels dictionary = read_dict('../../datasets/dataset_single.csv') # Load partitions if mode_dataset == 'full': partition = read_dict('../../datasets/partition_single.csv') elif mode_dataset == 'reduced': partition = read_dict('../../datasets/partition_single_red.csv') exec("partition['train'] = " + partition['train']) exec("partition['validation'] = " + partition['validation']) exec("partition['test'] = " + partition['test']) # Final computations partition['train'] = partition['train'] + partition['validation'] partition['validation'] = partition['test'] # Get class weights class_weights = get_class_weights(dictionary, partition['train'], mode=mode_weights) # Training generator training_generator = \ VolumeDataGenerator(list_enzymes=partition['train'], labels=dictionary, v_size=v_size, flips=flips, batch_size=batch_size, shuffle=shuffle, p=p, max_radius=max_radius, noise_treatment=noise_treatment, weights=weights, scaling_weights=scaling_weights) # Validation generator validation_generator = \ VolumeDataGenerator(list_enzymes=partition['validation'], labels=dictionary, v_size=v_size, flips=(0, 0, 0), # No flip batch_size=batch_size, shuffle=False, # Validate with fixed set p=p, max_radius=max_radius, noise_treatment=noise_treatment, weights=weights, scaling_weights=scaling_weights) # Check if data has been precomputed training_generator.check_precomputed() ##----------------------------- Testing --------------------------------------## # Voting object predictions = \ Voting(list_enzymes=partition['test'], labels=dictionary, voting_type=voting_type, v_size=v_size, augmentation=augmentation, p=p, max_radius=max_radius, noise_treatment=noise_treatment, weights=weights, scaling_weights=scaling_weights) ##------------------------------ Model ---------------------------------------## # Create model = Sequential() # Add layers model.add(Conv3D(filters=32, kernel_size=9, strides=2, padding='valid', kernel_initializer=RandomNormal(mean=0.0, stddev=stddev_conv3d * 9**(-3/2)), bias_initializer='zeros', kernel_regularizer=l2(0.001), bias_regularizer=None, input_shape=(v_size, v_size, v_size, n_channels))) model.add(LeakyReLU(alpha=0.1)) model.add(Dropout(rate=0.2)) model.add(Conv3D(filters=64, kernel_size=5, strides=1, padding='valid', kernel_initializer=RandomNormal(mean=0.0, stddev=stddev_conv3d * 5**(-3/2)), bias_initializer='zeros', kernel_regularizer=l2(0.001), bias_regularizer=None)) model.add(LeakyReLU(alpha=0.1)) model.add(MaxPooling3D(pool_size=(2,2,2))) model.add(Dropout(rate=0.3)) model.add(Flatten()) model.add(Dense(units=128, kernel_initializer=RandomNormal(mean=0.0, stddev=0.01), bias_initializer='zeros', kernel_regularizer=l2(0.001), bias_regularizer=None)) model.add(Dropout(rate=0.4)) model.add(Dense(units=n_classes, kernel_initializer=RandomNormal(mean=0.0, stddev=0.01), bias_initializer='zeros', kernel_regularizer=l2(0.001), bias_regularizer=None)) model.add(Activation('softmax')) # Track accuracy and loss in real-time history = MetricsHistory(saving_path=current_file_name + '.csv') # Checkpoints checkpoints = ModelCheckpoint('checkpoints/' + current_file_name + '_{epoch:02d}' + '.hd5f', save_weights_only=True, period=period_checkpoint) if mode_run == 'train': # Compile model.compile(optimizer=Adam(lr=0.001, decay=0.00016667), loss='categorical_crossentropy', metrics=['accuracy']) # Train model.fit_generator(generator=training_generator, epochs=max_epochs, verbose=1, validation_data=validation_generator, callbacks=[history, checkpoints], class_weight=class_weights, use_multiprocessing=True, workers=6, max_queue_size=30) if mode_run == 'test': # Load weights weights_path = \ 'checkpoints/' + current_file_name + '_{0:02d}'.format(max_epochs) + '.hd5f' model.load_weights(weights_path) # Predict predictions.predict(model) # Compute indicators predictions.get_assessment() # Clear session K.clear_session()
{ "repo_name": "shervinea/enzynet", "path": "scripts/architecture/enzynet_adapted.py", "copies": "1", "size": "6707", "license": "mit", "hash": -2624966482491894300, "line_mean": 30.0509259259, "line_max": 93, "alpha_frac": 0.5692560012, "autogenerated": false, "ratio": 3.9360328638497655, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5005288865049765, "avg_score": null, "num_lines": null }
'32x32x32 Enzynet architecture with uniform weights' # Authors: Afshine Amidi <lastname@mit.edu> # Shervine Amidi <firstname@stanford.edu> # MIT License import numpy as np import os.path from enzynet.keras_utils import MetricsHistory, Voting from enzynet.tools import read_dict, get_class_weights from enzynet.volume import VolumeDataGenerator from keras.callbacks import ModelCheckpoint from keras.initializers import RandomNormal from keras.layers import Dense, Dropout, Flatten, Activation from keras.layers import Conv3D, MaxPooling3D from keras.layers.advanced_activations import LeakyReLU from keras.models import Sequential from keras.optimizers import Adam from keras.regularizers import l2 from keras import backend as K mode_run = 'test' mode_dataset = 'full' mode_weights = 'unbalanced' ##----------------------------- Parameters -----------------------------------## # PDB weights = [] n_classes = 6 n_channels = 1 + len(weights) scaling_weights = True # Volume p = 0 v_size = 32 flips = (0.2, 0.2, 0.2) max_radius = 40 shuffle = True noise_treatment = False # Model batch_size = 32 max_epochs = 200 period_checkpoint = 50 # Testing voting_type = 'probabilities' augmentation = ['None', 'flips', 'weighted_flips'] # Miscellenaous current_file_name = os.path.basename(__file__)[:-3] stddev_conv3d = np.sqrt(2.0/(n_channels)) ##------------------------------ Dataset -------------------------------------## # Load dictionary of labels dictionary = read_dict('../../datasets/dataset_single.csv') # Load partitions if mode_dataset == 'full': partition = read_dict('../../datasets/partition_single.csv') elif mode_dataset == 'reduced': partition = read_dict('../../datasets/partition_single_red.csv') exec("partition['train'] = " + partition['train']) exec("partition['validation'] = " + partition['validation']) exec("partition['test'] = " + partition['test']) # Final computations partition['train'] = partition['train'] + partition['validation'] partition['validation'] = partition['test'] # Get class weights class_weights = get_class_weights(dictionary, partition['train'], mode=mode_weights) # Training generator training_generator = \ VolumeDataGenerator(list_enzymes=partition['train'], labels=dictionary, v_size=v_size, flips=flips, batch_size=batch_size, shuffle=shuffle, p=p, max_radius=max_radius, noise_treatment=noise_treatment, weights=weights, scaling_weights=scaling_weights) # Validation generator validation_generator = \ VolumeDataGenerator(list_enzymes=partition['validation'], labels=dictionary, v_size=v_size, flips=(0, 0, 0), # No flip batch_size=batch_size, shuffle=False, # Validate with fixed set p=p, max_radius=max_radius, noise_treatment=noise_treatment, weights=weights, scaling_weights=scaling_weights) # Check if data has been precomputed training_generator.check_precomputed() ##----------------------------- Testing --------------------------------------## # Voting object predictions = \ Voting(list_enzymes=partition['test'], labels=dictionary, voting_type=voting_type, v_size=v_size, augmentation=augmentation, p=p, max_radius=max_radius, noise_treatment=noise_treatment, weights=weights, scaling_weights=scaling_weights) ##------------------------------ Model ---------------------------------------## # Create model = Sequential() # Add layers model.add(Conv3D(filters=32, kernel_size=9, strides=2, padding='valid', kernel_initializer=RandomNormal(mean=0.0, stddev=stddev_conv3d * 9**(-3/2)), bias_initializer='zeros', kernel_regularizer=l2(0.001), bias_regularizer=None, input_shape=(v_size, v_size, v_size, n_channels))) model.add(LeakyReLU(alpha=0.1)) model.add(Dropout(rate=0.2)) model.add(Conv3D(filters=64, kernel_size=5, strides=1, padding='valid', kernel_initializer=RandomNormal(mean=0.0, stddev=stddev_conv3d * 5**(-3/2)), bias_initializer='zeros', kernel_regularizer=l2(0.001), bias_regularizer=None)) model.add(LeakyReLU(alpha=0.1)) model.add(MaxPooling3D(pool_size=(2,2,2))) model.add(Dropout(rate=0.3)) model.add(Flatten()) model.add(Dense(units=128, kernel_initializer=RandomNormal(mean=0.0, stddev=0.01), bias_initializer='zeros', kernel_regularizer=l2(0.001), bias_regularizer=None)) model.add(Dropout(rate=0.4)) model.add(Dense(units=n_classes, kernel_initializer=RandomNormal(mean=0.0, stddev=0.01), bias_initializer='zeros', kernel_regularizer=l2(0.001), bias_regularizer=None)) model.add(Activation('softmax')) # Track accuracy and loss in real-time history = MetricsHistory(saving_path=current_file_name + '.csv') # Checkpoints checkpoints = ModelCheckpoint('checkpoints/' + current_file_name + '_{epoch:02d}' + '.hd5f', save_weights_only=True, period=period_checkpoint) if mode_run == 'train': # Compile model.compile(optimizer=Adam(lr=0.001, decay=0.00016667), loss='categorical_crossentropy', metrics=['accuracy']) # Train model.fit_generator(generator=training_generator, epochs=max_epochs, verbose=1, validation_data=validation_generator, callbacks=[history, checkpoints], class_weight=class_weights, use_multiprocessing=True, workers=8, max_queue_size=30) if mode_run == 'test': # Load weights weights_path = \ 'checkpoints/' + current_file_name + '_{0:02d}'.format(max_epochs) + '.hd5f' model.load_weights(weights_path) # Predict predictions.predict(model) # Compute indicators predictions.get_assessment() # Clear session K.clear_session()
{ "repo_name": "shervinea/enzynet", "path": "scripts/architecture/enzynet_uniform.py", "copies": "1", "size": "6709", "license": "mit", "hash": 6131769097190653000, "line_mean": 30.0601851852, "line_max": 93, "alpha_frac": 0.569384409, "autogenerated": false, "ratio": 3.9348973607038125, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9999095114418473, "avg_score": 0.0010373310570680058, "num_lines": 216 }
# 330-patching-array.py class Solution(object): def minPatches_wa(self, nums, n): # Wrong answer. not this method. """ :type nums: List[int] :type n: int :rtype: int """ # Example: # nums = [1, 2, 4, 9] # rbound = 1 + 2 + 4 = 7 count = 0 toInsert = 2 rbound = 1 size = len(nums) if size == 0 or nums[0] != 1: nums.insert(0, 1) count += 1 insert_idx = 1 # nums[0] is always 1 while rbound < n: print "r: ", rbound, " count: ", count while insert_idx < size: curr = nums[insert_idx] if curr == toInsert: rbound += curr insert_idx += 1 toInsert *= 2 elif curr <= rbound: rbound += curr insert_idx += 1 else: break if rbound >= n: break nums.insert(insert_idx, toInsert) count += 1 rbound += toInsert toInsert *= 2 insert_idx += 1 size += 1 print nums return count def minPatches(self, nums, n): count, top = 0, 0 i = 0 while top < n: if i < len(nums) and nums[i] <= top + 1: top += nums[i] i += 1 else: print 'top: ', top, ' count: ', count top = top * 2 + 1 count += 1 return count s = Solution() print s.minPatches([1,5,10], 20) print s.minPatches([1,2,2], 5) print s.minPatches([1,2,31,33], 2147483647)
{ "repo_name": "daicang/Leetcode-solutions", "path": "330-patching-array.py", "copies": "1", "size": "1730", "license": "mit", "hash": 7442747472148930000, "line_mean": 23.3661971831, "line_max": 70, "alpha_frac": 0.4040462428, "autogenerated": false, "ratio": 3.949771689497717, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4853817932297717, "avg_score": null, "num_lines": null }
# 331. Verify Preorder Serialization of a Binary Tree # One way to serialize a binary tree is to use pre-order traversal. # When we encounter a non-null node, we record the node's value. # If it is a null node, we record using a sentinel value such as #. # # _9_ # / \ # 3 2 # / \ / \ # 4 1 # 6 # / \ / \ / \ # # # # # # # # # For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", # where # represents a null node. # # Given a string of comma separated values, verify whether it is a correct preorder traversal serialization # of a binary tree. Find an algorithm without reconstructing the tree. # # Each comma separated value in the string must be either an integer or a character '#' representing null pointer. # # You may assume that the input format is always valid, for example it could never contain two consecutive commas such as "1,,3". # # Example 1: # # Input: "9,3,4,#,#,1,#,#,2,#,6,#,#" # Output: true # # Example 2: # # Input: "1,#" # Output: false # # Example 3: # # Input: "9,#,#,1" # Output: false # class Solution: # https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/discuss/78564/The-simplest-python-solution-with-explanation-(no-stack-no-recursion) # We just need to remember how many empty slots we have during the process. # Initially we have one ( for the root ). # for each node we check if we still have empty slots to put it in: # a null node occupies one slot. # a non-null node occupies one slot before he creates two more. the net gain is one. def isValidSerialization(self, preorder): """ :type preorder: str :rtype: bool """ nodes = preorder.split(',') slot = 1 # initially we have one empty slot to put the root in for node in nodes: if slot == 0: # no empty slot to put current node in return False if node == '#': # a null node? slot -= 1 # occupy 1 slot else: # a non-null node? slot += 1 # create new slot return slot == 0 # we don't allow empty slots at the end sol = Solution() print(sol.isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#")) print(sol.isValidSerialization("1,#"))
{ "repo_name": "gengwg/leetcode", "path": "331_verify_preorder_serialization_of_a_binary_tree.py", "copies": "1", "size": "2336", "license": "apache-2.0", "hash": -6263315650736752000, "line_mean": 34.3939393939, "line_max": 166, "alpha_frac": 0.6125856164, "autogenerated": false, "ratio": 3.471025260029718, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45836108764297173, "avg_score": null, "num_lines": null }
# 331-verify-preorder-serialization-of-binary-tree.py class Solution(object): def isValidSerialization_TLE(self, preorder): """ :type preorder: str :rtype: bool """ def loop(l): length = len(l) if length < 3: if length == 1 and l[0] == '#': return True return False if l[0] == '#': return False for i in xrange(2, length): if loop(l[1:i]) and loop(l[i:]): return True return False l = preorder.split(',') return loop(l) def isValidSerialization(self, preorder): diff = 1 # In order - out order for i in preorder.split(","): diff -= 1 if diff < 0: return False if i != '#': diff += 2 return True if diff == 0 else False s = Solution() print(s.isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#")) print(s.isValidSerialization("9,9,9,9,9,#,#,#,9,#,9,9,#,#,#,9,9,9,9,9,#,#,9,#,9,9,#,#,#,9,9,#,#,#,9,#,#,9,9,9,#,#,#,9,#,#,9,9,9,#,#,#,9,9,9,9,#,9,#,9,#,#,9,#,#,9,#,#,9,#,#"))
{ "repo_name": "daicang/Leetcode-solutions", "path": "331-verify-preorder-serialization-of-binary-tree.py", "copies": "1", "size": "1138", "license": "mit", "hash": 3027573136362382000, "line_mean": 31.5142857143, "line_max": 174, "alpha_frac": 0.4551845343, "autogenerated": false, "ratio": 3.152354570637119, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4107539104937119, "avg_score": null, "num_lines": null }
# 332-reconstruct-itinerary.py class Solution(object): def findItinerary(self, tickets): """ :type tickets: List[List[str]] :rtype: List[str] """ # Wrong # ret = ["JFK"] # flag = 0 # while flag == 0: # tmp = "ZZZ" # found = 0 # for curr in tickets: # if curr[0] != ret[-1]: continue # if curr[1] < tmp: # tmp = curr[1] # found = 1 # if found == 0: break # if tmp in ret: flag = 1 # ret.append(tmp) # def minValue(l): # ret = l[0] # for i in l: # if i < ret: ret = i # return ret # dict = {} # for i in tickets: # key, value = i[0], i[1] # if key not in dict: # dict[key] = [value] # else: # dict[key].append(value) # ret = ["JFK"] # flag = 0 # while flag == 0: # next = minValue(dict[ret[-1]]) # if next not in dict or next in ret: flag = 1 # ret.append(next) # return ret targets = collections.defaultdict(list) for a, b in sorted(tickets)[::-1]: targets[a].append(b) ret, stack = [], ['JFK'] while stack: while targets[stack[-1]]: stack.append(targets[stack[-1]].pop()) ret.append(stack.pop()) return ret[::-1]
{ "repo_name": "daicang/Leetcode-solutions", "path": "332-reconstruct-itinerary.py", "copies": "1", "size": "1542", "license": "mit", "hash": -6769834705727384000, "line_mean": 25.5862068966, "line_max": 58, "alpha_frac": 0.4007782101, "autogenerated": false, "ratio": 3.645390070921986, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4546168281021986, "avg_score": null, "num_lines": null }
'''[3,3,5,5,6,7] Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. For example, Given nums = [1,3,-1,-3,5,3,6,7], and k = 3. Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7 Therefore, return the max sliding window as [3,3,5,5,6,7]. Note: You may assume k is always valid, ie: 1 <= k <= input array's size for non-empty array. Follow up: Could you solve it in linear time? ''' class Solution: def maxSlidingWindow(self,nums,k): num = [] for i in xrange(len(nums) - k + 1): num.append(max(nums[i:i+k])) return num assert Solution().maxSlidingWindow([1,3,-1,-3,5,3,6,7],3) == [3,3,5,5,6,7]
{ "repo_name": "liuyonggg/learning_python", "path": "leetcode/maxSlidingWindow.py", "copies": "1", "size": "1040", "license": "mit", "hash": 3996515629385024000, "line_mean": 31.5, "line_max": 227, "alpha_frac": 0.5451923077, "autogenerated": false, "ratio": 2.613065326633166, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8588613551716222, "avg_score": 0.013928816523388891, "num_lines": 32 }
# 335-self-crossing.py class Solution(object): def isSelfCrossing(self, x): """ :type x: List[int] :rtype: bool """ l = len(x) if (l < 4): return False flag = 0 # Is square decreasing hasBound = 0 # Has previous edge, cannot cross this bound prev4 = 0 prev3 = 0 prev2 = x[0] prev1 = x[1] for i in xrange(2, l): curr = x[i] if flag == 0: if curr <= prev2: flag = 1 # Start decreasing # No need to track p3 & p4 if curr < prev2 -prev4: # Region 1 prev2 = prev1 prev1 = curr else: prev2 = prev1 - prev3 prev1 = curr else: prev4 = prev3 prev3 = prev2 prev2 = prev1 prev1 = curr else: if curr >= prev2: return True prev2 = prev1 prev1 = curr return False s = Solution() print(s.isSelfCrossing([3, 3, 4, 2, 2]))
{ "repo_name": "daicang/Leetcode-solutions", "path": "335-self-crossing.py", "copies": "1", "size": "1258", "license": "mit", "hash": -619774399808925200, "line_mean": 27.5909090909, "line_max": 70, "alpha_frac": 0.3728139905, "autogenerated": false, "ratio": 4.460992907801418, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.010435506525715345, "num_lines": 44 }
"""336. Palindrome Pairs Hard URL: https://leetcode.com/problems/palindrome-pairs/ Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome. Example 1: Input: ["abcd","dcba","lls","s","sssll"] Output: [[0,1],[1,0],[3,2],[2,4]] Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"] Example 2: Input: ["bat","tab","cat"] Output: [[0,1],[1,0]] Explanation: The palindromes are ["battab","tabbat"] """ class SolutionWordPosDictPrefixSuffixPalindrome(object): def _isPalindrom(self, word): return word == word[::-1] def palindromePairs(self, words): """ :type words: List[str] :rtype: List[List[int]] Time complexity: O(n*m^2), where - n: number of words - m: max length of words Space complexity: O(n+m). """ # For each word, check if word's prefix and suffix are palindromes. n = len(words) pal_pairs = [] # Use dict: word->pos for quick lookup. word_pos_d = {word: pos for pos, word in enumerate(words)} # Iterate through words, check word's prefix and suffix based on each char. for word, pos in word_pos_d.items(): m = len(word) for j in range(m + 1): prefix = word[:j] suffix = word[j:] # If prefix is palindrome, reversed suffix in words but not current one, # append (reversed suffix pos, word pos). if self._isPalindrom(prefix): rev_suffix = suffix[::-1] if rev_suffix != word and rev_suffix in word_pos_d: pal_pairs.append([word_pos_d[rev_suffix], pos]) # If suffix is palindrome but not '', and prefix in words, # append (word pos, reversed prefix pos). if j != m and self._isPalindrom(suffix): rev_prefix = prefix[::-1] if rev_prefix in word_pos_d: pal_pairs.append([pos, word_pos_d[rev_prefix]]) return pal_pairs def main(): # Output: [[0,1],[1,0],[3,2],[2,4]] words = ["abcd","dcba","lls","s","sssll"] print SolutionWordPosDictPrefixSuffixPalindrome().palindromePairs(words) # Output: [[0,1],[1,0]] words = ["bat","tab","cat"] print SolutionWordPosDictPrefixSuffixPalindrome().palindromePairs(words) # Output: [[2,0],[2,1]] words = ["bot","t","to"] print SolutionWordPosDictPrefixSuffixPalindrome().palindromePairs(words) if __name__ == '__main__': main()
{ "repo_name": "bowen0701/algorithms_data_structures", "path": "lc0336_palindrome_pairs.py", "copies": "1", "size": "2698", "license": "bsd-2-clause", "hash": 8212894213480702000, "line_mean": 31.9024390244, "line_max": 88, "alpha_frac": 0.5681986657, "autogenerated": false, "ratio": 3.4238578680203045, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9464651980866976, "avg_score": 0.005480910570665627, "num_lines": 82 }
# 336-palindrome-pairs.py class Solution(object): """ :type words: List[str] :rtype: List[List[int]] """ # Brute force # def palindromePairs(self, words): # def isPalindrome(w): # return w == w[::-1] # ret = [] # for i in range(len(words)): # for j in range(len(words)): # if i == j: continue # if (isPalindrome(words[i]+words[j])): ret.append([i, j]) # return ret def palindromePairs(self, words): def isPalindrome(w): return w == w[::-1] ret = [] l = len(words) rdict = {} # reversed dict for i in xrange(l): # if words[i] == "": # for j in xrange(l): # if i == j: continue # if isPalindrome(words[j]): # ret.append([i, j]) # ret.append([j, i]) # continue rdict[words[i][::-1]] = i for i in xrange(l): curr = words[i] if curr != "" and isPalindrome(curr) and "" in rdict: ret.append([rdict[""], i]) for j in xrange(len(curr)): left = curr[:j] # could be "" right = curr[j:] # "" not included if left in rdict and isPalindrome(right) and rdict[left] != i: ret.append([i, rdict[left]]) if right in rdict and isPalindrome(left) and rdict[right] != i: ret.append([rdict[right], i]) return ret s = Solution() print(s.palindromePairs(["abcd","dcba","lls","s","sssll"]))
{ "repo_name": "daicang/Leetcode-solutions", "path": "336-palindrome-pairs.py", "copies": "1", "size": "1681", "license": "mit", "hash": -6214470868893065000, "line_mean": 31.3269230769, "line_max": 79, "alpha_frac": 0.4396192742, "autogenerated": false, "ratio": 3.5614406779661016, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45010599521661016, "avg_score": null, "num_lines": null }
# 339 - Nested List Weight Sum (Easy) # https://leetcode.com/problems/nested-list-weight-sum/ # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class Solution(object): # Do a DFS and multiply each value with the depth at that point. def dfs(self, nestedList, depth): if len(nestedList) == 0: return 0 acum = 0 for NI in nestedList: if NI.isInteger(): acum += NI.getInteger() * depth else: acum += self.dfs(NI.getList(), depth+1) return acum def depthSum(self, nestedList): """ :type nestedList: List[NestedInteger] :rtype: int """ return self.dfs(nestedList, 1)
{ "repo_name": "zubie7a/Algorithms", "path": "LeetCode/01_Easy/lc_339.py", "copies": "1", "size": "1512", "license": "mit", "hash": -3572588796100940000, "line_mean": 29.8775510204, "line_max": 95, "alpha_frac": 0.583994709, "autogenerated": false, "ratio": 3.9069767441860463, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9936113325724535, "avg_score": 0.010971625492302186, "num_lines": 49 }
#[3|3] def Tile(top, bottom): return {"top": top, "bottom": bottom} def placeDominioTile(tileArray, newTile): if (newTile["bottom"] == tileArray[0]["top"]): tileArray.insert(0, newTile) return tileArray if (newTile["top"] == tileArray[len(tileArray)-1]["bottom"]): tileArray.append(newTile) return tileArray for i in xrange(len(tileArray)-1): if ((newTile["top"] == tileArray[i]["bottom"]) and (newTile["bottom"] == tileArray[i+1]["top"])): tileArray.insert(i+1, newTile) return tileArray return tileArray #print placeDominioTile([Tile(1,1)], Tile(3,2)) #print placeDominioTile([Tile(2,1)], Tile(3,2)) #print placeDominioTile([Tile(1,3)], Tile(3,2)) #print placeDominioTile([Tile(2,1), Tile(1,3), Tile(3,5), Tile(5,6)], Tile(3,3)) def calculateDominoTiles(tilesArray): result = 0 for i in xrange(len(tilesArray)-1): if (tilesArray[i]["bottom"] != tilesArray[i+1]["top"]): return -1 result += tilesArray[i]["bottom"] result += tilesArray[i]["top"] return result #print calculateDominoTiles([Tile(3,3)]) #print calculateDominoTiles([Tile(3,3), Tile(3,5)]) #print calculateDominoTiles([Tile(3,3), Tile(3,4), Tile(5,1)])
{ "repo_name": "adrianbeloqui/Python", "path": "domino_tiles.py", "copies": "1", "size": "1295", "license": "mit", "hash": -1866446247554270200, "line_mean": 32.0789473684, "line_max": 105, "alpha_frac": 0.6023166023, "autogenerated": false, "ratio": 2.9770114942528734, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40793280965528733, "avg_score": null, "num_lines": null }
# 341-flatten-nested-list-iterator.py # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class NestedIterator(object): def __init__(self, nestedList): """ Initialize your data structure here. :type nestedList: List[NestedInteger] """ self.result = [] self.idx = 0 self.readlist(nestedList) def readlist(self, l): for i in l: if i.isInteger(): self.result.append(i.getInteger()) else: self.readlist(i.getList()) def next(self): """ :rtype: int """ ret = self.result[self.idx] self.idx += 1 return ret def hasNext(self): """ :rtype: bool """ return False if self.idx == len(self.result) else True # Your NestedIterator object will be instantiated and called as such: # i, v = NestedIterator(nestedList), [] # while i.hasNext(): v.append(i.next())
{ "repo_name": "daicang/Leetcode-solutions", "path": "341-flatten-nested-list-iterator.py", "copies": "1", "size": "1763", "license": "mit", "hash": 1987393945112994600, "line_mean": 26.546875, "line_max": 95, "alpha_frac": 0.5706182643, "autogenerated": false, "ratio": 3.997732426303855, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5068350690603854, "avg_score": null, "num_lines": null }
# 342. Power of Four # Given an integer (signed 32 bits), write a function to check whether it is a power of 4. # Example: # Given num = 16, return true. Given num = 5, return false. # Follow up: Could you solve it without loops/recursion? # O(1) / O(1) # No recursion or loops, but using count() class Solution(object): def isPowerOfFour(self, num): """ :type num: int :rtype: bool The bin() method: count if bin(num) has one 1 and even 0's. """ binstr = bin(num)[2:] return num > 0 and (binstr.count('1') == 1 and binstr.count('0') % 2 == 0) # following solutions from kamyu104/leetcode class Solution1(object): def isPowerOfFour(self, num): """ :type num: int :rtype: bool Test if num contains only one 1 and it's in an even digit. """ return num > 0 and (num & (num - 1)) == 0 and ((num & 0b01010101010101010101010101010101) == num) # O(1) / O(1) class Solution2(object): def isPowerOfFour(self, num): """ :type num: int :rtype: bool Remove all the tailing 0's, two at a time, and see if there is only one 1 left. """ while num and not (num & 0b11): num >>= 2 return (num == 1)
{ "repo_name": "aenon/OnlineJudge", "path": "leetcode/5.BitManipulation/342.PowerofFour.py", "copies": "1", "size": "1283", "license": "mit", "hash": 63444615020309800, "line_mean": 28.8604651163, "line_max": 105, "alpha_frac": 0.570537802, "autogenerated": false, "ratio": 3.4582210242587603, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9505993053294788, "avg_score": 0.004553154592794593, "num_lines": 43 }
# 345. Reverse Vowels of a String - LeetCode # https://leetcode.com/problems/reverse-vowels-of-a-string/description/ class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ vowels = { "a": True, "e": True, "i": True, "o": True, "u": True, "A": True, "E": True, "I": True, "O": True, "U": True, } s = list(s) start = 0 end = len(s) - 1 while end > start: if vowels.has_key(s[start]) and not vowels.has_key(s[end]): end -= 1 continue elif vowels.has_key(s[end]) and not vowels.has_key(s[start]): start += 1 continue elif vowels.has_key(s[end]) and vowels.has_key(s[start]): t = s[end] s[end] = s[start] s[start] = t end -= 1 start += 1 return "".join(s) ans = [ ("hello","holle"), ("a","a"), ("",""), ("leetcode","leotcede"), ] s = Solution() for i in ans: r = s.reverseVowels(i[0]) print r, r == i[1]
{ "repo_name": "heyf/cloaked-octo-adventure", "path": "leetcode/345_reverse-vowels-of-a-string.py", "copies": "1", "size": "1246", "license": "mit", "hash": -4454468884765435400, "line_mean": 24.4489795918, "line_max": 73, "alpha_frac": 0.4060995185, "autogenerated": false, "ratio": 3.3766937669376693, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42827932854376694, "avg_score": null, "num_lines": null }
# 345. Reverse Vowels of a String # Write a function that takes a string as input and reverse only the vowels of a string. # Example 1: # Given s = "hello", return "holle". # Example 2: # Given s = "leetcode", return "leotcede". # Note: # The vowels does not include the letter "y". class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ v = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] vowels = [] indices = [] res = [] for i, ch in enumerate(s): if ch in v: vowels.append(ch) indices.append(i) else: res.append(ch) vowels.reverse() for (i, x) in zip(indices, vowels): res.insert(i, x) return ''.join(res) def reverseVowels(self, s): """ :type s: str :rtype: str """ vowels = [i for i in range(len(s)) if s[i] in 'aeiouAEIOU'] s1 = list(s) for i in range(len(vowels)//2): s1[vowels[i]], s1[vowels[-i-1]] = s1[vowels[-i-1]], s1[vowels[i]] return ''.join(s1)
{ "repo_name": "gengwg/leetcode", "path": "345_reverse_vowels_of_string.py", "copies": "1", "size": "1165", "license": "apache-2.0", "hash": 6087780729574406000, "line_mean": 25.4772727273, "line_max": 88, "alpha_frac": 0.4815450644, "autogenerated": false, "ratio": 3.082010582010582, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4063555646410582, "avg_score": null, "num_lines": null }
# 3 4 5 triangle inscribed in a square. # j k # ._______.______. # | s /-_ | # | p / 3-_ s| m # | / -_| # | /4 -| # | / 5 _-` | # | / _-` | n # | / _-` | # |/_-___________| # l # # find p # # # Rational Trig view, quadrance, which is like distances squared # theta = spread s, which is similar to sine-squared # # J K # ._______.______. # | s /-_ | # | P / 9-_ s| M # | / -_| # | /16 -| # | / 25 _-` | # | / _-` | N # | / _-` | # |/_-___________| # L # # # Find P from sympy import * import math from fractions import Fraction P,J,K,M,N,L=symbols('P,K,J,M,N,L') import sys geometry='blue' # or green or red. see Quadrance() def Quadrance(x,y): if geometry=='blue': return x**2+y**2 if geometry=='green': return 2*x*y if geometry=='red': return x**2-y**2 #blue #J=16-P #K=Fraction(9,16)*P #eq=2*(J**2+K**2+P**2)-(J+K+P)**2 #green # Pa,Pb=solve(eq,P) print J,K,Pa,Pb sys.exit J=16-Pb K=Fraction(9,16)*Pb M=9-K N=25-Pb L=Pb New16=J+Pb New9=M+K New25=N+Pb legsa=[Pb,J,K,M,N,L,New16,New9,New25] print legsa print 'P,J=16-P,K=P*9/16,M=9-K,N=25-P,L=P' print map(lambda x:float(math.sqrt(x)),legsa) # for the other solution, J is the long side Pa=Pa J=16-Pa K=Fraction(9,16)*Pa M=9-K L=J N=symbols('N') eq2=2*(M**2+N**2+J**2)-(M+N+J)**2 print 'eq2',eq2 Na,Nb=solve(eq2,N) legsa=[Pa,J,K,M,Na,L] print legsa print 'Pa,J,K,M,N,L' print map(lambda x:float(math.sqrt(x)),legsa) print 'N+J',Na+J
{ "repo_name": "donbright/piliko", "path": "sympy/345chinscr.py", "copies": "1", "size": "1525", "license": "bsd-3-clause", "hash": 7202730081252031000, "line_mean": 15.7582417582, "line_max": 64, "alpha_frac": 0.4963934426, "autogenerated": false, "ratio": 1.9830949284785435, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.768408238007585, "avg_score": 0.05908119820053895, "num_lines": 91 }
# 346 - Moving Average From Data Stream (Easy) # https://leetcode.com/problems/moving-average-from-data-stream/ from collections import deque class MovingAverage(object): def __init__(self, size): """ Initialize your data structure here. :type size: int """ # Max amount of values to store. self.size = size # Deque to store values (a queue also does it). When a # problem says something about windows, use de/queues. self.dq = deque([]) # The acum of values so far. If a value is dropped from # the deque, then substract it from this acum. Then the # acum is divided by the total amount of values so that # the running average is found. self.acum = 0 def next(self, val): """ :type val: int :rtype: float """ # Append the value and update the acum. self.dq.append(val) self.acum += val # If the capacity was exceeded... if len(self.dq) > self.size: # Remove the last value and substract it from acum. left = self.dq.popleft() self.suma -= left # Now calculate the average for current window! Remember to # use float since this division in Python2 is integer div. return float(self.suma)/len(self.dq) # Your MovingAverage object will be instantiated and called as such: # obj = MovingAverage(size) # param_1 = obj.next(val)
{ "repo_name": "zubie7a/Algorithms", "path": "LeetCode/01_Easy/lc_346.py", "copies": "1", "size": "1478", "license": "mit", "hash": 6694097618496270000, "line_mean": 35.0731707317, "line_max": 68, "alpha_frac": 0.6062246279, "autogenerated": false, "ratio": 4.016304347826087, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5122528975726086, "avg_score": null, "num_lines": null }
# 346. Moving Average from Data Stream # Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window. # For example, # MovingAverage m = new MovingAverage(3); # m.next(1) = 1 # m.next(10) = (1 + 10) / 2 # m.next(3) = (1 + 10 + 3) / 3 # m.next(5) = (10 + 3 + 5) / 3 class MovingAverage(object): def __init__(self, size): """ Initialize your data structure here. :type size: int """ self.size = size self.vals = [0] * size self.cnt = 0 self.sum = 0 def next(self, val): """ :type val: int :rtype: float """ self.cnt += 1 idx = (self.cnt - 1) % self.size # replace old value self.sum -= self.vals[idx] self.sum += val self.vals[idx] = val return float(self.sum) / self.cnt if self.cnt < self.size \ else float(self.sum) / self.size # return float(self.sum) / min(self.cnt, self.size) # return float(self.sum) / [self.cnt, self.size][self.cnt > self.size] # Your MovingAverage object will be instantiated and called as such: # obj = MovingAverage(size) # param_1 = obj.next(val) if __name__ == '__main__': m = MovingAverage(3) assert m.next(1) == 1 assert m.next(10) == (1 + 10) / 2 assert m.next(3) == (1 + 10 + 3) / 3 assert m.next(5) == (10 + 3 + 5) / 3
{ "repo_name": "gengwg/leetcode", "path": "346_moving_average_from_data_stream.py", "copies": "1", "size": "1427", "license": "apache-2.0", "hash": 1825533509060422400, "line_mean": 27, "line_max": 115, "alpha_frac": 0.5423966363, "autogenerated": false, "ratio": 3.129385964912281, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8966442674692503, "avg_score": 0.041067985303955556, "num_lines": 51 }
# 351. Android Unlock Patterns # Given an Android 3x3 key lock screen and two integers m and n, where 1 ≤ m ≤ n ≤ 9, # count the total number of unlock patterns of the Android lock screen, # which consist of minimum of m keys and maximum n keys. # Rules for a valid pattern: # Each pattern must connect at least m keys and at most n keys. # All the keys must be distinct. # If the line connecting two consecutive keys in the pattern passes through any other keys, # the other keys must have previously selected in the pattern. # No jumps through non selected key is allowed. # The order of keys used matters. # Explanation: # | 1 | 2 | 3 | # | 4 | 5 | 6 | # | 7 | 8 | 9 | # Invalid move: 4 - 1 - 3 - 6 # Line 1 - 3 passes through key 2 which had not been selected in the pattern. # Invalid move: 4 - 1 - 9 - 2 # Line 1 - 9 passes through key 5 which had not been selected in the pattern. # Valid move: 2 - 4 - 1 - 3 - 6 # Line 1 - 3 is valid because it passes through key 2, # which had been selected in the pattern # Valid move: 6 - 5 - 4 - 1 - 9 - 2 # Line 1 - 9 is valid because it passes through key 5, # which had been selected in the pattern. # Example: # Given m = 1, n = 1, return 9. class Solution: def numberOfPatterns(self, m, n): """ https://www.cnblogs.com/grandyang/p/5541012.html 这道题说的是安卓机子的解锁方法,有9个数字键, 如果密码的长度范围在[m, n]之间,问所有的解锁模式共有多少种, 注意题目中给出的一些非法的滑动模式。 那么我们先来看一下哪些是非法的,首先1不能直接到3,必须经过2, 同理的有4到6,7到9,1到7,2到8,3到9, 还有就是对角线必须经过5,例如1到9,3到7等。 我们建立一个二维数组jumps,用来记录两个数字键之间是否有中间键, 然后再用一个一位数组visited来记录某个键是否被访问过, 然后我们用递归来解,我们先对1调用递归函数, 在递归函数中,我们遍历1到9每个数字next, 然后找他们之间是否有jump数字, 如果next没被访问过,并且jump为0,或者jump被访问过,我们对next调用递归函数。 数字1的模式个数算出来后,由于1,3,7,9是对称的,所以我们乘4即可, 然后再对数字2调用递归函数,2,4,6,9也是对称的,再乘4, 最后单独对5调用一次,然后把所有的加起来就是最终结果了 """ if m < 1 or n < 1: return 0 visited = [False] * 10 visited[0] = True hash = [[0 for _ in range(10)] for __ in range(10)] hash[1][3] = hash[3][1] = 2 hash[1][7] = hash[7][1] = 4 hash[3][9] = hash[9][3] = 6 hash[7][9] = hash[9][7] = 8 hash[2][8] = hash[8][2] = hash[4][6] = hash[6][4] = 5 hash[1][9] = hash[9][1] = hash[3][7] = hash[7][3] = 5 return self.dfs(m, n, 1, 1, visited, hash) * 4 + self.dfs(m, n, 1, 2, visited, hash) * 4 + self.dfs(m, n, 1, 5, visited, hash) def dfs(self, m, n, len, num, visited, hash): cnt = 0 if len >= m: cnt += 1 len += 1 if len > n: return cnt visited[num] = True for i in range(1, 10): if not visited[i] and visited[hash[num][i]]: cnt += self.dfs(m, n, len, i, visited, hash) visited[num] = False return cnt print(Solution().numberOfPatterns(8, 8))
{ "repo_name": "gengwg/leetcode", "path": "351_android_unlock_patterns.py", "copies": "1", "size": "3611", "license": "apache-2.0", "hash": 6489504121559216000, "line_mean": 32.3409090909, "line_max": 136, "alpha_frac": 0.5871121718, "autogenerated": false, "ratio": 2.16138540899042, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.324849758079042, "avg_score": null, "num_lines": null }
# 353. Design Snake Game # Design a Snake game that is played on a device with screen size = width x height. Play the game online if you are not familiar with the game. # # The snake is initially positioned at the top left corner (0,0) with length = 1 unit. # # You are given a list of food's positions in row-column order. When a snake eats the food, its length and the game's score both increase by 1. # # Each food appears one by one on the screen. For example, the second food will not appear until the first food was eaten by the snake. # # When a food does appear on the screen, it is guaranteed that it will not appear on a block occupied by the snake. # # Example: # # Given width = 3, height = 2, and food = [[1,2],[0,1]]. # # Snake snake = new Snake(width, height, food); # # Initially the snake appears at position (0,0) and the food at (1,2). # # |S| | | # | | |F| # # snake.move("R"); -> Returns 0 # # | |S| | # | | |F| # # snake.move("D"); -> Returns 0 # # | | | | # | |S|F| # # snake.move("R"); -> Returns 1 (Snake eats the first food and right after that, the second food appears at (0,1) ) # # | |F| | # | |S|S| # # snake.move("U"); -> Returns 1 # # | |F|S| # | | |S| # # snake.move("L"); -> Returns 2 (Snake eats the second food) # # | |S|S| # | | |S| # # snake.move("U"); -> Returns -1 (Game over because snake collides with border) # https://github.com/apachecn/awesome-algorithm/blob/master/docs/Leetcode_Solutions/Python/353.%20%20Design%20Snake%20Game.md class SnakeGame(object): def __init__(self, width,height,food): """ Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. :type width: int :type height: int :type food: List[List[int]] """ self.width = width self.height = height self.food = food self.snake = [[0, 0]] self.score = 0 def move(self, direction): """ Moves the snake. @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down @return The game's score after the move. Return -1 if game over. Game over when snake crosses the screen boundary or bites its body. :type direction: str :rtype: int """ nextx, nexty = self.snake[0] if direction == 'U': nextx -= 1 if direction == 'L': nexty -= 1 if direction == 'R': nexty += 1 if direction == 'D': nextx += 1 if self.food and [nextx, nexty] == self.food[0]: self.snake.insert(0, [nextx, nexty]) self.food = self.food[:1] self.score += 1 else: self.snake = self.snake[:-1] self.snake.insert(0, [nextx, nexty]) if nextx < 0 or nextx > self.height - 1 or nexty < 0 or self.y > self.width -1: return -1 noDupes = [] for snakePt in self.snake: if snakePt not in noDupes: noDupes.append(snakePt) if len(noDupes) < len(self.snake): return -1 return self.score
{ "repo_name": "gengwg/leetcode", "path": "353_design_snake_game.py", "copies": "1", "size": "3311", "license": "apache-2.0", "hash": -4158074529336397000, "line_mean": 28.8288288288, "line_max": 143, "alpha_frac": 0.5644820296, "autogenerated": false, "ratio": 3.171455938697318, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4235937968297318, "avg_score": null, "num_lines": null }
# 356 Line Reflection # Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given set of points. # # Example 1: # # Given points = [[1,1],[-1,1]], return true. # # Example 2: # # Given points = [[1,1],[-1,-1]], return false. # # Follow up: # Could you do better than O(n2)? # # Hint: # # Find the smallest and largest x-value for all points. # If there is a line then it should be at y = (minX + maxX) / 2. # For each point, make sure that it has a reflected point in the opposite side. class Solution: def isReflected(self, points): mn = -9223372036854775807 mx = 9223372036854775807 dct = {} for point in points: mn = max(mx, point[0]) mx = min(mn, point[0]) dct[point[0]] = point[1] # y = (mx + mn) / 2 y = mx + mn for p in points: left = p[0] right = y - left if not dct.get(right) or dct[right] != p[1]: return False return True print(Solution().isReflected([[1,1],[-1,1]])) print(Solution().isReflected([[1,1],[-1,-1]]))
{ "repo_name": "gengwg/leetcode", "path": "356_line_reflection.py", "copies": "1", "size": "1144", "license": "apache-2.0", "hash": 7141838148508542000, "line_mean": 25, "line_max": 117, "alpha_frac": 0.5550699301, "autogenerated": false, "ratio": 3.259259259259259, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9297348903368994, "avg_score": 0.0033960571980531525, "num_lines": 44 }
#359e800000-359e98a000 r-xp 00000000 fd:00 15176 /lib64/libc-2.12.so #Size: 1576 kB #Rss: 384 kB #Pss: 18 kB #Shared_Clean: 384 kB #Shared_Dirty: 0 kB #Private_Clean: 0 kB #Private_Dirty: 0 kB #Referenced: 384 kB #Anonymous: 0 kB #AnonHugePages: 0 kB #Swap: 0 kB #KernelPageSize: 4 kB #MMUPageSize: 4 kB #359e621000-359e622000 rw-p 00000000 00:00 0 def parse_smaps(lines): item = None for line in lines: fields = line.strip().split() if not fields: continue if len(fields) >= 5: if not (item is None): yield item item = {} item['addr'] = fields[0] item['mode'] = fields[1] if len(fields) >= 6: item['file'] = " ".join(fields[6:]) else: item['file'] = None else: key, number, suffix = fields assert suffix == "kB" item[key[:-1]] = int(number) if item: yield item
{ "repo_name": "RichardBarrell/snippets", "path": "smap.py", "copies": "1", "size": "1152", "license": "isc", "hash": -7055641152097075000, "line_mean": 27.8, "line_max": 93, "alpha_frac": 0.4539930556, "autogenerated": false, "ratio": 3.4698795180722892, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4423872573672289, "avg_score": null, "num_lines": null }
# 359 - Logger Rate Limiter (Easy) # https://leetcode.com/problems/logger-rate-limiter/ from collections import defaultdict class Logger(object): def __init__(self): """ Initialize your data structure here. """ # From timestamp to log messages. self.logs = defaultdict(lambda: -1) def shouldPrintMessage(self, timestamp, message): """ Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timestamp is in seconds granularity. :type timestamp: int :type message: str :rtype: bool """ if self.logs[message] != -1: if timestamp - self.logs[message] + 1 <= 10: return False self.logs[message] = timestamp return True # Your Logger object will be instantiated and called as such: # obj = Logger() # param_1 = obj.shouldPrintMessage(timestamp,message)
{ "repo_name": "zubie7a/Algorithms", "path": "LeetCode/01_Easy/lc_359.py", "copies": "1", "size": "1037", "license": "mit", "hash": -3480856575939477000, "line_mean": 32.4838709677, "line_max": 102, "alpha_frac": 0.6200578592, "autogenerated": false, "ratio": 4.489177489177489, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5609235348377489, "avg_score": null, "num_lines": null }
#359. Logger Rate Limiter # Design a logger system that receive stream of messages along with its timestamps, # each message should be printed if and only if it is not printed in the last 10 seconds. # Given a message and a timestamp (in seconds granularity), return true if the message should be printed in the given timestamp, otherwise returns false. # It is possible that several messages arrive roughly at the same time. # Example: # Logger logger = new Logger(); # # // logging string "foo" at timestamp 1 # logger.shouldPrintMessage(1, "foo"); returns true; # # // logging string "bar" at timestamp 2 # logger.shouldPrintMessage(2,"bar"); returns true; # # // logging string "foo" at timestamp 3 # logger.shouldPrintMessage(3,"foo"); returns false; # # // logging string "bar" at timestamp 8 # logger.shouldPrintMessage(8,"bar"); returns false; # # // logging string "foo" at timestamp 10 # logger.shouldPrintMessage(10,"foo"); returns false; # # // logging string "foo" at timestamp 11 # logger.shouldPrintMessage(11,"foo"); returns true; class Logger(object): def __init__(self): """ Initialize your data structure here. """ self.mp = {} def shouldPrintMessage(self, timestamp, message): """ Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timestamp is in seconds granularity. :type timestamp: int :type message: str :rtype: bool """ if message not in self.mp: self.mp[message] = timestamp return True elif timestamp - self.mp[message] >= 10: self.mp[message] = timestamp return True return False # Your Logger object will be instantiated and called as such: # obj = Logger() # param_1 = obj.shouldPrintMessage(timestamp,message) logger = Logger() print logger.shouldPrintMessage(1, "foo") print print logger.shouldPrintMessage(2,"bar") print print logger.shouldPrintMessage(3,"foo") print print logger.shouldPrintMessage(8,"bar") print print logger.shouldPrintMessage(10,"foo") print print logger.shouldPrintMessage(11,"foo")
{ "repo_name": "gengwg/leetcode", "path": "359_logger_rate_limiter.py", "copies": "1", "size": "2234", "license": "apache-2.0", "hash": 3276446825199665700, "line_mean": 30.9142857143, "line_max": 153, "alpha_frac": 0.6902417189, "autogenerated": false, "ratio": 4.017985611510792, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5208227330410792, "avg_score": null, "num_lines": null }
# 3-5. Changing Guest List: You just heard that one of your guests can’t make the dinner, so you need to send # out a new set of invitations. You’ll have to think of someone else to invite. # • Start with your program from Exercise 3-4. Add a print statement at the end of your program stating # the name of the guest who can’t make it. # • Modify your list, replacing the name of the guest who can’t make it with the name of the new person # you are inviting. # • Print a second set of invitation messages, one for each person who is still in your list. guests = ['Antonio', 'Emanuel', 'Francisco'] message = "1.- Hello dear uncle " + guests[0] + ", I hope you can come this 16th for a mexican dinner in my house." print(message) message = "2.- Hi " + guests[1] + "! The next monday we'll have a dinner, you should come here to spend time with " \ " the family and friends for a while, also we will have some beers. " print(message) message = "3.- Hello grandpa " + guests[2] + "!, my mother told me that we will have a dinner next monday and we want" \ " that you come here because we miss you. " print(message) print("\n My friend " + guests[1] + " can't make it to dinner.\n") # My friend Emanuel can't make it, so I'll invite my friend Luis. del(guests[1]) guests.insert(1, 'Luis') message = "1.- Uncle " + guests[0] + ", don't forget the dinner is today, see you later!." print(message) message = "2.- Hi " + guests[1] + "! Today we'll have a dinner, please come here to spend time with us, " \ "we will have meat and some beers. " print(message) message = "3.- Grandpa " + guests[2] + ", don't forget to come today to the dinner." print(message)
{ "repo_name": "AnhellO/DAS_Sistemas", "path": "Ago-Dic-2019/DanielM/PracticaUno/3.5_ChangingGuestList.py", "copies": "1", "size": "1790", "license": "mit", "hash": 9125151369563692000, "line_mean": 45.7631578947, "line_max": 120, "alpha_frac": 0.6497747748, "autogenerated": false, "ratio": 3.2828096118299444, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9407766940292963, "avg_score": 0.004963489267396157, "num_lines": 38 }
"""3-5. Changing Guest List: You just heard that one of your guests can’t make the dinner, so you need to send out a new set of invitations. You’ll have to think of someone else to invite. • Start with your program from Exercise 3-4. Add a print statement at the end of your program stating the name of the guest who can’t make it. • Modify your list, replacing the name of the guest who can’t make it with the name of the new person you are inviting. • Print a second set of invitation messages, one for each person who is still in your list.""" invitados = ['Teresa', 'Guadalupe', 'Rosendo'] name = invitados[0].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[1].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[2].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[1].title() print("\nLo siento, " + name + " no puede llegar a cenar.") # Cuando Guadalupe no puede. del(invitados[1]) invitados.insert(1, 'Samuel') # Imprimir las invitaciones de nuevo. name = invitados[0].title() print("\n" + name + ", te invito a cenar unos ricos taquitos!") name = invitados[1].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[2].title() print(name + ", te invito a cenar unos ricos taquitos!")
{ "repo_name": "AnhellO/DAS_Sistemas", "path": "Ago-Dic-2019/NoemiEstherFloresPardo/Practica1/ChangingGuestList.py", "copies": "1", "size": "1336", "license": "mit", "hash": -4735657929448656000, "line_mean": 34.7567567568, "line_max": 82, "alpha_frac": 0.7140695915, "autogenerated": false, "ratio": 2.8614718614718613, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9069852201947612, "avg_score": 0.001137850204849911, "num_lines": 37 }
# 361 Bomb Enemy # Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0' (the number zero), # return the maximum enemies you can kill using one bomb. # The bomb kills all the enemies in the same row and column from the planted point # until it hits the wall since the wall is too strong to be destroyed. # Note that you can only put the bomb at an empty cell. # Example: # For the given grid # 0 E 0 0 # E 0 W E # 0 E 0 0 # return 3. (Placing a bomb at (1,1) kills 3 enemies) class Solution: # https://www.youtube.com/watch?v=X3WrZG08ns8 # https://github.com/algorhythms/LeetCode/blob/master/361%20Bomb%20Enemy.py # def maxKilledEnemies(self, grid): """ :type grid: List[List[str]] :rtype: int rowKills: number of enemies killed in the current row at the current pos colKills[n]: number of enemies killed in column k (0 <= k < n) in the current row Time O(3mn) = O(mn) Space O(n) """ m = len(grid) n = len(grid[0]) if m else 0 if not m or not n: return 0 res = 0 colKills = [0] * n for i in range(m): for j in range(n): if j == 0 or grid[i][j-1] == 'W': rowKills = 0 for k in range(j, n): if grid[i][k] == 'E': rowKills += 1 if grid[i][k] == 'W': break if i == 0 or grid[i-1][j] == 'W': colKills[j] = 0 # colKills = [0] * n for k in range(i, m): if grid[k][j] == 'E': colKills[j] += 1 if grid[k][j] == 'W': break if grid[i][j] == '0': res = max(res, rowKills+colKills[j]) return res if __name__ == "__main__": print (Solution().maxKilledEnemies(["0E00", "E0WE", "0E00"])) #assert Solution().maxKilledEnemies(["0E00", "E0WE", "0E00"]) == 3
{ "repo_name": "gengwg/leetcode", "path": "361_bomb_enemy.py", "copies": "1", "size": "2113", "license": "apache-2.0", "hash": 1183746947073019400, "line_mean": 34.2166666667, "line_max": 96, "alpha_frac": 0.4803596782, "autogenerated": false, "ratio": 3.317111459968603, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9274386548775106, "avg_score": 0.0046169178786993345, "num_lines": 60 }
# 364 - Nested List Weight Sum II (Medium) # https://leetcode.com/problems/nested-list-weight-sum-ii/ # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class Solution(object): # Find the max depth, so that when the usual DFS is done, the inverse # depth is calculated. def findMaxDepth(self, nestedList, depth): if len(nestedList) == 0: return 0 nextDepth = depth + 1 for NI in nestedList: if NI.isInteger(): continue else: depth = max(depth, self.findMaxDepth(NI.getList(), nextDepth)) return depth # The usual DFS but instead of multiplying by real depth, do it with the # inverse which needs to have beforehand the max depth. def dfs(self, nestedList, depth, maxDepth): if len(nestedList) == 0: return 0 acum = 0 for NI in nestedList: if NI.isInteger(): acum += NI.getInteger() * (maxDepth - depth + 1) else: acum += self.dfs(NI.getList(), depth+1, maxDepth) return acum def depthSumInverse(self, nestedList): """ :type nestedList: List[NestedInteger] :rtype: int """ maxDepth = self.findMaxDepth(nestedList, 1) return self.dfs(nestedList, 1, maxDepth)
{ "repo_name": "zubie7a/Algorithms", "path": "LeetCode/02_Medium/lc_364.py", "copies": "1", "size": "2123", "license": "mit", "hash": -4652715492030583000, "line_mean": 32.7142857143, "line_max": 95, "alpha_frac": 0.5916156382, "autogenerated": false, "ratio": 3.9169741697416973, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.997308727846987, "avg_score": 0.0071005058943655434, "num_lines": 63 }
# 364 Nested List Weight Sum II # # Given a nested list of integers, return the sum of all integers in the list weighted by their depth. # # Each element is either an integer, or a list — whose elements may also be integers or other lists. # # Different from the previous question where weight is increasing from root to leaf, # now the weight is defined from bottom up. i.e., the leaf level integers have weight 1, # and the root level integers have the largest weight. # # Example 1: # Given the list [[1,1],2,[1,1]], return 8. (four 1’s at depth 1, one 2 at depth 2) # # Example 2: # Given the list [1,[4,[6]]], return 17. (one 1 at depth 3, one 4 at depth 2, and one 6 at depth 1; 1*3 + 4*2 + 6*1 = 17) # # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def __init__(self, value=None): # """ # If value is not specified, initializes an empty list. # Otherwise initializes a single integer equal to value. # """ # # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def add(self, elem): # """ # Set this NestedInteger to hold a nested list and adds a nested integer elem to it. # :rtype void # """ # # def setInteger(self, value): # """ # Set this NestedInteger to hold a single integer equal to value. # :rtype void # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class Solution(object): def depthSumInverse(self, nestedList): """ :type nestedList: List[NestedInteger] :rtype: int https://github.com/csujedihy/lc-all-solutions/blob/master/364.nested-list-weight-sum-ii/nested-list-weight-sum-ii.py """ def getDepth(root): res = 0 for nested in root: if not nested.isInteger(): res = max(res, getDepth(nested.getList())) return res + 1 def helper(root, depth, maxDepth): res = 0 for nested in root: if nested.isInteger(): res += (maxDepth - depth) * nested.getInteger() else: res += helper(nested.getList(), depth+1, maxDepth) return res return helper(nestedList, 0, getDepth(nestedList))
{ "repo_name": "gengwg/leetcode", "path": "364_nested_list_weight_sum_ii.py", "copies": "1", "size": "2925", "license": "apache-2.0", "hash": 4598221910275419000, "line_mean": 33.3647058824, "line_max": 124, "alpha_frac": 0.5997945909, "autogenerated": false, "ratio": 3.788586251621271, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4888380842521271, "avg_score": null, "num_lines": null }
# 366. Find Leaves of Binary Tree # Given a binary tree, collect a tree's nodes as if you were doing this: # Collect and remove all leaves, repeat until the tree is empty. # Example: # Given binary tree # 1 # / \ # 2 3 # / \ # 4 5 # Returns [4, 5, 3], [2], [1]. # Explanation: # 1. Removing the leaves [4, 5, 3] would result in this tree: # 1 # / # 2 # 2. Now removing the leaf [2] would result in this tree: # 1 # 3. Now removing the leaf [1] would result in the empty tree: # [] # Returns [4, 5, 3], [2], [1]. # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def findLeaves(self, root): """ :type root: TreeNode :rtype: List[List[int]] https://www.jianshu.com/p/ae3315ba7582 we don't actually remove the leaves. Instead, we add a node to its correct list by calculating its height. 明白了Binary Tree的Height和Depth的区别, Height是从下往上数,Leaf的height为0, Root的height最大; 而Depth是从上往下数,root的depth为0, Leaf的depth最高。 所以这道题说是Find leaves, 其实是把所有node按Height分, 比如第一层所有的Leaf nodes就是height = 0的node; 第二层的Leaf nodes就是height = 1的node; 第三层的leaf nodes就是height = 3的nodes。 这样发现这个问题其实只和height有关,就很好解决了。 """ res = [] self.helper(root, res) return res def helper(self, node, res): if node is None: return -1 # so that level corresponds to res[] index level = 1 + max(self.helper(node.left, res), self.helper(node.right, res)) if len(res) < level + 1: res.append([]) res[level].append(node.val) return level s = Solution()
{ "repo_name": "gengwg/leetcode", "path": "366_find_leaves_of_binary_tree.py", "copies": "1", "size": "2045", "license": "apache-2.0", "hash": 2246785332537145300, "line_mean": 28.2222222222, "line_max": 82, "alpha_frac": 0.5795763172, "autogenerated": false, "ratio": 2.867601246105919, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.39471775633059186, "avg_score": null, "num_lines": null }
# 368. Largest Divisible Subset # Given a set of distinct positive integers, # find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: # # Si % Sj = 0 or Sj % Si = 0. # # If there are multiple solutions, return any subset is fine. # # Example 1: # # Input: [1,2,3] # Output: [1,2] (of course, [1,3] will also be ok) # # Example 2: # # Input: [1,2,4,8] # Output: [1,2,4,8] # class Solution(object): def largestDivisibleSubset(self, nums): """ :type nums: List[int] :rtype: List[int] """ n = len(nums) count = [0] * n pre = [0] * n nums.sort() max = 0 index = -1 for i in range(n): count[i] = 1 pre[i] = -1 for j in range(i-1, -1, -1): if nums[i] % nums[j] == 0: if 1 + count[j] > count[i]: count[i] = count[j] + 1 pre[i] = j if count[i] > max: max = count[i] index = i res = [] while index != -1: res.append(nums[index]) index = pre[index] return res # https://leetcode.com/problems/largest-divisible-subset/discuss/83999/Easy-understood-Java-DP-solution-in-28ms-with-O(n2)-time # 1. Sort # 2. Find the length of longest subset # 3. Record the largest element of it. # 4. Do a loop from the largest element to nums[0], add every element belongs to the longest subset. def largestDivisibleSubset(self, nums): res = [] n = len(nums) if not nums or n == 0: return res nums.sort() dp = [1] * n # nums fill(dp, 1). 0 not work. every number at least has itself as subset # dp[0] = 1 # for each element in nums, find the largest subset it has for i in range(1, n): for j in range(i-1, -1, -1): if nums[i] % nums[j] == 0: dp[i] = max(dp[i], dp[j] + 1) # pick the index of largest element in dp maxIndex = 0 for i in range(1, n): #maxIndex = i if dp[i] > dp[maxIndex] else maxIndex if dp[i] > dp[maxIndex]: maxIndex = i # from nums[maxIndex] to nums[0], add every element belongs to the largest subset temp = nums[maxIndex] curDp = dp[maxIndex] for i in range(maxIndex, -1, -1): if temp % nums[i] == 0 and dp[i] == curDp: # dpi must be prev - 1 res.append(nums[i]) temp = nums[i] # current num belongs to subset so check next number curDp -= 1 # reduce length of subset return res print(Solution().largestDivisibleSubset([1,2,4,8])) print(Solution().largestDivisibleSubset([1,2,3])) print(Solution().largestDivisibleSubset([4,8,10,240])) print(Solution().largestDivisibleSubset([2,3,8,9,27])) print(Solution().largestDivisibleSubset( [1,2,4,8,9,72] )) print(Solution().largestDivisibleSubset([3,4,6,8,12,16,32]))
{ "repo_name": "gengwg/leetcode", "path": "368_largest_divisible_subset.py", "copies": "1", "size": "3072", "license": "apache-2.0", "hash": 8124748314830622000, "line_mean": 31, "line_max": 131, "alpha_frac": 0.5325520833, "autogenerated": false, "ratio": 3.282051282051282, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4314603365351282, "avg_score": null, "num_lines": null }
# 369. Plus One Linked List # Given a non-negative number represented as a singly linked list of digits, # plus one to the number. # The digits are stored such that the most significant digit is at the head of the list. # Example: # Input: # 1->2->3 # Output: # 1->2->4 class Solution: # https://closewen.wordpress.com/2017/04/17/369-plus-one-linked-list/ # 遍历链表,找到第一个不为9的数字,如果找不这样的数字,说明所有数字均为9, # 那么在表头新建一个值为0的新节点,进行加1处理,然后把右边所有的数字都置为0即可。 # 举例来说: # 比如1->2->3,那么第一个不为9的数字为3,对3进行加1,变成4, # 右边没有节点了,所以不做处理,返回1->2->4。 # 再比如说8->9->9,找第一个不为9的数字为8,进行加1处理变成了9, # 然后把后面的数字都置0,得到结果9->0->0。 # 再来看9->9->9的情况,找不到不为9的数字,那么再前面新建一个值为0的节点, # 进行加1处理变成了1,把后面的数字都置0,得到1->0->0->0。 def plusOne(self, head): cur = head right = None while cur: if cur.val != 9: right = cur cur = cur.next if not right: right = ListNode(0) right.next = head head = right right.val += 1 cur = right.next while cur: cur.val = 0 cur = cur.next return head
{ "repo_name": "gengwg/leetcode", "path": "369_plus_one_linked_list.py", "copies": "1", "size": "1557", "license": "apache-2.0", "hash": -315217181579346200, "line_mean": 21.66, "line_max": 88, "alpha_frac": 0.5772285966, "autogenerated": false, "ratio": 1.894648829431438, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7969471779243769, "avg_score": 0.0004811293575338519, "num_lines": 50 }
# 3-6. More Guests: You just found a bigger dinner table, so now more space is available. # Think of three more guests to invite to dinner. # • Start with your program from Exercise 3-4 or Exercise 3-5. Add a print statement to the end of your # program informing people that you found a bigger dinner table. # • Use insert() to add one new guest to the beginning of your list. # • Use insert() to add one new guest to the middle of your list. # • Use append() to add one new guest to the end of your list. # • Print a new set of invitation messages, one for each person in your list. guests = ['Antonio', 'Emanuel', 'Francisco'] message = "1.- Hello dear uncle " + guests[0] + ", I hope you can come this 16th for a mexican dinner in my house." print(message) message = "2.- Hi " + guests[1] + "! The next monday we'll have a dinner, you should come here to spend time with " \ " the family and friends for a while, also we will have some beers. " print(message) message = "3.- Hello grandpa " + guests[2] + "!, my mother told me that we will have a dinner next monday and we want" \ " that you come here because we miss you. " print(message) print("\n My friend " + guests[1] + " can't make it to dinner.\n") # My friend Emanuel can't make it, so I'll invite my friend Luis. del(guests[1]) guests.insert(1, 'Luis') message = "1.- Uncle " + guests[0] + ", don't forget the dinner is today, see you later!." print(message) message = "2.- Hi " + guests[1] + "! Today we'll have a dinner, please come here to spend time with us, " \ "we will have meat and some beers. " print(message) message = "3.- Grandpa " + guests[2] + ", don't forget to come today to the dinner." print(message) # Now we have more space, so I gonna invite more people xd print("\nNow we have more space! xdxd \n") guests.insert(0, 'Ariel') guests.insert(3, 'Sergio') guests.append('Norma') message = "1.- Hi " + guests[0] + "!, hey nigga come here tonight to dinner, we gonna celebrate this day! :v" print(message) message = "2.- Uncle " + guests[1] + ", don't forget the dinner is today, see you later!." print(message) message = "3.- Hi " + guests[2] + "! Today we'll have dinner, please come here to spend time with us, " \ "we will have a lot of meat and some beers. " print(message) message = "4.- Hey " + guests[3] + "!, how are you?, please come to my house tonight" print(message) message = "5.- Grandpa " + guests[4] + ", don't forget to come today to dinner." print(message) message = "6.- Hello " + guests[5] + "!, I was wondering if you would like to come here tonight to dinner?, " \ "I hope you don't have things to do!" print(message)
{ "repo_name": "AnhellO/DAS_Sistemas", "path": "Ago-Dic-2019/DanielM/PracticaUno/3.6_MoreGuests.py", "copies": "1", "size": "2809", "license": "mit", "hash": -5012520389493567000, "line_mean": 39.5797101449, "line_max": 120, "alpha_frac": 0.6427295463, "autogenerated": false, "ratio": 3.120401337792642, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9246261670219071, "avg_score": 0.0033738427747139602, "num_lines": 69 }
"""3-6. More Guests: You just found a bigger dinner table, so now more space is available. Think of three more guests to invite to dinner. • Start with your program from Exercise 3-4 or Exercise 3-5. Add a print statement to the end of your program informing people that you found a bigger dinner table. • Use insert() to add one new guest to the beginning of your list. • Use insert() to add one new guest to the middle of your list. • Use append() to add one new guest to the end of your list. • Print a new set of invitation messages, one for each person in your list.""" invitados = ['Teresa', 'Guadalupe', 'Rosendo'] name = invitados[0].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[1].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[2].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[1].title() print("\nLo siento, " + name + " no puede llegar a cenar.") # Cuando Guadalupe no puede del(invitados[1]) invitados.insert(1, 'Samuel') # Imprimir las invitaciones de nuevo. name = invitados[0].title() print("\n" + name + ", te invito a cenar unos ricos taquitos!") name = invitados[1].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[2].title() print(name + ", te invito a cenar unos ricos taquitos!") # Agregando mas personas a la lista. print("\nAgregando mas personas a la lista") invitados.insert(0, 'Maria') invitados.insert(2, 'Reynaldo') invitados.append('José') name = invitados[0].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[1].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[2].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[3].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[4].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[5].title() print(name + ", te invito a cenar unos ricos taquitos!")
{ "repo_name": "AnhellO/DAS_Sistemas", "path": "Ago-Dic-2019/NoemiEstherFloresPardo/Practica1/MoreGuests.py", "copies": "1", "size": "2045", "license": "mit", "hash": 6377739203077795000, "line_mean": 32.3606557377, "line_max": 79, "alpha_frac": 0.7079646018, "autogenerated": false, "ratio": 2.797799174690509, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9004300076256317, "avg_score": 0.0002927400468384075, "num_lines": 61 }
## 3.6 Using the Toolbox from deap import base from deap import tools toolbox = base.Toolbox() def evaluateInd(individual): # Do some computation result = sum(individual) return result, toolbox.register("mate", tools.cxTwoPoint) toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=0.2) toolbox.register("select", tools.selTournament, tournsize=3) toolbox.register("evaluate", evaluateInd) ## Data structure and initializer creation import random from deap import creator creator.create("FitnessMax", base.Fitness, weights=(1.0,)) creator.create("Individual", list, fitness=creator.FitnessMax) toolbox.register("attr_float", random.random) toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, 10) toolbox.register("population", tools.initRepeat, list, toolbox.individual) pop = toolbox.population(n=100) CXPB, MUTPB, NGEN = 0.7, 0.3, 25 ## 3.6.1 Using the Tools for g in range(NGEN): # Select the next generation individuals offspring = toolbox.select(pop, len(pop)) # Clone the selected individuals offspring = map(toolbox.clone, offspring) # Apply crossover on the offspring for child1, child2 in zip(offspring[::2], offspring[1::2]): if random.random() < CXPB: toolbox.mate(child1, child2) del child1.fitness.values del child2.fitness.values # Apply mutation on the offspring for mutant in offspring: if random.random() < MUTPB: toolbox.mutate(mutant) del mutant.fitness.values # Evaluate the individuals with an invalid fitness invalid_ind = [ind for ind in offspring if not ind.fitness.valid] fitnesses = toolbox.map(toolbox.evaluate, invalid_ind) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit # The population is entirely replaced by the offspring pop[:] = offspring
{ "repo_name": "DailyActie/Surrogate-Model", "path": "01-codes/deap-master/doc/code/tutorials/part_3/3_6_using_the_toolbox.py", "copies": "2", "size": "1912", "license": "mit", "hash": 7571456689247565000, "line_mean": 31.406779661, "line_max": 92, "alpha_frac": 0.7076359833, "autogenerated": false, "ratio": 3.445045045045045, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5152681028345045, "avg_score": null, "num_lines": null }
# 370. Range Addition # Assume you have an array of length n initialized with all 0's and are given k update operations. # Each operation is represented as a triplet: [startIndex, endIndex, inc] # which increments each element of subarray A[startIndex ... endIndex] # (startIndex and endIndex inclusive) with inc. # # Return the modified array after all k operations were executed. # # Example: # # Given: # # length = 5, # updates = [ # [1, 3, 2], # [2, 4, 3], # [0, 2, -2] # ] # # Output: # # [-2, 0, 3, 5, 3] # # Explanation: # # Initial state: # [ 0, 0, 0, 0, 0 ] # # After applying operation [1, 3, 2]: # [ 0, 2, 2, 2, 0 ] # # After applying operation [2, 4, 3]: # [ 0, 2, 5, 5, 3 ] # # After applying operation [0, 2, -2]: # [-2, 0, 3, 5, 3 ] # # --------------------- # # 原文:https://blog.csdn.net/qq508618087/article/details/51864853 class Solution: # https://all4win78.wordpress.com/2016/06/29/leetcode-370-range-addition/ # 在这题中没必要每次把区间的每一个值都更新, 只需要更新起点和终点后的一点即可. # 也就是说把增加的值放在起点, 终点后的一点减去增加的值, # 这样再扫描的时候把之前累加的和作为最终值即可. def getModifiedArray(self, length, updates): result = [0] * length for operation in updates: result[operation[0]] += operation[2] if operation[1] < length - 1: result[operation[1] + 1] -= operation[2] sum = 0 for i in range(0, length): sum += result[i] result[i] = sum return result length = 5 updates = [ [1, 3, 2], [2, 4, 3], [0, 2, -2] ] print(Solution().getModifiedArray(length, updates))
{ "repo_name": "gengwg/leetcode", "path": "370_range_addition.py", "copies": "1", "size": "1800", "license": "apache-2.0", "hash": -7705054047055545000, "line_mean": 22.2571428571, "line_max": 98, "alpha_frac": 0.5681818182, "autogenerated": false, "ratio": 2.437125748502994, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8498092559487986, "avg_score": 0.001443001443001443, "num_lines": 70 }
#3.7.2 про шифрование # put your python code heres=st ''' В какой-то момент в Институте перестали понимать, что говорят информатики: они говорили каким-то странным набором звуков. В какой-то момент один из биологов раскрыл секрет информатиков: они использовали при общении подстановочный шифр, т.е. заменяли каждый символ исходного сообщения на соответствующий ему другой символ. Биологи раздобыли ключ к шифру и теперь нуждаются в помощи: Напишите программу, которая умеет шифровать и расшифровывать шифр подстановки. Программа принимает на вход две строки одинаковой длины, на первой строке записаны символы исходного алфавита, на второй строке — символы конечного алфавита, после чего идёт строка, которую нужно зашифровать переданным ключом, и ещё одна строка, которую нужно расшифровать. Пусть, например, на вход программе передано: abcd *d%# abacabadaba #*%*d*% Это значит, что символ a исходного сообщения заменяется на символ * в шифре, b заменяется на d, c — на % и d — на #. Нужно зашифровать строку abacabadaba и расшифровать строку #*%*d*% с помощью этого шифра. Получаем следующие строки, которые и передаём на вывод программы: *d*%*d*#*d* dacabac Sample Input 1: abcd *d%# abacabadaba #*%*d*% Sample Output 1: *d*%*d*#*d* dacabac Sample Input 2: dcba badc dcba badc Sample Output 2: badc dcba ''' s = str(input()) a = [] # строка, которую необходимо зашифровать for i in range(len(s)): si = s[i] a.append(si) # print(a) b = [] n = str(input()) # символы шифра for j in range(len(n)): sj = n[j] b.append(sj) # print(b) p = {} # инициализация словаря for pi in range(len(s)): key = s[pi] p[key] = 0 # print(p) # актуализация словаря j1 = 0 for i in range(0, len(a)): key = a[i] while j1 < len(b): # print(j1) bj = b[0] if key in p: p[key] = bj b.remove(bj) # print(b) break # print(p) c = [] si = str(input()) for si1 in range(0, len(si)): ci = si[si1] c.append(ci) # print(c) co = [] for ci in range(0, len(c)): if c[ci] in p: cco = c[ci] pco = p[cco] co.append(pco) # print(co) d = [] di = str(input()) for sj1 in range(0, len(di)): dj = di[sj1] d.append(dj) # print(d) do = [] for di in range(0, len(d)): for key in p: pkey = key if p.get(key) == d[di]: ddo = pkey do.append(ddo) # print(do) for i in range(0, len(co)): print(co[i], end='') print() for j in range(0, len(do)): print(do[j], end='')
{ "repo_name": "RootTeam/pytaskscollect", "path": "other/task_002.py", "copies": "1", "size": "3494", "license": "mit", "hash": -644684157415359500, "line_mean": 16.7013888889, "line_max": 72, "alpha_frac": 0.6331894861, "autogenerated": false, "ratio": 1.5881619937694704, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.27213514798694705, "avg_score": null, "num_lines": null }
# 373. Find K Pairs with Smallest Sums # # You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k. # # Define a pair (u,v) which consists of one element from the first array and one element from the second array. # # Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums. # # Example 1: # # Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3 # Output: [[1,2],[1,4],[1,6]] # Explanation: The first 3 pairs are returned from the sequence: # [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6] # # Example 2: # # Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2 # Output: [1,1],[1,1] # Explanation: The first 2 pairs are returned from the sequence: # [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3] # # Example 3: # # Input: nums1 = [1,2], nums2 = [3], k = 3 # Output: [1,3],[2,3] # Explanation: All possible pairs are returned from the sequence: [1,3],[2,3] # https://leetcode.com/problems/find-k-pairs-with-smallest-sums/discuss/155676/Python-heapq-solution-beats-96 # https://leetcode.com/problems/find-k-pairs-with-smallest-sums/discuss/84551/simple-Java-O(KlogK)-solution-with-explanation # Basic idea: Use min_heap to keep track on next minimum pair sum, # and we only need to maintain K possible candidates in the data structure. # Some observations: For every numbers in nums1, its best partner(yields min sum) always strats from nums2[0] since arrays are all sorted; # And for a specific number in nums1, its next candidate sould be [this specific number] + nums2[current_associated_index + 1], # unless out of boundary;) import heapq class Solution(object): def kSmallestPairs(self, nums1, nums2, k): """ :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[List[int]] """ if not nums1 or not nums2: return [] h = [] for i in range(len(nums1)): heapq.heappush(h, (nums1[i] + nums2[0], i, 0)) res = [] while h and k > 0: small, i, j = heapq.heappop(h) res.append([nums1[i], nums2[j]]) if j + 1 < len(nums2): heapq.heappush(h, (nums1[i] + nums2[j+1], i, j+1)) k -= 1 return res sol = Solution() print (sol.kSmallestPairs(nums1 = [1,7,11], nums2 = [2,4,6], k = 3))
{ "repo_name": "gengwg/leetcode", "path": "373_find_k_pairs_with_smallest_sums.py", "copies": "1", "size": "2372", "license": "apache-2.0", "hash": -4368668682840415700, "line_mean": 31.9444444444, "line_max": 138, "alpha_frac": 0.6037099494, "autogenerated": false, "ratio": 2.817102137767221, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.39208120871672214, "avg_score": null, "num_lines": null }
# 374. Guess Number Higher or Lower # We are playing the Guess Game. The game is as follows: # I pick a number from 1 to n. You have to guess which number I picked. # # Every time you guess wrong, I'll tell you whether the number is higher or lower. # # You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): # # -1 : My number is lower # 1 : My number is higher # 0 : Congrats! You got it! # # Example : # # Input: n = 10, pick = 6 # Output: 6 # The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num): class Solution(object): def guessNumber(self, n): """ :type n: int :rtype: int """ L, R = 1, n while L < R: mid = L + ((R - L) >> 1) res = guess(mid) if res == 0: return mid elif res == 1: L = mid + 1 else: # res == -1 R = mid - 1 return L
{ "repo_name": "gengwg/leetcode", "path": "374_guess_number_higher_or_lower.py", "copies": "1", "size": "1065", "license": "apache-2.0", "hash": 1035923450720145800, "line_mean": 23.2045454545, "line_max": 91, "alpha_frac": 0.5417840376, "autogenerated": false, "ratio": 3.4466019417475726, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9366954528173237, "avg_score": 0.02428629023486715, "num_lines": 44 }
# 375. Guess Number Higher or Lower II # We are playing the Guess Game. The game is as follows: # # I pick a number from 1 to n. You have to guess which number I picked. # # Every time you guess wrong, I'll tell you whether the number I picked is higher or lower. # # However, when you guess a particular number x, and you guess wrong, you pay $x. You win the game when you guess the number I picked. # # Example: # # n = 10, I pick 8. # # First round: You guess 5, I tell you that it's higher. You pay $5. # Second round: You guess 7, I tell you that it's higher. You pay $7. # Third round: You guess 9, I tell you that it's lower. You pay $9. # # Game over. 8 is the number I picked. # # You end up paying $5 + $7 + $9 = $21. # # Given a particular n ≥ 1, find out how much money you need to have to guarantee a win. class Solution(object): # https://www.hrwhisper.me/leetcode-guess-number-higher-lower-ii/ def getMoneyAmount(self, n): """ :type n: int :rtype: int """ dp = [[0] * (n + 1) for _ in range(n + 1)] return self.solve(dp, 1, n) def solve(self, dp, L, R): if L >= R: return 0 if dp[L][R]: return dp[L][R] dp[L][R] = min(i + max(self.solve(dp, L, i - 1), self.solve(dp, i + 1, R)) for i in range(L, R+1)) return dp[L][R] # https://leetcode.com/problems/guess-number-higher-or-lower-ii/discuss/84769/Two-Python-solutions def getMoneyAmount(self, n): need = [[0] * (n+1) for _ in range(n+1)] for lo in range(n, 0, -1): for hi in range(lo+1, n+1): need[lo][hi] = min(x + max(need[lo][x-1], need[x+1][hi]) for x in range(lo, hi)) return need[1][n] print(Solution().getMoneyAmount(10))
{ "repo_name": "gengwg/leetcode", "path": "375_guess_number_higher_or_lower_ii.py", "copies": "1", "size": "1781", "license": "apache-2.0", "hash": 2624261675573934600, "line_mean": 31.9444444444, "line_max": 134, "alpha_frac": 0.5913434514, "autogenerated": false, "ratio": 2.965, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40563434513999996, "avg_score": null, "num_lines": null }
# 376 c2v = dict([(str(i), i) for i in range(2, 10)]) c2v['T'] = 10 c2v['J'] = 11 c2v['Q'] = 12 c2v['K'] = 13 c2v['A'] = 14 def flush(cards): if all(map(lambda c: c[1] == cards[0][1], cards)): return cards[-1][0] return False def straight(cards): m = [(cards[i][0], i + cards[0][0]) for i in range(5)] if all(map(lambda c: c[0] == c[1], m)): return cards[-1][0] return False def kind(cards): n = {} for c in cards: n[c[0]] = n.setdefault(c[0], 0) + 1 f = [(v,k) for k,v in n.items()] f.sort() return f[::-1] m = 0 for hand in [line.split() for line in file('../files/poker.txt')]: cards = [(c2v[c[0]], c[1]) for c in hand] p1, p2 = cards[:5], cards[5:] p1.sort() p2.sort() f1 = flush(p1) s1 = straight(p1) k1 = kind(p1) f2 = flush(p2) s2 = straight(p2) k2 = kind(p2) if f2 and s2: if f1 and s1 and f1 > f2: m += 1 elif f1 and s1: m += 1 elif k2[0][0] == 4: if k1 > k2: m += 1 elif k1[0][0] == 4: m += 1 elif k2[0][0] == 3 and k2[1][0] == 2: if k1[0][0] == 3 and k1[1][0] == 2 and k1 > k2: m += 1 elif k1[0][0] == 3 and k1[1][0] == 2: m += 1 elif f2: if f1 and f1 > f2: m += 1 elif f1: m += 1 elif s2: if s1 and s1 > s2: m += 1 elif s1: m += 1 elif k2[0][0] == 3: if k1 > k2: m += 1 elif k1[0][0] == 3: m += 1 elif k2[0][0] == 2 and k2[1][0] == 2: if k1[0][0] == 2 and k1[1][0] == 2 and k1 > k2: m += 1 elif k1[0][0] == 2 and k1[1][0] == 2: m += 1 elif k1 > k2: m += 1 print m
{ "repo_name": "higgsd/euler", "path": "py/54.py", "copies": "1", "size": "1749", "license": "bsd-2-clause", "hash": -4433786102486995000, "line_mean": 21.4230769231, "line_max": 66, "alpha_frac": 0.413950829, "autogenerated": false, "ratio": 2.432545201668985, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.33464960306689845, "avg_score": null, "num_lines": null }
# 377 Combination Sum IV # Given an integer array with all positive numbers and no duplicates, # find the number of possible combinations that add up to a positive integer target. # # Example: # # nums = [1, 2, 3] # target = 4 # # The possible combination ways are: # (1, 1, 1, 1) # (1, 1, 2) # (1, 2, 1) # (1, 3) # (2, 1, 1) # (2, 2) # (3, 1) # # Note that different sequences are counted as different combinations. # # Therefore the output is 7. # # Follow up: # What if negative numbers are allowed in the given array? # How does it change the problem? # What limitation we need to add to the question to allow negative numbers? class Solution: def combinationSum4(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() res = [0] * (target + 1) for i in range(1, len(res)): for num in nums: if num > i: break elif num == i: res[i] += 1 else: res[i] += res[i-num] return res[target] # https://www.hrwhisper.me/leetcode-combination-sum-iv/ # dp[i] += dp[i-num] def combinationSum4(self, nums, target): dp = [1] + [0] * target for i in range(1, target+1): for num in nums: if i >= num: dp[i] += dp[i-num] return dp[target] print(Solution().combinationSum4([1, 2, 3], 4))
{ "repo_name": "gengwg/leetcode", "path": "377_combination_sum_iv.py", "copies": "1", "size": "1495", "license": "apache-2.0", "hash": -7992855310839750000, "line_mean": 23.9166666667, "line_max": 84, "alpha_frac": 0.5357859532, "autogenerated": false, "ratio": 3.3823529411764706, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4418138894376471, "avg_score": null, "num_lines": null }
# 378. Kth Smallest Element in a Sorted Matrix # # Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. # # Note that it is the kth smallest element in the sorted order, not the kth distinct element. # # Example: # # matrix = [ # [ 1, 5, 9], # [10, 11, 13], # [12, 13, 15] # ], # k = 8, # # return 13. # # Note: # You may assume k is always valid, 1 <= k <= n2. # https://nb4799.neu.edu/wordpress/?p=2017 from heapq import * class Solution: def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ # heapq.merge: Merge multiple sorted inputs into a single sorted output # (for example, merge timestamped entries from multiple log files). # Returns an iterator over the sorted values. return list(merge(*matrix))[k-1] # Maintain a min-heap with k element, initialized by the elements of the first row. # Since it is a min-heap, and note the property that rows and columns are already sorted in ascending order, # the heap root after popping k-1 times is the k-th smallest element of the whole matrix. # When popping the heap, we also need to push necessary matrix elements into the heap. # Time complexity is O(KlogK) (every heap operation takes O(logK)) def kthSmallest(self, matrix, k): # element in the heap: (val, x coord, y coord) h = [] for i in range(min(len(matrix[0]), k)): heappush(h, (matrix[0][i], 0, i)) # pop k-1 times for i in range(k-1): val, x, y = heappop(h) if x < len(matrix) - 1: heappush(h, (matrix[x+1][y], x+1, y)) return h[0][0] # smallest element in heap. 0th index in tuple # binary search # We can eventually find the k-th smallest element by shrinking the search range in binary search. # Binary search is feasible for this problem since left, right,and mid in binary search are integers # and we know that matrix elements are integers. # The algorithm takes O(nlogN) time (N is the range of matrix[0][0] ~ matrix[n-1][n-1]) and O(1) space. # Time complexity analysis: the outer loop executes at most O(logN) times. # The inner for loop executes at most O(n) times. def kthSmallest(self, matrix, k): n = len(matrix) L = matrix[0][0] R = matrix[n-1][n-1] while L < R: mid = L + ((R - L) >> 1) count = 0 j = n - 1 for i in range(n): while j >= 0 and matrix[i][j] > mid: j -= 1 count += j+1 if count >= k: R = mid else: L = mid + 1 return L sol = Solution() matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ] k = 8 print(sol.kthSmallest(matrix, k))
{ "repo_name": "gengwg/leetcode", "path": "378_kth_smallest_element_in_a_sorted_matrix.py", "copies": "1", "size": "2958", "license": "apache-2.0", "hash": 6311400746413210000, "line_mean": 30.8064516129, "line_max": 133, "alpha_frac": 0.57775524, "autogenerated": false, "ratio": 3.415704387990762, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44934596279907624, "avg_score": null, "num_lines": null }
# 379 Design Phone Directory # Design a Phone Directory which supports the following operations: # # get: Provide a number which is not assigned to anyone. # check: Check if a number is available or not. # release: Recycle or release a number. # # Example: # # // Init a phone directory containing a total of 3 numbers: 0, 1, and 2. # PhoneDirectory directory = new PhoneDirectory(3); # # // It can return any available phone number. Here we assume it returns 0. # directory.get(); # # // Assume it returns 1. # directory.get(); # # // The number 2 is available, so return true. # directory.check(2); # # // It returns 2, the only number that is left. # directory.get(); # # // The number 2 is no longer available, so return false. # directory.check(2); # # // Release number 2 back to the pool. # directory.release(2); # # // Number 2 is available again, return true. # directory.check(2); # class PhoneDirectory: def __init__(self, maxNumbers): """ Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory. :type maxNumbers: int """ self.set = set(range(maxNumbers)) self.max = maxNumbers def get(self): """ Provide a number which is not assigned to anyone. @return - Return an available number. Return -1 if none is available. :rtype: int """ return self.set.pop() if self.set else -1 def check(self, number): """ Check if a number is available or not. :type number: int :rtype: bool """ return number in self.set def release(self, number): """ Recycle or release a number. :type number: int :rtype: void """ self.set.add(number) # Your PhoneDirectory object will be instantiated and called as such: # obj = PhoneDirectory(maxNumbers) # param_1 = obj.get() # param_2 = obj.check(number) # obj.release(number)
{ "repo_name": "gengwg/leetcode", "path": "379_design_phone_directory.py", "copies": "1", "size": "2009", "license": "apache-2.0", "hash": -9117401121379560000, "line_mean": 25.4342105263, "line_max": 90, "alpha_frac": 0.6296665007, "autogenerated": false, "ratio": 3.8339694656488548, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9962913005099578, "avg_score": 0.00014459224985540777, "num_lines": 76 }
# 3-7. Shrinking Guest List: You just found out that your new dinner table won’t arrive in time for the dinner, # and you have space for only two guests. # • Start with your program from Exercise 3-6. Add a new line that prints a message saying that you # can invite only two people for dinner. # • Use pop() to remove guests from your list one at a time until only two names remain in your list. # Each time you pop a name from your list, print a message to that person letting them know you’re sorry # you can’t invite them to dinner. # • Print a message to each of the two people still on your list, letting them know they’re still invited. # • Use del to remove the last two names from your list, so you have an empty list. Print your list to make sure # you actually have an empty list at the end of your program. guests = ['Antonio', 'Emanuel', 'Francisco'] message = "1.- Hello dear uncle " + guests[0] + ", I hope you can come this 16th for a mexican dinner in my house." print(message) message = "2.- Hi " + guests[1] + "! The next monday we'll have a dinner, you should come here to spend time with " \ " the family and friends for a while, also we will have some beers. " print(message) message = "3.- Hello grandpa " + guests[2] + "!, my mother told me that we will have a dinner next monday and we want" \ " that you come here because we miss you. " print(message) print("\n My friend " + guests[1] + " can't make it to dinner.\n") # My friend Emanuel can't make it, so I'll invite my friend Luis. del (guests[1]) guests.insert(1, 'Luis') message = "1.- Uncle " + guests[0] + ", don't forget the dinner is today, see you later!." print(message) message = "2.- Hi " + guests[1] + "! Today we'll have a dinner, please come here to spend time with us, " \ "we will have meat and some beers. " print(message) message = "3.- Grandpa " + guests[2] + ", don't forget to come today to the dinner." print(message) # Now we have more space, so I gonna invite more people xd print("\nNow we have more space! xdxd \n") guests.insert(0, 'Ariel') guests.insert(3, 'Sergio') guests.append('Norma') message = "1.- Hi " + guests[0] + "!, hey nigga come here tonight to dinner, we gonna celebrate this day! :v" print(message) message = "2.- Uncle " + guests[1] + ", don't forget the dinner is today, see you later!." print(message) message = "3.- Hi " + guests[2] + "! Today we'll have dinner, please come here to spend time with us, " \ "we will have a lot of meat and some beers. " print(message) message = "4.- Hey " + guests[3] + "!, how are you?, please come to my house tonight" print(message) message = "5.- Grandpa " + guests[4] + ", don't forget to come today to dinner." print(message) message = "6.- Hello " + guests[5] + "!, I was wondering if you would like to come here tonight to dinner?, " \ "I hope you don't have things to do!" print(message) # Dammit! I'm so sorry but I can invite only 2 people for dinner :( print("\nI'm so sorry but I can invite only 2 people for dinner :( \n") print("I'm so sorry " + guests.pop() + " but there is no room in my house :(") print("I'm so sorry " + guests.pop() + " but there is no room in my house :(") print("I'm so sorry " + guests.pop() + " but there is no room in my house :(") print("I'm so sorry " + guests.pop() + " but there is no room in my house :(") # Now we have 2 people that I can invite print("\n") message = "Hello " + guests[0] + " please don't forget to come tonight for dinner!" print(message) message = "Hello uncle " + guests[1] + " please don't forget to come tonight for dinner!" print(message) # Now I have to remove the last two names from my list print("\n") del(guests[1]) del(guests[0]) print(guests)
{ "repo_name": "AnhellO/DAS_Sistemas", "path": "Ago-Dic-2019/DanielM/PracticaUno/3.7_ShrinkingGuestList.py", "copies": "1", "size": "3910", "license": "mit", "hash": -4885624744334136000, "line_mean": 39.5729166667, "line_max": 120, "alpha_frac": 0.6497175141, "autogenerated": false, "ratio": 3.130225080385852, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4279942594485852, "avg_score": null, "num_lines": null }
"""3-7. Shrinking Guest List: You just found out that your new dinner table won’t arrive in time for the dinner, and you have space for only two guests. • Start with your program from Exercise 3-6. Add a new line that prints a message saying that you can invite only two people for dinner. • Use pop() to remove guests from your list one at a time until only two names remain in your list. Each time you pop a name from your list, print a message to that person letting them know you’re sorry you can’t invite them to dinner. • Print a message to each of the two people still on your list, letting them know they’re still invited. • Use del to remove the last two names from your list, so you have an empty list. Print your list to make sure you actually have an empty list at the end of your program.""" invitados = ['Teresa', 'Guadalupe', 'Rosendo'] name = invitados[0].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[1].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[2].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[1].title() print("\nLo siento, " + name + " no puede llegar a cenar.") # Cuando Guadalupe no puede del(invitados[1]) invitados.insert(1, 'Samuel') # Imprimir las invitaciones de nuevo. name = invitados[0].title() print("\n" + name + ", te invito a cenar unos ricos taquitos!") name = invitados[1].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[2].title() print(name + ", te invito a cenar unos ricos taquitos!") # Agregando mas personas a la lista. print("\nAgregando mas personas a la lista") invitados.insert(0, 'Maria') invitados.insert(2, 'Reynaldo') invitados.append('José') name = invitados[0].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[1].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[2].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[3].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[4].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[5].title() print(name + ", te invito a cenar unos ricos taquitos!") print("\nLo siento, solo podemos invitar a dos personas a cenar") name = invitados.pop() print("Lo siento, " + name.title() + " no puedo invitarte a cenar") name = invitados.pop() print("Lo siento, " + name.title() + " no puedo invitarte a cenar.") name = invitados.pop() print("Lo siento, " + name.title() + " no puedo invitarte a cenar.") name = invitados.pop() print("Lo siento, " + name.title() + " no puedo invitarte a cenar.") # Los que iran a cenar name = invitados[0].title() print(name + ", te invito a cenar unos ricos taquitos!") name = invitados[1].title() print(name + ", te invito a cenar unos ricos taquitos!") # Eliminar del(invitados[0]) del(invitados[0]) # Mostrando la lista vacia print(invitados)
{ "repo_name": "AnhellO/DAS_Sistemas", "path": "Ago-Dic-2019/NoemiEstherFloresPardo/Practica1/ShrinkingGuestList.py", "copies": "1", "size": "3008", "license": "mit", "hash": 304869354658099900, "line_mean": 30.829787234, "line_max": 81, "alpha_frac": 0.7081243731, "autogenerated": false, "ratio": 2.7694444444444444, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.39775688175444446, "avg_score": null, "num_lines": null }
## 3.7 Variations import random from deap import base from deap import creator from deap import tools ## Data structure and initializer creation creator.create("FitnessMax", base.Fitness, weights=(1.0,)) creator.create("Individual", list, fitness=creator.FitnessMax) toolbox = base.Toolbox() toolbox.register("attr_float", random.random) toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, 10) toolbox.register("population", tools.initRepeat, list, toolbox.individual) def onemax(individual): return sum(individual), toolbox.register("mate", tools.cxTwoPoint) toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=0.2) toolbox.register("select", tools.selTournament, tournsize=3) toolbox.register("evaluate", onemax) pop = toolbox.population(n=100) CXPB, MUTPB, NGEN = 0.7, 0.3, 25 fitnesses = toolbox.map(toolbox.evaluate, pop) for ind, fit in zip(pop, fitnesses): ind.fitness.values = fit from deap import algorithms algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=50)
{ "repo_name": "DailyActie/Surrogate-Model", "path": "docs/code/tutorials/part_3/3_8_algorithms.py", "copies": "2", "size": "1053", "license": "mit", "hash": 1591633770448304400, "line_mean": 27.4594594595, "line_max": 92, "alpha_frac": 0.7597340931, "autogenerated": false, "ratio": 3.0345821325648417, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47943162256648414, "avg_score": null, "num_lines": null }
# 382. Linked List Random Node # Given a singly linked list, return a random node's value from the linked list. # Each node must have the same probability of being chosen. # # Follow up: # What if the linked list is extremely large and its length is unknown to you? # Could you solve this efficiently without using extra space? # # Example: # # // Init a singly linked list [1,2,3]. # ListNode head = new ListNode(1); # head.next = new ListNode(2); # head.next.next = new ListNode(3); # Solution solution = new Solution(head); # # // getRandom() should return either 1, 2, or 3 randomly. # // Each element should have equal probability of returning. # solution.getRandom(); # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # https://www.hrwhisper.me/leetcode-linked-list-random-node/ # 题意: 给定一个链表,要求以相等的概率返回链表上的结点。 # 思路: # # 若已知链表长度len,那么直接随机一下0~len-1,然后遍历到那个结点。 # # 如果不知道长度呢? # # 我们实时的计算当前遍历了多少个元素cnt,然后以 1/cnt 的概率选择 当前的元素,直到遍历完链表。 # # 这样遍历一遍即可。 # # 为啥是对的? # # 我们以第2个数为例(就是head.next.val) # # 选取的概率为(1/2)* (2/3)*(3/4)* ……….. (n-1) / n = 1/n # (选取第2个数在长度为2的时候为1/2,其他的都不要选) # # 而对于任意的第x数,由于可以覆盖前面的数,均有: (1/x) * (x/(x+1)) *…….(n-1) / n = 1/n # # 第n个数就直接1/n啦 # # 大家都是1/n~ class Solution(object): def __init__(self, head): """ @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode """ self.head = head def getRandom(self): """ Returns a random node's value. :rtype: int """ import random # 在代码实现上,这里的cnt 比上面讲解中的cnt 少1 randint(x,y)返回的为[x,y]的闭区间。 ans = cnt = 0 # save some typing by asigning it to a variable head = self.head while head: if random.randint(0, cnt) == 0: # possibility is 1/cnt ans = head.val head = head.next cnt = cnt + 1 return ans # Your Solution object will be instantiated and called as such: # obj = Solution(head) # param_1 = obj.getRandom()
{ "repo_name": "gengwg/leetcode", "path": "382_linked_list_random_node.py", "copies": "1", "size": "2606", "license": "apache-2.0", "hash": 31297536371148350, "line_mean": 24.2470588235, "line_max": 90, "alpha_frac": 0.6178937558, "autogenerated": false, "ratio": 2.15678391959799, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8273305046574382, "avg_score": 0.00027452576472184316, "num_lines": 85 }
# 388 - Longest Absolute File Path (Medium) # https://leetcode.com/problems/longest-absolute-file-path/ class Solution(object): def lengthLongestPath(self, input): """ :type input: str :rtype: int """ # A file system: has either files or more fs/folders. class FileTree: def __init__(self, name, level, parent): self.name = name self.level = level self.parent = parent self.children = [] # Separate input by \n newlines. lines = input.split("\n") # Filesystem object. fs = FileTree("", -1, None) # Current pointer. folder = fs for i in range(len(lines)): line = lines[i] tabCount = line.count("\t") line = line.replace("\t", "") # If line its at a previous or current level, go up until reaching # the parent of this line. while tabCount <= folder.level: folder = folder.parent # Append to the children of this level. folder.children.append(FileTree(line + "/", tabCount, folder)) # If its a folder, enter that folder. if line.count(".") == 0: folder = folder.children[-1] # Do a DFS to build the longest possible chain. def DFS(fil): curName = fil.name # Remove the trailing "/" from a file. if curName.count(".") > 0: curName = curName.replace("/", "") maxName = curName # Iterate over the subfiles, if any. A file will not have # children and just the filename will be returned. for subfil in fil.children: nxt = curName + DFS(subfil) # Replace maxName only if length is exceeded and it has # a file at the end of the chain. if len(nxt) > len(maxName) and nxt.count(".") > 0: maxName = nxt return maxName return len(DFS(fs))
{ "repo_name": "zubie7a/Algorithms", "path": "LeetCode/02_Medium/lc_388.py", "copies": "1", "size": "2113", "license": "mit", "hash": 5201699824389490000, "line_mean": 36.7321428571, "line_max": 78, "alpha_frac": 0.5097018457, "autogenerated": false, "ratio": 4.392931392931393, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5402633238631392, "avg_score": null, "num_lines": null }
# 388. Longest Absolute File Path # Suppose we abstract our file system by a string in the following manner: # The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: # dir # subdir1 # subdir2 # file.ext # The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext. # The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" # represents: # dir # subdir1 # file1.ext # subsubdir1 # subdir2 # subsubdir2 # file2.ext # The directory dir contains two sub-directories subdir1 and subdir2. # subdir1 contains a file file1.ext and an empty second-level sub-directory subsubdir1. # subdir2 contains a second-level sub-directory subsubdir2 containing a file file2.ext. # We are interested in finding the longest (number of characters) absolute path to a file within our file system. # For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext", and its length is 32 (not including the double quotes). # Given a string representing the file system in the above format, # return the length of the longest absolute path to file in the abstracted file system. # If there is no file in the system, return 0. # Note: # The name of a file contains at least a . and an extension. # The name of a directory or sub-directory will not contain a .. # Time complexity required: O(n) where n is the size of the input string. # Notice that a/aa/aaa/file1.txt is not the longest file path, # if there is another path aaaaaaaaaaaaaaaaaaaaa/sth.png. class Solution(object): # https://gengwg.blogspot.com/2018/05/leetcode-388-longest-absolute-file-path.html def lengthLongestPath(self, input): """ :type input: str :rtype: int """ maxlen = 0 pathlen = {0: 0} # initial depth 0, length 0 # >>> "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext".splitlines() # ['dir', '\tsubdir1', '\tsubdir2', '\t\tfile.ext'] for line in input.splitlines(): # split by \n's name = line.lstrip('\t') # strip left \t's depth = len(line) - len(name) # depth = number of \t's if '.' in name: # is file # update max file length only maxlen = max(maxlen, pathlen[depth] + len(name)) else: # is dir # update path length at next depth level only pathlen[depth+1] = pathlen[depth] + len(name) + 1 # +1 is for '/' return maxlen
{ "repo_name": "gengwg/leetcode", "path": "388_longest_absolute_file_path.py", "copies": "1", "size": "2624", "license": "apache-2.0", "hash": 5182817440833726000, "line_mean": 38.7727272727, "line_max": 164, "alpha_frac": 0.652820122, "autogenerated": false, "ratio": 3.4122236671001303, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9542815915529048, "avg_score": 0.004445574714216504, "num_lines": 66 }
# 389. Find the Difference # Given two strings s and t which consist of only lowercase letters. # # String t is generated by random shuffling string s and then add one more letter at a random position. # # Find the letter that was added in t. # # Example: # # Input: # s = "abcd" # t = "abcde" # # Output: # e # # Explanation: # 'e' is the letter that was added. class Solution(object): # https://leetcode.com/problems/find-the-difference/discuss/86904/3-Different-Python-Solutions-(Dictionary-Difference-XOR) def findTheDifference(self, s, t): """ :type s: str :type t: str :rtype: str """ code = 0 for letter in s + t: code ^= ord(letter) return chr(code) def findTheDifference(self, s, t): dic = {} for ch in s: dic[ch] = dic.get(ch, 0) + 1 for ch in t: if dic.get(ch, 0) == 0: return ch else: dic[ch] -= 1 test = Solution() print(test.findTheDifference("abcd", "abcde"))
{ "repo_name": "gengwg/leetcode", "path": "389_find_difference.py", "copies": "1", "size": "1060", "license": "apache-2.0", "hash": -2741178108361048000, "line_mean": 22.0434782609, "line_max": 126, "alpha_frac": 0.5660377358, "autogenerated": false, "ratio": 3.3974358974358974, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9462428482734225, "avg_score": 0.00020903010033444818, "num_lines": 46 }
# 38. Count and Say - LeetCode # https://leetcode.com/problems/count-and-say/description/ # Example 1: # Input: 1 # Output: "1" # Example 2: # Input: 4 # Output: "1211" class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ res = "1" i = 1 while i < n: j = 0 new_res = "" while j < len(res): k = 1 if j == len(res) - 1: new_res += "1" + res[j] break while k <= len(res) - j: if j+k < len(res) and res[j+k] == res[j]: k += 1 else: new_res += str(k) + res[j] j += k break res = new_res i += 1 return res s = Solution() pairs = [ (1,"1"), (2,"11"), (3,"21"), (4,"1211"), (5,"111221"), (6,"312211"), (11,"11131221133112132113212221") ] for i in pairs: print s.countAndSay(i[0]), i[1] == s.countAndSay(i[0])
{ "repo_name": "heyf/cloaked-octo-adventure", "path": "leetcode/038_count-and-say.py", "copies": "1", "size": "1167", "license": "mit", "hash": 31960755531041550, "line_mean": 21.9019607843, "line_max": 61, "alpha_frac": 0.3633247644, "autogenerated": false, "ratio": 3.412280701754386, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9168637732762248, "avg_score": 0.02139354667842746, "num_lines": 51 }
"""38. Count and Say https://leetcode.com/problems/count-and-say/description/ The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n where 1 ≤ n ≤ 30, generate the n^th term of the count-and-say sequence. Note: Each term of the sequence of integers will be represented as a string. Example 1: Input: 1 Output: "1" Example 2: Input: 4 Output: "1211" """ class Solution: def count_and_say(self, n: int) -> str: assert 1 <= n <= 30 if n == 1: return "1" def say(num_str: str) -> str: res = "" cur_digit = num_str[0] cur_digit_count = 1 for i in range(1, len(num_str)): if num_str[i] == cur_digit: cur_digit_count += 1 else: res += str(cur_digit_count) + cur_digit cur_digit = num_str[i] cur_digit_count = 1 res += str(cur_digit_count) + cur_digit return res ans = "1" for i in range(1, n): ans = say(ans) return ans
{ "repo_name": "isudox/leetcode-solution", "path": "python-algorithm/leetcode/count_and_say.py", "copies": "1", "size": "1328", "license": "mit", "hash": -5497671432386917000, "line_mean": 18.4558823529, "line_max": 74, "alpha_frac": 0.5238095238, "autogenerated": false, "ratio": 3.2666666666666666, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42904761904666666, "avg_score": null, "num_lines": null }
# 3.8/pinmux.py # Part of PyBBIO # github.com/graycatlabs/PyBBIO # MIT License # # Beaglebone pinmux driver # For Beaglebones with 3.8 kernel from config import OCP_PATH, GPIO, GPIO_FILE_BASE, EXPORT_FILE, UNEXPORT_FILE,\ SLOTS_FILE from bbio.common import addToCleanup import glob, os, cape_manager, bbio def pinMux_universalio(gpio_pin, mode, preserve_mode_on_exit=False): return False def pinMux_dtOverlays(gpio_pin, mode, preserve_mode_on_exit=False): gpio_pin = gpio_pin.lower() mux_file_glob = glob.glob('%s/*%s*/state' % (OCP_PATH, gpio_pin)) if len(mux_file_glob) == 0: try: cape_manager.load('PyBBIO-%s' % gpio_pin, not preserve_mode_on_exit) bbio.delay(250) # Give driver time to load mux_file_glob = glob.glob('%s/*%s*/state' % (OCP_PATH, gpio_pin)) except IOError: print "*Could not load %s overlay, resource busy" % gpio_pin return False if len(mux_file_glob) == 0: print "*Could not load overlay for pin: %s" % gpio_pin return False mux_file = mux_file_glob[0] # Convert mode to ocp mux name: mode = 'mode_%s' % format(mode, '#010b') # Possible modes: # mode_0b00100111 # rx active | pull down # mode_0b00110111 # rx active | pull up # mode_0b00101111 # rx active | no pull # mode_0b00000111 # pull down # mode_0b00010111 # pull up # mode_0b00001111 # no pull # See /lib/firmware/PyBBIO-src/*.dts for more info for i in range(3): # If the pin's overlay was just loaded there may not have been enough # time for the driver to get fully initialized, which causes an IOError # when trying to write the mode; try up to 3 times to avoid this: try: with open(mux_file, 'wb') as f: f.write(mode) return True except IOError: # Wait a bit between attempts bbio.delay(10) # If we get here then it didn't work 3 times in a row; raise the IOError: raise def pinMux(gpio_pin, mode, preserve_mode_on_exit=False): """ Uses custom device tree overlays to set pin modes. If preserve_mode_on_exit=True the overlay will remain loaded when the program exits, otherwise it will be unloaded before exiting. *This should generally not be called directly from user code. """ if not gpio_pin: print "*unknown pinmux pin: %s" % gpio_pin return if SLOTS_FILE: status = pinMux_dtOverlays(gpio_pin, mode, preserve_mode_on_exit) else: status = pinMux_universalIO(gpio_pin, mode, preserve_mode_on_exit) if not status: print "*could not configure pinmux for pin %s" % gpio_pin def export(gpio_pin, unexport_on_exit=False): """ Reserves a pin for userspace use with sysfs /sys/class/gpio interface. If unexport_on_exit=True unexport(gpio_pin) will be called automatically when the program exits. Returns True if pin was exported, False if it was already under userspace control. """ if ("USR" in gpio_pin): # The user LEDs are already under userspace control return True gpio_num = GPIO[gpio_pin]['gpio_num'] gpio_file = '%s/gpio%i' % (GPIO_FILE_BASE, gpio_num) if (os.path.exists(gpio_file)): # Pin already under userspace control return True with open(EXPORT_FILE, 'wb') as f: f.write(str(gpio_num)) if unexport_on_exit: addToCleanup(lambda: unexport(gpio_pin)) return True def unexport(gpio_pin): """ Returns a pin to the kernel with sysfs /sys/class/gpio interface. Returns True if pin was unexported, False if it was already under kernel control. """ if ("USR" in gpio_pin): # The user LEDs are always under userspace control return False gpio_num = GPIO[gpio_pin]['gpio_num'] gpio_file = '%s/gpio%i' % (GPIO_FILE_BASE, gpio_num) if (not os.path.exists(gpio_file)): # Pin not under userspace control return False with open(UNEXPORT_FILE, 'wb') as f: f.write(str(gpio_num)) return True
{ "repo_name": "leftbrainstrain/PyBBIO", "path": "bbio/platform/beaglebone/pinmux.py", "copies": "3", "size": "3928", "license": "mit", "hash": 7142873911039920000, "line_mean": 34.0714285714, "line_max": 80, "alpha_frac": 0.6685336049, "autogenerated": false, "ratio": 3.2223133716160786, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.038389547722982184, "num_lines": 112 }
# 393. UTF-8 Validation # A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: # For 1-byte character, the first bit is a 0, followed by its unicode code. # For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10. # This is how the UTF-8 encoding would work: # Char. number range | UTF-8 octet sequence # (hexadecimal) | (binary) # --------------------+--------------------------------------------- # 0000 0000-0000 007F | 0xxxxxxx # 0000 0080-0000 07FF | 110xxxxx 10xxxxxx # 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx # 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx # Given an array of integers representing the data, return whether it is a valid utf-8 encoding. # Note: # The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data. # Example 1: # data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001. # Return true. # It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. # Example 2: # data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100. # Return false. # The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character. # The next byte is a continuation byte which starts with 10 and that's correct. # But the second continuation byte does not start with 10, so it is invalid. class Solution(object): def validUtf8(self, data): """ :type data: List[int] :rtype: bool """ i = 0 while i < len(data): try: length = bin(data[i])[2:].zfill(8).index('0') # print("Length is " + str(length)) except: # print("not containing 0") return False if length == 0: # 1-byte i += 1 elif length in [2, 3, 4]: # 2, 3, 4 byte for j in range(length - 1): # print(i+j+1) try: if bin(data[i + j + 1])[2:].zfill(8).index('0') != 1: return False except: return False i += length else: return False return True class Solution1(object): def validUtf8(self, data): """ :type data: List[int] :rtype: bool Solution from kamyu: use >> to get leading digits of c """ count = 0 for c in data: if count == 0: if (c >> 5) == 0b110: count = 1 elif (c >> 4) == 0b1110: count = 2 elif (c >> 3) == 0b11110: count = 3 elif (c >> 7): return False else: if (c >> 6) != 0b10: return False count -= 1 return count == 0
{ "repo_name": "aenon/OnlineJudge", "path": "leetcode/5.BitManipulation/393.UTF-8_Validation.py", "copies": "1", "size": "3183", "license": "mit", "hash": -2760603859693652000, "line_mean": 33.989010989, "line_max": 169, "alpha_frac": 0.520263902, "autogenerated": false, "ratio": 3.9442379182156135, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4964501820215613, "avg_score": null, "num_lines": null }
# 393 UTF-8 Validation # A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: # For 1-byte character, the first bit is a 0, followed by its unicode code. # For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, # followed by n-1 bytes with most significant 2 bits being 10. # This is how the UTF-8 encoding would work: # Char. number range | UTF-8 octet sequence # (hexadecimal) | (binary) # --------------------+--------------------------------------------- # 0000 0000-0000 007F | 0xxxxxxx # 0000 0080-0000 07FF | 110xxxxx 10xxxxxx # 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx # 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx # Given an array of integers representing the data, return whether it is a valid utf-8 encoding. # Note: # The input is an array of integers. # Only the least significant 8 bits of each integer is used to store the data. # This means each integer represents only 1 byte of data. # Example 1: # data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001. # Return true. # It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. # Example 2: # data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100. # Return false. # The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character. # The next byte is a continuation byte which starts with 10 and that's correct. # But the second continuation byte does not start with 10, so it is invalid. class Solution(object): def validUtf8(self, data): """ :type data: List[int] :rtype: bool """ # {00000000, 10000000, 11000000, 11100000, 11110000, 11111000} masks = [0x0, 0x80, 0xE0, 0xE0, 0xF8] bits = [0x0, 0x0, 0xC0, 0xE0, 0xF0] while data: for x in (4, 3, 2, 1, 0): if data[0] & masks[x] == bits[x]: break if x == 0 or len(data) < x: return False for y in range(1, x): if data[y] & 0xC0 != 0x80: return False data = data[x:] return True print(Solution().validUtf8([197, 130, 1]))
{ "repo_name": "gengwg/leetcode", "path": "393_utf8_validation.py", "copies": "1", "size": "2321", "license": "apache-2.0", "hash": -4463177007631892000, "line_mean": 34.1818181818, "line_max": 96, "alpha_frac": 0.6074967686, "autogenerated": false, "ratio": 3.428360413589365, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4535857182189365, "avg_score": null, "num_lines": null }
# 394. Decode String # Given an encoded string, return it's decoded string. # The encoding rule is: k[encoded_string], # where the encoded_string inside the square brackets is being repeated exactly k times. # Note that k is guaranteed to be a positive integer. # You may assume that the input string is always valid; # No extra white spaces, square brackets are well-formed, etc. # Furthermore, you may assume that the original data does not contain any digits # and that digits are only for those repeat numbers, k. # For example, there won't be input like 3a or 2[4]. # Examples: # s = "3[a]2[bc]", return "aaabcbc". # s = "3[a2[c]]", return "accaccacc". # s = "2[abc]3[cd]ef", return "abcabccdcdcdef". class Solution(object): # stack def decodeString(self, s): """ :type s: str :rtype: str """ stack = [] curNum = 0 curStr = '' for c in s: if c == '[': # push current string and number got so far stack.append(curStr) stack.append(curNum) # reset to empty/zero curStr = '' curNum = 0 elif c == ']': # pop num and previous string num = stack.pop() prevStr = stack.pop() # add prev string to cur * n curStr = prevStr + num * curStr elif c.isdigit(): # in case of '32[a]' curNum = curNum * 10 + int(c) else: curStr += c return curStr # regular expression def decodeString(self, s): import re while '[' in s: s = re.sub(r'(\d+)\[([a-z]*)\]', lambda m: int(m.group(1)) * m.group(2), s) return s if __name__ == '__main__': s = "2[abc]3[cd]ef" print(Solution().decodeString(s))
{ "repo_name": "gengwg/leetcode", "path": "394_decode_string.py", "copies": "1", "size": "1893", "license": "apache-2.0", "hash": -4221064492542397400, "line_mean": 29.5483870968, "line_max": 89, "alpha_frac": 0.5266772319, "autogenerated": false, "ratio": 3.7263779527559056, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47530551846559055, "avg_score": null, "num_lines": null }
# 397. Integer Replacement # Given a positive integer n and you can do operations as follow: # # If n is even, replace n with n/2. # If n is odd, you can replace n with either n + 1 or n - 1. # # What is the minimum number of replacements needed for n to become 1? # # Example 1: # # Input: # 8 # # Output: # 3 # # Explanation: # 8 -> 4 -> 2 -> 1 # # Example 2: # # Input: # 7 # # Output: # 4 # # Explanation: # 7 -> 8 -> 4 -> 2 -> 1 # or # 7 -> 6 -> 3 -> 2 -> 1 # class Solution(object): # http://www.voidcn.com/article/p-tdcnvoig-bcx.html # 推导出递推公式(在2147483647会超时,因为里面有n+1的递归,int溢出,所以单独拿出来) # f(1)=0; # f(2)=f(1)+1 # f(3)=min(f(2)+1,f(4)+1) # ... def integerReplacement(self, n): """ :type n: int :rtype: int """ if n == 2147483647: return 32 if n == 1: return 0 if n % 2 == 0: return self.integerReplacement(n//2) + 1 else: return min(self.integerReplacement((n-1)//2) + 2, self.integerReplacement((n+1)//2) + 2) print(Solution().integerReplacement(8)) print(Solution().integerReplacement(7))
{ "repo_name": "gengwg/leetcode", "path": "397_integer_replacement.py", "copies": "1", "size": "1214", "license": "apache-2.0", "hash": -7105124984226726000, "line_mean": 19.1403508772, "line_max": 100, "alpha_frac": 0.5461672474, "autogenerated": false, "ratio": 2.6270022883295194, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8672301027826097, "avg_score": 0.00017370158068438424, "num_lines": 57 }
"""3 add plot Revision ID: ab7e839f2b2d Revises: 299ddbcceeae Create Date: 2017-03-30 19:57:12.409636 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'ab7e839f2b2d' down_revision = '299ddbcceeae' branch_labels = None depends_on = None def upgrade(): op.execute(''' ALTER TABLE measurement ADD COLUMN name varchar(255); ALTER TABLE measurement ADD COLUMN type varchar(255); ALTER TABLE measurement ADD COLUMN value double precision; --UPDATE TABLE measurement set name = 'tilt_temp', type='temperature_celsius', value=temperature insert into measurement (name, type, ts, value, login) SELECT 'tilt_temp', 'temperature_celsius', ts, temperature, login from measurement; insert into measurement (name, type, ts, value, login) SELECT 'tilt_gravity', 'gravity', ts, cast(gravity as float), login from measurement; ''') op.execute(''' CREATE TABLE plot ( id serial PRIMARY KEY, start_time timestamp, end_time timestamp, name varchar (255), login varchar(255) REFERENCES login (id) ); ''') op.execute(''' CREATE TABLE instrument ( id serial PRIMARY KEY, name varchar(255), type varchar(255), plot int REFERENCES plot (id) ); ''') def downgrade(): op.execute(''' DROP TABLE plot ''') op.execute(''' DROP TABLE instrument ''')
{ "repo_name": "atlefren/pitilt-api", "path": "db/alembic/versions/ab7e839f2b2d_3_add_plot.py", "copies": "1", "size": "1529", "license": "mit", "hash": 5759882726647263000, "line_mean": 25.8245614035, "line_max": 148, "alpha_frac": 0.6206671027, "autogenerated": false, "ratio": 4.099195710455764, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0004041743861090887, "num_lines": 57 }
# 3a def lookup(d, k): return [v for l, v in d if l == k] d = [("a", 10), ("b", 20), ("c", 30), ("a", 40)] assert(lookup(d, "a") == [10, 40]) assert(lookup(d, "b") == [20]) assert(lookup(d, "c") == [30]) assert(lookup(d, "d") == []) # 3b def cond(b, t, f): if b: return t else: return f def update(d, k, v): return [(l, cond(l == k, v, w)) for l, w in d] d = [("a", 10), ("b", 20), ("c", 30), ("a", 40)] assert(update(d, "a", "CSE130") == [('a', 'CSE130'), ('b', 20), ('c', 30), ('a', 'CSE130')]) assert(update(d, "b", "CSE130") == [('a', 10), ('b', 'CSE130'), ('c', 30), ('a', 40)]) assert(update(d, "d", "CSE130") == [('a', 10), ('b', 20), ('c', 30), ('a', 40)]) # 3c def delete(d, k): return [(l, v) for l, v in d if l != k] d = [("a", 10), ("b", 20), ("c", 30), ("a", 40)] assert(delete(d, "a") == [("b", 20), ("c", 30)]) # 3d def add(d, k, v): return d + [(k, v)] d = [("a", 10), ("b", 20), ("c", 30), ("a", 40)] assert(add(d, "d", 5) == [("a", 10), ("b", 20), ("c", 30), ("a", 40), ("d", 5)]) # 3e def update(d, k, v): return map(lambda (l, w): (l, v if l == k else w), d) d = [("a", 10), ("b", 20), ("c", 30), ("a", 40)] assert(update(d, "a", "CSE130") == [('a', 'CSE130'), ('b', 20), ('c', 30), ('a', 'CSE130')]) assert(update(d, "b", "CSE130") == [('a', 10), ('b', 'CSE130'), ('c', 30), ('a', 40)]) assert(update(d, "d", "CSE130") == [('a', 10), ('b', 20), ('c', 30), ('a', 40)]) # 4 def in_range(i, (lo, hi)): def decorator(f): def decorated(*args): if 0 <= i < len(args) and not lo <= args[i] <= hi: raise Exception("%dth arg %d too %s" % (i, args[i], "small" if args[i] < lo else "big")) ret = f(*args) if i == -1 and not lo <= ret <= hi: raise Exception("Return value %d too %s" % (ret, "small" if args[i] < lo else "big")) return ret return decorated return decorator # Need to test manually because of exceptions
{ "repo_name": "metakirby5/cse130-exams", "path": "finals/fa13.py", "copies": "1", "size": "2101", "license": "mit", "hash": -8485780638522782000, "line_mean": 28.5915492958, "line_max": 68, "alpha_frac": 0.4117087101, "autogenerated": false, "ratio": 2.581081081081081, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8456564222270236, "avg_score": 0.00724511378216893, "num_lines": 71 }
''' 3b_angle_usage.py ========================= AIM: Plots the diagonistic angle usage of the PST in SALSA. Requires the monitor_angle_usage=True in 1_compute_<p>.py and log_all_data = .true. in straylight_<orbit_id>_<p>/CODE/parameter. INPUT: files: - <orbit_id>_misc/orbits.dat - <orbit_id>_flux/angles_<orbit_number>.dat variables: see section PARAMETERS (below) OUTPUT: in <orbit_id>_misc/ : file one stat file in <orbit_id>_figures/ : step distribution, step in function of time CMD: python 3b_angle_usage.py ISSUES: <none known> REQUIRES:- LATEX, epstopdf, pdfcrop, standard python libraries, specific libraries in resources/ - Structure of the root folder: * <orbit_id>_flux/ --> flux files * <orbit_id>_figures/ --> figures * <orbit_id>_misc/ --> storages of data * all_figures/ --> comparison figures REMARKS: <none> ''' ########################################################################### ### INCLUDES import numpy as np import pylab as plt from resources.routines import * from resources.TimeStepping import * import parameters as param import resources.constants as const import resources.figures as figures ########################################################################### orbit_id = 1001 sl_angle = 35 fancy = True show = True save = True orbit_ini = 1 orbit_end = 101 n_sampling = 55 # File name for the computed orbit file orbits_file = 'orbits.dat' ########################################################################### if fancy: figures.set_fancy() # Formatted folders definitions folder_flux, folder_figures, folder_misc = init_folders(orbit_id) orbits = np.loadtxt(folder_misc+orbits_file,dtype='i4') orbits = orbits[:,0] orbits = orbits[np.where(orbits>=orbit_ini)] orbits = orbits[np.where(orbits<=orbit_end)] orbit_current = orbit_ini orbit_calls = np.zeros([np.size(orbits),n_sampling]) total_calls = np.zeros(n_sampling) for ii, orbit_current in enumerate(orbits): filename = ('%sangles_%d.dat') % (folder_flux, orbit_current) data=np.loadtxt(filename) # print data.sum(axis=0)/data.sum() orbit_calls[ii] = data.sum(axis=0) total_calls += data.sum(axis=0) tot = total_calls.sum()/100 stddev = 3.*orbit_calls.std(axis=0)/tot #print stddev #print '*'*23 #print total_calls #print total_calls.sum() angles = np.linspace(sl_angle,89,n_sampling) fname = '%sangle_usage_%d_%d_%d-%d.dat' % (folder_misc,orbit_id,sl_angle,orbit_ini,orbit_end) tosave = np.zeros([np.size(angles),2]) ii = 0 for a,c in zip(angles,total_calls/tot): tosave[ii,0] = a tosave[ii,1] = c ii += 1 np.savetxt(fname,tosave,fmt='%d %1.6f') fig, ax = plt.subplots(1) plt.xlabel(r'$\theta\ \mathrm{Angular}\ \mathrm{distance}\ \mathrm{to}\ \mathrm{limb}\ \mathrm{[deg]}$') plt.ylabel('\% of calls') plt.plot(angles, total_calls/tot) ax.fill_between(angles, total_calls/tot-stddev, total_calls/tot+stddev, facecolor='yellow', alpha=0.5, label='3 sigma range') plt.grid() if show: plt.show() # Saves the figure if save: fname = '%sangle_usage_%d_%d_%d-%d' % (folder_figures,orbit_id,sl_angle,orbit_ini,orbit_end) figures.savefig(fname,fig,fancy)
{ "repo_name": "kuntzer/SALSA-public", "path": "3b_angle_usage.py", "copies": "1", "size": "3138", "license": "bsd-3-clause", "hash": 1437450933465167, "line_mean": 26.0517241379, "line_max": 188, "alpha_frac": 0.6427660931, "autogenerated": false, "ratio": 2.913649025069638, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4056415118169638, "avg_score": null, "num_lines": null }
# 3-bar pendulum # import all we need for solving the problem from pytrajectory import ControlSystem import numpy as np import sympy as sp from sympy import cos, sin from numpy import pi def n_bar_pendulum(N=1, param_values=dict()): ''' Returns the mass matrix :math:`M` and right hand site :math:`B` of motion equations .. math:: M * (d^2/dt^2) x = B for the :math:`N`\ -bar pendulum. Parameters ---------- N : int Number of bars. param_values : dict Numeric values for the system parameters, such as lengths, masses and gravitational acceleration. Returns ------- sympy.Matrix The mass matrix `M` sympy.Matrix The right hand site `B` list List of symbols for state variables list List with symbol for input variable ''' # first we have to create some symbols F = sp.Symbol('F') # the force that acts on the car g = sp.Symbol('g') # the gravitational acceleration m = sp.symarray('m', N+1) # masses of the car (`m0`) and the bars l = sp.symarray('l', N+1)#[1:] # length of the bars (`l0` is not needed nor used) phi = sp.symarray('phi', N+1)#[1:] # deflaction angles of the bars (`phi0` is not needed nor used) dphi = sp.symarray('dphi', N+1)#[1:] # 1st derivative of the deflaction angles (`dphi0` is not needed nor used) if param_values.has_key('F'): F = param_values['F'] elif param_values.has_key(F): F = param_values[F] if param_values.has_key('g'): g = param_values['g'] elif param_values.has_key(g): g = param_values[g] else: g = 9.81 for i, mi in enumerate(m): if param_values.has_key(mi.name): m[i] = param_values[mi.name] elif param_values.has_key(mi): m[i] = param_values[mi] for i, li in enumerate(l): if param_values.has_key(li.name): l[i] = param_values[li.name] elif param_values.has_key(li): l[i] = param_values[li] C = np.empty((N,N), dtype=object) S = np.empty((N,N), dtype=object) I = np.empty((N), dtype=object) for i in xrange(1,N+1): for j in xrange(1,N+1): C[i-1,j-1] = cos(phi[i] - phi[j]) S[i-1,j-1] = sin(phi[i] - phi[j]) for i in xrange(1,N+1): if param_values.has_key('I_%d'%i): I[i-1] = param_values['I_%d'%i] #elif param_values.has_key(Ii): # I[i] = param_values[Ii] else: I[i-1] = 4.0/3.0 * m[i] * l[i]**2 #-------------# # Mass matrix # #-------------# M = np.empty((N+1, N+1), dtype=object) # 1st row M[0,0] = m.sum() for j in xrange(1,N): M[0,j] = (m[j] + 2*m[j+1:].sum()) * l[j] * cos(phi[j]) M[0,N] = m[N] * l[N] * cos(phi[N]) # rest of upper triangular part, except last column for i in xrange(1,N): M[i,i] = I[i-1] + (m[i] + 4.0*m[i+1:].sum()) * l[i]**2 for j in xrange(i+1,N): M[i,j] = 2.0*(m[j] + 2.0*m[j+1:].sum())*l[i]*l[j]*C[j-1,i-1] # the last column for i in xrange(1,N): M[i,N] = 2.0*(m[N]*l[i]*l[N]*C[N-1,i-1]) M[N,N] = I[N-1] + m[N]*l[N]**2 # the rest (lower triangular part) for i in xrange(N+1): for j in xrange(i,N+1): M[j,i] = 1 * M[i,j] #-----------------# # Right hand site # #-----------------# B = np.empty((N+1), dtype=object) # first row B[0] = F for j in xrange(1,N): B[0] += (m[j] + 2.0*m[j+1:].sum())*l[j]*sin(phi[j]) * dphi[j]**2 B[0] += (m[N]*l[N]*sin(phi[N])) * dphi[N]**2 # rest except for last row for i in xrange(1,N): B[i] = (m[i] + 2.0*m[i+1:].sum())*g*l[i]*sin(phi[i]) for j in xrange(1,N): B[i] += (2.0*(m[j] + 2.0*m[j+1:].sum())*l[j]*l[i]*S[j-1,i-1]) * dphi[j]**2 B[i] += (2.0*m[N]*l[N]*l[N]*S[N-1,i-1]) * dphi[N]**2 # last row B[N] = m[N]*g*l[N]*sin(phi[N]) for j in xrange(1,N+1): B[N] += (2.0*m[N]*l[j]*l[N]*S[j-1,N-1]) * dphi[j]**2 # build lists of state and input variables x, dx = sp.symbols('x, dx') state_vars = [x, dx] for i in xrange(1,N+1): state_vars.append(phi[i]) state_vars.append(dphi[i]) input_vars = [F] # return stuff return sp.Matrix(M), sp.Matrix(B), state_vars, input_vars def solve_motion_equations(M, B, state_vars=[], input_vars=[], parameters_values=dict()): ''' Solves the motion equations given by the mass matrix and right hand side to define a callable function for the vector field of the respective control system. Parameters ---------- M : sympy.Matrix A sympy.Matrix containing sympy expressions and symbols that represent the mass matrix of the control system. B : sympy.Matrix A sympy.Matrix containing sympy expressions and symbols that represent the right hand site of the motion equations. state_vars : list A list with sympy.Symbols's for each state variable. input_vars : list A list with sympy.Symbols's for each input variable. parameter_values : dict A dictionary with a key:value pair for each system parameter. Returns ------- callable A callable function for the vectorfield. ''' M_shape = M.shape B_shape = B.shape assert(M_shape[0] == B_shape[0]) # at first we create a buffer for the string that we complete and execute # to dynamically define a function and return it fnc_str_buffer =''' def f(x, u): # System variables %s # x_str %s # u_str # Parameters %s # par_str # Sympy Common Expressions %s # cse_str # Vectorfield %s # ff_str return ff ''' ########################################### # handle system state and input variables # ########################################### # --> leads to x_str and u_str which show how to unpack the variables x_str = '' u_str = '' for var in state_vars: x_str += '%s, '%str(var) for var in input_vars: u_str += '%s, '%str(var) x_str = x_str + '= x' u_str = u_str + '= u' ############################ # handle system parameters # ############################ # --> leads to par_str par_str = '' for k, v in parameters_values.items(): # 'k' is the name of a system parameter such as mass or gravitational acceleration # 'v' is its value in SI units par_str += '%s = %s; '%(str(k), str(v)) # as a last we remove the trailing '; ' from par_str to avoid syntax errors par_str = par_str[:-2] # now solve the motion equations w.r.t. the accelerations # (might take some while...) #print " -> solving motion equations w.r.t. accelerations" # apply sympy.cse() on M and B to speed up solving the eqs M_cse_list, M_cse_res = sp.cse(M, symbols=sp.numbered_symbols('M_cse')) B_cse_list, B_cse_res = sp.cse(B, symbols=sp.numbered_symbols('B_cse')) # solve abbreviated equation system #sol = M.solve(B) Mse = M_cse_res[0] Bse = B_cse_res[0] cse_sol = Mse.solve(Bse) # substitute back the common subexpressions to the solution for expr in reversed(B_cse_list): cse_sol = cse_sol.subs(*expr) for expr in reversed(M_cse_list): cse_sol = cse_sol.subs(*expr) # use SymPy's Common Subexpression Elimination #cse_list, cse_res = sp.cse(sol, symbols=sp.numbered_symbols('q')) cse_list, cse_res = sp.cse(cse_sol, symbols=sp.numbered_symbols('q')) ################################ # handle common subexpressions # ################################ # --> leads to cse_str cse_str = '' #cse_list = [(str(l), str(r)) for l, r in cse_list] for cse_pair in cse_list: cse_str += '%s = %s; '%(str(cse_pair[0]), str(cse_pair[1])) # add result of cse for i in xrange(M_shape[0]): cse_str += 'q%d_dd = %s; '%(i, str(cse_res[0][i])) cse_str = cse_str[:-2] ###################### # create vectorfield # ###################### # --> leads to ff_str ff_str = 'ff = [' for i in xrange(M_shape[0]): ff_str += '%s, '%str(state_vars[2*i+1]) ff_str += 'q%s_dd, '%(i) # remove trailing ',' and add closing brackets ff_str = ff_str[:-2] + ']' ############################ # Create callable function # ############################ # now we can replace all placeholders in the function string buffer fnc_str = fnc_str_buffer%(x_str, u_str, par_str, cse_str, ff_str) # and finally execute it which will create a python function 'f' exec(fnc_str) # now we have defined a callable function that can be used within PyTrajectory return f # we consider the case of a 3-bar pendulum N = 3 # set model parameters l1 = 0.25 # 1/2 * length of the pendulum 1 l2 = 0.25 # 1/2 * length of the pendulum 2 l3 = 0.25 # 1/2 * length of the pendulum 3 m1 = 0.1 # mass of the pendulum 1 m2 = 0.1 # mass of the pendulum 2 m3 = 0.1 # mass of the pendulum 3 m = 1.0 # mass of the car g = 9.81 # gravitational acceleration I1 = 4.0/3.0 * m1 * l1**2 # inertia 1 I2 = 4.0/3.0 * m2 * l2**2 # inertia 2 I3 = 4.0/3.0 * m2 * l2**2 # inertia 3 param_values = {'l_1':l1, 'l_2':l2, 'l_3':l3, 'm_1':m1, 'm_2':m2, 'm_3':m3, 'm_0':m, 'g':g, 'I_1':I1, 'I_2':I2, 'I_3':I3} # get matrices of motion equations M, B, state_vars, input_vars = n_bar_pendulum(N=3, param_values=param_values) # get callable function for vectorfield that can be used with PyTrajectory f = solve_motion_equations(M, B, state_vars, input_vars) # then we specify all boundary conditions a = 0.0 xa = [0.0, 0.0, pi, 0.0, pi, 0.0, pi, 0.0] b = 3.5 xb = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ua = [0.0] ub = [0.0] # now we create our Trajectory object and alter some method parameters via the keyword arguments S = ControlSystem(f, a, b, xa, xb, ua, ub, constraints=None, eps=4e-1, su=30, kx=2, use_chains=False, use_std_approach=False) # time to run the iteration x, u = S.solve() # the following code provides an animation of the system above # for a more detailed explanation have a look at the 'Visualisation' section # in the documentation import sys import matplotlib as mpl from pytrajectory.visualisation import Animation # all rods have the same length rod_lengths = [0.5] * N # all pendulums have the same size pendulum_sizes = [0.015] * N car_width, car_height = [0.05, 0.02] # the drawing function def draw(xt, image): x = xt[0] phi = xt[2::2] x_car = x y_car = 0 # coordinates of the pendulums x_p = [] y_p = [] # first pendulum x_p.append( x_car + rod_lengths[0] * sin(phi[0]) ) y_p.append( rod_lengths[0] * cos(phi[0]) ) # the rest for i in xrange(1,3): x_p.append( x_p[i-1] + rod_lengths[i] * sin(phi[i]) ) y_p.append( y_p[i-1] + rod_lengths[i] * cos(phi[i]) ) # create image # first the car and joint car = mpl.patches.Rectangle((x_car-0.5*car_width, y_car-car_height), car_width, car_height, fill=True, facecolor='grey', linewidth=2.0) joint = mpl.patches.Circle((x_car,0), 0.005, color='black') image.patches.append(car) image.patches.append(joint) # then the pendulums for i in xrange(3): image.patches.append( mpl.patches.Circle(xy=(x_p[i], y_p[i]), radius=pendulum_sizes[i], color='black') ) if i == 0: image.lines.append( mpl.lines.Line2D(xdata=[x_car, x_p[0]], ydata=[y_car, y_p[0]], color='black', zorder=1, linewidth=2.0) ) else: image.lines.append( mpl.lines.Line2D(xdata=[x_p[i-1], x_p[i]], ydata=[y_p[i-1], y_p[i]], color='black', zorder=1, linewidth=2.0) ) # and return the image return image # create Animation object if 'plot' in sys.argv or 'animate' in sys.argv: A = Animation(drawfnc=draw, simdata=S.sim_data, plotsys=[(0,'$x$'),(1,'$\\dot{x}$')], plotinputs=[(0,'$u$')]) xmin = np.min(S.sim_data[1][:,0]) xmax = np.max(S.sim_data[1][:,0]) A.set_limits(xlim=(xmin - 1.5, xmax + 1.5), ylim=(-2.0,2.0)) if 'plot' in sys.argv: A.show(t=S.b) if 'animate' in sys.argv: A.animate() A.save('ex9_TriplePendulum.gif')
{ "repo_name": "akunze3/pytrajectory", "path": "examples/ex9_TriplePendulum.py", "copies": "1", "size": "13108", "license": "bsd-3-clause", "hash": -250199391809554460, "line_mean": 29.8423529412, "line_max": 118, "alpha_frac": 0.5215898688, "autogenerated": false, "ratio": 3.014026212922511, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40356160817225106, "avg_score": null, "num_lines": null }
## 3. Base Cases ## # Recursive factorial function def factorial(n): # Check the base case if n == 0: return 1 # Recursive case return n * factorial(n - 1) factorial1 = factorial(1) factorial5 = factorial(5) factorial25 = factorial(25) ## 5. Fibonacci ## # Add your function below def fib(n): if n == 0: return 1 if n == 1: return 1 return fib(n - 1) + fib(n - 2) fib1 = fib(1) fib5 = fib(5) fib25 = fib(25) ## 7. Exercise: Find the Length of a Linked List ## # First person's name first_item = people.head().get_data() # Getting the length of the linked list using iteration def length_iterative(ls): count = 0 while not ls.is_empty(): count = count + 1 ls = ls.tail() return count # Getting the length of the linked list using recursion def length_recursive(ls): if ls.is_empty(): return 0 return 1 + length_recursive(ls.tail()) people_length = length_recursive(people) ## 9. Exercise: Linked List Time Complexity ## # Retrieving an item in the linked list by index retrieval_by_index = "linear" # Retrieving an item in the linked list by value retrieval_by_value = "linear" # Deleting an item from the linked list, with access to the item and # the item before it deletion = "constant" # Inserting an item into the linked list, with access to the location # where we are inserting insertion = "constant" # Calculating the length of a linked list using a loop length_iterative = "linear" # Calculating the length of a linked list using recursion length_recursive = "linear"
{ "repo_name": "vipmunot/Data-Analysis-using-Python", "path": "Data Structures & Algorithms/Recursion and Advanced Data Structures-109.py", "copies": "1", "size": "1571", "license": "mit", "hash": -5955157774082165000, "line_mean": 23.1846153846, "line_max": 69, "alpha_frac": 0.6804583068, "autogenerated": false, "ratio": 3.321353065539112, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4501811372339112, "avg_score": null, "num_lines": null }
## 3. Bikesharing distribution ## import pandas bikes = pandas.read_csv("bike_rental_day.csv") prob_over_5000 = bikes[bikes["cnt"] > 5000].shape[0] / bikes.shape[0] ## 4. Computing the distribution ## import math # Each item in this list represents one k, starting from 0 and going up to and including 30. outcome_counts = list(range(31)) def find_probability(N, k, p, q): # Find the probability of any single combination. term_1 = p ** k term_2 = q ** (N-k) combo_prob = term_1 * term_2 # Find the number of combinations. numerator = math.factorial(N) denominator = math.factorial(k) * math.factorial(N - k) combo_count = numerator / denominator return combo_prob * combo_count outcome_probs = [find_probability(30, i, .39, .61) for i in outcome_counts] ## 5. Plotting the distribution ## import matplotlib.pyplot as plt # The most likely number of days is between 10 and 15. plt.bar(outcome_counts, outcome_probs) plt.show() ## 6. Simplifying the computation ## import scipy from scipy import linspace from scipy.stats import binom # Create a range of numbers from 0 to 30, with 31 elements (each number has one entry). outcome_counts = linspace(0,30,31) dist = binom.pmf(outcome_counts,30,0.39) plt.bar(outcome_counts, dist) plt.show() ## 8. Computing the mean of a probability distribution ## dist_mean = None dist_mean = 30 * .39 ## 9. Computing the standard deviation ## dist_stdev = None dist_stdev = (30*0.39*0.61)** (1/2) ## 10. A different plot ## # Enter your answer here. import scipy from scipy import linspace from scipy.stats import binom outcome_counts = linspace(0,10,11) dist = binom.pmf(outcome_counts,10,0.39) plt.bar(outcome_counts,dist) plt.show() outcome_counts = linspace(0,100,101) dist = binom.pmf(outcome_counts,100,0.39) plt.bar(outcome_counts,dist) plt.show() ## 11. The normal distribution ## # Create a range of numbers from 0 to 100, with 101 elements (each number has one entry). outcome_counts = scipy.linspace(0,100,101) # Create a probability mass function along the outcome_counts. outcome_probs = binom.pmf(outcome_counts,100,0.39) # Plot a line, not a bar chart. plt.plot(outcome_counts, outcome_probs) plt.show() ## 12. Cumulative density function ## outcome_counts = linspace(0,30,31) outcome_probs = binom.cdf(outcome_counts,30,0.39) plt.plot(outcome_counts, outcome_probs) plt.show() ## 14. Faster way to calculate likelihood ## left_16 = None right_16 = None left_16 = binom.cdf(16,30,0.39) right_16 = 1 - left_16
{ "repo_name": "vipmunot/Data-Analysis-using-Python", "path": "Probability Statistics Intermediate/Probability distributions-135.py", "copies": "1", "size": "2530", "license": "mit", "hash": 8564072370799763000, "line_mean": 24.5656565657, "line_max": 92, "alpha_frac": 0.709486166, "autogenerated": false, "ratio": 3.0481927710843375, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9163998086527915, "avg_score": 0.018736170111284558, "num_lines": 99 }
''' 3c_angle_usage.py ========================= AIM: Plots the diagonistic angle usage of the PST in SALSA. Requires the monitor_angle_usage=True in 1_compute_<p>.py and log_all_data = .true. in straylight_<orbit_id>_<p>/CODE/parameter. INPUT: files: - <orbit_id>_misc/orbits.dat - <orbit_id>_flux/angles_<orbit_number>.dat variables: see section PARAMETERS (below) OUTPUT: in <orbit_id>_misc/ : file one stat file in <orbit_id>_figures/ : step distribution, step in function of time CMD: python 3b_angle_usage.py ISSUES: <none known> REQUIRES:- LATEX, epstopdf, pdfcrop, standard python libraries, specific libraries in resources/ - Structure of the root folder: * <orbit_id>_flux/ --> flux files * <orbit_id>_figures/ --> figures * <orbit_id>_misc/ --> storages of data * all_figures/ --> comparison figures REMARKS: This is a better version than the 3b_angle_usage.py ''' ########################################################################### ### INCLUDES import numpy as np import pylab as plt from resources.routines import * from resources.TimeStepping import * import resources.figures as figures from matplotlib import cm ########################################################################### orbit_id = 704 sl_angle = 35 fancy = True show = True save = True # Bins and their legends orbit_ini = [1,441,891,1331,1771,2221,2661,3111,3551,3991,4441,4881,1] orbit_end = [441,891,1331,1771,2221,2661,3111,3551,3991,4441,4881,5322,5322] legends = ['Jan','Feb','Mar','Avr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Year'] ########################################################################### if fancy: figures.set_fancy() # Formatted folders definitions folder_flux, folder_figures, folder_misc = init_folders(orbit_id) fig, ax = plt.subplots(1) ii = 0. size = len(orbit_ini) minv=100 maxv=0 for ini, end,label in zip(orbit_ini,orbit_end,legends): print ini, end, label c = cm.rainbow(ii/float(size)) fname = '%sangle_usage_%d_%d_%d-%d.dat' % (folder_misc,orbit_id,sl_angle,ini,end) values = np.loadtxt(fname) plt.plot(values[:,0], values[:,1],label=label, lw=2, c=c) if np.min(values[:,1]) < minv: minv = np.min(values[:,1]) if np.max(values[:,1]) > maxv: maxv = np.max(values[:,1]) ii += 1 plt.ylim( [ np.floor(minv), np.ceil(maxv) ] ) plt.xlabel(r'$\theta\ \mathrm{Angular}\ \mathrm{distance}\ \mathrm{to}\ \mathrm{limb}\ \mathrm{[deg]}$') plt.ylabel('\% of calls') plt.legend(loc=2,prop={'size':14}, ncol=2) plt.grid() if show: plt.show() # Saves the figure if save: fname = '%stot_angle_usage_%d_%d' % (folder_figures,orbit_id,sl_angle) figures.savefig(fname,fig,fancy)
{ "repo_name": "kuntzer/SALSA-public", "path": "3c_angle_usage.py", "copies": "1", "size": "2662", "license": "bsd-3-clause", "hash": 7039105860325497000, "line_mean": 29.25, "line_max": 189, "alpha_frac": 0.6202103681, "autogenerated": false, "ratio": 2.847058823529412, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.884339026503286, "avg_score": 0.024775785319310274, "num_lines": 88 }
## 3. Class Syntax ## class Car(): def __init__(self): self.color = "black" self.make = "honda" self.model = "accord" black_honda_accord = Car() print(black_honda_accord.color) class Team(): def __init__(self): self.name = "Tampa Bay Buccaneers" bucs = Team() print(bucs.name) ## 4. Instance Methods and __init__ ## class Team(): def __init__(self,name): self.name = name bucs = Team("Tampa Bay Buccaneers") giants = Team("New York Giants") ## 6. More Instance Methods ## import csv f = open("nfl.csv", 'r') nfl = list(csv.reader(f)) # The NFL data is loaded into the nfl variable. class Team(): def __init__(self, name): self.name = name def print_name(self): print(self.name) # Your method goes here def count_total_wins(self): wins = 0 for item in nfl: if item[3]==self.name: wins +=1 return(wins) bucs = Team("Tampa Bay Buccaneers") bucs.print_name() broncos_wins = Team("Kansas City Chiefs").count_total_wins() chiefs_wins = Team("Denver Broncos").count_total_wins() ## 7. Adding to the init Function ## import csv class Team(): def __init__(self, name,filename): self.name = name self.nfl = list(csv.reader(open(filename,'r'))) def count_total_wins(self): count = 0 for row in self.nfl: if row[2] == self.name: count = count + 1 return count jaguars_wins = Team("Jacksonville Jaguars", "nfl.csv").count_total_wins() ## 8. Wins in a Year ## import csv class Team(): def __init__(self, name,year): self.name = name self.nfl = list(csv.reader(open('nfl.csv','r'))) self.year = year def count_total_wins(self): count = 0 for row in self.nfl: if row[2] == self.name: count = count + 1 return count def count_wins_in_year(self): wins = 0 for item in self.nfl: if(item[2]==self.name and item[0] == self.year): wins +=1 return(wins) niners_wins_2013 = Team("San Francisco 49ers","2013").count_wins_in_year()
{ "repo_name": "vipmunot/Data-Analysis-using-Python", "path": "Python Programming Intermediate/Classes-162.py", "copies": "1", "size": "2186", "license": "mit", "hash": 8971483250927273000, "line_mean": 22.5161290323, "line_max": 74, "alpha_frac": 0.5626715462, "autogenerated": false, "ratio": 3.0875706214689265, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4150242167668926, "avg_score": null, "num_lines": null }
# 3. Cleanse CSV format [ ] # 4. Insert into SQL db to be called by the app [ ] import csv import psycopg2 import sys from datetime import datetime def main(): try: conn = psycopg2.connect("dbname=speedcams user=ubuntu host=localhost password=Kypw123!") except: print('Cannot connect to db') cur = conn.cursor() # check if this pdf is new cur.execute("SELECT got_date FROM speedcamraw LIMIT 1;") existing_date = cur.fetchall() print existing_date csvfile = os.path.join(os.path.curdir, 'speedcam.csv') with open (csvfile, 'rb') as csvfile: rows = list(csv.reader(csvfile, delimiter=',')) new_date = (rows[0][0]).split(' ') new_date = new_date[3] +' '+ new_date[2] + ' '+ new_date[1] new_date = datetime.strptime(new_date, '%Y %B %d').date() print new_date if (new_date == existing_date): sys.exit() print 'PDF has already been loaded' else: # copy pdf csv output into a clean instance of speedcamraw table cur.execute("TRUNCATE TABLE speedcamraw;" "ALTER TABLE speedcamraw DROP COLUMN id;" "COPY speedcamraw (street_name, suburb, street_name2, suburb2)" "FROM '/home/ubuntu/workspace/speedcam/speedcam.csv' DELIMITER ',' CSV;" # create an autoincrementing primary key (id) - http://stackoverflow.com/questions/2944499/how-to-add-an-auto-incrementing-primary-key-to-an-existing-table-in-postgresql "ALTER TABLE speedcamraw ADD id SERIAL PRIMARY KEY;") # check if suburb and street_name2 are empty, if so pull the PDF text date cur.execute('''SELECT street_name, id FROM speedcamraw WHERE ((suburb IS NULL) AND (street_name2 IS NULL));''') datesfrompdf = cur.fetchall() for rowdate, rowid in datesfrompdf: # delete all 'street name' header rows (ie. date header rows + 1) cur.execute("DELETE FROM speedcamraw WHERE id = %s;", (rowid + 1,)) # Fill down dates based on date headers for rowdate, rowid in datesfrompdf: cur.execute('''UPDATE speedcamraw SET got_date = %s WHERE ((suburb IS NOT NULL) AND (street_name IS NOT NULL) AND (id > %s));''', (rowdate, rowid)) # Delete date header rows cur.execute('''DELETE FROM speedcamraw WHERE ((suburb IS NULL) AND (street_name2 IS NULL) AND (suburb2 IS NULL) AND (got_date IS NULL));''') # Copy date, streetname2 and suburb2 cur.execute('''INSERT INTO speedcamraw (got_date, suburb, street_name) SELECT got_date, suburb2, street_name2 FROM speedcamraw;''') # Clean up any blank rows cur.execute('''DELETE FROM speedcamraw WHERE ((suburb IS NULL) AND (street_name IS NULL));''') # Copy date, street_name and suburb into speedcamclean cur.execute('''INSERT INTO speedcamclean (date, suburb, street_name) SELECT got_date, street_name, suburb FROM speedcamraw;''') conn.commit() cur.close() conn.close() if __name__ == "__main__": main()
{ "repo_name": "kptyap/speedcam", "path": "cleancsv.py", "copies": "1", "size": "3419", "license": "mit", "hash": 2387267364120208400, "line_mean": 39.7142857143, "line_max": 189, "alpha_frac": 0.569757239, "autogenerated": false, "ratio": 3.994158878504673, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5063916117504673, "avg_score": null, "num_lines": null }
# 3 (continued). tnrs/ot/names # This service seems to be the same as tnrs/ot/resolve, but with POST # instead of GET. # Maybe we should just run the same tests? """ __Parameters:__ * *Name:* scientificNames * *Category:* mandatory * *Data Type:* list of string * *Description:* list of scientific names to be resolved __Citation:__ https://github.com/OpenTreeOfLife/opentree/wiki/Open-Tree-of-Life-APIs#tnrs """ import sys, unittest, json sys.path.append('./') sys.path.append('../') import webapp from test_tnrs_ot_resolve import TnrsTester service = webapp.get_service(5004, 'tnrs/ot/names') class TestTnrsOtNames(TnrsTester): @classmethod def get_service(cls): return service @classmethod def http_method(cls): return 'POST' @classmethod def namelist(cls, x): return x.json()[u'scientificNames'] @classmethod def tnrs_request(cls, names): return service.get_request('POST', {'scientificNames': names}) def test_2(self): """Edge case: names= is supplied, but there are no names. In this case, the deployed web service says that there is no names parameter. (The difference between missing and supplied but null is academic? Depends on taste.)""" request = self.__class__.tnrs_request([]) x = request.exchange() # 204 = no content (from open tree) # message = "Could not resolve any name" # Changed: now returns 400, not 204. Better. # As of 2017-11-01, we get 500, not 400. Issue. self.assert_response_status(x, 400) # Insert here: edge case tests # Insert here: inputs out of range, leading to error or long delay # Insert here: error-generating conditions # (See ../README.md) def test_example_8(self): x = self.start_request_tests(example_8) # Insert: whether result is what it should be according to docs self.assert_success(x) null=None; false=False; true=True example_8 = service.get_request('POST', {u'scientificNames': [u'Formica exsectoides', u'Formica pecefica', u'Formica polyctena']}) if __name__ == '__main__': webapp.main()
{ "repo_name": "jar398/tryphy", "path": "tests/test_tnrs_ot_names.py", "copies": "1", "size": "2184", "license": "bsd-2-clause", "hash": 2005073281707309800, "line_mean": 30.2, "line_max": 130, "alpha_frac": 0.6515567766, "autogenerated": false, "ratio": 3.4502369668246446, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9568609228801681, "avg_score": 0.006636902924592667, "num_lines": 70 }
"""3D backpropagation algorithm""" import ctypes import multiprocessing as mp import numexpr as ne import numpy as np import pyfftw import scipy.ndimage from . import util ncores = mp.cpu_count() mprotate_dict = {} def _cleanup_worker(): if "X" in mprotate_dict: mprotate_dict.pop("X") if "X_shape" in mprotate_dict: mprotate_dict.pop("X_shape") if "X_dtype" in mprotate_dict: mprotate_dict.pop("X_dtype") def _init_worker(X, X_shape, X_dtype): """Initializer for pool for _mprotate""" # Using a dictionary is not strictly necessary. You can also # use global variables. mprotate_dict["X"] = X mprotate_dict["X_shape"] = X_shape mprotate_dict["X_dtype"] = X_dtype def _mprotate(ang, lny, pool, order): """Uses multiprocessing to wrap around _rotate 4x speedup on an intel i7-3820 CPU @ 3.60GHz with 8 cores. The function calls _rotate which accesses the `mprotate_dict`. Data is rotated in-place. Parameters ---------- ang: float rotation angle in degrees lny: int total number of rotations to perform pool: instance of multiprocessing.pool.Pool the pool object used for the computation order: int interpolation order """ targ_args = list() slsize = int(np.floor(lny / ncores)) for t in range(ncores): ymin = t * slsize ymax = (t + 1) * slsize if t == ncores - 1: ymax = lny targ_args.append((ymin, ymax, ang, order)) pool.map(_rotate, targ_args) def _rotate(d): arr = np.frombuffer(mprotate_dict["X"], dtype=mprotate_dict["X_dtype"]).reshape( mprotate_dict["X_shape"]) (ymin, ymax, ang, order) = d return scipy.ndimage.interpolation.rotate( arr[:, ymin:ymax, :], # input angle=-ang, # angle axes=(0, 2), # axes reshape=False, # reshape output=arr[:, ymin:ymax, :], # output order=order, # order mode="constant", # mode cval=0) def backpropagate_3d(uSin, angles, res, nm, lD=0, coords=None, weight_angles=True, onlyreal=False, padding=(True, True), padfac=1.75, padval="edge", intp_order=2, dtype=None, num_cores=ncores, save_memory=False, copy=True, count=None, max_count=None, verbose=0): r"""3D backpropagation Three-dimensional diffraction tomography reconstruction algorithm for scattering of a plane wave :math:`u_0(\mathbf{r}) = u_0(x,y,z)` by a dielectric object with refractive index :math:`n(x,y,z)`. This method implements the 3D backpropagation algorithm :cite:`Mueller2015arxiv`. .. math:: f(\mathbf{r}) = -\frac{i k_\mathrm{m}}{2\pi} \sum_{j=1}^{N} \! \Delta \phi_0 D_{-\phi_j} \!\! \left \{ \text{FFT}^{-1}_{\mathrm{2D}} \left \{ \left| k_\mathrm{Dx} \right| \frac{\text{FFT}_{\mathrm{2D}} \left \{ u_{\mathrm{B},\phi_j}(x_\mathrm{D}, y_\mathrm{D}) \right \}} {u_0(l_\mathrm{D})} \exp \! \left[i k_\mathrm{m}(M - 1) \cdot (z_{\phi_j}-l_\mathrm{D}) \right] \right \} \right \} with the forward :math:`\text{FFT}_{\mathrm{2D}}` and inverse :math:`\text{FFT}^{-1}_{\mathrm{2D}}` 2D fast Fourier transform, the rotational operator :math:`D_{-\phi_j}`, the angular distance between the projections :math:`\Delta \phi_0`, the ramp filter in Fourier space :math:`|k_\mathrm{Dx}|`, and the propagation distance :math:`(z_{\phi_j}-l_\mathrm{D})`. Parameters ---------- uSin: (A, Ny, Nx) ndarray Three-dimensional sinogram of plane recordings :math:`u_{\mathrm{B}, \phi_j}(x_\mathrm{D}, y_\mathrm{D})` divided by the incident plane wave :math:`u_0(l_\mathrm{D})` measured at the detector. angles: (A,) ndarray Angular positions :math:`\phi_j` of `uSin` in radians. res: float Vacuum wavelength of the light :math:`\lambda` in pixels. nm: float Refractive index of the surrounding medium :math:`n_\mathrm{m}`. lD: float Distance from center of rotation to detector plane :math:`l_\mathrm{D}` in pixels. coords: None [(3, M) ndarray] Only compute the output image at these coordinates. This keyword is reserved for future versions and is not implemented yet. weight_angles: bool If `True`, weights each backpropagated projection with a factor proportional to the angular distance between the neighboring projections. .. math:: \Delta \phi_0 \longmapsto \Delta \phi_j = \frac{\phi_{j+1} - \phi_{j-1}}{2} .. versionadded:: 0.1.1 onlyreal: bool If `True`, only the real part of the reconstructed image will be returned. This saves computation time. padding: tuple of bool Pad the input data to the second next power of 2 before Fourier transforming. This reduces artifacts and speeds up the process for input image sizes that are not powers of 2. The default is padding in x and y: `padding=(True, True)`. For padding only in x-direction (e.g. for cylindrical symmetries), set `padding` to `(True, False)`. To turn off padding, set it to `(False, False)`. padfac: float Increase padding size of the input data. A value greater than one will trigger padding to the second-next power of two. For example, a value of 1.75 will lead to a padded size of 256 for an initial size of 144, whereas it will lead to a padded size of 512 for an initial size of 150. Values geater than 2 are allowed. This parameter may greatly increase memory usage! padval: float or "edge" The value used for padding. This is important for the Rytov approximation, where an approximat zero in the phase might translate to 2πi due to the unwrapping algorithm. In that case, this value should be a multiple of 2πi. If `padval` is "edge", then the edge values are used for padding (see documentation of :func:`numpy.pad`). If `padval` is a float, then padding is done with a linear ramp. intp_order: int between 0 and 5 Order of the interpolation for rotation. See :func:`scipy.ndimage.interpolation.rotate` for details. dtype: dtype object or argument for :func:`numpy.dtype` The data type that is used for calculations (float or double). Defaults to `numpy.float_`. num_cores: int The number of cores to use for parallel operations. This value defaults to the number of cores on the system. save_memory: bool Saves memory at the cost of longer computation time. .. versionadded:: 0.1.5 copy: bool Copy input sinogram `uSin` for data processing. If `copy` is set to `False`, then `uSin` will be overridden. .. versionadded:: 0.1.5 count, max_count: multiprocessing.Value or `None` Can be used to monitor the progress of the algorithm. Initially, the value of `max_count.value` is incremented by the total number of steps. At each step, the value of `count.value` is incremented. verbose: int Increment to increase verbosity. Returns ------- f: ndarray of shape (Nx, Ny, Nx), complex if `onlyreal==False` Reconstructed object function :math:`f(\mathbf{r})` as defined by the Helmholtz equation. :math:`f(x,z) = k_m^2 \left(\left(\frac{n(x,z)}{n_m}\right)^2 -1\right)` See Also -------- odt_to_ri: conversion of the object function :math:`f(\mathbf{r})` to refractive index :math:`n(\mathbf{r})` Notes ----- Do not use the parameter `lD` in combination with the Rytov approximation - the propagation is not correctly described. Instead, numerically refocus the sinogram prior to converting it to Rytov data (using e.g. :func:`odtbrain.sinogram_as_rytov`) with a numerical focusing algorithm (available in the Python package :py:mod:`nrefocus`). """ A = angles.size if len(uSin.shape) != 3: raise ValueError("Input data `uSin` must have shape (A,Ny,Nx).") if len(uSin) != A: raise ValueError("`len(angles)` must be equal to `len(uSin)`.") if len(list(padding)) != 2: raise ValueError("`padding` must be boolean tuple of length 2!") if np.array(padding).dtype is not np.dtype(bool): raise ValueError("Parameter `padding` must be boolean tuple.") if coords is not None: raise NotImplementedError("Setting coordinates is not yet supported.") if num_cores > ncores: raise ValueError("`num_cores` must not exceed number " + "of physical cores: {}".format(ncores)) # setup dtype if dtype is None: dtype = np.float_ dtype = np.dtype(dtype) if dtype.name not in ["float32", "float64"]: raise ValueError("dtype must be float32 or float64!") dtype_complex = np.dtype("complex{}".format( 2 * int(dtype.name.strip("float")))) # set ctype ct_dt_map = {np.dtype(np.float32): ctypes.c_float, np.dtype(np.float64): ctypes.c_double } # progress if max_count is not None: max_count.value += A + 2 ne.set_num_threads(num_cores) uSin = np.array(uSin, copy=copy) # lengths of the input data lny, lnx = uSin.shape[1], uSin.shape[2] # The z-size of the output array must match the x-size. # The rotation is performed about the y-axis (lny). ln = lnx # We perform zero-padding before performing the Fourier transform. # This gets rid of artifacts due to false periodicity and also # speeds up Fourier transforms of the input image size is not # a power of 2. if padding[0]: orderx = int(max(64., 2**np.ceil(np.log(lnx * padfac) / np.log(2)))) padx = orderx - lnx else: padx = 0 if padding[1]: ordery = int(max(64., 2**np.ceil(np.log(lny * padfac) / np.log(2)))) pady = ordery - lny else: pady = 0 padyl = int(np.ceil(pady / 2)) padyr = pady - padyl padxl = int(np.ceil(padx / 2)) padxr = padx - padxl # zero-padded length of sinogram. lNx = lnx + padx lNy = lny + pady lNz = ln if verbose > 0: print("......Image size (x,y): {}x{}, padded: {}x{}".format( lnx, lny, lNx, lNy)) # Perform weighting if weight_angles: weights = util.compute_angle_weights_1d(angles).reshape(-1, 1, 1) uSin *= weights # Cut-Off frequency # km [1/px] km = (2 * np.pi * nm) / res # Here, the notation for # a wave propagating to the right is: # # u0(x) = exp(ikx) # # However, in physics usually we use the other sign convention: # # u0(x) = exp(-ikx) # # In order to be consistent with programs like Meep or our # scattering script for a dielectric cylinder, we want to use the # latter sign convention. # This is not a big problem. We only need to multiply the imaginary # part of the scattered wave by -1. # Ask for the filter. Do not include zero (first element). # # Integrals over ϕ₀ [0,2π]; kx [-kₘ,kₘ] # - double coverage factor 1/2 already included # - unitary angular frequency to unitary ordinary frequency # conversion performed in calculation of UB=FT(uB). # # f(r) = -i kₘ / ((2π)² a₀) (prefactor) # * iiint dϕ₀ dkx dky (prefactor) # * |kx| (prefactor) # * exp(-i kₘ M lD ) (prefactor) # * UBϕ₀(kx) (dependent on ϕ₀) # * exp( i (kx t⊥ + kₘ (M - 1) s₀) r ) (dependent on ϕ₀ and r) # (r and s₀ are vectors. The last term contains a dot-product) # # kₘM = sqrt( kₘ² - kx² - ky² ) # t⊥ = ( cos(ϕ₀), ky/kx, sin(ϕ₀) ) # s₀ = ( -sin(ϕ₀), 0 , cos(ϕ₀) ) # # The filter can be split into two parts # # 1) part without dependence on the z-coordinate # # -i kₘ / ((2π)² a₀) # * iiint dϕ₀ dkx dky # * |kx| # * exp(-i kₘ M lD ) # # 2) part with dependence of the z-coordinate # # exp( i (kx t⊥ + kₘ (M - 1) s₀) r ) # # The filter (1) can be performed using the classical filter process # as in the backprojection algorithm. # # # Corresponding sample frequencies fx = np.fft.fftfreq(lNx) # 1D array fy = np.fft.fftfreq(lNy) # 1D array # kx is a 1D array. kx = 2 * np.pi * fx ky = 2 * np.pi * fy # Differentials for integral dphi0 = 2 * np.pi / A # We will later multiply with phi0. # y, x kx = kx.reshape(1, -1) ky = ky.reshape(-1, 1) # Low-pass filter: # less-than-or-equal would give us zero division error. filter_klp = (kx**2 + ky**2 < km**2) # Filter M so there are no nans from the root M = 1. / km * np.sqrt((km**2 - kx**2 - ky**2) * filter_klp) prefactor = -1j * km / (2 * np.pi) prefactor *= dphi0 # Also filter the prefactor, so nothing outside the required # low-pass contributes to the sum. prefactor *= np.abs(kx) * filter_klp # prefactor *= np.sqrt(((kx**2+ky**2)) * filter_klp ) # new in version 0.1.4: # We multiply by the factor (M-1) instead of just (M) # to take into account that we have a scattered # wave that is normalized by u0. prefactor *= np.exp(-1j * km * (M-1) * lD) if count is not None: count.value += 1 # filter (2) must be applied before rotation as well # exp( i (kx t⊥ + kₘ (M - 1) s₀) r ) # # kₘM = sqrt( kₘ² - kx² - ky² ) # t⊥ = ( cos(ϕ₀), ky/kx, sin(ϕ₀) ) # s₀ = ( -sin(ϕ₀), 0 , cos(ϕ₀) ) # # This filter is effectively an inverse Fourier transform # # exp(i kx xD) exp(i ky yD) exp(i kₘ (M - 1) zD ) # # xD = x cos(ϕ₀) + z sin(ϕ₀) # zD = - x sin(ϕ₀) + z cos(ϕ₀) # Everything is in pixels center = lNz / 2.0 z = np.linspace(-center, center, lNz, endpoint=False) zv = z.reshape(-1, 1, 1) # z, y, x Mp = M.reshape(lNy, lNx) # filter2 = np.exp(1j * zv * km * (Mp - 1)) f2_exp_fac = 1j * km * (Mp - 1) if save_memory: # compute filter2 later pass else: # compute filter2 now filter2 = ne.evaluate("exp(factor * zv)", local_dict={"factor": f2_exp_fac, "zv": zv}, casting="same_kind") # occupies some amount of ram, but yields faster # computation later if count is not None: count.value += 1 # Prepare complex output image if onlyreal: outarr = np.zeros((ln, lny, lnx), dtype=dtype) else: outarr = np.zeros((ln, lny, lnx), dtype=dtype_complex) # Create plan for FFTW # save memory by in-place operations # projection = np.fft.fft2(sino, axes=(-1,-2)) * prefactor # FFTW-flag is "estimate": # specifies that, instead of actual measurements of different # algorithms, a simple heuristic is used to pick a (probably # sub-optimal) plan quickly. With this flag, the input/output # arrays are not overwritten during planning. # Byte-aligned arrays oneslice = pyfftw.empty_aligned((lNy, lNx), dtype_complex) myfftw_plan = pyfftw.FFTW(oneslice, oneslice, threads=num_cores, flags=["FFTW_ESTIMATE"], axes=(0, 1)) # Create plan for IFFTW: inarr = pyfftw.empty_aligned((lNy, lNx), dtype_complex) # inarr[:] = (projection[0]*filter2)[0,:,:] # plan is "patient": # FFTW_PATIENT is like FFTW_MEASURE, but considers a wider range # of algorithms and often produces a “more optimal” plan # (especially for large transforms), but at the expense of # several times longer planning time (especially for large # transforms). # print(inarr.flags) myifftw_plan = pyfftw.FFTW(inarr, inarr, threads=num_cores, axes=(0, 1), direction="FFTW_BACKWARD", flags=["FFTW_MEASURE"]) # Setup a shared array shared_array = mp.RawArray(ct_dt_map[dtype], ln * lny * lnx) arr = np.frombuffer(shared_array, dtype=dtype).reshape(ln, lny, lnx) # Initialize the pool with the shared array pool4loop = mp.Pool(processes=num_cores, initializer=_init_worker, initargs=(shared_array, (ln, lny, lnx), dtype)) # filtered projections in loop filtered_proj = np.zeros((ln, lny, lnx), dtype=dtype_complex) for aa in np.arange(A): if not (padding[0] and padding[1]): # no padding oneslice[:] = uSin[aa] elif padval == "edge": # padding with edge values oneslice[:] = np.pad(uSin[aa], ((padyl, padyr), (padxl, padxr)), mode="edge") else: # padding with linear ramp oneslice[:] = np.pad(uSin[aa], ((padyl, padyr), (padxl, padxr)), mode="linear_ramp", end_values=(padval,)) myfftw_plan.execute() # normalize to (lNx * lNy) for FFTW and multiply with prefactor oneslice *= prefactor / (lNx * lNy) # 14x Speedup with fftw3 compared to numpy fft and # memory reduction by a factor of 2! # ifft will be computed in-place for p in range(len(zv)): if save_memory: # compute filter2 here; # this is comparatively slower than the other case ne.evaluate("exp(factor * zvp) * projectioni", local_dict={"zvp": zv[p], "projectioni": oneslice, "factor": f2_exp_fac}, casting="same_kind", out=inarr) else: # use universal functions np.multiply(filter2[p], oneslice, out=inarr) myifftw_plan.execute() filtered_proj[p, :, :] = inarr[padyl:lny+padyl, padxl:lnx+padxl] # resize image to original size # The copy is necessary to prevent memory leakage. arr[:] = filtered_proj.real phi0 = np.rad2deg(angles[aa]) if not onlyreal: filtered_proj_imag = filtered_proj.imag _mprotate(phi0, lny, pool4loop, intp_order) outarr.real += arr if not onlyreal: arr[:] = filtered_proj_imag _mprotate(phi0, lny, pool4loop, intp_order) outarr.imag += arr if count is not None: count.value += 1 pool4loop.terminate() pool4loop.join() _cleanup_worker() return outarr
{ "repo_name": "paulmueller/ODTbrain", "path": "odtbrain/_alg3d_bpp.py", "copies": "2", "size": "19612", "license": "bsd-3-clause", "hash": -2736602947750555600, "line_mean": 34.0485611511, "line_max": 78, "alpha_frac": 0.5676604916, "autogenerated": false, "ratio": 3.439286974938228, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5006947466538227, "avg_score": null, "num_lines": null }
"""3D backpropagation algorithm with a tilted axis of rotation""" import multiprocessing as mp import warnings import numexpr as ne import numpy as np import pyfftw import scipy.ndimage from . import util _ncores = mp.cpu_count() def estimate_major_rotation_axis(loc): """ For a list of points on the unit sphere, estimate the main rotational axis and return a list of angles that correspond to the rotational position for each point. """ # TODO: raise NotImplementedError("estimation of rotational axis not implemented.") def norm_vec(vector): """Normalize the length of a vector to one""" assert len(vector) == 3 v = np.array(vector) return v/np.sqrt(np.sum(v**2)) def rotate_points_to_axis(points, axis): """Rotate all points of a list, such that `axis==[0,1,0]` This is accomplished by rotating in the x-z-plane by phi into the y-z-plane, then rotation in the y-z-plane by theta up to [0,1,0], and finally rotating back in the x-z-plane by -phi. Parameters ---------- points: list-like with elements of length 3 The Cartesian points. These should be in the same format as produced by `sphere_points_from_angles_and_tilt`. axis: list-like, length 3 The reference axis that will be used to determine the rotation angle of the points. The points will be rotated about the origin such that `axis` matches [0,1,0]. Returns ------- rotated_points: np.ndarray of shape (N,3) The rotated points. """ axis = norm_vec(axis) u, v, w = axis points = np.array(points) # Determine the rotational angle in the x-z plane phi = np.arctan2(u, w) # Determine the tilt angle w.r.t. the y-axis theta = np.arccos(v) # Negative rotation about y-axis Rphi = np.array([ [np.cos(phi), 0, -np.sin(phi)], [0, 1, 0], [np.sin(phi), 0, np.cos(phi)], ]) # Negative rotation about x-axis Rtheta = np.array([ [1, 0, 0], [0, np.cos(theta), np.sin(theta)], [0, -np.sin(theta), np.cos(theta)], ]) DR1 = np.dot(Rtheta, Rphi) # Rotate back by -phi such that effective rotation was only # towards [0,1,0]. DR = np.dot(Rphi.T, DR1) rotpoints = np.zeros((len(points), 3)) for ii, pnt in enumerate(points): rotpoints[ii] = np.dot(DR, pnt) # For visualiztaion: # import matplotlib.pylab as plt # from mpl_toolkits.mplot3d import Axes3D # from matplotlib.patches import FancyArrowPatch # from mpl_toolkits.mplot3d import proj3d # # class Arrow3D(FancyArrowPatch): # def __init__(self, xs, ys, zs, *args, **kwargs): # FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs) # self._verts3d = xs, ys, zs # # def draw(self, renderer): # xs3d, ys3d, zs3d = self._verts3d # xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) # self.set_positions((xs[0],ys[0]),(xs[1],ys[1])) # FancyArrowPatch.draw(self, renderer) # # fig = plt.figure(figsize=(10,10)) # ax = fig.add_subplot(111, projection='3d') # for vec in rotpoints: # u,v,w = vec # a = Arrow3D([0,u],[0,v],[0,w], # mutation_scale=20, lw=1, arrowstyle="-|>") # ax.add_artist(a) # # radius=1 # ax.set_xlabel('X') # ax.set_ylabel('Y') # ax.set_zlabel('Z') # ax.set_xlim(-radius*1.5, radius*1.5) # ax.set_ylim(-radius*1.5, radius*1.5) # ax.set_zlim(-radius*1.5, radius*1.5) # plt.tight_layout() # plt.show() return rotpoints def rotation_matrix_from_point(point, ret_inv=False): """Compute rotation matrix to go from [0,0,1] to `point`. First, the matrix rotates to in the polar direction. Then, a rotation about the y-axis is performed to match the azimuthal angle in the x-z-plane. This rotation matrix is required for the correct 3D orientation of the backpropagated projections. Parameters ---------- points: list-like, length 3 The coordinates of the point in 3D. ret_inv: bool Also return the inverse of the rotation matrix. The inverse is required for :func:`scipy.ndimage.interpolation.affine_transform` which maps the output coordinates to the input coordinates. Returns ------- Rmat [, Rmat_inv]: 3x3 ndarrays The rotation matrix that rotates [0,0,1] to `point` and optionally its inverse. """ x, y, z = point # azimuthal angle phi = np.arctan2(x, z) # angle in polar direction (negative) theta = -np.arctan2(y, np.sqrt(x**2+z**2)) # Rotation in polar direction Rtheta = np.array([ [1, 0, 0], [0, np.cos(theta), -np.sin(theta)], [0, np.sin(theta), np.cos(theta)], ]) # rotation in x-z-plane Rphi = np.array([ [np.cos(phi), 0, -np.sin(phi)], [0, 1, 0], [np.sin(phi), 0, np.cos(phi)], ]) D = np.dot(Rphi, Rtheta) # The inverse of D Dinv = np.dot(Rtheta.T, Rphi.T) if ret_inv: return D, Dinv else: return D def rotation_matrix_from_point_planerot(point, plane_angle, ret_inv=False): """ Compute rotation matrix to go from [0,0,1] to `point`, while taking into account the tilted axis of rotation. First, the matrix rotates to in the polar direction. Then, a rotation about the y-axis is performed to match the azimuthal angle in the x-z-plane. This rotation matrix is required for the correct 3D orientation of the backpropagated projections. Parameters ---------- points: list-like, length 3 The coordinates of the point in 3D. axis: list-like, length 3 The coordinates of the point in 3D. ret_inv: bool Also return the inverse of the rotation matrix. The inverse is required for :func:`scipy.ndimage.interpolation.affine_transform` which maps the output coordinates to the input coordinates. Returns ------- Rmat [, Rmat_inv]: 3x3 ndarrays The rotation matrix that rotates [0,0,1] to `point` and optionally its inverse. """ # These matrices are correct if there is no tilt of the # rotational axis within the detector plane (x-y). D, Dinv = rotation_matrix_from_point(point, ret_inv=True) # We need an additional rotation about the z-axis to correct # for the tilt for all the the other cases. angz = plane_angle Rz = np.array([ [np.cos(angz), -np.sin(angz), 0], [np.sin(angz), np.cos(angz), 0], [0, 0, 1], ]) DR = np.dot(D, Rz) DRinv = np.dot(Rz.T, Dinv) if ret_inv: return DR, DRinv else: return DR def sphere_points_from_angles_and_tilt(angles, tilted_axis): """ For a given tilt of the rotational axis `tilted_axis`, compute the points on a unit sphere that correspond to the distribution `angles` along the great circle about this axis. Parameters ---------- angles: 1d ndarray The angles that will be distributed on the great circle. tilted_axis: list of length 3 The tilted axis of rotation that determines the great circle. Notes ----- The reference axis is always [0,1,0]. `theta` is the azimuthal angle measured down from the y-axis. `phi` is the polar angle in the x-z plane measured from z towards x. """ assert len(angles.shape) == 1 # Normalize tilted axis. tilted_axis = norm_vec(tilted_axis) [u, v, w] = tilted_axis # Initial distribution of points about great circle (x-z). newang = np.zeros((angles.shape[0], 3), dtype=float) # We subtract angles[0], because in step (a) we want that # newang[0]==[0,0,1]. This only works if we actually start # at that point. newang[:, 0] = np.sin(angles-angles[0]) newang[:, 2] = np.cos(angles-angles[0]) # Compute rotational angles w.r.t. [0,1,0]. # - Draw a unit sphere with the y-axis pointing up and the # z-axis pointing right # - The rotation of `tilted_axis` can be described by two # separate rotations. We will use these two angles: # (a) Rotation from y=1 within the y-z plane: theta # This is the rotation that is critical for data # reconstruction. If this angle is zero, then we # have a rotational axis in the imaging plane. If # this angle is PI/2, then our sinogram consists # of a rotating image and 3D reconstruction is # impossible. This angle is counted from the y-axis # onto the x-z plane. # (b) Rotation in the x-z plane: phi # This angle is responsible for matching up the angles # with the correct sinogram images. If this angle is zero, # then the projection of the rotational axis onto the # x-y plane is aligned with the y-axis. If this angle is # PI/2, then the axis and its projection onto the x-y # plane are identical. This angle is counted from the # positive z-axis towards the positive x-axis. By default, # angles[0] is the point that touches the great circle # that lies in the x-z plane. angles[1] is the next point # towards the x-axis if phi==0. # (a) This angle is the azimuthal angle theta measured from the # y-axis. theta = np.arccos(v) # (b) This is the polar angle measured in the x-z plane starting # at the x-axis and measured towards the positive z-axis. if np.allclose(u, 0) and np.allclose(w, 0): # Avoid flipping the axis of rotation due to numerical # errors during its computation. phi = 0 else: phi = np.arctan2(u, w) # Determine the projection points on the unit sphere. # The resulting circle meets the x-z-plane at phi, and # is tilted by theta w.r.t. the y-axis. # (a) Create a tilted data set. This is achieved in 3 steps. # a1) Determine radius of tilted circle and get the centered # circle with a smaller radius. rtilt = np.cos(theta) newang *= rtilt # a2) Rotate this circle about the x-axis by theta # (right-handed/counter-clockwise/basic/elemental rotation) Rx = np.array([ [1, 0, 0], [0, np.cos(theta), -np.sin(theta)], [0, np.sin(theta), np.cos(theta)] ]) for ii in range(newang.shape[0]): newang[ii] = np.dot(Rx, newang[ii]) # a3) Shift newang such that newang[0] is located at (0,0,1) newang = newang - (newang[0] - np.array([0, 0, 1])).reshape(1, 3) # (b) Rotate the entire thing with phi about the y-axis # (right-handed/counter-clockwise/basic/elemental rotation) Ry = np.array([ [+np.cos(phi), 0, np.sin(phi)], [0, 1, 0], [-np.sin(phi), 0, np.cos(phi)] ]) for jj in range(newang.shape[0]): newang[jj] = np.dot(Ry, newang[jj]) # For visualiztaion: # import matplotlib.pylab as plt # from mpl_toolkits.mplot3d import Axes3D # from matplotlib.patches import FancyArrowPatch # from mpl_toolkits.mplot3d import proj3d # # class Arrow3D(FancyArrowPatch): # def __init__(self, xs, ys, zs, *args, **kwargs): # FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs) # self._verts3d = xs, ys, zs # # def draw(self, renderer): # xs3d, ys3d, zs3d = self._verts3d # xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) # self.set_positions((xs[0],ys[0]),(xs[1],ys[1])) # FancyArrowPatch.draw(self, renderer) # # fig = plt.figure(figsize=(10,10)) # ax = fig.add_subplot(111, projection='3d') # for vec in newang: # u,v,w = vec # a = Arrow3D([0,u],[0,v],[0,w], # mutation_scale=20, lw=1, arrowstyle="-|>") # ax.add_artist(a) # # radius=1 # ax.set_xlabel('X') # ax.set_ylabel('Y') # ax.set_zlabel('Z') # ax.set_xlim(-radius*1.5, radius*1.5) # ax.set_ylim(-radius*1.5, radius*1.5) # ax.set_zlim(-radius*1.5, radius*1.5) # plt.tight_layout() # plt.show() return newang def backpropagate_3d_tilted(uSin, angles, res, nm, lD=0, tilted_axis=[0, 1, 0], coords=None, weight_angles=True, onlyreal=False, padding=(True, True), padfac=1.75, padval="edge", intp_order=2, dtype=None, num_cores=_ncores, save_memory=False, copy=True, count=None, max_count=None, verbose=0): r"""3D backpropagation with a tilted axis of rotation Three-dimensional diffraction tomography reconstruction algorithm for scattering of a plane wave :math:`u_0(\mathbf{r}) = u_0(x,y,z)` by a dielectric object with refractive index :math:`n(x,y,z)`. This method implements the 3D backpropagation algorithm with a rotational axis that is tilted by :math:`\theta_\mathrm{tilt}` w.r.t. the imaging plane :cite:`Mueller2015tilted`. .. math:: f(\mathbf{r}) = -\frac{i k_\mathrm{m}}{2\pi} \sum_{j=1}^{N} \! \Delta \phi_0 D_{-\phi_j}^\mathrm{tilt} \!\! \left \{ \text{FFT}^{-1}_{\mathrm{2D}} \left \{ \left| k_\mathrm{Dx} \cdot \cos \theta_\mathrm{tilt}\right| \frac{\text{FFT}_{\mathrm{2D}} \left \{ u_{\mathrm{B},\phi_j}(x_\mathrm{D}, y_\mathrm{D}) \right \}} {u_0(l_\mathrm{D})} \exp \! \left[i k_\mathrm{m}(M - 1) \cdot (z_{\phi_j}-l_\mathrm{D}) \right] \right \} \right \} with a modified rotational operator :math:`D_{-\phi_j}^\mathrm{tilt}` and a different filter in Fourier space :math:`|k_\mathrm{Dx} \cdot \cos \theta_\mathrm{tilt}|` when compared to :func:`backpropagate_3d`. .. versionadded:: 0.1.2 Parameters ---------- uSin: (A, Ny, Nx) ndarray Three-dimensional sinogram of plane recordings :math:`u_{\mathrm{B}, \phi_j}(x_\mathrm{D}, y_\mathrm{D})` divided by the incident plane wave :math:`u_0(l_\mathrm{D})` measured at the detector. angles: ndarray of shape (A,3) or 1D array of length A If the shape is (A,3), then `angles` consists of vectors on the unit sphere that correspond to the direction of illumination and acquisition (s₀). If the shape is (A,), then `angles` is a one-dimensional array of angles in radians that determines the angular position :math:`\phi_j`. In both cases, `tilted_axis` must be set according to the tilt of the rotational axis. res: float Vacuum wavelength of the light :math:`\lambda` in pixels. nm: float Refractive index of the surrounding medium :math:`n_\mathrm{m}`. lD: float Distance from center of rotation to detector plane :math:`l_\mathrm{D}` in pixels. tilted_axis: list of floats The coordinates [x, y, z] on a unit sphere representing the tilted axis of rotation. The default is (0,1,0), which corresponds to a rotation about the y-axis and follows the behavior of :func:`odtbrain.backpropagate_3d`. coords: None [(3, M) ndarray] Only compute the output image at these coordinates. This keyword is reserved for future versions and is not implemented yet. weight_angles: bool If `True`, weights each backpropagated projection with a factor proportional to the angular distance between the neighboring projections. .. math:: \Delta \phi_0 \longmapsto \Delta \phi_j = \frac{\phi_{j+1} - \phi_{j-1}}{2} This currently only works when `angles` has the shape (A,). onlyreal: bool If `True`, only the real part of the reconstructed image will be returned. This saves computation time. padding: tuple of bool Pad the input data to the second next power of 2 before Fourier transforming. This reduces artifacts and speeds up the process for input image sizes that are not powers of 2. The default is padding in x and y: `padding=(True, True)`. For padding only in x-direction (e.g. for cylindrical symmetries), set `padding` to `(True, False)`. To turn off padding, set it to `(False, False)`. padfac: float Increase padding size of the input data. A value greater than one will trigger padding to the second-next power of two. For example, a value of 1.75 will lead to a padded size of 256 for an initial size of 144, whereas it will lead to a padded size of 512 for an initial size of 150. Values greater than 2 are allowed. This parameter may greatly increase memory usage! padval: float or "edge" The value used for padding. This is important for the Rytov approximation, where an approximate zero in the phase might translate to 2πi due to the unwrapping algorithm. In that case, this value should be a multiple of 2πi. If `padval` is "edge", then the edge values are used for padding (see documentation of :func:`numpy.pad`). If `padval` is a float, then padding is done with a linear ramp. intp_order: int between 0 and 5 Order of the interpolation for rotation. See :func:`scipy.ndimage.interpolation.affine_transform` for details. dtype: dtype object or argument for :func:`numpy.dtype` The data type that is used for calculations (float or double). Defaults to `numpy.float_`. num_cores: int The number of cores to use for parallel operations. This value defaults to the number of cores on the system. save_memory: bool Saves memory at the cost of longer computation time. .. versionadded:: 0.1.5 copy: bool Copy input sinogram `uSin` for data processing. If `copy` is set to `False`, then `uSin` will be overridden. .. versionadded:: 0.1.5 count, max_count: multiprocessing.Value or `None` Can be used to monitor the progress of the algorithm. Initially, the value of `max_count.value` is incremented by the total number of steps. At each step, the value of `count.value` is incremented. verbose: int Increment to increase verbosity. Returns ------- f: ndarray of shape (Nx, Ny, Nx), complex if `onlyreal==False` Reconstructed object function :math:`f(\mathbf{r})` as defined by the Helmholtz equation. :math:`f(x,z) = k_m^2 \left(\left(\frac{n(x,z)}{n_m}\right)^2 -1\right)` See Also -------- odt_to_ri: conversion of the object function :math:`f(\mathbf{r})` to refractive index :math:`n(\mathbf{r})` Notes ----- This implementation can deal with projection angles that are not distributed along a circle about the rotational axis. If there are slight deviations from this circle, simply pass the 3D rotational positions instead of the 1D angles to the `angles` argument. In principle, this should improve the reconstruction. The general problem here is that the backpropagation algorithm requires a ramp filter in Fourier space that is oriented perpendicular to the rotational axis. If the sample does not rotate about a single axis, then a 1D parametric representation of this rotation must be found to correctly determine the filter in Fourier space. Such a parametric representation could e.g. be a spiral between the poles of the unit sphere (but this kind of rotation is probably difficult to implement experimentally). If you have input images with rectangular shape, e.g. Nx!=Ny and the rotational axis deviates by approximately PI/2 from the axis (0,1,0), then data might get cropped in the reconstruction volume. You can avoid that by rotating your input data and the rotational axis by PI/2. For instance, change`tilted_axis` from [1,0,0] to [0,1,0] and `np.rot90` the sinogram images. Do not use the parameter `lD` in combination with the Rytov approximation - the propagation is not correctly described. Instead, numerically refocus the sinogram prior to converting it to Rytov data (using e.g. :func:`odtbrain.sinogram_as_rytov`) with a numerical focusing algorithm (available in the Python package :py:mod:`nrefocus`). """ A = angles.shape[0] if angles.shape not in [(A,), (A, 1), (A, 3)]: raise ValueError("`angles` must have shape (A,) or (A,3)!") if len(uSin.shape) != 3: raise ValueError("Input data `uSin` must have shape (A,Ny,Nx).") if len(uSin) != A: raise ValueError("`len(angles)` must be equal to `len(uSin)`.") if len(list(padding)) != 2: raise ValueError("`padding` must be boolean tuple of length 2!") if np.array(padding).dtype is not np.dtype(bool): raise ValueError("Parameter `padding` must be boolean tuple.") if coords is not None: raise NotImplementedError("Setting coordinates is not yet supported.") if num_cores > _ncores: raise ValueError("`num_cores` must not exceed number " + "of physical cores: {}".format(_ncores)) # setup dtype if dtype is None: dtype = np.float_ dtype = np.dtype(dtype) if dtype.name not in ["float32", "float64"]: raise ValueError("dtype must be float32 or float64!") dtype_complex = np.dtype("complex{}".format( 2 * int(dtype.name.strip("float")))) # progess monitoring if max_count is not None: max_count.value += A + 2 ne.set_num_threads(num_cores) uSin = np.array(uSin, copy=copy) angles = np.array(angles, copy=copy) angles = np.squeeze(angles) # support shape (A,1) # lengths of the input data lny, lnx = uSin.shape[1], uSin.shape[2] ln = lnx # We perform zero-padding before performing the Fourier transform. # This gets rid of artifacts due to false periodicity and also # speeds up Fourier transforms of the input image size is not # a power of 2. if padding[0]: orderx = int(max(64., 2**np.ceil(np.log(lnx * padfac) / np.log(2)))) padx = orderx - lnx else: padx = 0 if padding[1]: ordery = int(max(64., 2**np.ceil(np.log(lny * padfac) / np.log(2)))) pady = ordery - lny else: pady = 0 padyl = int(np.ceil(pady / 2)) padyr = pady - padyl padxl = int(np.ceil(padx / 2)) padxr = padx - padxl # zero-padded length of sinogram. lNx = lnx + padx lNy = lny + pady lNz = ln if verbose > 0: print("......Image size (x,y): {}x{}, padded: {}x{}".format( lnx, lny, lNx, lNy)) # `tilted_axis` is required for several things: # 1. the filter |kDx*v + kDy*u| with (u,v,w)==tilted_axis # 2. the alignment of the rotational axis with the y-axis # 3. the determination of the point coordinates if only # angles in radians are given. # For (1) we need the exact axis that corresponds to our input data. # For (2) and (3) we need `tilted_axis_yz` (see below) which is the # axis `tilted_axis` rotated in the detector plane such that its # projection onto the detector coincides with the y-axis. # Normalize input axis tilted_axis = norm_vec(tilted_axis) # `tilted_axis_yz` is computed by performing the inverse rotation in # the x-y plane with `angz`. We will again use `angz` in the transform # within the for-loop to rotate each projection according to its # acquisition angle. angz = np.arctan2(tilted_axis[0], tilted_axis[1]) rotmat = np.array([ [np.cos(angz), -np.sin(angz), 0], [np.sin(angz), np.cos(angz), 0], [0, 0, 1], ]) # rotate `tilted_axis` onto the y-z plane. tilted_axis_yz = norm_vec(np.dot(rotmat, tilted_axis)) if len(angles.shape) == 1: if weight_angles: weights = util.compute_angle_weights_1d(angles).reshape(-1, 1, 1) # compute the 3D points from tilted axis angles = sphere_points_from_angles_and_tilt(angles, tilted_axis_yz) else: if weight_angles: warnings.warn("3D angular weighting not yet supported!") weights = 1 # normalize and rotate angles for ii in range(angles.shape[0]): # angles[ii] = norm_vec(angles[ii]) #-> not correct # instead rotate like `tilted_axis` onto the y-z plane. angles[ii] = norm_vec(np.dot(rotmat, angles[ii])) if weight_angles: uSin *= weights # Cut-Off frequency # km [1/px] km = (2 * np.pi * nm) / res # The notation in the our optical tomography script for # a wave propagating to the right is: # # u0(x) = exp(ikx) # # However, in physics usually we use the other sign convention: # # u0(x) = exp(-ikx) # # In order to be consistent with programs like Meep or our # scattering script for a dielectric cylinder, we want to use the # latter sign convention. # This is not a big problem. We only need to multiply the imaginary # part of the scattered wave by -1. # Ask for the filter. Do not include zero (first element). # # Integrals over ϕ₀ [0,2π]; kx [-kₘ,kₘ] # - double coverage factor 1/2 already included # - unitary angular frequency to unitary ordinary frequency # conversion performed in calculation of UB=FT(uB). # # f(r) = -i kₘ / ((2π)² a₀) (prefactor) # * iiint dϕ₀ dkx dky (prefactor) # * |kx| (prefactor) # * exp(-i kₘ M lD ) (prefactor) # * UBϕ₀(kx) (dependent on ϕ₀) # * exp( i (kx t⊥ + kₘ (M - 1) s₀) r ) (dependent on ϕ₀ and r) # (r and s₀ are vectors. The last term contains a dot-product) # # kₘM = sqrt( kₘ² - kx² - ky² ) # t⊥ = ( cos(ϕ₀), ky/kx, sin(ϕ₀) ) # s₀ = ( -sin(ϕ₀), 0 , cos(ϕ₀) ) # # The filter can be split into two parts # # 1) part without dependence on the z-coordinate # # -i kₘ / ((2π)² a₀) # * iiint dϕ₀ dkx dky # * |kx| # * exp(-i kₘ M lD ) # # 2) part with dependence of the z-coordinate # # exp( i (kx t⊥ + kₘ (M - 1) s₀) r ) # # The filter (1) can be performed using the classical filter process # as in the backprojection algorithm. # # # if lNx != lNy: # raise NotImplementedError("Input data must be square shaped!") # Corresponding sample frequencies fx = np.fft.fftfreq(lNx) # 1D array fy = np.fft.fftfreq(lNy) # 1D array # kx is a 1D array. kx = 2 * np.pi * fx ky = 2 * np.pi * fy # Differentials for integral dphi0 = 2 * np.pi / A # We will later multiply with phi0. # a, y, x kx = kx.reshape(1, -1) ky = ky.reshape(-1, 1) # Low-pass filter: # less-than-or-equal would give us zero division error. filter_klp = (kx**2 + ky**2 < km**2) # Filter M so there are no nans from the root M = 1. / km * np.sqrt((km**2 - kx**2 - ky**2) * filter_klp) prefactor = -1j * km / (2 * np.pi) prefactor *= dphi0 # Also filter the prefactor, so nothing outside the required # low-pass contributes to the sum. # The filter is now dependent on the rotational position of the # specimen. We have to include information from the angles. # We want to estimate the rotational axis for every frame. We # do that by computing the cross-product of the vectors in # angles from the current and previous image. u, v, _w = tilted_axis filterabs = np.abs(kx*v+ky*u) * filter_klp # new in version 0.1.4: # We multiply by the factor (M-1) instead of just (M) # to take into account that we have a scattered # wave that is normalized by u0. prefactor *= np.exp(-1j * km * (M-1) * lD) if count is not None: count.value += 1 # # # filter (2) must be applied before rotation as well # exp( i (kx t⊥ + kₘ (M - 1) s₀) r ) # # kₘM = sqrt( kₘ² - kx² - ky² ) # t⊥ = ( cos(ϕ₀), ky/kx, sin(ϕ₀) ) # s₀ = ( -sin(ϕ₀), 0 , cos(ϕ₀) ) # # This filter is effectively an inverse Fourier transform # # exp(i kx xD) exp(i ky yD) exp(i kₘ (M - 1) zD ) # # xD = x cos(ϕ₀) + z sin(ϕ₀) # zD = - x sin(ϕ₀) + z cos(ϕ₀) # Everything is in pixels center = lNz / 2.0 # x = np.linspace(-centerx, centerx, lNx, endpoint=False) # x = np.arange(lNx) - center + .5 # Meshgrid for output array # zv, yv, xv = np.meshgrid(x,x,x) # z, y, x # xv = x.reshape( 1, 1,-1) # yv = x.reshape( 1,-1, 1) # z = np.arange(ln) - center + .5 z = np.linspace(-center, center, lNz, endpoint=False) zv = z.reshape(-1, 1, 1) # y, x Mp = M.reshape(lNy, lNx) # filter2 = np.exp(1j * zv * km * (Mp - 1)) f2_exp_fac = 1j * km * (Mp - 1) if save_memory: # compute filter2 later pass else: # compute filter2 now # (this requires more RAM but is faster) filter2 = ne.evaluate("exp(factor * zv)", local_dict={"factor": f2_exp_fac, "zv": zv}, casting="same_kind") if count is not None: count.value += 1 # Prepare complex output image if onlyreal: outarr = np.zeros((ln, lny, lnx), dtype=dtype) else: outarr = np.zeros((ln, lny, lnx), dtype=dtype_complex) # Create plan for FFTW: # Flag is "estimate": # specifies that, instead of actual measurements of different # algorithms, a simple heuristic is used to pick a (probably # sub-optimal) plan quickly. With this flag, the input/output # arrays are not overwritten during planning. # Byte-aligned arrays oneslice = pyfftw.empty_aligned((lNy, lNx), dtype_complex) myfftw_plan = pyfftw.FFTW(oneslice, oneslice, threads=num_cores, flags=["FFTW_ESTIMATE"], axes=(0, 1)) # Create plan for IFFTW: inarr = pyfftw.empty_aligned((lNy, lNx), dtype_complex) # plan is "patient": # FFTW_PATIENT is like FFTW_MEASURE, but considers a wider range # of algorithms and often produces a “more optimal” plan # (especially for large transforms), but at the expense of # several times longer planning time (especially for large # transforms). # print(inarr.flags) myifftw_plan = pyfftw.FFTW(inarr, inarr, threads=num_cores, axes=(0, 1), direction="FFTW_BACKWARD", flags=["FFTW_MEASURE"]) # filtered projections in loop filtered_proj = np.zeros((ln, lny, lnx), dtype=dtype_complex) # Rotate all points such that we are effectively rotating everything # about the y-axis. angles = rotate_points_to_axis(points=angles, axis=tilted_axis_yz) for aa in np.arange(A): if not (padding[0] and padding[1]): # no padding oneslice[:] = uSin[aa] elif padval == "edge": # padding with edge values oneslice[:] = np.pad(uSin[aa], ((padyl, padyr), (padxl, padxr)), mode="edge") else: # padding with linear ramp oneslice[:] = np.pad(uSin[aa], ((padyl, padyr), (padxl, padxr)), mode="linear_ramp", end_values=(padval,)) myfftw_plan.execute() # normalize to (lNx * lNy) for FFTW and multiply with prefactor, filter oneslice *= filterabs * prefactor / (lNx * lNy) for p in range(len(zv)): if save_memory: # compute filter2 here; # this is comparatively slower than the other case ne.evaluate("exp(factor * zvp) * projectioni", local_dict={"zvp": zv[p], "projectioni": oneslice, "factor": f2_exp_fac}, casting="same_kind", out=inarr) else: # use universal functions np.multiply(filter2[p], oneslice, out=inarr) myifftw_plan.execute() filtered_proj[p, :, :] = inarr[padyl:padyl+lny, padxl:padxl+lnx] # The Cartesian axes in our array are ordered like this: [z,y,x] # However, the rotation matrix requires [x,y,z]. Therefore, we # need to np.transpose the first and last axis and also invert the # y-axis. fil_p_t = filtered_proj.transpose(2, 1, 0)[:, ::-1, :] # get rotation matrix for this point and also rotate in plane _drot, drotinv = rotation_matrix_from_point_planerot(angles[aa], plane_angle=angz, ret_inv=True) # apply offset required by affine_transform # The offset is only required for the rotation in # the x-z-plane. # This could be achieved like so: # The offset "-.5" assures that we are rotating about # the center of the image and not the value at the center # of the array (this is also what `scipy.ndimage.rotate` does. c = 0.5 * np.array(fil_p_t.shape) - .5 offset = c - np.dot(drotinv, c) # Perform rotation # We cannot split the inplace-rotation into multiple subrotations # as we did in _Back_3d_tilted.backpropagate_3d, because the rotation # axis is arbitrarily placed in the 3d array. Rotating single # slices does not yield the same result as rotating the entire # array. Instead of using affine_transform, map_coordinates might # be faster for multiple cores. # Also undo the axis transposition that we performed previously. outarr.real += scipy.ndimage.interpolation.affine_transform( fil_p_t.real, drotinv, offset=offset, mode="constant", cval=0, order=intp_order).transpose(2, 1, 0)[:, ::-1, :] if not onlyreal: outarr.imag += scipy.ndimage.interpolation.affine_transform( fil_p_t.imag, drotinv, offset=offset, mode="constant", cval=0, order=intp_order).transpose(2, 1, 0)[:, ::-1, :] if count is not None: count.value += 1 return outarr
{ "repo_name": "paulmueller/ODTbrain", "path": "odtbrain/_alg3d_bppt.py", "copies": "2", "size": "35592", "license": "bsd-3-clause", "hash": -4720322253566234000, "line_mean": 36.3315789474, "line_max": 79, "alpha_frac": 0.5886648809, "autogenerated": false, "ratio": 3.435865142414261, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 950 }
"""3D backpropagation with tilted axis of rotation: sphere coordinates""" import numpy as np import odtbrain import odtbrain._alg3d_bppt def test_simple_sphere(): """simple geometrical tests""" angles = np.array([0, np.pi/2, np.pi]) axes = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1]] results = [] for tilted_axis in axes: angle_coords = odtbrain._alg3d_bppt.sphere_points_from_angles_and_tilt( angles, tilted_axis) results.append(angle_coords) s2 = 1/np.sqrt(2) correct = np.array([[[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[0, 0, 1], [1, 0, 0], [0, 0, -1]], [[0, 0, 1], [0, 0, 1], [0, 0, 1]], [[0, 0, 1], [s2, .5, .5], [0, 1, 0]], [[s2, 0, s2], [s2, 0, s2], [s2, 0, s2]], [[s2, 0, s2], [0.87965281125489458, s2/3*2, 0.063156230327168605], [s2/3, s2/3*4, s2/3]], ]) assert np.allclose(correct, np.array(results)) if __name__ == "__main__": # Run all tests loc = locals() for key in list(loc.keys()): if key.startswith("test_") and hasattr(loc[key], "__call__"): loc[key]() import matplotlib.pylab as plt from mpl_toolkits.mplot3d import Axes3D # noqa: F401 from matplotlib.patches import FancyArrowPatch from mpl_toolkits.mplot3d import proj3d class Arrow3D(FancyArrowPatch): def __init__(self, xs, ys, zs, *args, **kwargs): FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs) self._verts3d = xs, ys, zs def draw(self, renderer): xs3d, ys3d, zs3d = self._verts3d xs, ys, _zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0], ys[0]), (xs[1], ys[1])) FancyArrowPatch.draw(self, renderer) axes = [[0, 1, 0], [0, 1, 0.1], [0, 1, -1], [1, 0.1, 0]] colors = ["k", "blue", "red", "green"] angles = np.linspace(0, 2*np.pi, 100) fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111, projection='3d') for i in range(len(axes)): tilted_axis = axes[i] color = colors[i] tilted_axis = np.array(tilted_axis) tilted_axis = tilted_axis/np.sqrt(np.sum(tilted_axis**2)) angle_coords = odtbrain._alg3d_bppt.sphere_points_from_angles_and_tilt( angles, tilted_axis) u, v, w = tilted_axis a = Arrow3D([0, u], [0, v], [0, w], mutation_scale=20, lw=1, arrowstyle="-|>", color=color) ax.add_artist(a) ax.scatter(angle_coords[:, 0], angle_coords[:, 1], angle_coords[:, 2], c=color, marker='o') radius = 1 ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') ax.set_xlim(-radius*1.5, radius*1.5) ax.set_ylim(-radius*1.5, radius*1.5) ax.set_zlim(-radius*1.5, radius*1.5) plt.tight_layout() plt.show()
{ "repo_name": "RI-imaging/ODTbrain", "path": "tests/test_spherecoords_from_angles_and_axis.py", "copies": "2", "size": "3039", "license": "bsd-3-clause", "hash": -2287857034767263000, "line_mean": 33.9310344828, "line_max": 79, "alpha_frac": 0.5123395854, "autogenerated": false, "ratio": 2.829608938547486, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9341948523947486, "avg_score": 0, "num_lines": 87 }
"""3D cone shape settings.""" from ctypes import byref, c_float from .fmodobject import _dll from .utils import ckresult class ConeSettings: """Convenience wrapper class to handle 3D cone shape settings for simulated occlusion which is based on direction. """ def __init__(self, sptr, class_name): """Constructor. Creates ConeSettings for an FMOD object. Usually not called directly, but through the `cone_settings` or `threed_cone_settings` property of an FMOD object. The :py:class:`~pyfmodex.flags.MODE` flag THREED must be set on this object otherwise :py:const:`~pyfmodex.enums.RESULT.NEEDS3D` is returned. When :py:meth:`~pyfmodex.channel_control.ChannelControl.cone_orientation` is set and a 3D 'cone' is set up, attenuation will automatically occur for a sound based on the relative angle of the direction the cone is facing, vs the angle between the sound and the listener. - If the relative angle is within the :py:attr:`inside_angle`, the sound will not have any attenuation applied. - If the relative angle is between the :py:attr:`inside_angle` and :py:attr:`outside_angle`, linear volume attenuation (between 1 and :py:attr:`outside_volume`) is applied between the two angles until it reaches the :py:attr:`outside_angle`. - If the relative angle is outside of the :py:attr:`outside_angle` the volume does not attenuate any further. :param sptr: pointer of the object having cone settings. :param class_name: class of the object having cone settings (Channel or ChannelGroup) """ self._sptr = sptr self._in = c_float() self._out = c_float() self._outvol = c_float() self._get_func = "FMOD_%s_Get3DConeSettings" % class_name self._set_func = "FMOD_%s_Set3DConeSettings" % class_name ckresult( getattr(_dll, self._get_func)( self._sptr, byref(self._in), byref(self._out), byref(self._outvol) ) ) @property def inside_angle(self): """Inside cone angle. This is the angle spread within which the sound is unattenuated. Between 0 and 360. :type: int """ return self._in.value @inside_angle.setter def inside_angle(self, angle): self._in = c_float(angle) self._commit() @property def outside_angle(self): """Outside cone angle. This is the angle spread outside of which the sound is attenuated to its :py:attr:`outside_volume`. Between 0 and 360. :type: int """ return self._out.value @outside_angle.setter def outside_angle(self, angle): self._out = c_float(angle) self._commit() @property def outside_volume(self): """Cone outside volume. Between 0 and 1. :type: float """ return self._outvol.value @outside_volume.setter def outside_volume(self, vol): self._outvol = c_float(vol) self._commit() def _commit(self): """Apply a changed code setting.""" ckresult( getattr(_dll, self._set_func)(self._sptr, self._in, self._out, self._outvol) )
{ "repo_name": "tyrylu/pyfmodex", "path": "pyfmodex/cone_settings.py", "copies": "1", "size": "3371", "license": "mit", "hash": 3076296166176087000, "line_mean": 30.5046728972, "line_max": 88, "alpha_frac": 0.6093147434, "autogenerated": false, "ratio": 3.9152148664343787, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5024529609834378, "avg_score": null, "num_lines": null }
"""3D cube example.""" from galry import * import numpy as np # cube creation function def create_cube(color, scale=1.): """Create a cube as a set of independent triangles. Arguments: * color: the colors of each face, as a 6*4 array. * scale: the scale of the cube, the ridge length is 2*scale. Returns: * position: a Nx3 array with the positions of the vertices. * normal: a Nx3 array with the normals for each vertex. * color: a Nx3 array with the color for each vertex. """ position = np.array([ # Front [-1., -1., -1.], [1., -1., -1.], [-1., 1., -1.], [1., 1., -1.], [-1., 1., -1.], [1., -1., -1.], # Right [1., -1., -1.], [1., -1., 1.], [1., 1., -1.], [1., 1., 1.], [1., 1., -1.], [1., -1., 1.], # Back [1., -1., 1.], [-1., -1., 1.], [1., 1., 1.], [-1., 1., 1.], [1., 1., 1.], [-1., -1., 1.], # Left [-1., -1., 1.], [-1., -1., -1.], [-1., 1., 1.], [-1., 1., -1.], [-1., 1., 1.], [-1., -1., -1.], # Bottom [1., -1., 1.], [1., -1., -1.], [-1., -1., 1.], [-1., -1., -1.], [-1., -1., 1.], [1., -1., -1.], # Top [-1., 1., -1.], [-1., 1., 1.], [1., 1., -1.], [1., 1., 1.], [1., 1., -1.], [-1., 1., 1.], ]) normal = np.array([ # Front [0., 0., -1.], [0., 0., -1.], [0., 0., -1.], [0., 0., -1.], [0., 0., -1.], [0., 0., -1.], # Right [1., 0., 0.], [1., 0., 0.], [1., 0., 0.], [1., 0., 0.], [1., 0., 0.], [1., 0., 0.], # Back [0., 0., 1.], [0., 0., 1.], [0., 0., 1.], [0., 0., 1.], [0., 0., 1.], [0., 0., 1.], # Left [-1., 0., 0.], [-1., 0., 0.], [-1., 0., 0.], [-1., 0., 0.], [-1., 0., 0.], [-1., 0., 0.], # Bottom [0., -1., 0.], [0., -1., 0.], [0., -1., 0.], [0., -1., 0.], [0., -1., 0.], [0., -1., 0.], # Top [0., 1., 0.], [0., 1., 0.], [0., 1., 0.], [0., 1., 0.], [0., 1., 0.], [0., 1., 0.], ]) position *= scale color = np.repeat(color, 6, axis=0) return position, normal, color # face colors color = np.ones((6, 4)) color[0,[0,1]] = 0 color[1,[0,2]] = 0 color[2,[1,2]] = 0 color[3,[0]] = 0 color[4,[1]] = 0 color[5,[2]] = 0 # create the cube position, normal, color = create_cube(color) # render it as a set of triangles mesh(position=position, color=color, normal=normal) show()
{ "repo_name": "rossant/galry", "path": "examples/3dcube.py", "copies": "1", "size": "3035", "license": "bsd-3-clause", "hash": 5687697177946649000, "line_mean": 19.2333333333, "line_max": 66, "alpha_frac": 0.2962108731, "autogenerated": false, "ratio": 3.1032719836400817, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3899482856740082, "avg_score": null, "num_lines": null }
# 3D CUBE MicroPython version with ESP32 and ssd1306 OLED from machine import Pin, I2C from micropython import const from time import sleep_ms from math import sin, cos from ssd1306 import SSD1306_I2C X = const(64) Y = const(32) f = [[0.0 for _ in range(3)] for _ in range(8)] cube = ((-20,-20, 20), (20,-20, 20), (20,20, 20), (-20,20, 20), (-20,-20,-20), (20,-20,-20), (20,20,-20), (-20,20,-20)) i2c = I2C(scl=Pin(23), sda=Pin(22)) oled = SSD1306_I2C(X * 2, Y * 2, i2c) while True: for angle in range(0, 361, 3): # 0 to 360 deg 3step for i in range(8): r = angle * 0.0174532 # 1 degree x1 = cube[i][2] * sin(r) + cube[i][0] * cos(r) # rotate Y ya = cube[i][1] z1 = cube[i][2] * cos(r) - cube[i][0] * sin(r) x2 = x1 y2 = ya * cos(r) - z1 * sin(r) # rotate X z2 = ya * sin(r) + z1 * cos(r) x3 = x2 * cos(r) - y2 * sin(r) # rotate Z y3 = x2 * sin(r) + y2 * cos(r) z3 = z2 x3 = x3 + X y3 = y3 + Y f[i][0] = x3 # store new values f[i][1] = y3 f[i][2] = z3 oled.fill(0) # clear oled.line(int(f[0][0]), int(f[0][1]), int(f[1][0]), int(f[1][1]), 1) oled.line(int(f[1][0]), int(f[1][1]), int(f[2][0]), int(f[2][1]), 1) oled.line(int(f[2][0]), int(f[2][1]), int(f[3][0]), int(f[3][1]), 1) oled.line(int(f[3][0]), int(f[3][1]), int(f[0][0]), int(f[0][1]), 1) oled.line(int(f[4][0]), int(f[4][1]), int(f[5][0]), int(f[5][1]), 1) oled.line(int(f[5][0]), int(f[5][1]), int(f[6][0]), int(f[6][1]), 1) oled.line(int(f[6][0]), int(f[6][1]), int(f[7][0]), int(f[7][1]), 1) oled.line(int(f[7][0]), int(f[7][1]), int(f[4][0]), int(f[4][1]), 1) oled.line(int(f[0][0]), int(f[0][1]), int(f[4][0]), int(f[4][1]), 1) oled.line(int(f[1][0]), int(f[1][1]), int(f[5][0]), int(f[5][1]), 1) oled.line(int(f[2][0]), int(f[2][1]), int(f[6][0]), int(f[6][1]), 1) oled.line(int(f[3][0]), int(f[3][1]), int(f[7][0]), int(f[7][1]), 1) oled.line(int(f[1][0]), int(f[1][1]), int(f[3][0]), int(f[3][1]), 1) # cross oled.line(int(f[0][0]), int(f[0][1]), int(f[2][0]), int(f[2][1]), 1) # cross oled.text('3D CUBE', 0, 0) oled.show() # display sleep_ms(1)
{ "repo_name": "CUEICHI/micropython", "path": "sample/3dcube.py", "copies": "1", "size": "2377", "license": "mit", "hash": 7266997936898778000, "line_mean": 43.0185185185, "line_max": 85, "alpha_frac": 0.4530921329, "autogenerated": false, "ratio": 2.1968576709796674, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.31499498038796675, "avg_score": null, "num_lines": null }
"""3D DenseNet Model file""" import tensorflow as tf class DenseNet3D(object): """3D DenseNet Model class""" def __init__( self, video_clips, # Shape: [batch_size, sequence_length, height, width, channels] labels, # Shape: [batch_size, num_classes] initial_learning_rate, decay_step, lr_decay_factor, num_classes, growth_rate, network_depth, total_blocks, keep_prob, weight_decay, reduction, bc_mode=False, **kwargs): self.video_clips = video_clips self.labels = labels self.num_classes = num_classes self.growth_rate = growth_rate self.network_depth = network_depth # How many features will be received after first convolution value self.first_output_features = growth_rate * 2 self.total_blocks = total_blocks self.layers_per_block = (network_depth - (total_blocks + 1)) // total_blocks # Compression rate at the transition layers self.reduction = reduction self.bc_mode = bc_mode if not bc_mode: self.reduction = 1.0 print( "Build 3D DenseNet model with %d blocks, %d composite layers each." % (total_blocks, self.layers_per_block)) if bc_mode: self.layers_per_block = self.layers_per_block // 2 print( "Build 3D DenseNet-BC model with %d blocks, %d bottleneck layers and %d composite layers each." % (total_blocks, self.layers_per_block, self.layers_per_block)) self.keep_prob = keep_prob self.weight_decay = weight_decay self._is_training = tf.convert_to_tensor(True) # Initialize the global step self.global_step = tf.train.get_or_create_global_step() self.learning_rate = tf.train.exponential_decay( initial_learning_rate, self.global_step, decay_step, lr_decay_factor, staircase=True) self._build_graph() def _build_graph(self): # First convolution layer with tf.variable_scope('Initial_convolution'): output = self._conv3d( self.video_clips, out_features_count=self.first_output_features, kernel_size=7, strides=[1, 1, 2, 2, 1]) output = self._pool(output, k=3, d=2, k_stride=2, d_stride=1) # Add 3D DenseNet blocks for block in range(self.total_blocks): with tf.variable_scope("Block_%d" % block): output = self._add_block(output, self.growth_rate, self.layers_per_block) # The last block exist without transition layer if block != self.total_blocks - 1: with tf.variable_scope("Transition_after_block_%d" % block): output = self._transition_layer(output, pool_depth=2) # Fully connected layers with tf.variable_scope('Transition_to_classes'): self._logits = self._trainsition_layer_to_classes(output) # Prediction result self._prediction = tf.argmax(self._logits, 1) # Losses self._cross_entropy = tf.reduce_mean( tf.nn.sparse_softmax_cross_entropy_with_logits( logits=self._logits, labels=self.labels), name='Cross_entropy') self.l2_loss = tf.add_n( [tf.nn.l2_loss(var) for var in tf.trainable_variables()]) self.total_loss = self._cross_entropy + self.l2_loss * self.weight_decay # Optimizer and training op self._train_op = tf.contrib.layers.optimize_loss( loss=self.total_loss, global_step=self.global_step, learning_rate=self.learning_rate, optimizer='Momentum') @property def logits(self): return self._logits @property def train_op(self): return self._train_op @property def losses(self): return self._cross_entropy @property def prediction(self): return self._prediction @property def accuracy(self): correct_prediction = tf.equal(tf.argmax(self._logits, 1), self.labels) return tf.metrics.mean(tf.cast(correct_prediction, tf.float32)) @property def is_training(self): return self._is_training @is_training.setter def is_training(self, value): self._is_training = tf.convert_to_tensor(value) def _conv3d(self, inputs, out_features_count, kernel_size, strides=[1, 1, 1, 1, 1], padding='SAME'): input_features_count = int(inputs.get_shape()[-1]) kernel = tf.get_variable( 'kernel', shape=[ kernel_size, kernel_size, kernel_size, input_features_count, out_features_count ], initializer=tf.random_normal_initializer()) with tf.name_scope('3d_conv'): return tf.nn.conv3d( inputs, filter=kernel, strides=strides, padding=padding) def _pool(self, inputs, k, d=2, k_stride=None, d_stride=None, width_k=None, k_stride_width=None): if not width_k: width_k = k kernel_size = [1, d, k, width_k, 1] if not k_stride: k_stride = k if not k_stride_width: k_stride_width = k_stride if not d_stride: d_stride = d strides = [1, d_stride, k_stride, k_stride_width, 1] return tf.nn.max_pool3d( inputs, ksize=kernel_size, strides=strides, padding='SAME') def _add_block(self, inputs, growth_rate, layers_per_block): for layer in range(layers_per_block): with tf.variable_scope("layer_%d" % layer): return self._add_internal_layer(inputs, growth_rate) def _add_internal_layer(self, inputs, growth_rate): if not self.bc_mode: composite_out = self._composite_function( inputs, out_features_count=growth_rate, kernel_size=3) elif self.bc_mode: bottleneck_out = self._bottleneck( inputs, out_features_count=growth_rate) composite_out = self._composite_function( bottleneck_out, out_features_count=growth_rate, kernel_size=3) with tf.name_scope('concat'): return tf.concat(axis=4, values=(inputs, composite_out)) def _composite_function(self, inputs, out_features_count, kernel_size): with tf.variable_scope('composite_function'): # Batch normalization output = self._batch_norm(inputs) # ReLU with tf.name_scope('ReLU'): output = tf.nn.relu(output) # Convolution output = self._conv3d( output, out_features_count=out_features_count, kernel_size=kernel_size) # Dropout output = self._dropout(output) return output def _bottleneck(self, inputs, out_features_count): with tf.variable_scope('bottleneck'): # Batch normalization output = self._batch_norm(inputs) # ReLU with tf.name_scope('ReLU'): output = tf.nn.relu(output) inter_features = out_features_count * 4 output = self._conv3d( output, out_features_count=inter_features, kernel_size=1, padding='VALID') output = self._dropout(output) return output def _batch_norm(self, inputs): with tf.name_scope('batch_normalization'): output = tf.contrib.layers.batch_norm( inputs, scale=True, is_training=self._is_training, updates_collections=None) return output def _dropout(self, inputs): if self.keep_prob < 1: with tf.name_scope('dropout'): output = tf.cond(self._is_training, lambda: tf.nn.dropout(inputs, self.keep_prob), lambda: inputs) else: output = inputs return output def _transition_layer(self, inputs, pool_depth): out_features_count = int(int(inputs.get_shape()[-1]) * self.reduction) output = self._composite_function( inputs, out_features_count=out_features_count, kernel_size=1) with tf.name_scope('pooling'): output = self._pool(output, k=2, d=pool_depth) return output def _trainsition_layer_to_classes(self, inputs): # Batch normalization output = self._batch_norm(inputs) # ReLU with tf.name_scope('ReLU'): output = tf.nn.relu(output) # pooling last_pool_kernel_width = int(output.get_shape()[-2]) last_pool_kernel_height = int(output.get_shape()[-3]) last_sequence_length = int(output.get_shape()[1]) with tf.name_scope('pooling'): output = self._pool( output, k=last_pool_kernel_height, d=last_sequence_length, width_k=last_pool_kernel_width, k_stride_width=last_pool_kernel_width) # Fully connected features_total = int(output.get_shape()[-1]) output = tf.reshape(output, [-1, features_total]) weight = tf.get_variable( 'fc_w', shape=[features_total, self.num_classes], initializer=tf.contrib.layers.xavier_initializer()) bias = tf.get_variable( 'fc_bias', shape=[self.num_classes], initializer=tf.zeros_initializer()) logits = tf.matmul(output, weight) + bias return logits
{ "repo_name": "frankgu/3d-DenseNet", "path": "source_dir/densenet_3d_model.py", "copies": "1", "size": "10162", "license": "mit", "hash": -6838488191977322000, "line_mean": 34.5314685315, "line_max": 111, "alpha_frac": 0.546250738, "autogenerated": false, "ratio": 4.046993229788929, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5093243967788929, "avg_score": null, "num_lines": null }
# 3D example of viewing aggregates from SA using VTK from pyamg.aggregation import standard_aggregation from pyamg.vis import vis_coarse, vtk_writer from pyamg.gallery import load_example # retrieve the problem data = load_example('unit_cube') A = data['A'].tocsr() V = data['vertices'] E2V = data['elements'] # perform smoothed aggregation Agg = standard_aggregation(A) # create the vtk file of aggregates vis_coarse.vis_aggregate_groups(Verts=V, E2V=E2V, Agg=Agg, \ mesh_type='tet', output='vtk', \ fname='output_aggs.vtu') # create the vtk file for a mesh vtk_writer.write_basic_mesh(Verts=V, E2V=E2V, \ mesh_type='tet', \ fname='output_mesh.vtu') # to use Paraview: # start Paraview: Paraview --data=output_mesh.vtu # apply # under display in the object inspector: # select wireframe representation # select a better solid color # selecting surface with edges and low opacity also helps # open file: output_aggs.vtu # under display in the object inspector: # select surface with edges representation # select a better solid color # increase line width and point size to see these aggs (if present) # reduce the opacity, sometimes helps
{ "repo_name": "pombreda/pyamg", "path": "Examples/VisualizingAggregation/demo2.py", "copies": "1", "size": "1338", "license": "bsd-3-clause", "hash": 5362754349692463000, "line_mean": 35.1621621622, "line_max": 77, "alpha_frac": 0.6464872945, "autogenerated": false, "ratio": 3.6859504132231407, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9812043275370369, "avg_score": 0.0040788864705543345, "num_lines": 37 }
"""3D frustum representation.""" # Copyright © 2014 Mikko Ronkainen <firstname@mikkoronkainen.com> # License: MIT, see the LICENSE file. from math import * from pymazing import plane TOP = 0 BOTTOM = 1 LEFT = 2 RIGHT = 3 NEAR = 4 FAR = 5 class Frustum: def __init__(self): self.planes = [plane.Plane() for _ in range(6)] def setup_from_camera(self, camera): """ Construct the bounding planes from the camera orientation data. """ tangent = tan(camera.vertical_fov * pi / 180.0 / 2.0) near_distance = camera.near_z near_half_height = tangent * near_distance near_half_width = near_half_height * camera.aspect_ratio far_distance = camera.far_z far_half_height = tangent * far_distance far_half_width = far_half_height * camera.aspect_ratio origin = camera.position near_forward = camera.forward_vector * near_distance near_up = camera.up_vector * near_half_height near_right = camera.right_vector * near_half_width far_forward = camera.forward_vector * far_distance far_up = camera.up_vector * far_half_height far_right = camera.right_vector * far_half_width ntl = origin + near_forward + near_up - near_right ntr = origin + near_forward + near_up + near_right nbr = origin + near_forward - near_up + near_right nbl = origin + near_forward - near_up - near_right ftl = origin + far_forward + far_up - far_right ftr = origin + far_forward + far_up + far_right fbr = origin + far_forward - far_up + far_right fbl = origin + far_forward - far_up - far_right self.planes[TOP].setup_from_points(ntl, ftl, ftr) self.planes[BOTTOM].setup_from_points(nbl, fbr, fbl) self.planes[LEFT].setup_from_points(ntl, fbl, ftl) self.planes[RIGHT].setup_from_points(ntr, ftr, fbr) self.planes[NEAR].setup_from_points(ntl, ntr, nbr) self.planes[FAR].setup_from_points(ftr, ftl, fbl) def point_is_inside(self, p): """ Test if a point is inside the frustum. """ for plane in self.planes: if plane.point_distance(p) < 0.0: return False return True def sphere_is_inside(self, center, radius): """ Test if a sphere is inside the frustum (even partially). """ for plane in self.planes: if (plane.point_distance(center) + radius) < 0.0: return False return True
{ "repo_name": "mikoro/pymazing", "path": "pymazing/frustum.py", "copies": "1", "size": "2631", "license": "mit", "hash": 3341514919957270500, "line_mean": 32.6052631579, "line_max": 71, "alpha_frac": 0.5870722433, "autogenerated": false, "ratio": 3.49269588313413, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9579768126434131, "avg_score": 0, "num_lines": 76 }
"""3D mesh manipulation utilities.""" from builtins import str from collections import OrderedDict import numpy as np def frustum(left, right, bottom, top, znear, zfar): """Create view frustum matrix.""" assert right != left assert bottom != top assert znear != zfar M = np.zeros((4, 4), dtype=np.float32) M[0, 0] = +2.0 * znear / (right - left) M[2, 0] = (right + left) / (right - left) M[1, 1] = +2.0 * znear / (top - bottom) M[3, 1] = (top + bottom) / (top - bottom) M[2, 2] = -(zfar + znear) / (zfar - znear) M[3, 2] = -2.0 * znear * zfar / (zfar - znear) M[2, 3] = -1.0 return M def perspective(fovy, aspect, znear, zfar): """Create perspective projection matrix.""" assert znear != zfar h = np.tan(fovy / 360.0 * np.pi) * znear w = h * aspect return frustum(-w, w, -h, h, znear, zfar) def anorm(x, axis=None, keepdims=False): """Compute L2 norms alogn specified axes.""" return np.sqrt((x*x).sum(axis=axis, keepdims=keepdims)) def normalize(v, axis=None, eps=1e-10): """L2 Normalize along specified axes.""" return v / max(anorm(v, axis=axis, keepdims=True), eps) def lookat(eye, target=[0, 0, 0], up=[0, 1, 0]): """Generate LookAt modelview matrix.""" eye = np.float32(eye) forward = normalize(target - eye) side = normalize(np.cross(forward, up)) up = np.cross(side, forward) M = np.eye(4, dtype=np.float32) R = M[:3, :3] R[:] = [side, up, -forward] M[:3, 3] = -R.dot(eye) return M def sample_view(min_dist, max_dist=None): '''Sample random camera position. Sample origin directed camera position in given distance range from the origin. ModelView matrix is returned. ''' if max_dist is None: max_dist = min_dist dist = np.random.uniform(min_dist, max_dist) eye = np.random.normal(size=3) eye = normalize(eye)*dist return lookat(eye) def homotrans(M, p): p = np.asarray(p) if p.shape[-1] == M.shape[1]-1: p = np.append(p, np.ones_like(p[...,:1]), -1) p = np.dot(p, M.T) return p[...,:-1] / p[...,-1:] def _parse_vertex_tuple(s): """Parse vertex indices in '/' separated form (like 'i/j/k', 'i//k' ...).""" vt = [0, 0, 0] for i, c in enumerate(s.split('/')): if c: vt[i] = int(c) return tuple(vt) def _unify_rows(a): """Unify lengths of each row of a.""" lens = np.fromiter(map(len, a), np.int32) if not (lens[0] == lens).all(): out = np.zeros((len(a), lens.max()), np.float32) for i, row in enumerate(a): out[i, :lens[i]] = row else: out = np.float32(a) return out def load_obj(fn): """Load 3d mesh form .obj' file. Args: fn: Input file name or file-like object. Returns: dictionary with the following keys (some of which may be missing): position: np.float32, (n, 3) array, vertex positions uv: np.float32, (n, 2) array, vertex uv coordinates normal: np.float32, (n, 3) array, vertex uv normals face: np.int32, (k*3,) traingular face indices """ position = [np.zeros(3, dtype=np.float32)] normal = [np.zeros(3, dtype=np.float32)] uv = [np.zeros(2, dtype=np.float32)] tuple2idx = OrderedDict() trinagle_indices = [] input_file = open(fn) if isinstance(fn, str) else fn for line in input_file: line = line.strip() if not line or line[0] == '#': continue line = line.split(' ', 1) tag = line[0] if len(line) > 1: line = line[1] else: line = '' if tag == 'v': position.append(np.fromstring(line, sep=' ')) elif tag == 'vt': uv.append(np.fromstring(line, sep=' ')) elif tag == 'vn': normal.append(np.fromstring(line, sep=' ')) elif tag == 'f': output_face_indices = [] for chunk in line.split(): # tuple order: pos_idx, uv_idx, normal_idx vt = _parse_vertex_tuple(chunk) if vt not in tuple2idx: # create a new output vertex? tuple2idx[vt] = len(tuple2idx) output_face_indices.append(tuple2idx[vt]) # generate face triangles for i in range(1, len(output_face_indices)-1): for vi in [0, i, i+1]: trinagle_indices.append(output_face_indices[vi]) outputs = {} outputs['face'] = np.int32(trinagle_indices) pos_idx, uv_idx, normal_idx = np.int32(list(tuple2idx)).T if np.any(pos_idx): outputs['position'] = _unify_rows(position)[pos_idx] if np.any(uv_idx): outputs['uv'] = _unify_rows(uv)[uv_idx] if np.any(normal_idx): outputs['normal'] = _unify_rows(normal)[normal_idx] return outputs def normalize_mesh(mesh): '''Scale mesh to fit into -1..1 cube''' mesh = dict(mesh) pos = mesh['position'][:,:3].copy() pos -= (pos.max(0)+pos.min(0)) / 2.0 pos /= np.abs(pos).max() mesh['position'] = pos return mesh
{ "repo_name": "tensorflow/lucid", "path": "lucid/misc/gl/meshutil.py", "copies": "1", "size": "4745", "license": "apache-2.0", "hash": -1723399036655642400, "line_mean": 27.244047619, "line_max": 78, "alpha_frac": 0.5997892518, "autogenerated": false, "ratio": 2.8862530413625302, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.39860422931625306, "avg_score": null, "num_lines": null }
"""3D Projective Geometric Algebra. Written by a generator written by enki. """ __author__ = 'Enki' import math class CGA: def __init__(self, value=0, index=0): """Initiate a new CGA. Optional, the component index can be set with value. """ self.mvec = [0] * 32 self._base = ["1", "e1", "e2", "e3", "e4", "e5", "e12", "e13", "e14", "e15", "e23", "e24", "e25", "e34", "e35", "e45", "e123", "e124", "e125", "e134", "e135", "e145", "e234", "e235", "e245", "e345", "e1234", "e1235", "e1245", "e1345", "e2345", "e12345"] if (value != 0): self.mvec[index] = value @classmethod def fromarray(cls, array): """Initiate a new CGA from an array-like object. The first axis of the array is assumed to correspond to the elements of the algebra, and needs to have the same length. Any other dimensions are left unchanged, and should have simple operations such as addition and multiplication defined. NumPy arrays are therefore a perfect candidate. :param array: array-like object whose length is the dimension of the algebra. :return: new instance of CGA. """ self = cls() if len(array) != len(self): raise TypeError('length of array must be identical to the dimension ' 'of the algebra.') self.mvec = array return self def __str__(self): if isinstance(self.mvec, list): res = ' + '.join(filter(None, [("%.7f" % x).rstrip("0").rstrip(".")+(["",self._base[i]][i>0]) if abs(x) > 0.000001 else None for i,x in enumerate(self)])) else: # Assume array-like, redirect str conversion res = str(self.mvec) if (res == ''): return "0" return res def __getitem__(self, key): return self.mvec[key] def __setitem__(self, key, value): self.mvec[key] = value def __len__(self): return len(self.mvec) def __invert__(a): """CGA.Reverse Reverse the order of the basis blades. """ res = a.mvec.copy() res[0]=a[0] res[1]=a[1] res[2]=a[2] res[3]=a[3] res[4]=a[4] res[5]=a[5] res[6]=-a[6] res[7]=-a[7] res[8]=-a[8] res[9]=-a[9] res[10]=-a[10] res[11]=-a[11] res[12]=-a[12] res[13]=-a[13] res[14]=-a[14] res[15]=-a[15] res[16]=-a[16] res[17]=-a[17] res[18]=-a[18] res[19]=-a[19] res[20]=-a[20] res[21]=-a[21] res[22]=-a[22] res[23]=-a[23] res[24]=-a[24] res[25]=-a[25] res[26]=a[26] res[27]=a[27] res[28]=a[28] res[29]=a[29] res[30]=a[30] res[31]=a[31] return CGA.fromarray(res) def Dual(a): """CGA.Dual Poincare duality operator. """ res = a.mvec.copy() res[0]=-a[31] res[1]=-a[30] res[2]=a[29] res[3]=-a[28] res[4]=a[27] res[5]=a[26] res[6]=a[25] res[7]=-a[24] res[8]=a[23] res[9]=a[22] res[10]=a[21] res[11]=-a[20] res[12]=-a[19] res[13]=a[18] res[14]=a[17] res[15]=-a[16] res[16]=a[15] res[17]=-a[14] res[18]=-a[13] res[19]=a[12] res[20]=a[11] res[21]=-a[10] res[22]=-a[9] res[23]=-a[8] res[24]=a[7] res[25]=-a[6] res[26]=-a[5] res[27]=-a[4] res[28]=a[3] res[29]=-a[2] res[30]=a[1] res[31]=a[0] return CGA.fromarray(res) def Conjugate(a): """CGA.Conjugate Clifford Conjugation """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] res[2]=-a[2] res[3]=-a[3] res[4]=-a[4] res[5]=-a[5] res[6]=-a[6] res[7]=-a[7] res[8]=-a[8] res[9]=-a[9] res[10]=-a[10] res[11]=-a[11] res[12]=-a[12] res[13]=-a[13] res[14]=-a[14] res[15]=-a[15] res[16]=a[16] res[17]=a[17] res[18]=a[18] res[19]=a[19] res[20]=a[20] res[21]=a[21] res[22]=a[22] res[23]=a[23] res[24]=a[24] res[25]=a[25] res[26]=a[26] res[27]=a[27] res[28]=a[28] res[29]=a[29] res[30]=a[30] res[31]=-a[31] return CGA.fromarray(res) def Involute(a): """CGA.Involute Main involution """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] res[2]=-a[2] res[3]=-a[3] res[4]=-a[4] res[5]=-a[5] res[6]=a[6] res[7]=a[7] res[8]=a[8] res[9]=a[9] res[10]=a[10] res[11]=a[11] res[12]=a[12] res[13]=a[13] res[14]=a[14] res[15]=a[15] res[16]=-a[16] res[17]=-a[17] res[18]=-a[18] res[19]=-a[19] res[20]=-a[20] res[21]=-a[21] res[22]=-a[22] res[23]=-a[23] res[24]=-a[24] res[25]=-a[25] res[26]=a[26] res[27]=a[27] res[28]=a[28] res[29]=a[29] res[30]=a[30] res[31]=-a[31] return CGA.fromarray(res) def __mul__(a,b): """CGA.Mul The geometric product. """ if type(b) in (int, float): return a.muls(b) res = a.mvec.copy() res[0]=b[0]*a[0]+b[1]*a[1]+b[2]*a[2]+b[3]*a[3]+b[4]*a[4]-b[5]*a[5]-b[6]*a[6]-b[7]*a[7]-b[8]*a[8]+b[9]*a[9]-b[10]*a[10]-b[11]*a[11]+b[12]*a[12]-b[13]*a[13]+b[14]*a[14]+b[15]*a[15]-b[16]*a[16]-b[17]*a[17]+b[18]*a[18]-b[19]*a[19]+b[20]*a[20]+b[21]*a[21]-b[22]*a[22]+b[23]*a[23]+b[24]*a[24]+b[25]*a[25]+b[26]*a[26]-b[27]*a[27]-b[28]*a[28]-b[29]*a[29]-b[30]*a[30]-b[31]*a[31] res[1]=b[1]*a[0]+b[0]*a[1]-b[6]*a[2]-b[7]*a[3]-b[8]*a[4]+b[9]*a[5]+b[2]*a[6]+b[3]*a[7]+b[4]*a[8]-b[5]*a[9]-b[16]*a[10]-b[17]*a[11]+b[18]*a[12]-b[19]*a[13]+b[20]*a[14]+b[21]*a[15]-b[10]*a[16]-b[11]*a[17]+b[12]*a[18]-b[13]*a[19]+b[14]*a[20]+b[15]*a[21]+b[26]*a[22]-b[27]*a[23]-b[28]*a[24]-b[29]*a[25]-b[22]*a[26]+b[23]*a[27]+b[24]*a[28]+b[25]*a[29]-b[31]*a[30]-b[30]*a[31] res[2]=b[2]*a[0]+b[6]*a[1]+b[0]*a[2]-b[10]*a[3]-b[11]*a[4]+b[12]*a[5]-b[1]*a[6]+b[16]*a[7]+b[17]*a[8]-b[18]*a[9]+b[3]*a[10]+b[4]*a[11]-b[5]*a[12]-b[22]*a[13]+b[23]*a[14]+b[24]*a[15]+b[7]*a[16]+b[8]*a[17]-b[9]*a[18]-b[26]*a[19]+b[27]*a[20]+b[28]*a[21]-b[13]*a[22]+b[14]*a[23]+b[15]*a[24]-b[30]*a[25]+b[19]*a[26]-b[20]*a[27]-b[21]*a[28]+b[31]*a[29]+b[25]*a[30]+b[29]*a[31] res[3]=b[3]*a[0]+b[7]*a[1]+b[10]*a[2]+b[0]*a[3]-b[13]*a[4]+b[14]*a[5]-b[16]*a[6]-b[1]*a[7]+b[19]*a[8]-b[20]*a[9]-b[2]*a[10]+b[22]*a[11]-b[23]*a[12]+b[4]*a[13]-b[5]*a[14]+b[25]*a[15]-b[6]*a[16]+b[26]*a[17]-b[27]*a[18]+b[8]*a[19]-b[9]*a[20]+b[29]*a[21]+b[11]*a[22]-b[12]*a[23]+b[30]*a[24]+b[15]*a[25]-b[17]*a[26]+b[18]*a[27]-b[31]*a[28]-b[21]*a[29]-b[24]*a[30]-b[28]*a[31] res[4]=b[4]*a[0]+b[8]*a[1]+b[11]*a[2]+b[13]*a[3]+b[0]*a[4]+b[15]*a[5]-b[17]*a[6]-b[19]*a[7]-b[1]*a[8]-b[21]*a[9]-b[22]*a[10]-b[2]*a[11]-b[24]*a[12]-b[3]*a[13]-b[25]*a[14]-b[5]*a[15]-b[26]*a[16]-b[6]*a[17]-b[28]*a[18]-b[7]*a[19]-b[29]*a[20]-b[9]*a[21]-b[10]*a[22]-b[30]*a[23]-b[12]*a[24]-b[14]*a[25]+b[16]*a[26]+b[31]*a[27]+b[18]*a[28]+b[20]*a[29]+b[23]*a[30]+b[27]*a[31] res[5]=b[5]*a[0]+b[9]*a[1]+b[12]*a[2]+b[14]*a[3]+b[15]*a[4]+b[0]*a[5]-b[18]*a[6]-b[20]*a[7]-b[21]*a[8]-b[1]*a[9]-b[23]*a[10]-b[24]*a[11]-b[2]*a[12]-b[25]*a[13]-b[3]*a[14]-b[4]*a[15]-b[27]*a[16]-b[28]*a[17]-b[6]*a[18]-b[29]*a[19]-b[7]*a[20]-b[8]*a[21]-b[30]*a[22]-b[10]*a[23]-b[11]*a[24]-b[13]*a[25]+b[31]*a[26]+b[16]*a[27]+b[17]*a[28]+b[19]*a[29]+b[22]*a[30]+b[26]*a[31] res[6]=b[6]*a[0]+b[2]*a[1]-b[1]*a[2]+b[16]*a[3]+b[17]*a[4]-b[18]*a[5]+b[0]*a[6]-b[10]*a[7]-b[11]*a[8]+b[12]*a[9]+b[7]*a[10]+b[8]*a[11]-b[9]*a[12]-b[26]*a[13]+b[27]*a[14]+b[28]*a[15]+b[3]*a[16]+b[4]*a[17]-b[5]*a[18]-b[22]*a[19]+b[23]*a[20]+b[24]*a[21]+b[19]*a[22]-b[20]*a[23]-b[21]*a[24]+b[31]*a[25]-b[13]*a[26]+b[14]*a[27]+b[15]*a[28]-b[30]*a[29]+b[29]*a[30]+b[25]*a[31] res[7]=b[7]*a[0]+b[3]*a[1]-b[16]*a[2]-b[1]*a[3]+b[19]*a[4]-b[20]*a[5]+b[10]*a[6]+b[0]*a[7]-b[13]*a[8]+b[14]*a[9]-b[6]*a[10]+b[26]*a[11]-b[27]*a[12]+b[8]*a[13]-b[9]*a[14]+b[29]*a[15]-b[2]*a[16]+b[22]*a[17]-b[23]*a[18]+b[4]*a[19]-b[5]*a[20]+b[25]*a[21]-b[17]*a[22]+b[18]*a[23]-b[31]*a[24]-b[21]*a[25]+b[11]*a[26]-b[12]*a[27]+b[30]*a[28]+b[15]*a[29]-b[28]*a[30]-b[24]*a[31] res[8]=b[8]*a[0]+b[4]*a[1]-b[17]*a[2]-b[19]*a[3]-b[1]*a[4]-b[21]*a[5]+b[11]*a[6]+b[13]*a[7]+b[0]*a[8]+b[15]*a[9]-b[26]*a[10]-b[6]*a[11]-b[28]*a[12]-b[7]*a[13]-b[29]*a[14]-b[9]*a[15]-b[22]*a[16]-b[2]*a[17]-b[24]*a[18]-b[3]*a[19]-b[25]*a[20]-b[5]*a[21]+b[16]*a[22]+b[31]*a[23]+b[18]*a[24]+b[20]*a[25]-b[10]*a[26]-b[30]*a[27]-b[12]*a[28]-b[14]*a[29]+b[27]*a[30]+b[23]*a[31] res[9]=b[9]*a[0]+b[5]*a[1]-b[18]*a[2]-b[20]*a[3]-b[21]*a[4]-b[1]*a[5]+b[12]*a[6]+b[14]*a[7]+b[15]*a[8]+b[0]*a[9]-b[27]*a[10]-b[28]*a[11]-b[6]*a[12]-b[29]*a[13]-b[7]*a[14]-b[8]*a[15]-b[23]*a[16]-b[24]*a[17]-b[2]*a[18]-b[25]*a[19]-b[3]*a[20]-b[4]*a[21]+b[31]*a[22]+b[16]*a[23]+b[17]*a[24]+b[19]*a[25]-b[30]*a[26]-b[10]*a[27]-b[11]*a[28]-b[13]*a[29]+b[26]*a[30]+b[22]*a[31] res[10]=b[10]*a[0]+b[16]*a[1]+b[3]*a[2]-b[2]*a[3]+b[22]*a[4]-b[23]*a[5]-b[7]*a[6]+b[6]*a[7]-b[26]*a[8]+b[27]*a[9]+b[0]*a[10]-b[13]*a[11]+b[14]*a[12]+b[11]*a[13]-b[12]*a[14]+b[30]*a[15]+b[1]*a[16]-b[19]*a[17]+b[20]*a[18]+b[17]*a[19]-b[18]*a[20]+b[31]*a[21]+b[4]*a[22]-b[5]*a[23]+b[25]*a[24]-b[24]*a[25]-b[8]*a[26]+b[9]*a[27]-b[29]*a[28]+b[28]*a[29]+b[15]*a[30]+b[21]*a[31] res[11]=b[11]*a[0]+b[17]*a[1]+b[4]*a[2]-b[22]*a[3]-b[2]*a[4]-b[24]*a[5]-b[8]*a[6]+b[26]*a[7]+b[6]*a[8]+b[28]*a[9]+b[13]*a[10]+b[0]*a[11]+b[15]*a[12]-b[10]*a[13]-b[30]*a[14]-b[12]*a[15]+b[19]*a[16]+b[1]*a[17]+b[21]*a[18]-b[16]*a[19]-b[31]*a[20]-b[18]*a[21]-b[3]*a[22]-b[25]*a[23]-b[5]*a[24]+b[23]*a[25]+b[7]*a[26]+b[29]*a[27]+b[9]*a[28]-b[27]*a[29]-b[14]*a[30]-b[20]*a[31] res[12]=b[12]*a[0]+b[18]*a[1]+b[5]*a[2]-b[23]*a[3]-b[24]*a[4]-b[2]*a[5]-b[9]*a[6]+b[27]*a[7]+b[28]*a[8]+b[6]*a[9]+b[14]*a[10]+b[15]*a[11]+b[0]*a[12]-b[30]*a[13]-b[10]*a[14]-b[11]*a[15]+b[20]*a[16]+b[21]*a[17]+b[1]*a[18]-b[31]*a[19]-b[16]*a[20]-b[17]*a[21]-b[25]*a[22]-b[3]*a[23]-b[4]*a[24]+b[22]*a[25]+b[29]*a[26]+b[7]*a[27]+b[8]*a[28]-b[26]*a[29]-b[13]*a[30]-b[19]*a[31] res[13]=b[13]*a[0]+b[19]*a[1]+b[22]*a[2]+b[4]*a[3]-b[3]*a[4]-b[25]*a[5]-b[26]*a[6]-b[8]*a[7]+b[7]*a[8]+b[29]*a[9]-b[11]*a[10]+b[10]*a[11]+b[30]*a[12]+b[0]*a[13]+b[15]*a[14]-b[14]*a[15]-b[17]*a[16]+b[16]*a[17]+b[31]*a[18]+b[1]*a[19]+b[21]*a[20]-b[20]*a[21]+b[2]*a[22]+b[24]*a[23]-b[23]*a[24]-b[5]*a[25]-b[6]*a[26]-b[28]*a[27]+b[27]*a[28]+b[9]*a[29]+b[12]*a[30]+b[18]*a[31] res[14]=b[14]*a[0]+b[20]*a[1]+b[23]*a[2]+b[5]*a[3]-b[25]*a[4]-b[3]*a[5]-b[27]*a[6]-b[9]*a[7]+b[29]*a[8]+b[7]*a[9]-b[12]*a[10]+b[30]*a[11]+b[10]*a[12]+b[15]*a[13]+b[0]*a[14]-b[13]*a[15]-b[18]*a[16]+b[31]*a[17]+b[16]*a[18]+b[21]*a[19]+b[1]*a[20]-b[19]*a[21]+b[24]*a[22]+b[2]*a[23]-b[22]*a[24]-b[4]*a[25]-b[28]*a[26]-b[6]*a[27]+b[26]*a[28]+b[8]*a[29]+b[11]*a[30]+b[17]*a[31] res[15]=b[15]*a[0]+b[21]*a[1]+b[24]*a[2]+b[25]*a[3]+b[5]*a[4]-b[4]*a[5]-b[28]*a[6]-b[29]*a[7]-b[9]*a[8]+b[8]*a[9]-b[30]*a[10]-b[12]*a[11]+b[11]*a[12]-b[14]*a[13]+b[13]*a[14]+b[0]*a[15]-b[31]*a[16]-b[18]*a[17]+b[17]*a[18]-b[20]*a[19]+b[19]*a[20]+b[1]*a[21]-b[23]*a[22]+b[22]*a[23]+b[2]*a[24]+b[3]*a[25]+b[27]*a[26]-b[26]*a[27]-b[6]*a[28]-b[7]*a[29]-b[10]*a[30]-b[16]*a[31] res[16]=b[16]*a[0]+b[10]*a[1]-b[7]*a[2]+b[6]*a[3]-b[26]*a[4]+b[27]*a[5]+b[3]*a[6]-b[2]*a[7]+b[22]*a[8]-b[23]*a[9]+b[1]*a[10]-b[19]*a[11]+b[20]*a[12]+b[17]*a[13]-b[18]*a[14]+b[31]*a[15]+b[0]*a[16]-b[13]*a[17]+b[14]*a[18]+b[11]*a[19]-b[12]*a[20]+b[30]*a[21]-b[8]*a[22]+b[9]*a[23]-b[29]*a[24]+b[28]*a[25]+b[4]*a[26]-b[5]*a[27]+b[25]*a[28]-b[24]*a[29]+b[21]*a[30]+b[15]*a[31] res[17]=b[17]*a[0]+b[11]*a[1]-b[8]*a[2]+b[26]*a[3]+b[6]*a[4]+b[28]*a[5]+b[4]*a[6]-b[22]*a[7]-b[2]*a[8]-b[24]*a[9]+b[19]*a[10]+b[1]*a[11]+b[21]*a[12]-b[16]*a[13]-b[31]*a[14]-b[18]*a[15]+b[13]*a[16]+b[0]*a[17]+b[15]*a[18]-b[10]*a[19]-b[30]*a[20]-b[12]*a[21]+b[7]*a[22]+b[29]*a[23]+b[9]*a[24]-b[27]*a[25]-b[3]*a[26]-b[25]*a[27]-b[5]*a[28]+b[23]*a[29]-b[20]*a[30]-b[14]*a[31] res[18]=b[18]*a[0]+b[12]*a[1]-b[9]*a[2]+b[27]*a[3]+b[28]*a[4]+b[6]*a[5]+b[5]*a[6]-b[23]*a[7]-b[24]*a[8]-b[2]*a[9]+b[20]*a[10]+b[21]*a[11]+b[1]*a[12]-b[31]*a[13]-b[16]*a[14]-b[17]*a[15]+b[14]*a[16]+b[15]*a[17]+b[0]*a[18]-b[30]*a[19]-b[10]*a[20]-b[11]*a[21]+b[29]*a[22]+b[7]*a[23]+b[8]*a[24]-b[26]*a[25]-b[25]*a[26]-b[3]*a[27]-b[4]*a[28]+b[22]*a[29]-b[19]*a[30]-b[13]*a[31] res[19]=b[19]*a[0]+b[13]*a[1]-b[26]*a[2]-b[8]*a[3]+b[7]*a[4]+b[29]*a[5]+b[22]*a[6]+b[4]*a[7]-b[3]*a[8]-b[25]*a[9]-b[17]*a[10]+b[16]*a[11]+b[31]*a[12]+b[1]*a[13]+b[21]*a[14]-b[20]*a[15]-b[11]*a[16]+b[10]*a[17]+b[30]*a[18]+b[0]*a[19]+b[15]*a[20]-b[14]*a[21]-b[6]*a[22]-b[28]*a[23]+b[27]*a[24]+b[9]*a[25]+b[2]*a[26]+b[24]*a[27]-b[23]*a[28]-b[5]*a[29]+b[18]*a[30]+b[12]*a[31] res[20]=b[20]*a[0]+b[14]*a[1]-b[27]*a[2]-b[9]*a[3]+b[29]*a[4]+b[7]*a[5]+b[23]*a[6]+b[5]*a[7]-b[25]*a[8]-b[3]*a[9]-b[18]*a[10]+b[31]*a[11]+b[16]*a[12]+b[21]*a[13]+b[1]*a[14]-b[19]*a[15]-b[12]*a[16]+b[30]*a[17]+b[10]*a[18]+b[15]*a[19]+b[0]*a[20]-b[13]*a[21]-b[28]*a[22]-b[6]*a[23]+b[26]*a[24]+b[8]*a[25]+b[24]*a[26]+b[2]*a[27]-b[22]*a[28]-b[4]*a[29]+b[17]*a[30]+b[11]*a[31] res[21]=b[21]*a[0]+b[15]*a[1]-b[28]*a[2]-b[29]*a[3]-b[9]*a[4]+b[8]*a[5]+b[24]*a[6]+b[25]*a[7]+b[5]*a[8]-b[4]*a[9]-b[31]*a[10]-b[18]*a[11]+b[17]*a[12]-b[20]*a[13]+b[19]*a[14]+b[1]*a[15]-b[30]*a[16]-b[12]*a[17]+b[11]*a[18]-b[14]*a[19]+b[13]*a[20]+b[0]*a[21]+b[27]*a[22]-b[26]*a[23]-b[6]*a[24]-b[7]*a[25]-b[23]*a[26]+b[22]*a[27]+b[2]*a[28]+b[3]*a[29]-b[16]*a[30]-b[10]*a[31] res[22]=b[22]*a[0]+b[26]*a[1]+b[13]*a[2]-b[11]*a[3]+b[10]*a[4]+b[30]*a[5]-b[19]*a[6]+b[17]*a[7]-b[16]*a[8]-b[31]*a[9]+b[4]*a[10]-b[3]*a[11]-b[25]*a[12]+b[2]*a[13]+b[24]*a[14]-b[23]*a[15]+b[8]*a[16]-b[7]*a[17]-b[29]*a[18]+b[6]*a[19]+b[28]*a[20]-b[27]*a[21]+b[0]*a[22]+b[15]*a[23]-b[14]*a[24]+b[12]*a[25]-b[1]*a[26]-b[21]*a[27]+b[20]*a[28]-b[18]*a[29]-b[5]*a[30]-b[9]*a[31] res[23]=b[23]*a[0]+b[27]*a[1]+b[14]*a[2]-b[12]*a[3]+b[30]*a[4]+b[10]*a[5]-b[20]*a[6]+b[18]*a[7]-b[31]*a[8]-b[16]*a[9]+b[5]*a[10]-b[25]*a[11]-b[3]*a[12]+b[24]*a[13]+b[2]*a[14]-b[22]*a[15]+b[9]*a[16]-b[29]*a[17]-b[7]*a[18]+b[28]*a[19]+b[6]*a[20]-b[26]*a[21]+b[15]*a[22]+b[0]*a[23]-b[13]*a[24]+b[11]*a[25]-b[21]*a[26]-b[1]*a[27]+b[19]*a[28]-b[17]*a[29]-b[4]*a[30]-b[8]*a[31] res[24]=b[24]*a[0]+b[28]*a[1]+b[15]*a[2]-b[30]*a[3]-b[12]*a[4]+b[11]*a[5]-b[21]*a[6]+b[31]*a[7]+b[18]*a[8]-b[17]*a[9]+b[25]*a[10]+b[5]*a[11]-b[4]*a[12]-b[23]*a[13]+b[22]*a[14]+b[2]*a[15]+b[29]*a[16]+b[9]*a[17]-b[8]*a[18]-b[27]*a[19]+b[26]*a[20]+b[6]*a[21]-b[14]*a[22]+b[13]*a[23]+b[0]*a[24]-b[10]*a[25]+b[20]*a[26]-b[19]*a[27]-b[1]*a[28]+b[16]*a[29]+b[3]*a[30]+b[7]*a[31] res[25]=b[25]*a[0]+b[29]*a[1]+b[30]*a[2]+b[15]*a[3]-b[14]*a[4]+b[13]*a[5]-b[31]*a[6]-b[21]*a[7]+b[20]*a[8]-b[19]*a[9]-b[24]*a[10]+b[23]*a[11]-b[22]*a[12]+b[5]*a[13]-b[4]*a[14]+b[3]*a[15]-b[28]*a[16]+b[27]*a[17]-b[26]*a[18]+b[9]*a[19]-b[8]*a[20]+b[7]*a[21]+b[12]*a[22]-b[11]*a[23]+b[10]*a[24]+b[0]*a[25]-b[18]*a[26]+b[17]*a[27]-b[16]*a[28]-b[1]*a[29]-b[2]*a[30]-b[6]*a[31] res[26]=b[26]*a[0]+b[22]*a[1]-b[19]*a[2]+b[17]*a[3]-b[16]*a[4]-b[31]*a[5]+b[13]*a[6]-b[11]*a[7]+b[10]*a[8]+b[30]*a[9]+b[8]*a[10]-b[7]*a[11]-b[29]*a[12]+b[6]*a[13]+b[28]*a[14]-b[27]*a[15]+b[4]*a[16]-b[3]*a[17]-b[25]*a[18]+b[2]*a[19]+b[24]*a[20]-b[23]*a[21]-b[1]*a[22]-b[21]*a[23]+b[20]*a[24]-b[18]*a[25]+b[0]*a[26]+b[15]*a[27]-b[14]*a[28]+b[12]*a[29]-b[9]*a[30]-b[5]*a[31] res[27]=b[27]*a[0]+b[23]*a[1]-b[20]*a[2]+b[18]*a[3]-b[31]*a[4]-b[16]*a[5]+b[14]*a[6]-b[12]*a[7]+b[30]*a[8]+b[10]*a[9]+b[9]*a[10]-b[29]*a[11]-b[7]*a[12]+b[28]*a[13]+b[6]*a[14]-b[26]*a[15]+b[5]*a[16]-b[25]*a[17]-b[3]*a[18]+b[24]*a[19]+b[2]*a[20]-b[22]*a[21]-b[21]*a[22]-b[1]*a[23]+b[19]*a[24]-b[17]*a[25]+b[15]*a[26]+b[0]*a[27]-b[13]*a[28]+b[11]*a[29]-b[8]*a[30]-b[4]*a[31] res[28]=b[28]*a[0]+b[24]*a[1]-b[21]*a[2]+b[31]*a[3]+b[18]*a[4]-b[17]*a[5]+b[15]*a[6]-b[30]*a[7]-b[12]*a[8]+b[11]*a[9]+b[29]*a[10]+b[9]*a[11]-b[8]*a[12]-b[27]*a[13]+b[26]*a[14]+b[6]*a[15]+b[25]*a[16]+b[5]*a[17]-b[4]*a[18]-b[23]*a[19]+b[22]*a[20]+b[2]*a[21]+b[20]*a[22]-b[19]*a[23]-b[1]*a[24]+b[16]*a[25]-b[14]*a[26]+b[13]*a[27]+b[0]*a[28]-b[10]*a[29]+b[7]*a[30]+b[3]*a[31] res[29]=b[29]*a[0]+b[25]*a[1]-b[31]*a[2]-b[21]*a[3]+b[20]*a[4]-b[19]*a[5]+b[30]*a[6]+b[15]*a[7]-b[14]*a[8]+b[13]*a[9]-b[28]*a[10]+b[27]*a[11]-b[26]*a[12]+b[9]*a[13]-b[8]*a[14]+b[7]*a[15]-b[24]*a[16]+b[23]*a[17]-b[22]*a[18]+b[5]*a[19]-b[4]*a[20]+b[3]*a[21]-b[18]*a[22]+b[17]*a[23]-b[16]*a[24]-b[1]*a[25]+b[12]*a[26]-b[11]*a[27]+b[10]*a[28]+b[0]*a[29]-b[6]*a[30]-b[2]*a[31] res[30]=b[30]*a[0]+b[31]*a[1]+b[25]*a[2]-b[24]*a[3]+b[23]*a[4]-b[22]*a[5]-b[29]*a[6]+b[28]*a[7]-b[27]*a[8]+b[26]*a[9]+b[15]*a[10]-b[14]*a[11]+b[13]*a[12]+b[12]*a[13]-b[11]*a[14]+b[10]*a[15]+b[21]*a[16]-b[20]*a[17]+b[19]*a[18]+b[18]*a[19]-b[17]*a[20]+b[16]*a[21]+b[5]*a[22]-b[4]*a[23]+b[3]*a[24]-b[2]*a[25]-b[9]*a[26]+b[8]*a[27]-b[7]*a[28]+b[6]*a[29]+b[0]*a[30]+b[1]*a[31] res[31]=b[31]*a[0]+b[30]*a[1]-b[29]*a[2]+b[28]*a[3]-b[27]*a[4]+b[26]*a[5]+b[25]*a[6]-b[24]*a[7]+b[23]*a[8]-b[22]*a[9]+b[21]*a[10]-b[20]*a[11]+b[19]*a[12]+b[18]*a[13]-b[17]*a[14]+b[16]*a[15]+b[15]*a[16]-b[14]*a[17]+b[13]*a[18]+b[12]*a[19]-b[11]*a[20]+b[10]*a[21]-b[9]*a[22]+b[8]*a[23]-b[7]*a[24]+b[6]*a[25]+b[5]*a[26]-b[4]*a[27]+b[3]*a[28]-b[2]*a[29]+b[1]*a[30]+b[0]*a[31] return CGA.fromarray(res) __rmul__=__mul__ def __xor__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0] res[1]=b[1]*a[0]+b[0]*a[1] res[2]=b[2]*a[0]+b[0]*a[2] res[3]=b[3]*a[0]+b[0]*a[3] res[4]=b[4]*a[0]+b[0]*a[4] res[5]=b[5]*a[0]+b[0]*a[5] res[6]=b[6]*a[0]+b[2]*a[1]-b[1]*a[2]+b[0]*a[6] res[7]=b[7]*a[0]+b[3]*a[1]-b[1]*a[3]+b[0]*a[7] res[8]=b[8]*a[0]+b[4]*a[1]-b[1]*a[4]+b[0]*a[8] res[9]=b[9]*a[0]+b[5]*a[1]-b[1]*a[5]+b[0]*a[9] res[10]=b[10]*a[0]+b[3]*a[2]-b[2]*a[3]+b[0]*a[10] res[11]=b[11]*a[0]+b[4]*a[2]-b[2]*a[4]+b[0]*a[11] res[12]=b[12]*a[0]+b[5]*a[2]-b[2]*a[5]+b[0]*a[12] res[13]=b[13]*a[0]+b[4]*a[3]-b[3]*a[4]+b[0]*a[13] res[14]=b[14]*a[0]+b[5]*a[3]-b[3]*a[5]+b[0]*a[14] res[15]=b[15]*a[0]+b[5]*a[4]-b[4]*a[5]+b[0]*a[15] res[16]=b[16]*a[0]+b[10]*a[1]-b[7]*a[2]+b[6]*a[3]+b[3]*a[6]-b[2]*a[7]+b[1]*a[10]+b[0]*a[16] res[17]=b[17]*a[0]+b[11]*a[1]-b[8]*a[2]+b[6]*a[4]+b[4]*a[6]-b[2]*a[8]+b[1]*a[11]+b[0]*a[17] res[18]=b[18]*a[0]+b[12]*a[1]-b[9]*a[2]+b[6]*a[5]+b[5]*a[6]-b[2]*a[9]+b[1]*a[12]+b[0]*a[18] res[19]=b[19]*a[0]+b[13]*a[1]-b[8]*a[3]+b[7]*a[4]+b[4]*a[7]-b[3]*a[8]+b[1]*a[13]+b[0]*a[19] res[20]=b[20]*a[0]+b[14]*a[1]-b[9]*a[3]+b[7]*a[5]+b[5]*a[7]-b[3]*a[9]+b[1]*a[14]+b[0]*a[20] res[21]=b[21]*a[0]+b[15]*a[1]-b[9]*a[4]+b[8]*a[5]+b[5]*a[8]-b[4]*a[9]+b[1]*a[15]+b[0]*a[21] res[22]=b[22]*a[0]+b[13]*a[2]-b[11]*a[3]+b[10]*a[4]+b[4]*a[10]-b[3]*a[11]+b[2]*a[13]+b[0]*a[22] res[23]=b[23]*a[0]+b[14]*a[2]-b[12]*a[3]+b[10]*a[5]+b[5]*a[10]-b[3]*a[12]+b[2]*a[14]+b[0]*a[23] res[24]=b[24]*a[0]+b[15]*a[2]-b[12]*a[4]+b[11]*a[5]+b[5]*a[11]-b[4]*a[12]+b[2]*a[15]+b[0]*a[24] res[25]=b[25]*a[0]+b[15]*a[3]-b[14]*a[4]+b[13]*a[5]+b[5]*a[13]-b[4]*a[14]+b[3]*a[15]+b[0]*a[25] res[26]=b[26]*a[0]+b[22]*a[1]-b[19]*a[2]+b[17]*a[3]-b[16]*a[4]+b[13]*a[6]-b[11]*a[7]+b[10]*a[8]+b[8]*a[10]-b[7]*a[11]+b[6]*a[13]+b[4]*a[16]-b[3]*a[17]+b[2]*a[19]-b[1]*a[22]+b[0]*a[26] res[27]=b[27]*a[0]+b[23]*a[1]-b[20]*a[2]+b[18]*a[3]-b[16]*a[5]+b[14]*a[6]-b[12]*a[7]+b[10]*a[9]+b[9]*a[10]-b[7]*a[12]+b[6]*a[14]+b[5]*a[16]-b[3]*a[18]+b[2]*a[20]-b[1]*a[23]+b[0]*a[27] res[28]=b[28]*a[0]+b[24]*a[1]-b[21]*a[2]+b[18]*a[4]-b[17]*a[5]+b[15]*a[6]-b[12]*a[8]+b[11]*a[9]+b[9]*a[11]-b[8]*a[12]+b[6]*a[15]+b[5]*a[17]-b[4]*a[18]+b[2]*a[21]-b[1]*a[24]+b[0]*a[28] res[29]=b[29]*a[0]+b[25]*a[1]-b[21]*a[3]+b[20]*a[4]-b[19]*a[5]+b[15]*a[7]-b[14]*a[8]+b[13]*a[9]+b[9]*a[13]-b[8]*a[14]+b[7]*a[15]+b[5]*a[19]-b[4]*a[20]+b[3]*a[21]-b[1]*a[25]+b[0]*a[29] res[30]=b[30]*a[0]+b[25]*a[2]-b[24]*a[3]+b[23]*a[4]-b[22]*a[5]+b[15]*a[10]-b[14]*a[11]+b[13]*a[12]+b[12]*a[13]-b[11]*a[14]+b[10]*a[15]+b[5]*a[22]-b[4]*a[23]+b[3]*a[24]-b[2]*a[25]+b[0]*a[30] res[31]=b[31]*a[0]+b[30]*a[1]-b[29]*a[2]+b[28]*a[3]-b[27]*a[4]+b[26]*a[5]+b[25]*a[6]-b[24]*a[7]+b[23]*a[8]-b[22]*a[9]+b[21]*a[10]-b[20]*a[11]+b[19]*a[12]+b[18]*a[13]-b[17]*a[14]+b[16]*a[15]+b[15]*a[16]-b[14]*a[17]+b[13]*a[18]+b[12]*a[19]-b[11]*a[20]+b[10]*a[21]-b[9]*a[22]+b[8]*a[23]-b[7]*a[24]+b[6]*a[25]+b[5]*a[26]-b[4]*a[27]+b[3]*a[28]-b[2]*a[29]+b[1]*a[30]+b[0]*a[31] return CGA.fromarray(res) def __and__(a,b): res = a.mvec.copy() res[31]=1*(a[31]*b[31]) res[30]=1*(a[30]*b[31]+a[31]*b[30]) res[29]=-1*(a[29]*-1*b[31]+a[31]*b[29]*-1) res[28]=1*(a[28]*b[31]+a[31]*b[28]) res[27]=-1*(a[27]*-1*b[31]+a[31]*b[27]*-1) res[26]=1*(a[26]*b[31]+a[31]*b[26]) res[25]=1*(a[25]*b[31]+a[29]*-1*b[30]-a[30]*b[29]*-1+a[31]*b[25]) res[24]=-1*(a[24]*-1*b[31]+a[28]*b[30]-a[30]*b[28]+a[31]*b[24]*-1) res[23]=1*(a[23]*b[31]+a[27]*-1*b[30]-a[30]*b[27]*-1+a[31]*b[23]) res[22]=-1*(a[22]*-1*b[31]+a[26]*b[30]-a[30]*b[26]+a[31]*b[22]*-1) res[21]=1*(a[21]*b[31]+a[28]*b[29]*-1-a[29]*-1*b[28]+a[31]*b[21]) res[20]=-1*(a[20]*-1*b[31]+a[27]*-1*b[29]*-1-a[29]*-1*b[27]*-1+a[31]*b[20]*-1) res[19]=1*(a[19]*b[31]+a[26]*b[29]*-1-a[29]*-1*b[26]+a[31]*b[19]) res[18]=1*(a[18]*b[31]+a[27]*-1*b[28]-a[28]*b[27]*-1+a[31]*b[18]) res[17]=-1*(a[17]*-1*b[31]+a[26]*b[28]-a[28]*b[26]+a[31]*b[17]*-1) res[16]=1*(a[16]*b[31]+a[26]*b[27]*-1-a[27]*-1*b[26]+a[31]*b[16]) res[15]=1*(a[15]*b[31]+a[21]*b[30]-a[24]*-1*b[29]*-1+a[25]*b[28]+a[28]*b[25]-a[29]*-1*b[24]*-1+a[30]*b[21]+a[31]*b[15]) res[14]=-1*(a[14]*-1*b[31]+a[20]*-1*b[30]-a[23]*b[29]*-1+a[25]*b[27]*-1+a[27]*-1*b[25]-a[29]*-1*b[23]+a[30]*b[20]*-1+a[31]*b[14]*-1) res[13]=1*(a[13]*b[31]+a[19]*b[30]-a[22]*-1*b[29]*-1+a[25]*b[26]+a[26]*b[25]-a[29]*-1*b[22]*-1+a[30]*b[19]+a[31]*b[13]) res[12]=1*(a[12]*b[31]+a[18]*b[30]-a[23]*b[28]+a[24]*-1*b[27]*-1+a[27]*-1*b[24]*-1-a[28]*b[23]+a[30]*b[18]+a[31]*b[12]) res[11]=-1*(a[11]*-1*b[31]+a[17]*-1*b[30]-a[22]*-1*b[28]+a[24]*-1*b[26]+a[26]*b[24]*-1-a[28]*b[22]*-1+a[30]*b[17]*-1+a[31]*b[11]*-1) res[10]=1*(a[10]*b[31]+a[16]*b[30]-a[22]*-1*b[27]*-1+a[23]*b[26]+a[26]*b[23]-a[27]*-1*b[22]*-1+a[30]*b[16]+a[31]*b[10]) res[9]=-1*(a[9]*-1*b[31]+a[18]*b[29]*-1-a[20]*-1*b[28]+a[21]*b[27]*-1+a[27]*-1*b[21]-a[28]*b[20]*-1+a[29]*-1*b[18]+a[31]*b[9]*-1) res[8]=1*(a[8]*b[31]+a[17]*-1*b[29]*-1-a[19]*b[28]+a[21]*b[26]+a[26]*b[21]-a[28]*b[19]+a[29]*-1*b[17]*-1+a[31]*b[8]) res[7]=-1*(a[7]*-1*b[31]+a[16]*b[29]*-1-a[19]*b[27]*-1+a[20]*-1*b[26]+a[26]*b[20]*-1-a[27]*-1*b[19]+a[29]*-1*b[16]+a[31]*b[7]*-1) res[6]=1*(a[6]*b[31]+a[16]*b[28]-a[17]*-1*b[27]*-1+a[18]*b[26]+a[26]*b[18]-a[27]*-1*b[17]*-1+a[28]*b[16]+a[31]*b[6]) res[5]=1*(a[5]*b[31]+a[9]*-1*b[30]-a[12]*b[29]*-1+a[14]*-1*b[28]-a[15]*b[27]*-1+a[18]*b[25]-a[20]*-1*b[24]*-1+a[21]*b[23]+a[23]*b[21]-a[24]*-1*b[20]*-1+a[25]*b[18]+a[27]*-1*b[15]-a[28]*b[14]*-1+a[29]*-1*b[12]-a[30]*b[9]*-1+a[31]*b[5]) res[4]=-1*(a[4]*-1*b[31]+a[8]*b[30]-a[11]*-1*b[29]*-1+a[13]*b[28]-a[15]*b[26]+a[17]*-1*b[25]-a[19]*b[24]*-1+a[21]*b[22]*-1+a[22]*-1*b[21]-a[24]*-1*b[19]+a[25]*b[17]*-1+a[26]*b[15]-a[28]*b[13]+a[29]*-1*b[11]*-1-a[30]*b[8]+a[31]*b[4]*-1) res[3]=1*(a[3]*b[31]+a[7]*-1*b[30]-a[10]*b[29]*-1+a[13]*b[27]*-1-a[14]*-1*b[26]+a[16]*b[25]-a[19]*b[23]+a[20]*-1*b[22]*-1+a[22]*-1*b[20]*-1-a[23]*b[19]+a[25]*b[16]+a[26]*b[14]*-1-a[27]*-1*b[13]+a[29]*-1*b[10]-a[30]*b[7]*-1+a[31]*b[3]) res[2]=-1*(a[2]*-1*b[31]+a[6]*b[30]-a[10]*b[28]+a[11]*-1*b[27]*-1-a[12]*b[26]+a[16]*b[24]*-1-a[17]*-1*b[23]+a[18]*b[22]*-1+a[22]*-1*b[18]-a[23]*b[17]*-1+a[24]*-1*b[16]+a[26]*b[12]-a[27]*-1*b[11]*-1+a[28]*b[10]-a[30]*b[6]+a[31]*b[2]*-1) res[1]=1*(a[1]*b[31]+a[6]*b[29]*-1-a[7]*-1*b[28]+a[8]*b[27]*-1-a[9]*-1*b[26]+a[16]*b[21]-a[17]*-1*b[20]*-1+a[18]*b[19]+a[19]*b[18]-a[20]*-1*b[17]*-1+a[21]*b[16]+a[26]*b[9]*-1-a[27]*-1*b[8]+a[28]*b[7]*-1-a[29]*-1*b[6]+a[31]*b[1]) res[0]=1*(a[0]*b[31]+a[1]*b[30]-a[2]*-1*b[29]*-1+a[3]*b[28]-a[4]*-1*b[27]*-1+a[5]*b[26]+a[6]*b[25]-a[7]*-1*b[24]*-1+a[8]*b[23]-a[9]*-1*b[22]*-1+a[10]*b[21]-a[11]*-1*b[20]*-1+a[12]*b[19]+a[13]*b[18]-a[14]*-1*b[17]*-1+a[15]*b[16]+a[16]*b[15]-a[17]*-1*b[14]*-1+a[18]*b[13]+a[19]*b[12]-a[20]*-1*b[11]*-1+a[21]*b[10]-a[22]*-1*b[9]*-1+a[23]*b[8]-a[24]*-1*b[7]*-1+a[25]*b[6]+a[26]*b[5]-a[27]*-1*b[4]*-1+a[28]*b[3]-a[29]*-1*b[2]*-1+a[30]*b[1]+a[31]*b[0]) return CGA.fromarray(res) def __or__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0]+b[1]*a[1]+b[2]*a[2]+b[3]*a[3]+b[4]*a[4]-b[5]*a[5]-b[6]*a[6]-b[7]*a[7]-b[8]*a[8]+b[9]*a[9]-b[10]*a[10]-b[11]*a[11]+b[12]*a[12]-b[13]*a[13]+b[14]*a[14]+b[15]*a[15]-b[16]*a[16]-b[17]*a[17]+b[18]*a[18]-b[19]*a[19]+b[20]*a[20]+b[21]*a[21]-b[22]*a[22]+b[23]*a[23]+b[24]*a[24]+b[25]*a[25]+b[26]*a[26]-b[27]*a[27]-b[28]*a[28]-b[29]*a[29]-b[30]*a[30]-b[31]*a[31] res[1]=b[1]*a[0]+b[0]*a[1]-b[6]*a[2]-b[7]*a[3]-b[8]*a[4]+b[9]*a[5]+b[2]*a[6]+b[3]*a[7]+b[4]*a[8]-b[5]*a[9]-b[16]*a[10]-b[17]*a[11]+b[18]*a[12]-b[19]*a[13]+b[20]*a[14]+b[21]*a[15]-b[10]*a[16]-b[11]*a[17]+b[12]*a[18]-b[13]*a[19]+b[14]*a[20]+b[15]*a[21]+b[26]*a[22]-b[27]*a[23]-b[28]*a[24]-b[29]*a[25]-b[22]*a[26]+b[23]*a[27]+b[24]*a[28]+b[25]*a[29]-b[31]*a[30]-b[30]*a[31] res[2]=b[2]*a[0]+b[6]*a[1]+b[0]*a[2]-b[10]*a[3]-b[11]*a[4]+b[12]*a[5]-b[1]*a[6]+b[16]*a[7]+b[17]*a[8]-b[18]*a[9]+b[3]*a[10]+b[4]*a[11]-b[5]*a[12]-b[22]*a[13]+b[23]*a[14]+b[24]*a[15]+b[7]*a[16]+b[8]*a[17]-b[9]*a[18]-b[26]*a[19]+b[27]*a[20]+b[28]*a[21]-b[13]*a[22]+b[14]*a[23]+b[15]*a[24]-b[30]*a[25]+b[19]*a[26]-b[20]*a[27]-b[21]*a[28]+b[31]*a[29]+b[25]*a[30]+b[29]*a[31] res[3]=b[3]*a[0]+b[7]*a[1]+b[10]*a[2]+b[0]*a[3]-b[13]*a[4]+b[14]*a[5]-b[16]*a[6]-b[1]*a[7]+b[19]*a[8]-b[20]*a[9]-b[2]*a[10]+b[22]*a[11]-b[23]*a[12]+b[4]*a[13]-b[5]*a[14]+b[25]*a[15]-b[6]*a[16]+b[26]*a[17]-b[27]*a[18]+b[8]*a[19]-b[9]*a[20]+b[29]*a[21]+b[11]*a[22]-b[12]*a[23]+b[30]*a[24]+b[15]*a[25]-b[17]*a[26]+b[18]*a[27]-b[31]*a[28]-b[21]*a[29]-b[24]*a[30]-b[28]*a[31] res[4]=b[4]*a[0]+b[8]*a[1]+b[11]*a[2]+b[13]*a[3]+b[0]*a[4]+b[15]*a[5]-b[17]*a[6]-b[19]*a[7]-b[1]*a[8]-b[21]*a[9]-b[22]*a[10]-b[2]*a[11]-b[24]*a[12]-b[3]*a[13]-b[25]*a[14]-b[5]*a[15]-b[26]*a[16]-b[6]*a[17]-b[28]*a[18]-b[7]*a[19]-b[29]*a[20]-b[9]*a[21]-b[10]*a[22]-b[30]*a[23]-b[12]*a[24]-b[14]*a[25]+b[16]*a[26]+b[31]*a[27]+b[18]*a[28]+b[20]*a[29]+b[23]*a[30]+b[27]*a[31] res[5]=b[5]*a[0]+b[9]*a[1]+b[12]*a[2]+b[14]*a[3]+b[15]*a[4]+b[0]*a[5]-b[18]*a[6]-b[20]*a[7]-b[21]*a[8]-b[1]*a[9]-b[23]*a[10]-b[24]*a[11]-b[2]*a[12]-b[25]*a[13]-b[3]*a[14]-b[4]*a[15]-b[27]*a[16]-b[28]*a[17]-b[6]*a[18]-b[29]*a[19]-b[7]*a[20]-b[8]*a[21]-b[30]*a[22]-b[10]*a[23]-b[11]*a[24]-b[13]*a[25]+b[31]*a[26]+b[16]*a[27]+b[17]*a[28]+b[19]*a[29]+b[22]*a[30]+b[26]*a[31] res[6]=b[6]*a[0]+b[16]*a[3]+b[17]*a[4]-b[18]*a[5]+b[0]*a[6]-b[26]*a[13]+b[27]*a[14]+b[28]*a[15]+b[3]*a[16]+b[4]*a[17]-b[5]*a[18]+b[31]*a[25]-b[13]*a[26]+b[14]*a[27]+b[15]*a[28]+b[25]*a[31] res[7]=b[7]*a[0]-b[16]*a[2]+b[19]*a[4]-b[20]*a[5]+b[0]*a[7]+b[26]*a[11]-b[27]*a[12]+b[29]*a[15]-b[2]*a[16]+b[4]*a[19]-b[5]*a[20]-b[31]*a[24]+b[11]*a[26]-b[12]*a[27]+b[15]*a[29]-b[24]*a[31] res[8]=b[8]*a[0]-b[17]*a[2]-b[19]*a[3]-b[21]*a[5]+b[0]*a[8]-b[26]*a[10]-b[28]*a[12]-b[29]*a[14]-b[2]*a[17]-b[3]*a[19]-b[5]*a[21]+b[31]*a[23]-b[10]*a[26]-b[12]*a[28]-b[14]*a[29]+b[23]*a[31] res[9]=b[9]*a[0]-b[18]*a[2]-b[20]*a[3]-b[21]*a[4]+b[0]*a[9]-b[27]*a[10]-b[28]*a[11]-b[29]*a[13]-b[2]*a[18]-b[3]*a[20]-b[4]*a[21]+b[31]*a[22]-b[10]*a[27]-b[11]*a[28]-b[13]*a[29]+b[22]*a[31] res[10]=b[10]*a[0]+b[16]*a[1]+b[22]*a[4]-b[23]*a[5]-b[26]*a[8]+b[27]*a[9]+b[0]*a[10]+b[30]*a[15]+b[1]*a[16]+b[31]*a[21]+b[4]*a[22]-b[5]*a[23]-b[8]*a[26]+b[9]*a[27]+b[15]*a[30]+b[21]*a[31] res[11]=b[11]*a[0]+b[17]*a[1]-b[22]*a[3]-b[24]*a[5]+b[26]*a[7]+b[28]*a[9]+b[0]*a[11]-b[30]*a[14]+b[1]*a[17]-b[31]*a[20]-b[3]*a[22]-b[5]*a[24]+b[7]*a[26]+b[9]*a[28]-b[14]*a[30]-b[20]*a[31] res[12]=b[12]*a[0]+b[18]*a[1]-b[23]*a[3]-b[24]*a[4]+b[27]*a[7]+b[28]*a[8]+b[0]*a[12]-b[30]*a[13]+b[1]*a[18]-b[31]*a[19]-b[3]*a[23]-b[4]*a[24]+b[7]*a[27]+b[8]*a[28]-b[13]*a[30]-b[19]*a[31] res[13]=b[13]*a[0]+b[19]*a[1]+b[22]*a[2]-b[25]*a[5]-b[26]*a[6]+b[29]*a[9]+b[30]*a[12]+b[0]*a[13]+b[31]*a[18]+b[1]*a[19]+b[2]*a[22]-b[5]*a[25]-b[6]*a[26]+b[9]*a[29]+b[12]*a[30]+b[18]*a[31] res[14]=b[14]*a[0]+b[20]*a[1]+b[23]*a[2]-b[25]*a[4]-b[27]*a[6]+b[29]*a[8]+b[30]*a[11]+b[0]*a[14]+b[31]*a[17]+b[1]*a[20]+b[2]*a[23]-b[4]*a[25]-b[6]*a[27]+b[8]*a[29]+b[11]*a[30]+b[17]*a[31] res[15]=b[15]*a[0]+b[21]*a[1]+b[24]*a[2]+b[25]*a[3]-b[28]*a[6]-b[29]*a[7]-b[30]*a[10]+b[0]*a[15]-b[31]*a[16]+b[1]*a[21]+b[2]*a[24]+b[3]*a[25]-b[6]*a[28]-b[7]*a[29]-b[10]*a[30]-b[16]*a[31] res[16]=b[16]*a[0]-b[26]*a[4]+b[27]*a[5]+b[31]*a[15]+b[0]*a[16]+b[4]*a[26]-b[5]*a[27]+b[15]*a[31] res[17]=b[17]*a[0]+b[26]*a[3]+b[28]*a[5]-b[31]*a[14]+b[0]*a[17]-b[3]*a[26]-b[5]*a[28]-b[14]*a[31] res[18]=b[18]*a[0]+b[27]*a[3]+b[28]*a[4]-b[31]*a[13]+b[0]*a[18]-b[3]*a[27]-b[4]*a[28]-b[13]*a[31] res[19]=b[19]*a[0]-b[26]*a[2]+b[29]*a[5]+b[31]*a[12]+b[0]*a[19]+b[2]*a[26]-b[5]*a[29]+b[12]*a[31] res[20]=b[20]*a[0]-b[27]*a[2]+b[29]*a[4]+b[31]*a[11]+b[0]*a[20]+b[2]*a[27]-b[4]*a[29]+b[11]*a[31] res[21]=b[21]*a[0]-b[28]*a[2]-b[29]*a[3]-b[31]*a[10]+b[0]*a[21]+b[2]*a[28]+b[3]*a[29]-b[10]*a[31] res[22]=b[22]*a[0]+b[26]*a[1]+b[30]*a[5]-b[31]*a[9]+b[0]*a[22]-b[1]*a[26]-b[5]*a[30]-b[9]*a[31] res[23]=b[23]*a[0]+b[27]*a[1]+b[30]*a[4]-b[31]*a[8]+b[0]*a[23]-b[1]*a[27]-b[4]*a[30]-b[8]*a[31] res[24]=b[24]*a[0]+b[28]*a[1]-b[30]*a[3]+b[31]*a[7]+b[0]*a[24]-b[1]*a[28]+b[3]*a[30]+b[7]*a[31] res[25]=b[25]*a[0]+b[29]*a[1]+b[30]*a[2]-b[31]*a[6]+b[0]*a[25]-b[1]*a[29]-b[2]*a[30]-b[6]*a[31] res[26]=b[26]*a[0]-b[31]*a[5]+b[0]*a[26]-b[5]*a[31] res[27]=b[27]*a[0]-b[31]*a[4]+b[0]*a[27]-b[4]*a[31] res[28]=b[28]*a[0]+b[31]*a[3]+b[0]*a[28]+b[3]*a[31] res[29]=b[29]*a[0]-b[31]*a[2]+b[0]*a[29]-b[2]*a[31] res[30]=b[30]*a[0]+b[31]*a[1]+b[0]*a[30]+b[1]*a[31] res[31]=b[31]*a[0]+b[0]*a[31] return CGA.fromarray(res) def __add__(a,b): """CGA.Add Multivector addition """ if type(b) in (int, float): return a.adds(b) res = a.mvec.copy() res[0] = a[0]+b[0] res[1] = a[1]+b[1] res[2] = a[2]+b[2] res[3] = a[3]+b[3] res[4] = a[4]+b[4] res[5] = a[5]+b[5] res[6] = a[6]+b[6] res[7] = a[7]+b[7] res[8] = a[8]+b[8] res[9] = a[9]+b[9] res[10] = a[10]+b[10] res[11] = a[11]+b[11] res[12] = a[12]+b[12] res[13] = a[13]+b[13] res[14] = a[14]+b[14] res[15] = a[15]+b[15] res[16] = a[16]+b[16] res[17] = a[17]+b[17] res[18] = a[18]+b[18] res[19] = a[19]+b[19] res[20] = a[20]+b[20] res[21] = a[21]+b[21] res[22] = a[22]+b[22] res[23] = a[23]+b[23] res[24] = a[24]+b[24] res[25] = a[25]+b[25] res[26] = a[26]+b[26] res[27] = a[27]+b[27] res[28] = a[28]+b[28] res[29] = a[29]+b[29] res[30] = a[30]+b[30] res[31] = a[31]+b[31] return CGA.fromarray(res) __radd__=__add__ def __sub__(a,b): """CGA.Sub Multivector subtraction """ if type(b) in (int, float): return a.subs(b) res = a.mvec.copy() res[0] = a[0]-b[0] res[1] = a[1]-b[1] res[2] = a[2]-b[2] res[3] = a[3]-b[3] res[4] = a[4]-b[4] res[5] = a[5]-b[5] res[6] = a[6]-b[6] res[7] = a[7]-b[7] res[8] = a[8]-b[8] res[9] = a[9]-b[9] res[10] = a[10]-b[10] res[11] = a[11]-b[11] res[12] = a[12]-b[12] res[13] = a[13]-b[13] res[14] = a[14]-b[14] res[15] = a[15]-b[15] res[16] = a[16]-b[16] res[17] = a[17]-b[17] res[18] = a[18]-b[18] res[19] = a[19]-b[19] res[20] = a[20]-b[20] res[21] = a[21]-b[21] res[22] = a[22]-b[22] res[23] = a[23]-b[23] res[24] = a[24]-b[24] res[25] = a[25]-b[25] res[26] = a[26]-b[26] res[27] = a[27]-b[27] res[28] = a[28]-b[28] res[29] = a[29]-b[29] res[30] = a[30]-b[30] res[31] = a[31]-b[31] return CGA.fromarray(res) def __rsub__(a,b): """CGA.Sub Multivector subtraction """ return b + -1 * a def smul(a,b): res = a.mvec.copy() res[0] = a*b[0] res[1] = a*b[1] res[2] = a*b[2] res[3] = a*b[3] res[4] = a*b[4] res[5] = a*b[5] res[6] = a*b[6] res[7] = a*b[7] res[8] = a*b[8] res[9] = a*b[9] res[10] = a*b[10] res[11] = a*b[11] res[12] = a*b[12] res[13] = a*b[13] res[14] = a*b[14] res[15] = a*b[15] res[16] = a*b[16] res[17] = a*b[17] res[18] = a*b[18] res[19] = a*b[19] res[20] = a*b[20] res[21] = a*b[21] res[22] = a*b[22] res[23] = a*b[23] res[24] = a*b[24] res[25] = a*b[25] res[26] = a*b[26] res[27] = a*b[27] res[28] = a*b[28] res[29] = a*b[29] res[30] = a*b[30] res[31] = a*b[31] return CGA.fromarray(res) def muls(a,b): res = a.mvec.copy() res[0] = a[0]*b res[1] = a[1]*b res[2] = a[2]*b res[3] = a[3]*b res[4] = a[4]*b res[5] = a[5]*b res[6] = a[6]*b res[7] = a[7]*b res[8] = a[8]*b res[9] = a[9]*b res[10] = a[10]*b res[11] = a[11]*b res[12] = a[12]*b res[13] = a[13]*b res[14] = a[14]*b res[15] = a[15]*b res[16] = a[16]*b res[17] = a[17]*b res[18] = a[18]*b res[19] = a[19]*b res[20] = a[20]*b res[21] = a[21]*b res[22] = a[22]*b res[23] = a[23]*b res[24] = a[24]*b res[25] = a[25]*b res[26] = a[26]*b res[27] = a[27]*b res[28] = a[28]*b res[29] = a[29]*b res[30] = a[30]*b res[31] = a[31]*b return CGA.fromarray(res) def sadd(a,b): res = a.mvec.copy() res[0] = a+b[0] res[1] = b[1] res[2] = b[2] res[3] = b[3] res[4] = b[4] res[5] = b[5] res[6] = b[6] res[7] = b[7] res[8] = b[8] res[9] = b[9] res[10] = b[10] res[11] = b[11] res[12] = b[12] res[13] = b[13] res[14] = b[14] res[15] = b[15] res[16] = b[16] res[17] = b[17] res[18] = b[18] res[19] = b[19] res[20] = b[20] res[21] = b[21] res[22] = b[22] res[23] = b[23] res[24] = b[24] res[25] = b[25] res[26] = b[26] res[27] = b[27] res[28] = b[28] res[29] = b[29] res[30] = b[30] res[31] = b[31] return CGA.fromarray(res) def adds(a,b): res = a.mvec.copy() res[0] = a[0]+b res[1] = a[1] res[2] = a[2] res[3] = a[3] res[4] = a[4] res[5] = a[5] res[6] = a[6] res[7] = a[7] res[8] = a[8] res[9] = a[9] res[10] = a[10] res[11] = a[11] res[12] = a[12] res[13] = a[13] res[14] = a[14] res[15] = a[15] res[16] = a[16] res[17] = a[17] res[18] = a[18] res[19] = a[19] res[20] = a[20] res[21] = a[21] res[22] = a[22] res[23] = a[23] res[24] = a[24] res[25] = a[25] res[26] = a[26] res[27] = a[27] res[28] = a[28] res[29] = a[29] res[30] = a[30] res[31] = a[31] return CGA.fromarray(res) def ssub(a,b): res = a.mvec.copy() res[0] = a-b[0] res[1] = -b[1] res[2] = -b[2] res[3] = -b[3] res[4] = -b[4] res[5] = -b[5] res[6] = -b[6] res[7] = -b[7] res[8] = -b[8] res[9] = -b[9] res[10] = -b[10] res[11] = -b[11] res[12] = -b[12] res[13] = -b[13] res[14] = -b[14] res[15] = -b[15] res[16] = -b[16] res[17] = -b[17] res[18] = -b[18] res[19] = -b[19] res[20] = -b[20] res[21] = -b[21] res[22] = -b[22] res[23] = -b[23] res[24] = -b[24] res[25] = -b[25] res[26] = -b[26] res[27] = -b[27] res[28] = -b[28] res[29] = -b[29] res[30] = -b[30] res[31] = -b[31] return CGA.fromarray(res) def subs(a,b): res = a.mvec.copy() res[0] = a[0]-b res[1] = a[1] res[2] = a[2] res[3] = a[3] res[4] = a[4] res[5] = a[5] res[6] = a[6] res[7] = a[7] res[8] = a[8] res[9] = a[9] res[10] = a[10] res[11] = a[11] res[12] = a[12] res[13] = a[13] res[14] = a[14] res[15] = a[15] res[16] = a[16] res[17] = a[17] res[18] = a[18] res[19] = a[19] res[20] = a[20] res[21] = a[21] res[22] = a[22] res[23] = a[23] res[24] = a[24] res[25] = a[25] res[26] = a[26] res[27] = a[27] res[28] = a[28] res[29] = a[29] res[30] = a[30] res[31] = a[31] return CGA.fromarray(res) def norm(a): return abs((a * a.Conjugate())[0])**0.5 def inorm(a): return a.Dual().norm() def normalized(a): return a * (1 / a.norm()) if __name__ == '__main__': # CGA is point based. Vectors are points. E1 = CGA(1.0, 1) E2 = CGA(1.0, 2) E3 = CGA(1.0, 3) E4 = CGA(1.0, 4) E5 = CGA(1.0, 5) EO = E4 + E5 EI = (E5 - E4) * 0.5 def up(x, y, z): return x * E1 + y * E2 + z * E3 + 0.5 * (x * x + y * y + z * z) * EI + EO PX = up(1, 2, 3) LINE = PX ^ EO ^ EI SPHERE = (EO - EI).Dual() # output some numbers. print("a point :", str(PX)) print("a line :", str(LINE)) print("a sphere :", str(SPHERE))
{ "repo_name": "enkimute/ganja.js", "path": "codegen/python/cga.py", "copies": "1", "size": "39258", "license": "mit", "hash": -4138712392566444500, "line_mean": 53.6008344924, "line_max": 454, "alpha_frac": 0.4281929798, "autogenerated": false, "ratio": 1.7332450331125828, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.2661438012912583, "avg_score": null, "num_lines": null }
"""3D Projective Geometric Algebra. Written by a generator written by enki. """ __author__ = 'Enki' import math class C: def __init__(self, value=0, index=0): """Initiate a new C. Optional, the component index can be set with value. """ self.mvec = [0] * 2 self._base = ["1", "e1"] if (value != 0): self.mvec[index] = value @classmethod def fromarray(cls, array): """Initiate a new C from an array-like object. The first axis of the array is assumed to correspond to the elements of the algebra, and needs to have the same length. Any other dimensions are left unchanged, and should have simple operations such as addition and multiplication defined. NumPy arrays are therefore a perfect candidate. :param array: array-like object whose length is the dimension of the algebra. :return: new instance of C. """ self = cls() if len(array) != len(self): raise TypeError('length of array must be identical to the dimension ' 'of the algebra.') self.mvec = array return self def __str__(self): if isinstance(self.mvec, list): res = ' + '.join(filter(None, [("%.7f" % x).rstrip("0").rstrip(".")+(["",self._base[i]][i>0]) if abs(x) > 0.000001 else None for i,x in enumerate(self)])) else: # Assume array-like, redirect str conversion res = str(self.mvec) if (res == ''): return "0" return res def __getitem__(self, key): return self.mvec[key] def __setitem__(self, key, value): self.mvec[key] = value def __len__(self): return len(self.mvec) def __invert__(a): """C.Reverse Reverse the order of the basis blades. """ res = a.mvec.copy() res[0]=a[0] res[1]=a[1] return C.fromarray(res) def Dual(a): """C.Dual Poincare duality operator. """ res = a.mvec.copy() res[0]=-a[1] res[1]=a[0] return C.fromarray(res) def Conjugate(a): """C.Conjugate Clifford Conjugation """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] return C.fromarray(res) def Involute(a): """C.Involute Main involution """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] return C.fromarray(res) def __mul__(a,b): """C.Mul The geometric product. """ if type(b) in (int, float): return a.muls(b) res = a.mvec.copy() res[0]=b[0]*a[0]-b[1]*a[1] res[1]=b[1]*a[0]+b[0]*a[1] return C.fromarray(res) __rmul__=__mul__ def __xor__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0] res[1]=b[1]*a[0]+b[0]*a[1] return C.fromarray(res) def __and__(a,b): res = a.mvec.copy() res[1]=1*(a[1]*b[1]) res[0]=1*(a[0]*b[1]+a[1]*b[0]) return C.fromarray(res) def __or__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0]-b[1]*a[1] res[1]=b[1]*a[0]+b[0]*a[1] return C.fromarray(res) def __add__(a,b): """C.Add Multivector addition """ if type(b) in (int, float): return a.adds(b) res = a.mvec.copy() res[0] = a[0]+b[0] res[1] = a[1]+b[1] return C.fromarray(res) __radd__=__add__ def __sub__(a,b): """C.Sub Multivector subtraction """ if type(b) in (int, float): return a.subs(b) res = a.mvec.copy() res[0] = a[0]-b[0] res[1] = a[1]-b[1] return C.fromarray(res) def __rsub__(a,b): """C.Sub Multivector subtraction """ return b + -1 * a def smul(a,b): res = a.mvec.copy() res[0] = a*b[0] res[1] = a*b[1] return C.fromarray(res) def muls(a,b): res = a.mvec.copy() res[0] = a[0]*b res[1] = a[1]*b return C.fromarray(res) def sadd(a,b): res = a.mvec.copy() res[0] = a+b[0] res[1] = b[1] return C.fromarray(res) def adds(a,b): res = a.mvec.copy() res[0] = a[0]+b res[1] = a[1] return C.fromarray(res) def ssub(a,b): res = a.mvec.copy() res[0] = a-b[0] res[1] = -b[1] return C.fromarray(res) def subs(a,b): res = a.mvec.copy() res[0] = a[0]-b res[1] = a[1] return C.fromarray(res) def norm(a): return abs((a * a.Conjugate())[0])**0.5 def inorm(a): return a.Dual().norm() def normalized(a): return a * (1 / a.norm()) e1 = C(1.0, 1) if __name__ == '__main__': print("e1*e1 :", str(e1*e1)) print("pss :", str(e1)) print("pss*pss :", str(e1*e1))
{ "repo_name": "enkimute/ganja.js", "path": "codegen/python/c.py", "copies": "1", "size": "5174", "license": "mit", "hash": 6599231279891997000, "line_mean": 22.201793722, "line_max": 166, "alpha_frac": 0.4586393506, "autogenerated": false, "ratio": 3.1338582677165356, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4092497618316535, "avg_score": null, "num_lines": null }
"""3D Projective Geometric Algebra. Written by a generator written by enki. """ __author__ = 'Enki' import math class DUAL: def __init__(self, value=0, index=0): """Initiate a new DUAL. Optional, the component index can be set with value. """ self.mvec = [0] * 2 self._base = ["1", "e0"] if (value != 0): self.mvec[index] = value @classmethod def fromarray(cls, array): """Initiate a new DUAL from an array-like object. The first axis of the array is assumed to correspond to the elements of the algebra, and needs to have the same length. Any other dimensions are left unchanged, and should have simple operations such as addition and multiplication defined. NumPy arrays are therefore a perfect candidate. :param array: array-like object whose length is the dimension of the algebra. :return: new instance of DUAL. """ self = cls() if len(array) != len(self): raise TypeError('length of array must be identical to the dimension ' 'of the algebra.') self.mvec = array return self def __str__(self): if isinstance(self.mvec, list): res = ' + '.join(filter(None, [("%.7f" % x).rstrip("0").rstrip(".")+(["",self._base[i]][i>0]) if abs(x) > 0.000001 else None for i,x in enumerate(self)])) else: # Assume array-like, redirect str conversion res = str(self.mvec) if (res == ''): return "0" return res def __getitem__(self, key): return self.mvec[key] def __setitem__(self, key, value): self.mvec[key] = value def __len__(self): return len(self.mvec) def __invert__(a): """DUAL.Reverse Reverse the order of the basis blades. """ res = a.mvec.copy() res[0]=a[0] res[1]=a[1] return DUAL.fromarray(res) def Dual(a): """DUAL.Dual Poincare duality operator. """ res = a.mvec.copy() res[0]=a[1] res[1]=a[0] return DUAL.fromarray(res) def Conjugate(a): """DUAL.Conjugate Clifford Conjugation """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] return DUAL.fromarray(res) def Involute(a): """DUAL.Involute Main involution """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] return DUAL.fromarray(res) def __mul__(a,b): """DUAL.Mul The geometric product. """ if type(b) in (int, float): return a.muls(b) res = a.mvec.copy() res[0]=b[0]*a[0] res[1]=b[1]*a[0]+b[0]*a[1] return DUAL.fromarray(res) __rmul__=__mul__ def __xor__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0] res[1]=b[1]*a[0]+b[0]*a[1] return DUAL.fromarray(res) def __and__(a,b): res = a.mvec.copy() res[1]=1*(a[1]*b[1]) res[0]=1*(a[0]*b[1]+a[1]*b[0]) return DUAL.fromarray(res) def __or__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0] res[1]=b[1]*a[0]+b[0]*a[1] return DUAL.fromarray(res) def __add__(a,b): """DUAL.Add Multivector addition """ if type(b) in (int, float): return a.adds(b) res = a.mvec.copy() res[0] = a[0]+b[0] res[1] = a[1]+b[1] return DUAL.fromarray(res) __radd__=__add__ def __sub__(a,b): """DUAL.Sub Multivector subtraction """ if type(b) in (int, float): return a.subs(b) res = a.mvec.copy() res[0] = a[0]-b[0] res[1] = a[1]-b[1] return DUAL.fromarray(res) def __rsub__(a,b): """DUAL.Sub Multivector subtraction """ return b + -1 * a def smul(a,b): res = a.mvec.copy() res[0] = a*b[0] res[1] = a*b[1] return DUAL.fromarray(res) def muls(a,b): res = a.mvec.copy() res[0] = a[0]*b res[1] = a[1]*b return DUAL.fromarray(res) def sadd(a,b): res = a.mvec.copy() res[0] = a+b[0] res[1] = b[1] return DUAL.fromarray(res) def adds(a,b): res = a.mvec.copy() res[0] = a[0]+b res[1] = a[1] return DUAL.fromarray(res) def ssub(a,b): res = a.mvec.copy() res[0] = a-b[0] res[1] = -b[1] return DUAL.fromarray(res) def subs(a,b): res = a.mvec.copy() res[0] = a[0]-b res[1] = a[1] return DUAL.fromarray(res) def norm(a): return abs((a * a.Conjugate())[0])**0.5 def inorm(a): return a.Dual().norm() def normalized(a): return a * (1 / a.norm()) e0 = DUAL(1.0, 1) if __name__ == '__main__': print("e0*e0 :", str(e0*e0)) print("pss :", str(e0)) print("pss*pss :", str(e0*e0))
{ "repo_name": "enkimute/ganja.js", "path": "codegen/python/dual.py", "copies": "1", "size": "5240", "license": "mit", "hash": -507750122268628700, "line_mean": 22.4977578475, "line_max": 166, "alpha_frac": 0.4679389313, "autogenerated": false, "ratio": 3.1509320505111247, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.41188709818111247, "avg_score": null, "num_lines": null }
"""3D Projective Geometric Algebra. Written by a generator written by enki. """ __author__ = 'Enki' import math class HYPERBOLIC: def __init__(self, value=0, index=0): """Initiate a new HYPERBOLIC. Optional, the component index can be set with value. """ self.mvec = [0] * 2 self._base = ["1", "e1"] if (value != 0): self.mvec[index] = value @classmethod def fromarray(cls, array): """Initiate a new HYPERBOLIC from an array-like object. The first axis of the array is assumed to correspond to the elements of the algebra, and needs to have the same length. Any other dimensions are left unchanged, and should have simple operations such as addition and multiplication defined. NumPy arrays are therefore a perfect candidate. :param array: array-like object whose length is the dimension of the algebra. :return: new instance of HYPERBOLIC. """ self = cls() if len(array) != len(self): raise TypeError('length of array must be identical to the dimension ' 'of the algebra.') self.mvec = array return self def __str__(self): if isinstance(self.mvec, list): res = ' + '.join(filter(None, [("%.7f" % x).rstrip("0").rstrip(".")+(["",self._base[i]][i>0]) if abs(x) > 0.000001 else None for i,x in enumerate(self)])) else: # Assume array-like, redirect str conversion res = str(self.mvec) if (res == ''): return "0" return res def __getitem__(self, key): return self.mvec[key] def __setitem__(self, key, value): self.mvec[key] = value def __len__(self): return len(self.mvec) def __invert__(a): """HYPERBOLIC.Reverse Reverse the order of the basis blades. """ res = a.mvec.copy() res[0]=a[0] res[1]=a[1] return HYPERBOLIC.fromarray(res) def Dual(a): """HYPERBOLIC.Dual Poincare duality operator. """ res = a.mvec.copy() res[0]=a[1] res[1]=a[0] return HYPERBOLIC.fromarray(res) def Conjugate(a): """HYPERBOLIC.Conjugate Clifford Conjugation """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] return HYPERBOLIC.fromarray(res) def Involute(a): """HYPERBOLIC.Involute Main involution """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] return HYPERBOLIC.fromarray(res) def __mul__(a,b): """HYPERBOLIC.Mul The geometric product. """ if type(b) in (int, float): return a.muls(b) res = a.mvec.copy() res[0]=b[0]*a[0]+b[1]*a[1] res[1]=b[1]*a[0]+b[0]*a[1] return HYPERBOLIC.fromarray(res) __rmul__=__mul__ def __xor__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0] res[1]=b[1]*a[0]+b[0]*a[1] return HYPERBOLIC.fromarray(res) def __and__(a,b): res = a.mvec.copy() res[1]=1*(a[1]*b[1]) res[0]=1*(a[0]*b[1]+a[1]*b[0]) return HYPERBOLIC.fromarray(res) def __or__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0]+b[1]*a[1] res[1]=b[1]*a[0]+b[0]*a[1] return HYPERBOLIC.fromarray(res) def __add__(a,b): """HYPERBOLIC.Add Multivector addition """ if type(b) in (int, float): return a.adds(b) res = a.mvec.copy() res[0] = a[0]+b[0] res[1] = a[1]+b[1] return HYPERBOLIC.fromarray(res) __radd__=__add__ def __sub__(a,b): """HYPERBOLIC.Sub Multivector subtraction """ if type(b) in (int, float): return a.subs(b) res = a.mvec.copy() res[0] = a[0]-b[0] res[1] = a[1]-b[1] return HYPERBOLIC.fromarray(res) def __rsub__(a,b): """HYPERBOLIC.Sub Multivector subtraction """ return b + -1 * a def smul(a,b): res = a.mvec.copy() res[0] = a*b[0] res[1] = a*b[1] return HYPERBOLIC.fromarray(res) def muls(a,b): res = a.mvec.copy() res[0] = a[0]*b res[1] = a[1]*b return HYPERBOLIC.fromarray(res) def sadd(a,b): res = a.mvec.copy() res[0] = a+b[0] res[1] = b[1] return HYPERBOLIC.fromarray(res) def adds(a,b): res = a.mvec.copy() res[0] = a[0]+b res[1] = a[1] return HYPERBOLIC.fromarray(res) def ssub(a,b): res = a.mvec.copy() res[0] = a-b[0] res[1] = -b[1] return HYPERBOLIC.fromarray(res) def subs(a,b): res = a.mvec.copy() res[0] = a[0]-b res[1] = a[1] return HYPERBOLIC.fromarray(res) def norm(a): return abs((a * a.Conjugate())[0])**0.5 def inorm(a): return a.Dual().norm() def normalized(a): return a * (1 / a.norm()) e1 = HYPERBOLIC(1.0, 1) if __name__ == '__main__': print("e1*e1 :", str(e1*e1)) print("pss :", str(e1)) print("pss*pss :", str(e1*e1))
{ "repo_name": "enkimute/ganja.js", "path": "codegen/python/hyperbolic.py", "copies": "1", "size": "5434", "license": "mit", "hash": -8663207635289836000, "line_mean": 23.3677130045, "line_max": 166, "alpha_frac": 0.4847258005, "autogenerated": false, "ratio": 3.0408505875769447, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8923340122209369, "avg_score": 0.020447253173515062, "num_lines": 223 }
"""3D Projective Geometric Algebra. Written by a generator written by enki. """ __author__ = 'Enki' import math class MINK: def __init__(self, value=0, index=0): """Initiate a new MINK. Optional, the component index can be set with value. """ self.mvec = [0] * 4 self._base = ["1", "e1", "e2", "e12"] if (value != 0): self.mvec[index] = value @classmethod def fromarray(cls, array): """Initiate a new MINK from an array-like object. The first axis of the array is assumed to correspond to the elements of the algebra, and needs to have the same length. Any other dimensions are left unchanged, and should have simple operations such as addition and multiplication defined. NumPy arrays are therefore a perfect candidate. :param array: array-like object whose length is the dimension of the algebra. :return: new instance of MINK. """ self = cls() if len(array) != len(self): raise TypeError('length of array must be identical to the dimension ' 'of the algebra.') self.mvec = array return self def __str__(self): if isinstance(self.mvec, list): res = ' + '.join(filter(None, [("%.7f" % x).rstrip("0").rstrip(".")+(["",self._base[i]][i>0]) if abs(x) > 0.000001 else None for i,x in enumerate(self)])) else: # Assume array-like, redirect str conversion res = str(self.mvec) if (res == ''): return "0" return res def __getitem__(self, key): return self.mvec[key] def __setitem__(self, key, value): self.mvec[key] = value def __len__(self): return len(self.mvec) def __invert__(a): """MINK.Reverse Reverse the order of the basis blades. """ res = a.mvec.copy() res[0]=a[0] res[1]=a[1] res[2]=a[2] res[3]=-a[3] return MINK.fromarray(res) def Dual(a): """MINK.Dual Poincare duality operator. """ res = a.mvec.copy() res[0]=a[3] res[1]=-a[2] res[2]=-a[1] res[3]=a[0] return MINK.fromarray(res) def Conjugate(a): """MINK.Conjugate Clifford Conjugation """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] res[2]=-a[2] res[3]=-a[3] return MINK.fromarray(res) def Involute(a): """MINK.Involute Main involution """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] res[2]=-a[2] res[3]=a[3] return MINK.fromarray(res) def __mul__(a,b): """MINK.Mul The geometric product. """ if type(b) in (int, float): return a.muls(b) res = a.mvec.copy() res[0]=b[0]*a[0]+b[1]*a[1]-b[2]*a[2]+b[3]*a[3] res[1]=b[1]*a[0]+b[0]*a[1]+b[3]*a[2]-b[2]*a[3] res[2]=b[2]*a[0]+b[3]*a[1]+b[0]*a[2]-b[1]*a[3] res[3]=b[3]*a[0]+b[2]*a[1]-b[1]*a[2]+b[0]*a[3] return MINK.fromarray(res) __rmul__=__mul__ def __xor__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0] res[1]=b[1]*a[0]+b[0]*a[1] res[2]=b[2]*a[0]+b[0]*a[2] res[3]=b[3]*a[0]+b[2]*a[1]-b[1]*a[2]+b[0]*a[3] return MINK.fromarray(res) def __and__(a,b): res = a.mvec.copy() res[3]=1*(a[3]*b[3]) res[2]=-1*(a[2]*-1*b[3]+a[3]*b[2]*-1) res[1]=1*(a[1]*b[3]+a[3]*b[1]) res[0]=1*(a[0]*b[3]+a[1]*b[2]*-1-a[2]*-1*b[1]+a[3]*b[0]) return MINK.fromarray(res) def __or__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0]+b[1]*a[1]-b[2]*a[2]+b[3]*a[3] res[1]=b[1]*a[0]+b[0]*a[1]+b[3]*a[2]-b[2]*a[3] res[2]=b[2]*a[0]+b[3]*a[1]+b[0]*a[2]-b[1]*a[3] res[3]=b[3]*a[0]+b[0]*a[3] return MINK.fromarray(res) def __add__(a,b): """MINK.Add Multivector addition """ if type(b) in (int, float): return a.adds(b) res = a.mvec.copy() res[0] = a[0]+b[0] res[1] = a[1]+b[1] res[2] = a[2]+b[2] res[3] = a[3]+b[3] return MINK.fromarray(res) __radd__=__add__ def __sub__(a,b): """MINK.Sub Multivector subtraction """ if type(b) in (int, float): return a.subs(b) res = a.mvec.copy() res[0] = a[0]-b[0] res[1] = a[1]-b[1] res[2] = a[2]-b[2] res[3] = a[3]-b[3] return MINK.fromarray(res) def __rsub__(a,b): """MINK.Sub Multivector subtraction """ return b + -1 * a def smul(a,b): res = a.mvec.copy() res[0] = a*b[0] res[1] = a*b[1] res[2] = a*b[2] res[3] = a*b[3] return MINK.fromarray(res) def muls(a,b): res = a.mvec.copy() res[0] = a[0]*b res[1] = a[1]*b res[2] = a[2]*b res[3] = a[3]*b return MINK.fromarray(res) def sadd(a,b): res = a.mvec.copy() res[0] = a+b[0] res[1] = b[1] res[2] = b[2] res[3] = b[3] return MINK.fromarray(res) def adds(a,b): res = a.mvec.copy() res[0] = a[0]+b res[1] = a[1] res[2] = a[2] res[3] = a[3] return MINK.fromarray(res) def ssub(a,b): res = a.mvec.copy() res[0] = a-b[0] res[1] = -b[1] res[2] = -b[2] res[3] = -b[3] return MINK.fromarray(res) def subs(a,b): res = a.mvec.copy() res[0] = a[0]-b res[1] = a[1] res[2] = a[2] res[3] = a[3] return MINK.fromarray(res) def norm(a): return abs((a * a.Conjugate())[0])**0.5 def inorm(a): return a.Dual().norm() def normalized(a): return a * (1 / a.norm()) e1 = MINK(1.0, 1) e2 = MINK(1.0, 2) e12 = MINK(1.0, 3) if __name__ == '__main__': print("e1*e1 :", str(e1*e1)) print("pss :", str(e12)) print("pss*pss :", str(e12*e12))
{ "repo_name": "enkimute/ganja.js", "path": "codegen/python/mink.py", "copies": "1", "size": "6342", "license": "mit", "hash": 75175144384030350, "line_mean": 23.6770428016, "line_max": 166, "alpha_frac": 0.4441816462, "autogenerated": false, "ratio": 2.7526041666666665, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.36967858128666664, "avg_score": null, "num_lines": null }
"""3D Projective Geometric Algebra. Written by a generator written by enki. """ __author__ = 'Enki' import math class PGA3D: def __init__(self, value=0, index=0): """Initiate a new PGA3D. Optional, the component index can be set with value. """ self.mvec = [0] * 16 self._base = ["1", "e0", "e1", "e2", "e3", "e01", "e02", "e03", "e12", "e31", "e23", "e021", "e013", "e032", "e123", "e0123"] if (value != 0): self.mvec[index] = value @classmethod def fromarray(cls, array): """Initiate a new PGA3D from an array-like object. The first axis of the array is assumed to correspond to the elements of the algebra, and needs to have the same length. Any other dimensions are left unchanged, and should have simple operations such as addition and multiplication defined. NumPy arrays are therefore a perfect candidate. :param array: array-like object whose length is the dimension of the algebra. :return: new instance of PGA3D. """ self = cls() if len(array) != len(self): raise TypeError('length of array must be identical to the dimension ' 'of the algebra.') self.mvec = array return self def __str__(self): if isinstance(self.mvec, list): res = ' + '.join(filter(None, [("%.7f" % x).rstrip("0").rstrip(".")+(["",self._base[i]][i>0]) if abs(x) > 0.000001 else None for i,x in enumerate(self)])) else: # Assume array-like, redirect str conversion res = str(self.mvec) if (res == ''): return "0" return res def __getitem__(self, key): return self.mvec[key] def __setitem__(self, key, value): self.mvec[key] = value def __len__(self): return len(self.mvec) def __invert__(a): """PGA3D.Reverse Reverse the order of the basis blades. """ res = a.mvec.copy() res[0]=a[0] res[1]=a[1] res[2]=a[2] res[3]=a[3] res[4]=a[4] res[5]=-a[5] res[6]=-a[6] res[7]=-a[7] res[8]=-a[8] res[9]=-a[9] res[10]=-a[10] res[11]=-a[11] res[12]=-a[12] res[13]=-a[13] res[14]=-a[14] res[15]=a[15] return PGA3D.fromarray(res) def Dual(a): """PGA3D.Dual Poincare duality operator. """ res = a.mvec.copy() res[0]=a[15] res[1]=a[14] res[2]=a[13] res[3]=a[12] res[4]=a[11] res[5]=a[10] res[6]=a[9] res[7]=a[8] res[8]=a[7] res[9]=a[6] res[10]=a[5] res[11]=a[4] res[12]=a[3] res[13]=a[2] res[14]=a[1] res[15]=a[0] return PGA3D.fromarray(res) def Conjugate(a): """PGA3D.Conjugate Clifford Conjugation """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] res[2]=-a[2] res[3]=-a[3] res[4]=-a[4] res[5]=-a[5] res[6]=-a[6] res[7]=-a[7] res[8]=-a[8] res[9]=-a[9] res[10]=-a[10] res[11]=a[11] res[12]=a[12] res[13]=a[13] res[14]=a[14] res[15]=a[15] return PGA3D.fromarray(res) def Involute(a): """PGA3D.Involute Main involution """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] res[2]=-a[2] res[3]=-a[3] res[4]=-a[4] res[5]=a[5] res[6]=a[6] res[7]=a[7] res[8]=a[8] res[9]=a[9] res[10]=a[10] res[11]=-a[11] res[12]=-a[12] res[13]=-a[13] res[14]=-a[14] res[15]=a[15] return PGA3D.fromarray(res) def __mul__(a,b): """PGA3D.Mul The geometric product. """ if type(b) in (int, float): return a.muls(b) res = a.mvec.copy() res[0]=b[0]*a[0]+b[2]*a[2]+b[3]*a[3]+b[4]*a[4]-b[8]*a[8]-b[9]*a[9]-b[10]*a[10]-b[14]*a[14] res[1]=b[1]*a[0]+b[0]*a[1]-b[5]*a[2]-b[6]*a[3]-b[7]*a[4]+b[2]*a[5]+b[3]*a[6]+b[4]*a[7]+b[11]*a[8]+b[12]*a[9]+b[13]*a[10]+b[8]*a[11]+b[9]*a[12]+b[10]*a[13]+b[15]*a[14]-b[14]*a[15] res[2]=b[2]*a[0]+b[0]*a[2]-b[8]*a[3]+b[9]*a[4]+b[3]*a[8]-b[4]*a[9]-b[14]*a[10]-b[10]*a[14] res[3]=b[3]*a[0]+b[8]*a[2]+b[0]*a[3]-b[10]*a[4]-b[2]*a[8]-b[14]*a[9]+b[4]*a[10]-b[9]*a[14] res[4]=b[4]*a[0]-b[9]*a[2]+b[10]*a[3]+b[0]*a[4]-b[14]*a[8]+b[2]*a[9]-b[3]*a[10]-b[8]*a[14] res[5]=b[5]*a[0]+b[2]*a[1]-b[1]*a[2]-b[11]*a[3]+b[12]*a[4]+b[0]*a[5]-b[8]*a[6]+b[9]*a[7]+b[6]*a[8]-b[7]*a[9]-b[15]*a[10]-b[3]*a[11]+b[4]*a[12]+b[14]*a[13]-b[13]*a[14]-b[10]*a[15] res[6]=b[6]*a[0]+b[3]*a[1]+b[11]*a[2]-b[1]*a[3]-b[13]*a[4]+b[8]*a[5]+b[0]*a[6]-b[10]*a[7]-b[5]*a[8]-b[15]*a[9]+b[7]*a[10]+b[2]*a[11]+b[14]*a[12]-b[4]*a[13]-b[12]*a[14]-b[9]*a[15] res[7]=b[7]*a[0]+b[4]*a[1]-b[12]*a[2]+b[13]*a[3]-b[1]*a[4]-b[9]*a[5]+b[10]*a[6]+b[0]*a[7]-b[15]*a[8]+b[5]*a[9]-b[6]*a[10]+b[14]*a[11]-b[2]*a[12]+b[3]*a[13]-b[11]*a[14]-b[8]*a[15] res[8]=b[8]*a[0]+b[3]*a[2]-b[2]*a[3]+b[14]*a[4]+b[0]*a[8]+b[10]*a[9]-b[9]*a[10]+b[4]*a[14] res[9]=b[9]*a[0]-b[4]*a[2]+b[14]*a[3]+b[2]*a[4]-b[10]*a[8]+b[0]*a[9]+b[8]*a[10]+b[3]*a[14] res[10]=b[10]*a[0]+b[14]*a[2]+b[4]*a[3]-b[3]*a[4]+b[9]*a[8]-b[8]*a[9]+b[0]*a[10]+b[2]*a[14] res[11]=b[11]*a[0]-b[8]*a[1]+b[6]*a[2]-b[5]*a[3]+b[15]*a[4]-b[3]*a[5]+b[2]*a[6]-b[14]*a[7]-b[1]*a[8]+b[13]*a[9]-b[12]*a[10]+b[0]*a[11]+b[10]*a[12]-b[9]*a[13]+b[7]*a[14]-b[4]*a[15] res[12]=b[12]*a[0]-b[9]*a[1]-b[7]*a[2]+b[15]*a[3]+b[5]*a[4]+b[4]*a[5]-b[14]*a[6]-b[2]*a[7]-b[13]*a[8]-b[1]*a[9]+b[11]*a[10]-b[10]*a[11]+b[0]*a[12]+b[8]*a[13]+b[6]*a[14]-b[3]*a[15] res[13]=b[13]*a[0]-b[10]*a[1]+b[15]*a[2]+b[7]*a[3]-b[6]*a[4]-b[14]*a[5]-b[4]*a[6]+b[3]*a[7]+b[12]*a[8]-b[11]*a[9]-b[1]*a[10]+b[9]*a[11]-b[8]*a[12]+b[0]*a[13]+b[5]*a[14]-b[2]*a[15] res[14]=b[14]*a[0]+b[10]*a[2]+b[9]*a[3]+b[8]*a[4]+b[4]*a[8]+b[3]*a[9]+b[2]*a[10]+b[0]*a[14] res[15]=b[15]*a[0]+b[14]*a[1]+b[13]*a[2]+b[12]*a[3]+b[11]*a[4]+b[10]*a[5]+b[9]*a[6]+b[8]*a[7]+b[7]*a[8]+b[6]*a[9]+b[5]*a[10]-b[4]*a[11]-b[3]*a[12]-b[2]*a[13]-b[1]*a[14]+b[0]*a[15] return PGA3D.fromarray(res) __rmul__=__mul__ def __xor__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0] res[1]=b[1]*a[0]+b[0]*a[1] res[2]=b[2]*a[0]+b[0]*a[2] res[3]=b[3]*a[0]+b[0]*a[3] res[4]=b[4]*a[0]+b[0]*a[4] res[5]=b[5]*a[0]+b[2]*a[1]-b[1]*a[2]+b[0]*a[5] res[6]=b[6]*a[0]+b[3]*a[1]-b[1]*a[3]+b[0]*a[6] res[7]=b[7]*a[0]+b[4]*a[1]-b[1]*a[4]+b[0]*a[7] res[8]=b[8]*a[0]+b[3]*a[2]-b[2]*a[3]+b[0]*a[8] res[9]=b[9]*a[0]-b[4]*a[2]+b[2]*a[4]+b[0]*a[9] res[10]=b[10]*a[0]+b[4]*a[3]-b[3]*a[4]+b[0]*a[10] res[11]=b[11]*a[0]-b[8]*a[1]+b[6]*a[2]-b[5]*a[3]-b[3]*a[5]+b[2]*a[6]-b[1]*a[8]+b[0]*a[11] res[12]=b[12]*a[0]-b[9]*a[1]-b[7]*a[2]+b[5]*a[4]+b[4]*a[5]-b[2]*a[7]-b[1]*a[9]+b[0]*a[12] res[13]=b[13]*a[0]-b[10]*a[1]+b[7]*a[3]-b[6]*a[4]-b[4]*a[6]+b[3]*a[7]-b[1]*a[10]+b[0]*a[13] res[14]=b[14]*a[0]+b[10]*a[2]+b[9]*a[3]+b[8]*a[4]+b[4]*a[8]+b[3]*a[9]+b[2]*a[10]+b[0]*a[14] res[15]=b[15]*a[0]+b[14]*a[1]+b[13]*a[2]+b[12]*a[3]+b[11]*a[4]+b[10]*a[5]+b[9]*a[6]+b[8]*a[7]+b[7]*a[8]+b[6]*a[9]+b[5]*a[10]-b[4]*a[11]-b[3]*a[12]-b[2]*a[13]-b[1]*a[14]+b[0]*a[15] return PGA3D.fromarray(res) def __and__(a,b): res = a.mvec.copy() res[15]=1*(a[15]*b[15]) res[14]=-1*(a[14]*-1*b[15]+a[15]*b[14]*-1) res[13]=-1*(a[13]*-1*b[15]+a[15]*b[13]*-1) res[12]=-1*(a[12]*-1*b[15]+a[15]*b[12]*-1) res[11]=-1*(a[11]*-1*b[15]+a[15]*b[11]*-1) res[10]=1*(a[10]*b[15]+a[13]*-1*b[14]*-1-a[14]*-1*b[13]*-1+a[15]*b[10]) res[9]=1*(a[9]*b[15]+a[12]*-1*b[14]*-1-a[14]*-1*b[12]*-1+a[15]*b[9]) res[8]=1*(a[8]*b[15]+a[11]*-1*b[14]*-1-a[14]*-1*b[11]*-1+a[15]*b[8]) res[7]=1*(a[7]*b[15]+a[12]*-1*b[13]*-1-a[13]*-1*b[12]*-1+a[15]*b[7]) res[6]=1*(a[6]*b[15]-a[11]*-1*b[13]*-1+a[13]*-1*b[11]*-1+a[15]*b[6]) res[5]=1*(a[5]*b[15]+a[11]*-1*b[12]*-1-a[12]*-1*b[11]*-1+a[15]*b[5]) res[4]=1*(a[4]*b[15]-a[7]*b[14]*-1+a[9]*b[13]*-1-a[10]*b[12]*-1-a[12]*-1*b[10]+a[13]*-1*b[9]-a[14]*-1*b[7]+a[15]*b[4]) res[3]=1*(a[3]*b[15]-a[6]*b[14]*-1-a[8]*b[13]*-1+a[10]*b[11]*-1+a[11]*-1*b[10]-a[13]*-1*b[8]-a[14]*-1*b[6]+a[15]*b[3]) res[2]=1*(a[2]*b[15]-a[5]*b[14]*-1+a[8]*b[12]*-1-a[9]*b[11]*-1-a[11]*-1*b[9]+a[12]*-1*b[8]-a[14]*-1*b[5]+a[15]*b[2]) res[1]=1*(a[1]*b[15]+a[5]*b[13]*-1+a[6]*b[12]*-1+a[7]*b[11]*-1+a[11]*-1*b[7]+a[12]*-1*b[6]+a[13]*-1*b[5]+a[15]*b[1]) res[0]=1*(a[0]*b[15]+a[1]*b[14]*-1+a[2]*b[13]*-1+a[3]*b[12]*-1+a[4]*b[11]*-1+a[5]*b[10]+a[6]*b[9]+a[7]*b[8]+a[8]*b[7]+a[9]*b[6]+a[10]*b[5]-a[11]*-1*b[4]-a[12]*-1*b[3]-a[13]*-1*b[2]-a[14]*-1*b[1]+a[15]*b[0]) return PGA3D.fromarray(res) def __or__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0]+b[2]*a[2]+b[3]*a[3]+b[4]*a[4]-b[8]*a[8]-b[9]*a[9]-b[10]*a[10]-b[14]*a[14] res[1]=b[1]*a[0]+b[0]*a[1]-b[5]*a[2]-b[6]*a[3]-b[7]*a[4]+b[2]*a[5]+b[3]*a[6]+b[4]*a[7]+b[11]*a[8]+b[12]*a[9]+b[13]*a[10]+b[8]*a[11]+b[9]*a[12]+b[10]*a[13]+b[15]*a[14]-b[14]*a[15] res[2]=b[2]*a[0]+b[0]*a[2]-b[8]*a[3]+b[9]*a[4]+b[3]*a[8]-b[4]*a[9]-b[14]*a[10]-b[10]*a[14] res[3]=b[3]*a[0]+b[8]*a[2]+b[0]*a[3]-b[10]*a[4]-b[2]*a[8]-b[14]*a[9]+b[4]*a[10]-b[9]*a[14] res[4]=b[4]*a[0]-b[9]*a[2]+b[10]*a[3]+b[0]*a[4]-b[14]*a[8]+b[2]*a[9]-b[3]*a[10]-b[8]*a[14] res[5]=b[5]*a[0]-b[11]*a[3]+b[12]*a[4]+b[0]*a[5]-b[15]*a[10]-b[3]*a[11]+b[4]*a[12]-b[10]*a[15] res[6]=b[6]*a[0]+b[11]*a[2]-b[13]*a[4]+b[0]*a[6]-b[15]*a[9]+b[2]*a[11]-b[4]*a[13]-b[9]*a[15] res[7]=b[7]*a[0]-b[12]*a[2]+b[13]*a[3]+b[0]*a[7]-b[15]*a[8]-b[2]*a[12]+b[3]*a[13]-b[8]*a[15] res[8]=b[8]*a[0]+b[14]*a[4]+b[0]*a[8]+b[4]*a[14] res[9]=b[9]*a[0]+b[14]*a[3]+b[0]*a[9]+b[3]*a[14] res[10]=b[10]*a[0]+b[14]*a[2]+b[0]*a[10]+b[2]*a[14] res[11]=b[11]*a[0]+b[15]*a[4]+b[0]*a[11]-b[4]*a[15] res[12]=b[12]*a[0]+b[15]*a[3]+b[0]*a[12]-b[3]*a[15] res[13]=b[13]*a[0]+b[15]*a[2]+b[0]*a[13]-b[2]*a[15] res[14]=b[14]*a[0]+b[0]*a[14] res[15]=b[15]*a[0]+b[0]*a[15] return PGA3D.fromarray(res) def __add__(a,b): """PGA3D.Add Multivector addition """ if type(b) in (int, float): return a.adds(b) res = a.mvec.copy() res[0] = a[0]+b[0] res[1] = a[1]+b[1] res[2] = a[2]+b[2] res[3] = a[3]+b[3] res[4] = a[4]+b[4] res[5] = a[5]+b[5] res[6] = a[6]+b[6] res[7] = a[7]+b[7] res[8] = a[8]+b[8] res[9] = a[9]+b[9] res[10] = a[10]+b[10] res[11] = a[11]+b[11] res[12] = a[12]+b[12] res[13] = a[13]+b[13] res[14] = a[14]+b[14] res[15] = a[15]+b[15] return PGA3D.fromarray(res) __radd__=__add__ def __sub__(a,b): """PGA3D.Sub Multivector subtraction """ if type(b) in (int, float): return a.subs(b) res = a.mvec.copy() res[0] = a[0]-b[0] res[1] = a[1]-b[1] res[2] = a[2]-b[2] res[3] = a[3]-b[3] res[4] = a[4]-b[4] res[5] = a[5]-b[5] res[6] = a[6]-b[6] res[7] = a[7]-b[7] res[8] = a[8]-b[8] res[9] = a[9]-b[9] res[10] = a[10]-b[10] res[11] = a[11]-b[11] res[12] = a[12]-b[12] res[13] = a[13]-b[13] res[14] = a[14]-b[14] res[15] = a[15]-b[15] return PGA3D.fromarray(res) def __rsub__(a,b): """PGA3D.Sub Multivector subtraction """ return b + -1 * a def smul(a,b): res = a.mvec.copy() res[0] = a*b[0] res[1] = a*b[1] res[2] = a*b[2] res[3] = a*b[3] res[4] = a*b[4] res[5] = a*b[5] res[6] = a*b[6] res[7] = a*b[7] res[8] = a*b[8] res[9] = a*b[9] res[10] = a*b[10] res[11] = a*b[11] res[12] = a*b[12] res[13] = a*b[13] res[14] = a*b[14] res[15] = a*b[15] return PGA3D.fromarray(res) def muls(a,b): res = a.mvec.copy() res[0] = a[0]*b res[1] = a[1]*b res[2] = a[2]*b res[3] = a[3]*b res[4] = a[4]*b res[5] = a[5]*b res[6] = a[6]*b res[7] = a[7]*b res[8] = a[8]*b res[9] = a[9]*b res[10] = a[10]*b res[11] = a[11]*b res[12] = a[12]*b res[13] = a[13]*b res[14] = a[14]*b res[15] = a[15]*b return PGA3D.fromarray(res) def sadd(a,b): res = a.mvec.copy() res[0] = a+b[0] res[1] = b[1] res[2] = b[2] res[3] = b[3] res[4] = b[4] res[5] = b[5] res[6] = b[6] res[7] = b[7] res[8] = b[8] res[9] = b[9] res[10] = b[10] res[11] = b[11] res[12] = b[12] res[13] = b[13] res[14] = b[14] res[15] = b[15] return PGA3D.fromarray(res) def adds(a,b): res = a.mvec.copy() res[0] = a[0]+b res[1] = a[1] res[2] = a[2] res[3] = a[3] res[4] = a[4] res[5] = a[5] res[6] = a[6] res[7] = a[7] res[8] = a[8] res[9] = a[9] res[10] = a[10] res[11] = a[11] res[12] = a[12] res[13] = a[13] res[14] = a[14] res[15] = a[15] return PGA3D.fromarray(res) def ssub(a,b): res = a.mvec.copy() res[0] = a-b[0] res[1] = -b[1] res[2] = -b[2] res[3] = -b[3] res[4] = -b[4] res[5] = -b[5] res[6] = -b[6] res[7] = -b[7] res[8] = -b[8] res[9] = -b[9] res[10] = -b[10] res[11] = -b[11] res[12] = -b[12] res[13] = -b[13] res[14] = -b[14] res[15] = -b[15] return PGA3D.fromarray(res) def subs(a,b): res = a.mvec.copy() res[0] = a[0]-b res[1] = a[1] res[2] = a[2] res[3] = a[3] res[4] = a[4] res[5] = a[5] res[6] = a[6] res[7] = a[7] res[8] = a[8] res[9] = a[9] res[10] = a[10] res[11] = a[11] res[12] = a[12] res[13] = a[13] res[14] = a[14] res[15] = a[15] return PGA3D.fromarray(res) def norm(a): return abs((a * a.Conjugate())[0])**0.5 def inorm(a): return a.Dual().norm() def normalized(a): return a * (1 / a.norm()) if __name__ == '__main__': # A rotor (Euclidean line) and translator (Ideal line) def rotor(angle, line): return math.cos(angle / 2.0) + math.sin(angle / 2.0) * line.normalized() def translator(dist, line): return 1.0 + dist / 2.0 * line # PGA is plane based. Vectors are planes. (think linear functionals) E0 = PGA3D(1.0, 1) # ideal plane E1 = PGA3D(1.0, 2) # x=0 plane E2 = PGA3D(1.0, 3) # y=0 plane E3 = PGA3D(1.0, 4) # z=0 plane # A plane is defined using its homogenous equation ax + by + cz + d = 0 def PLANE(a, b, c, d): return a * E1 + b * E2 + c * E3 + d * E0 # PGA points are trivectors. E123 = E1 ^ E2 ^ E3 E032 = E0 ^ E3 ^ E2 E013 = E0 ^ E1 ^ E3 E021 = E0 ^ E2 ^ E1 # A point is just a homogeneous point, euclidean coordinates plus the origin def POINT(x, y, z): return E123 + x * E032 + y * E013 + z * E021 # for our toy problem (generate points on the surface of a torus) # we start with a function that generates motors. # circle(t) with t going from 0 to 1. def CIRCLE(t, radius, line): return rotor(t * math.pi * 2.0, line) * translator(radius, E1 * E0) # a torus is now the product of two circles. def TORUS(s, t, r1, l1, r2, l2): return CIRCLE(s, r2, l2)*CIRCLE(t, r1, l1) # sample the torus points by sandwich with the origin def POINT_ON_TORUS(s, t): to = TORUS(s, t, 0.25, E1 * E2, 0.6, E1 * E3) return to * E123 * ~to # Elements of the even subalgebra (scalar + bivector + pss) of unit length are motors ROT = rotor(math.pi / 2.0, E1 * E2) # The outer product ^ is the MEET. Here we intersect the yz (x=0) and xz (y=0) planes. AXZ = E1 ^ E2 # x=0, y=0 -> z-axis line # line and plane meet in point. We intersect the line along the z-axis (x=0,y=0) with the xy (z=0) plane. ORIG = AXZ ^ E3 # x=0, y=0, z=0 -> origin # We can also easily create points and join them into a line using the regressive (vee, &) product. PX = POINT(1, 0, 0) LINE = ORIG & PX # & = regressive product, JOIN, here, x-axis line. # Lets also create the plane with equation 2x + z - 3 = 0 P = PLANE(2, 0, 1, -3) # rotations work on all elements .. ROTATED_LINE = ROT * LINE * ~ROT ROTATED_POINT = ROT * PX * ~ROT ROTATED_PLANE = ROT * P * ~ROT # See the 3D PGA Cheat sheet for a huge collection of useful formulas POINT_ON_PLANE = (P | PX) * P # output some numbers. print("a point :", str(PX)) print("a line :", str(LINE)) print("a plane :", str(P)) print("a rotor :", str(ROT)) print("rotated line :", str(ROTATED_LINE)) print("rotated point :", str(ROTATED_POINT)) print("rotated plane :", str(ROTATED_PLANE)) print("point on plane:", str(POINT_ON_PLANE.normalized())) print("point on torus:", str(POINT_ON_TORUS(0.0, 0.0))) print(E0 - 1) print(1 - E0)
{ "repo_name": "enkimute/ganja.js", "path": "codegen/python/pga3d.py", "copies": "1", "size": "18084", "license": "mit", "hash": 3751141442031898600, "line_mean": 33.7769230769, "line_max": 214, "alpha_frac": 0.4350254369, "autogenerated": false, "ratio": 2.091844997108155, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7920422071515265, "avg_score": 0.021289672498578112, "num_lines": 520 }
"""3D Projective Geometric Algebra. Written by a generator written by enki. """ __author__ = 'Enki' import math class QUAT: def __init__(self, value=0, index=0): """Initiate a new QUAT. Optional, the component index can be set with value. """ self.mvec = [0] * 4 self._base = ["1", "e1", "e2", "e12"] if (value != 0): self.mvec[index] = value @classmethod def fromarray(cls, array): """Initiate a new QUAT from an array-like object. The first axis of the array is assumed to correspond to the elements of the algebra, and needs to have the same length. Any other dimensions are left unchanged, and should have simple operations such as addition and multiplication defined. NumPy arrays are therefore a perfect candidate. :param array: array-like object whose length is the dimension of the algebra. :return: new instance of QUAT. """ self = cls() if len(array) != len(self): raise TypeError('length of array must be identical to the dimension ' 'of the algebra.') self.mvec = array return self def __str__(self): if isinstance(self.mvec, list): res = ' + '.join(filter(None, [("%.7f" % x).rstrip("0").rstrip(".")+(["",self._base[i]][i>0]) if abs(x) > 0.000001 else None for i,x in enumerate(self)])) else: # Assume array-like, redirect str conversion res = str(self.mvec) if (res == ''): return "0" return res def __getitem__(self, key): return self.mvec[key] def __setitem__(self, key, value): self.mvec[key] = value def __len__(self): return len(self.mvec) def __invert__(a): """QUAT.Reverse Reverse the order of the basis blades. """ res = a.mvec.copy() res[0]=a[0] res[1]=a[1] res[2]=a[2] res[3]=-a[3] return QUAT.fromarray(res) def Dual(a): """QUAT.Dual Poincare duality operator. """ res = a.mvec.copy() res[0]=-a[3] res[1]=-a[2] res[2]=a[1] res[3]=a[0] return QUAT.fromarray(res) def Conjugate(a): """QUAT.Conjugate Clifford Conjugation """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] res[2]=-a[2] res[3]=-a[3] return QUAT.fromarray(res) def Involute(a): """QUAT.Involute Main involution """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] res[2]=-a[2] res[3]=a[3] return QUAT.fromarray(res) def __mul__(a,b): """QUAT.Mul The geometric product. """ if type(b) in (int, float): return a.muls(b) res = a.mvec.copy() res[0]=b[0]*a[0]-b[1]*a[1]-b[2]*a[2]-b[3]*a[3] res[1]=b[1]*a[0]+b[0]*a[1]+b[3]*a[2]-b[2]*a[3] res[2]=b[2]*a[0]-b[3]*a[1]+b[0]*a[2]+b[1]*a[3] res[3]=b[3]*a[0]+b[2]*a[1]-b[1]*a[2]+b[0]*a[3] return QUAT.fromarray(res) __rmul__=__mul__ def __xor__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0] res[1]=b[1]*a[0]+b[0]*a[1] res[2]=b[2]*a[0]+b[0]*a[2] res[3]=b[3]*a[0]+b[2]*a[1]-b[1]*a[2]+b[0]*a[3] return QUAT.fromarray(res) def __and__(a,b): res = a.mvec.copy() res[3]=1*(a[3]*b[3]) res[2]=-1*(a[2]*-1*b[3]+a[3]*b[2]*-1) res[1]=1*(a[1]*b[3]+a[3]*b[1]) res[0]=1*(a[0]*b[3]+a[1]*b[2]*-1-a[2]*-1*b[1]+a[3]*b[0]) return QUAT.fromarray(res) def __or__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0]-b[1]*a[1]-b[2]*a[2]-b[3]*a[3] res[1]=b[1]*a[0]+b[0]*a[1]+b[3]*a[2]-b[2]*a[3] res[2]=b[2]*a[0]-b[3]*a[1]+b[0]*a[2]+b[1]*a[3] res[3]=b[3]*a[0]+b[0]*a[3] return QUAT.fromarray(res) def __add__(a,b): """QUAT.Add Multivector addition """ if type(b) in (int, float): return a.adds(b) res = a.mvec.copy() res[0] = a[0]+b[0] res[1] = a[1]+b[1] res[2] = a[2]+b[2] res[3] = a[3]+b[3] return QUAT.fromarray(res) __radd__=__add__ def __sub__(a,b): """QUAT.Sub Multivector subtraction """ if type(b) in (int, float): return a.subs(b) res = a.mvec.copy() res[0] = a[0]-b[0] res[1] = a[1]-b[1] res[2] = a[2]-b[2] res[3] = a[3]-b[3] return QUAT.fromarray(res) def __rsub__(a,b): """QUAT.Sub Multivector subtraction """ return b + -1 * a def smul(a,b): res = a.mvec.copy() res[0] = a*b[0] res[1] = a*b[1] res[2] = a*b[2] res[3] = a*b[3] return QUAT.fromarray(res) def muls(a,b): res = a.mvec.copy() res[0] = a[0]*b res[1] = a[1]*b res[2] = a[2]*b res[3] = a[3]*b return QUAT.fromarray(res) def sadd(a,b): res = a.mvec.copy() res[0] = a+b[0] res[1] = b[1] res[2] = b[2] res[3] = b[3] return QUAT.fromarray(res) def adds(a,b): res = a.mvec.copy() res[0] = a[0]+b res[1] = a[1] res[2] = a[2] res[3] = a[3] return QUAT.fromarray(res) def ssub(a,b): res = a.mvec.copy() res[0] = a-b[0] res[1] = -b[1] res[2] = -b[2] res[3] = -b[3] return QUAT.fromarray(res) def subs(a,b): res = a.mvec.copy() res[0] = a[0]-b res[1] = a[1] res[2] = a[2] res[3] = a[3] return QUAT.fromarray(res) def norm(a): return abs((a * a.Conjugate())[0])**0.5 def inorm(a): return a.Dual().norm() def normalized(a): return a * (1 / a.norm()) e1 = QUAT(1.0, 1) e2 = QUAT(1.0, 2) e12 = QUAT(1.0, 3) if __name__ == '__main__': print("e1*e1 :", str(e1*e1)) print("pss :", str(e12)) print("pss*pss :", str(e12*e12))
{ "repo_name": "enkimute/ganja.js", "path": "codegen/python/quat.py", "copies": "1", "size": "6342", "license": "mit", "hash": -7595225626792239000, "line_mean": 23.6770428016, "line_max": 166, "alpha_frac": 0.4441816462, "autogenerated": false, "ratio": 2.7526041666666665, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8597319784769275, "avg_score": 0.019893205619478202, "num_lines": 257 }
"""3D Projective Geometric Algebra. Written by a generator written by enki. """ __author__ = 'Enki' import math class R2: def __init__(self, value=0, index=0): """Initiate a new R2. Optional, the component index can be set with value. """ self.mvec = [0] * 4 self._base = ["1", "e1", "e2", "e12"] if (value != 0): self.mvec[index] = value @classmethod def fromarray(cls, array): """Initiate a new R2 from an array-like object. The first axis of the array is assumed to correspond to the elements of the algebra, and needs to have the same length. Any other dimensions are left unchanged, and should have simple operations such as addition and multiplication defined. NumPy arrays are therefore a perfect candidate. :param array: array-like object whose length is the dimension of the algebra. :return: new instance of R2. """ self = cls() if len(array) != len(self): raise TypeError('length of array must be identical to the dimension ' 'of the algebra.') self.mvec = array return self def __str__(self): if isinstance(self.mvec, list): res = ' + '.join(filter(None, [("%.7f" % x).rstrip("0").rstrip(".")+(["",self._base[i]][i>0]) if abs(x) > 0.000001 else None for i,x in enumerate(self)])) else: # Assume array-like, redirect str conversion res = str(self.mvec) if (res == ''): return "0" return res def __getitem__(self, key): return self.mvec[key] def __setitem__(self, key, value): self.mvec[key] = value def __len__(self): return len(self.mvec) def __invert__(a): """R2.Reverse Reverse the order of the basis blades. """ res = a.mvec.copy() res[0]=a[0] res[1]=a[1] res[2]=a[2] res[3]=-a[3] return R2.fromarray(res) def Dual(a): """R2.Dual Poincare duality operator. """ res = a.mvec.copy() res[0]=-a[3] res[1]=a[2] res[2]=-a[1] res[3]=a[0] return R2.fromarray(res) def Conjugate(a): """R2.Conjugate Clifford Conjugation """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] res[2]=-a[2] res[3]=-a[3] return R2.fromarray(res) def Involute(a): """R2.Involute Main involution """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] res[2]=-a[2] res[3]=a[3] return R2.fromarray(res) def __mul__(a,b): """R2.Mul The geometric product. """ if type(b) in (int, float): return a.muls(b) res = a.mvec.copy() res[0]=b[0]*a[0]+b[1]*a[1]+b[2]*a[2]-b[3]*a[3] res[1]=b[1]*a[0]+b[0]*a[1]-b[3]*a[2]+b[2]*a[3] res[2]=b[2]*a[0]+b[3]*a[1]+b[0]*a[2]-b[1]*a[3] res[3]=b[3]*a[0]+b[2]*a[1]-b[1]*a[2]+b[0]*a[3] return R2.fromarray(res) __rmul__=__mul__ def __xor__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0] res[1]=b[1]*a[0]+b[0]*a[1] res[2]=b[2]*a[0]+b[0]*a[2] res[3]=b[3]*a[0]+b[2]*a[1]-b[1]*a[2]+b[0]*a[3] return R2.fromarray(res) def __and__(a,b): res = a.mvec.copy() res[3]=1*(a[3]*b[3]) res[2]=-1*(a[2]*-1*b[3]+a[3]*b[2]*-1) res[1]=1*(a[1]*b[3]+a[3]*b[1]) res[0]=1*(a[0]*b[3]+a[1]*b[2]*-1-a[2]*-1*b[1]+a[3]*b[0]) return R2.fromarray(res) def __or__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0]+b[1]*a[1]+b[2]*a[2]-b[3]*a[3] res[1]=b[1]*a[0]+b[0]*a[1]-b[3]*a[2]+b[2]*a[3] res[2]=b[2]*a[0]+b[3]*a[1]+b[0]*a[2]-b[1]*a[3] res[3]=b[3]*a[0]+b[0]*a[3] return R2.fromarray(res) def __add__(a,b): """R2.Add Multivector addition """ if type(b) in (int, float): return a.adds(b) res = a.mvec.copy() res[0] = a[0]+b[0] res[1] = a[1]+b[1] res[2] = a[2]+b[2] res[3] = a[3]+b[3] return R2.fromarray(res) __radd__=__add__ def __sub__(a,b): """R2.Sub Multivector subtraction """ if type(b) in (int, float): return a.subs(b) res = a.mvec.copy() res[0] = a[0]-b[0] res[1] = a[1]-b[1] res[2] = a[2]-b[2] res[3] = a[3]-b[3] return R2.fromarray(res) def __rsub__(a,b): """R2.Sub Multivector subtraction """ return b + -1 * a def smul(a,b): res = a.mvec.copy() res[0] = a*b[0] res[1] = a*b[1] res[2] = a*b[2] res[3] = a*b[3] return R2.fromarray(res) def muls(a,b): res = a.mvec.copy() res[0] = a[0]*b res[1] = a[1]*b res[2] = a[2]*b res[3] = a[3]*b return R2.fromarray(res) def sadd(a,b): res = a.mvec.copy() res[0] = a+b[0] res[1] = b[1] res[2] = b[2] res[3] = b[3] return R2.fromarray(res) def adds(a,b): res = a.mvec.copy() res[0] = a[0]+b res[1] = a[1] res[2] = a[2] res[3] = a[3] return R2.fromarray(res) def ssub(a,b): res = a.mvec.copy() res[0] = a-b[0] res[1] = -b[1] res[2] = -b[2] res[3] = -b[3] return R2.fromarray(res) def subs(a,b): res = a.mvec.copy() res[0] = a[0]-b res[1] = a[1] res[2] = a[2] res[3] = a[3] return R2.fromarray(res) def norm(a): return abs((a * a.Conjugate())[0])**0.5 def inorm(a): return a.Dual().norm() def normalized(a): return a * (1 / a.norm()) e1 = R2(1.0, 1) e2 = R2(1.0, 2) e12 = R2(1.0, 3) if __name__ == '__main__': print("e1*e1 :", str(e1*e1)) print("pss :", str(e12)) print("pss*pss :", str(e12*e12))
{ "repo_name": "enkimute/ganja.js", "path": "codegen/python/r2.py", "copies": "1", "size": "6280", "license": "mit", "hash": 1969324215358765000, "line_mean": 23.4357976654, "line_max": 166, "alpha_frac": 0.4386942675, "autogenerated": false, "ratio": 2.7256944444444446, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8564463323708705, "avg_score": 0.019985077647147898, "num_lines": 257 }
"""3D Projective Geometric Algebra. Written by a generator written by enki. """ __author__ = 'Enki' import math class R3: def __init__(self, value=0, index=0): """Initiate a new R3. Optional, the component index can be set with value. """ self.mvec = [0] * 8 self._base = ["1", "e1", "e2", "e3", "e12", "e13", "e23", "e123"] if (value != 0): self.mvec[index] = value @classmethod def fromarray(cls, array): """Initiate a new R3 from an array-like object. The first axis of the array is assumed to correspond to the elements of the algebra, and needs to have the same length. Any other dimensions are left unchanged, and should have simple operations such as addition and multiplication defined. NumPy arrays are therefore a perfect candidate. :param array: array-like object whose length is the dimension of the algebra. :return: new instance of R3. """ self = cls() if len(array) != len(self): raise TypeError('length of array must be identical to the dimension ' 'of the algebra.') self.mvec = array return self def __str__(self): if isinstance(self.mvec, list): res = ' + '.join(filter(None, [("%.7f" % x).rstrip("0").rstrip(".")+(["",self._base[i]][i>0]) if abs(x) > 0.000001 else None for i,x in enumerate(self)])) else: # Assume array-like, redirect str conversion res = str(self.mvec) if (res == ''): return "0" return res def __getitem__(self, key): return self.mvec[key] def __setitem__(self, key, value): self.mvec[key] = value def __len__(self): return len(self.mvec) def __invert__(a): """R3.Reverse Reverse the order of the basis blades. """ res = a.mvec.copy() res[0]=a[0] res[1]=a[1] res[2]=a[2] res[3]=a[3] res[4]=-a[4] res[5]=-a[5] res[6]=-a[6] res[7]=-a[7] return R3.fromarray(res) def Dual(a): """R3.Dual Poincare duality operator. """ res = a.mvec.copy() res[0]=-a[7] res[1]=-a[6] res[2]=a[5] res[3]=-a[4] res[4]=a[3] res[5]=-a[2] res[6]=a[1] res[7]=a[0] return R3.fromarray(res) def Conjugate(a): """R3.Conjugate Clifford Conjugation """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] res[2]=-a[2] res[3]=-a[3] res[4]=-a[4] res[5]=-a[5] res[6]=-a[6] res[7]=a[7] return R3.fromarray(res) def Involute(a): """R3.Involute Main involution """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] res[2]=-a[2] res[3]=-a[3] res[4]=a[4] res[5]=a[5] res[6]=a[6] res[7]=-a[7] return R3.fromarray(res) def __mul__(a,b): """R3.Mul The geometric product. """ if type(b) in (int, float): return a.muls(b) res = a.mvec.copy() res[0]=b[0]*a[0]+b[1]*a[1]+b[2]*a[2]+b[3]*a[3]-b[4]*a[4]-b[5]*a[5]-b[6]*a[6]-b[7]*a[7] res[1]=b[1]*a[0]+b[0]*a[1]-b[4]*a[2]-b[5]*a[3]+b[2]*a[4]+b[3]*a[5]-b[7]*a[6]-b[6]*a[7] res[2]=b[2]*a[0]+b[4]*a[1]+b[0]*a[2]-b[6]*a[3]-b[1]*a[4]+b[7]*a[5]+b[3]*a[6]+b[5]*a[7] res[3]=b[3]*a[0]+b[5]*a[1]+b[6]*a[2]+b[0]*a[3]-b[7]*a[4]-b[1]*a[5]-b[2]*a[6]-b[4]*a[7] res[4]=b[4]*a[0]+b[2]*a[1]-b[1]*a[2]+b[7]*a[3]+b[0]*a[4]-b[6]*a[5]+b[5]*a[6]+b[3]*a[7] res[5]=b[5]*a[0]+b[3]*a[1]-b[7]*a[2]-b[1]*a[3]+b[6]*a[4]+b[0]*a[5]-b[4]*a[6]-b[2]*a[7] res[6]=b[6]*a[0]+b[7]*a[1]+b[3]*a[2]-b[2]*a[3]-b[5]*a[4]+b[4]*a[5]+b[0]*a[6]+b[1]*a[7] res[7]=b[7]*a[0]+b[6]*a[1]-b[5]*a[2]+b[4]*a[3]+b[3]*a[4]-b[2]*a[5]+b[1]*a[6]+b[0]*a[7] return R3.fromarray(res) __rmul__=__mul__ def __xor__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0] res[1]=b[1]*a[0]+b[0]*a[1] res[2]=b[2]*a[0]+b[0]*a[2] res[3]=b[3]*a[0]+b[0]*a[3] res[4]=b[4]*a[0]+b[2]*a[1]-b[1]*a[2]+b[0]*a[4] res[5]=b[5]*a[0]+b[3]*a[1]-b[1]*a[3]+b[0]*a[5] res[6]=b[6]*a[0]+b[3]*a[2]-b[2]*a[3]+b[0]*a[6] res[7]=b[7]*a[0]+b[6]*a[1]-b[5]*a[2]+b[4]*a[3]+b[3]*a[4]-b[2]*a[5]+b[1]*a[6]+b[0]*a[7] return R3.fromarray(res) def __and__(a,b): res = a.mvec.copy() res[7]=1*(a[7]*b[7]) res[6]=1*(a[6]*b[7]+a[7]*b[6]) res[5]=-1*(a[5]*-1*b[7]+a[7]*b[5]*-1) res[4]=1*(a[4]*b[7]+a[7]*b[4]) res[3]=1*(a[3]*b[7]+a[5]*-1*b[6]-a[6]*b[5]*-1+a[7]*b[3]) res[2]=-1*(a[2]*-1*b[7]+a[4]*b[6]-a[6]*b[4]+a[7]*b[2]*-1) res[1]=1*(a[1]*b[7]+a[4]*b[5]*-1-a[5]*-1*b[4]+a[7]*b[1]) res[0]=1*(a[0]*b[7]+a[1]*b[6]-a[2]*-1*b[5]*-1+a[3]*b[4]+a[4]*b[3]-a[5]*-1*b[2]*-1+a[6]*b[1]+a[7]*b[0]) return R3.fromarray(res) def __or__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0]+b[1]*a[1]+b[2]*a[2]+b[3]*a[3]-b[4]*a[4]-b[5]*a[5]-b[6]*a[6]-b[7]*a[7] res[1]=b[1]*a[0]+b[0]*a[1]-b[4]*a[2]-b[5]*a[3]+b[2]*a[4]+b[3]*a[5]-b[7]*a[6]-b[6]*a[7] res[2]=b[2]*a[0]+b[4]*a[1]+b[0]*a[2]-b[6]*a[3]-b[1]*a[4]+b[7]*a[5]+b[3]*a[6]+b[5]*a[7] res[3]=b[3]*a[0]+b[5]*a[1]+b[6]*a[2]+b[0]*a[3]-b[7]*a[4]-b[1]*a[5]-b[2]*a[6]-b[4]*a[7] res[4]=b[4]*a[0]+b[7]*a[3]+b[0]*a[4]+b[3]*a[7] res[5]=b[5]*a[0]-b[7]*a[2]+b[0]*a[5]-b[2]*a[7] res[6]=b[6]*a[0]+b[7]*a[1]+b[0]*a[6]+b[1]*a[7] res[7]=b[7]*a[0]+b[0]*a[7] return R3.fromarray(res) def __add__(a,b): """R3.Add Multivector addition """ if type(b) in (int, float): return a.adds(b) res = a.mvec.copy() res[0] = a[0]+b[0] res[1] = a[1]+b[1] res[2] = a[2]+b[2] res[3] = a[3]+b[3] res[4] = a[4]+b[4] res[5] = a[5]+b[5] res[6] = a[6]+b[6] res[7] = a[7]+b[7] return R3.fromarray(res) __radd__=__add__ def __sub__(a,b): """R3.Sub Multivector subtraction """ if type(b) in (int, float): return a.subs(b) res = a.mvec.copy() res[0] = a[0]-b[0] res[1] = a[1]-b[1] res[2] = a[2]-b[2] res[3] = a[3]-b[3] res[4] = a[4]-b[4] res[5] = a[5]-b[5] res[6] = a[6]-b[6] res[7] = a[7]-b[7] return R3.fromarray(res) def __rsub__(a,b): """R3.Sub Multivector subtraction """ return b + -1 * a def smul(a,b): res = a.mvec.copy() res[0] = a*b[0] res[1] = a*b[1] res[2] = a*b[2] res[3] = a*b[3] res[4] = a*b[4] res[5] = a*b[5] res[6] = a*b[6] res[7] = a*b[7] return R3.fromarray(res) def muls(a,b): res = a.mvec.copy() res[0] = a[0]*b res[1] = a[1]*b res[2] = a[2]*b res[3] = a[3]*b res[4] = a[4]*b res[5] = a[5]*b res[6] = a[6]*b res[7] = a[7]*b return R3.fromarray(res) def sadd(a,b): res = a.mvec.copy() res[0] = a+b[0] res[1] = b[1] res[2] = b[2] res[3] = b[3] res[4] = b[4] res[5] = b[5] res[6] = b[6] res[7] = b[7] return R3.fromarray(res) def adds(a,b): res = a.mvec.copy() res[0] = a[0]+b res[1] = a[1] res[2] = a[2] res[3] = a[3] res[4] = a[4] res[5] = a[5] res[6] = a[6] res[7] = a[7] return R3.fromarray(res) def ssub(a,b): res = a.mvec.copy() res[0] = a-b[0] res[1] = -b[1] res[2] = -b[2] res[3] = -b[3] res[4] = -b[4] res[5] = -b[5] res[6] = -b[6] res[7] = -b[7] return R3.fromarray(res) def subs(a,b): res = a.mvec.copy() res[0] = a[0]-b res[1] = a[1] res[2] = a[2] res[3] = a[3] res[4] = a[4] res[5] = a[5] res[6] = a[6] res[7] = a[7] return R3.fromarray(res) def norm(a): return abs((a * a.Conjugate())[0])**0.5 def inorm(a): return a.Dual().norm() def normalized(a): return a * (1 / a.norm()) e1 = R3(1.0, 1) e2 = R3(1.0, 2) e3 = R3(1.0, 3) e12 = R3(1.0, 4) e13 = R3(1.0, 5) e23 = R3(1.0, 6) e123 = R3(1.0, 7) if __name__ == '__main__': print("e1*e1 :", str(e1*e1)) print("pss :", str(e123)) print("pss*pss :", str(e123*e123))
{ "repo_name": "enkimute/ganja.js", "path": "codegen/python/r3.py", "copies": "1", "size": "8914", "license": "mit", "hash": -6061443992692504000, "line_mean": 26.4276923077, "line_max": 166, "alpha_frac": 0.4099169845, "autogenerated": false, "ratio": 2.265311308767471, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.807903686852229, "avg_score": 0.019238284949036205, "num_lines": 325 }
"""3D Projective Geometric Algebra. Written by a generator written by enki. """ __author__ = 'Enki' import math class SPACETIME: def __init__(self, value=0, index=0): """Initiate a new SPACETIME. Optional, the component index can be set with value. """ self.mvec = [0] * 16 self._base = ["1", "e1", "e2", "e3", "e4", "e12", "e13", "e14", "e23", "e24", "e34", "e123", "e124", "e134", "e234", "e1234"] if (value != 0): self.mvec[index] = value @classmethod def fromarray(cls, array): """Initiate a new SPACETIME from an array-like object. The first axis of the array is assumed to correspond to the elements of the algebra, and needs to have the same length. Any other dimensions are left unchanged, and should have simple operations such as addition and multiplication defined. NumPy arrays are therefore a perfect candidate. :param array: array-like object whose length is the dimension of the algebra. :return: new instance of SPACETIME. """ self = cls() if len(array) != len(self): raise TypeError('length of array must be identical to the dimension ' 'of the algebra.') self.mvec = array return self def __str__(self): if isinstance(self.mvec, list): res = ' + '.join(filter(None, [("%.7f" % x).rstrip("0").rstrip(".")+(["",self._base[i]][i>0]) if abs(x) > 0.000001 else None for i,x in enumerate(self)])) else: # Assume array-like, redirect str conversion res = str(self.mvec) if (res == ''): return "0" return res def __getitem__(self, key): return self.mvec[key] def __setitem__(self, key, value): self.mvec[key] = value def __len__(self): return len(self.mvec) def __invert__(a): """SPACETIME.Reverse Reverse the order of the basis blades. """ res = a.mvec.copy() res[0]=a[0] res[1]=a[1] res[2]=a[2] res[3]=a[3] res[4]=a[4] res[5]=-a[5] res[6]=-a[6] res[7]=-a[7] res[8]=-a[8] res[9]=-a[9] res[10]=-a[10] res[11]=-a[11] res[12]=-a[12] res[13]=-a[13] res[14]=-a[14] res[15]=a[15] return SPACETIME.fromarray(res) def Dual(a): """SPACETIME.Dual Poincare duality operator. """ res = a.mvec.copy() res[0]=-a[15] res[1]=a[14] res[2]=-a[13] res[3]=a[12] res[4]=a[11] res[5]=a[10] res[6]=-a[9] res[7]=-a[8] res[8]=a[7] res[9]=a[6] res[10]=-a[5] res[11]=-a[4] res[12]=-a[3] res[13]=a[2] res[14]=-a[1] res[15]=a[0] return SPACETIME.fromarray(res) def Conjugate(a): """SPACETIME.Conjugate Clifford Conjugation """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] res[2]=-a[2] res[3]=-a[3] res[4]=-a[4] res[5]=-a[5] res[6]=-a[6] res[7]=-a[7] res[8]=-a[8] res[9]=-a[9] res[10]=-a[10] res[11]=a[11] res[12]=a[12] res[13]=a[13] res[14]=a[14] res[15]=a[15] return SPACETIME.fromarray(res) def Involute(a): """SPACETIME.Involute Main involution """ res = a.mvec.copy() res[0]=a[0] res[1]=-a[1] res[2]=-a[2] res[3]=-a[3] res[4]=-a[4] res[5]=a[5] res[6]=a[6] res[7]=a[7] res[8]=a[8] res[9]=a[9] res[10]=a[10] res[11]=-a[11] res[12]=-a[12] res[13]=-a[13] res[14]=-a[14] res[15]=a[15] return SPACETIME.fromarray(res) def __mul__(a,b): """SPACETIME.Mul The geometric product. """ if type(b) in (int, float): return a.muls(b) res = a.mvec.copy() res[0]=b[0]*a[0]+b[1]*a[1]+b[2]*a[2]+b[3]*a[3]-b[4]*a[4]-b[5]*a[5]-b[6]*a[6]+b[7]*a[7]-b[8]*a[8]+b[9]*a[9]+b[10]*a[10]-b[11]*a[11]+b[12]*a[12]+b[13]*a[13]+b[14]*a[14]-b[15]*a[15] res[1]=b[1]*a[0]+b[0]*a[1]-b[5]*a[2]-b[6]*a[3]+b[7]*a[4]+b[2]*a[5]+b[3]*a[6]-b[4]*a[7]-b[11]*a[8]+b[12]*a[9]+b[13]*a[10]-b[8]*a[11]+b[9]*a[12]+b[10]*a[13]-b[15]*a[14]+b[14]*a[15] res[2]=b[2]*a[0]+b[5]*a[1]+b[0]*a[2]-b[8]*a[3]+b[9]*a[4]-b[1]*a[5]+b[11]*a[6]-b[12]*a[7]+b[3]*a[8]-b[4]*a[9]+b[14]*a[10]+b[6]*a[11]-b[7]*a[12]+b[15]*a[13]+b[10]*a[14]-b[13]*a[15] res[3]=b[3]*a[0]+b[6]*a[1]+b[8]*a[2]+b[0]*a[3]+b[10]*a[4]-b[11]*a[5]-b[1]*a[6]-b[13]*a[7]-b[2]*a[8]-b[14]*a[9]-b[4]*a[10]-b[5]*a[11]-b[15]*a[12]-b[7]*a[13]-b[9]*a[14]+b[12]*a[15] res[4]=b[4]*a[0]+b[7]*a[1]+b[9]*a[2]+b[10]*a[3]+b[0]*a[4]-b[12]*a[5]-b[13]*a[6]-b[1]*a[7]-b[14]*a[8]-b[2]*a[9]-b[3]*a[10]-b[15]*a[11]-b[5]*a[12]-b[6]*a[13]-b[8]*a[14]+b[11]*a[15] res[5]=b[5]*a[0]+b[2]*a[1]-b[1]*a[2]+b[11]*a[3]-b[12]*a[4]+b[0]*a[5]-b[8]*a[6]+b[9]*a[7]+b[6]*a[8]-b[7]*a[9]+b[15]*a[10]+b[3]*a[11]-b[4]*a[12]+b[14]*a[13]-b[13]*a[14]+b[10]*a[15] res[6]=b[6]*a[0]+b[3]*a[1]-b[11]*a[2]-b[1]*a[3]-b[13]*a[4]+b[8]*a[5]+b[0]*a[6]+b[10]*a[7]-b[5]*a[8]-b[15]*a[9]-b[7]*a[10]-b[2]*a[11]-b[14]*a[12]-b[4]*a[13]+b[12]*a[14]-b[9]*a[15] res[7]=b[7]*a[0]+b[4]*a[1]-b[12]*a[2]-b[13]*a[3]-b[1]*a[4]+b[9]*a[5]+b[10]*a[6]+b[0]*a[7]-b[15]*a[8]-b[5]*a[9]-b[6]*a[10]-b[14]*a[11]-b[2]*a[12]-b[3]*a[13]+b[11]*a[14]-b[8]*a[15] res[8]=b[8]*a[0]+b[11]*a[1]+b[3]*a[2]-b[2]*a[3]-b[14]*a[4]-b[6]*a[5]+b[5]*a[6]+b[15]*a[7]+b[0]*a[8]+b[10]*a[9]-b[9]*a[10]+b[1]*a[11]+b[13]*a[12]-b[12]*a[13]-b[4]*a[14]+b[7]*a[15] res[9]=b[9]*a[0]+b[12]*a[1]+b[4]*a[2]-b[14]*a[3]-b[2]*a[4]-b[7]*a[5]+b[15]*a[6]+b[5]*a[7]+b[10]*a[8]+b[0]*a[9]-b[8]*a[10]+b[13]*a[11]+b[1]*a[12]-b[11]*a[13]-b[3]*a[14]+b[6]*a[15] res[10]=b[10]*a[0]+b[13]*a[1]+b[14]*a[2]+b[4]*a[3]-b[3]*a[4]-b[15]*a[5]-b[7]*a[6]+b[6]*a[7]-b[9]*a[8]+b[8]*a[9]+b[0]*a[10]-b[12]*a[11]+b[11]*a[12]+b[1]*a[13]+b[2]*a[14]-b[5]*a[15] res[11]=b[11]*a[0]+b[8]*a[1]-b[6]*a[2]+b[5]*a[3]+b[15]*a[4]+b[3]*a[5]-b[2]*a[6]-b[14]*a[7]+b[1]*a[8]+b[13]*a[9]-b[12]*a[10]+b[0]*a[11]+b[10]*a[12]-b[9]*a[13]+b[7]*a[14]-b[4]*a[15] res[12]=b[12]*a[0]+b[9]*a[1]-b[7]*a[2]+b[15]*a[3]+b[5]*a[4]+b[4]*a[5]-b[14]*a[6]-b[2]*a[7]+b[13]*a[8]+b[1]*a[9]-b[11]*a[10]+b[10]*a[11]+b[0]*a[12]-b[8]*a[13]+b[6]*a[14]-b[3]*a[15] res[13]=b[13]*a[0]+b[10]*a[1]-b[15]*a[2]-b[7]*a[3]+b[6]*a[4]+b[14]*a[5]+b[4]*a[6]-b[3]*a[7]-b[12]*a[8]+b[11]*a[9]+b[1]*a[10]-b[9]*a[11]+b[8]*a[12]+b[0]*a[13]-b[5]*a[14]+b[2]*a[15] res[14]=b[14]*a[0]+b[15]*a[1]+b[10]*a[2]-b[9]*a[3]+b[8]*a[4]-b[13]*a[5]+b[12]*a[6]-b[11]*a[7]+b[4]*a[8]-b[3]*a[9]+b[2]*a[10]+b[7]*a[11]-b[6]*a[12]+b[5]*a[13]+b[0]*a[14]-b[1]*a[15] res[15]=b[15]*a[0]+b[14]*a[1]-b[13]*a[2]+b[12]*a[3]-b[11]*a[4]+b[10]*a[5]-b[9]*a[6]+b[8]*a[7]+b[7]*a[8]-b[6]*a[9]+b[5]*a[10]+b[4]*a[11]-b[3]*a[12]+b[2]*a[13]-b[1]*a[14]+b[0]*a[15] return SPACETIME.fromarray(res) __rmul__=__mul__ def __xor__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0] res[1]=b[1]*a[0]+b[0]*a[1] res[2]=b[2]*a[0]+b[0]*a[2] res[3]=b[3]*a[0]+b[0]*a[3] res[4]=b[4]*a[0]+b[0]*a[4] res[5]=b[5]*a[0]+b[2]*a[1]-b[1]*a[2]+b[0]*a[5] res[6]=b[6]*a[0]+b[3]*a[1]-b[1]*a[3]+b[0]*a[6] res[7]=b[7]*a[0]+b[4]*a[1]-b[1]*a[4]+b[0]*a[7] res[8]=b[8]*a[0]+b[3]*a[2]-b[2]*a[3]+b[0]*a[8] res[9]=b[9]*a[0]+b[4]*a[2]-b[2]*a[4]+b[0]*a[9] res[10]=b[10]*a[0]+b[4]*a[3]-b[3]*a[4]+b[0]*a[10] res[11]=b[11]*a[0]+b[8]*a[1]-b[6]*a[2]+b[5]*a[3]+b[3]*a[5]-b[2]*a[6]+b[1]*a[8]+b[0]*a[11] res[12]=b[12]*a[0]+b[9]*a[1]-b[7]*a[2]+b[5]*a[4]+b[4]*a[5]-b[2]*a[7]+b[1]*a[9]+b[0]*a[12] res[13]=b[13]*a[0]+b[10]*a[1]-b[7]*a[3]+b[6]*a[4]+b[4]*a[6]-b[3]*a[7]+b[1]*a[10]+b[0]*a[13] res[14]=b[14]*a[0]+b[10]*a[2]-b[9]*a[3]+b[8]*a[4]+b[4]*a[8]-b[3]*a[9]+b[2]*a[10]+b[0]*a[14] res[15]=b[15]*a[0]+b[14]*a[1]-b[13]*a[2]+b[12]*a[3]-b[11]*a[4]+b[10]*a[5]-b[9]*a[6]+b[8]*a[7]+b[7]*a[8]-b[6]*a[9]+b[5]*a[10]+b[4]*a[11]-b[3]*a[12]+b[2]*a[13]-b[1]*a[14]+b[0]*a[15] return SPACETIME.fromarray(res) def __and__(a,b): res = a.mvec.copy() res[15]=1*(a[15]*b[15]) res[14]=-1*(a[14]*-1*b[15]+a[15]*b[14]*-1) res[13]=1*(a[13]*b[15]+a[15]*b[13]) res[12]=-1*(a[12]*-1*b[15]+a[15]*b[12]*-1) res[11]=1*(a[11]*b[15]+a[15]*b[11]) res[10]=1*(a[10]*b[15]+a[13]*b[14]*-1-a[14]*-1*b[13]+a[15]*b[10]) res[9]=-1*(a[9]*-1*b[15]+a[12]*-1*b[14]*-1-a[14]*-1*b[12]*-1+a[15]*b[9]*-1) res[8]=1*(a[8]*b[15]+a[11]*b[14]*-1-a[14]*-1*b[11]+a[15]*b[8]) res[7]=1*(a[7]*b[15]+a[12]*-1*b[13]-a[13]*b[12]*-1+a[15]*b[7]) res[6]=-1*(a[6]*-1*b[15]+a[11]*b[13]-a[13]*b[11]+a[15]*b[6]*-1) res[5]=1*(a[5]*b[15]+a[11]*b[12]*-1-a[12]*-1*b[11]+a[15]*b[5]) res[4]=-1*(a[4]*-1*b[15]+a[7]*b[14]*-1-a[9]*-1*b[13]+a[10]*b[12]*-1+a[12]*-1*b[10]-a[13]*b[9]*-1+a[14]*-1*b[7]+a[15]*b[4]*-1) res[3]=1*(a[3]*b[15]+a[6]*-1*b[14]*-1-a[8]*b[13]+a[10]*b[11]+a[11]*b[10]-a[13]*b[8]+a[14]*-1*b[6]*-1+a[15]*b[3]) res[2]=-1*(a[2]*-1*b[15]+a[5]*b[14]*-1-a[8]*b[12]*-1+a[9]*-1*b[11]+a[11]*b[9]*-1-a[12]*-1*b[8]+a[14]*-1*b[5]+a[15]*b[2]*-1) res[1]=1*(a[1]*b[15]+a[5]*b[13]-a[6]*-1*b[12]*-1+a[7]*b[11]+a[11]*b[7]-a[12]*-1*b[6]*-1+a[13]*b[5]+a[15]*b[1]) res[0]=1*(a[0]*b[15]+a[1]*b[14]*-1-a[2]*-1*b[13]+a[3]*b[12]*-1-a[4]*-1*b[11]+a[5]*b[10]-a[6]*-1*b[9]*-1+a[7]*b[8]+a[8]*b[7]-a[9]*-1*b[6]*-1+a[10]*b[5]+a[11]*b[4]*-1-a[12]*-1*b[3]+a[13]*b[2]*-1-a[14]*-1*b[1]+a[15]*b[0]) return SPACETIME.fromarray(res) def __or__(a,b): res = a.mvec.copy() res[0]=b[0]*a[0]+b[1]*a[1]+b[2]*a[2]+b[3]*a[3]-b[4]*a[4]-b[5]*a[5]-b[6]*a[6]+b[7]*a[7]-b[8]*a[8]+b[9]*a[9]+b[10]*a[10]-b[11]*a[11]+b[12]*a[12]+b[13]*a[13]+b[14]*a[14]-b[15]*a[15] res[1]=b[1]*a[0]+b[0]*a[1]-b[5]*a[2]-b[6]*a[3]+b[7]*a[4]+b[2]*a[5]+b[3]*a[6]-b[4]*a[7]-b[11]*a[8]+b[12]*a[9]+b[13]*a[10]-b[8]*a[11]+b[9]*a[12]+b[10]*a[13]-b[15]*a[14]+b[14]*a[15] res[2]=b[2]*a[0]+b[5]*a[1]+b[0]*a[2]-b[8]*a[3]+b[9]*a[4]-b[1]*a[5]+b[11]*a[6]-b[12]*a[7]+b[3]*a[8]-b[4]*a[9]+b[14]*a[10]+b[6]*a[11]-b[7]*a[12]+b[15]*a[13]+b[10]*a[14]-b[13]*a[15] res[3]=b[3]*a[0]+b[6]*a[1]+b[8]*a[2]+b[0]*a[3]+b[10]*a[4]-b[11]*a[5]-b[1]*a[6]-b[13]*a[7]-b[2]*a[8]-b[14]*a[9]-b[4]*a[10]-b[5]*a[11]-b[15]*a[12]-b[7]*a[13]-b[9]*a[14]+b[12]*a[15] res[4]=b[4]*a[0]+b[7]*a[1]+b[9]*a[2]+b[10]*a[3]+b[0]*a[4]-b[12]*a[5]-b[13]*a[6]-b[1]*a[7]-b[14]*a[8]-b[2]*a[9]-b[3]*a[10]-b[15]*a[11]-b[5]*a[12]-b[6]*a[13]-b[8]*a[14]+b[11]*a[15] res[5]=b[5]*a[0]+b[11]*a[3]-b[12]*a[4]+b[0]*a[5]+b[15]*a[10]+b[3]*a[11]-b[4]*a[12]+b[10]*a[15] res[6]=b[6]*a[0]-b[11]*a[2]-b[13]*a[4]+b[0]*a[6]-b[15]*a[9]-b[2]*a[11]-b[4]*a[13]-b[9]*a[15] res[7]=b[7]*a[0]-b[12]*a[2]-b[13]*a[3]+b[0]*a[7]-b[15]*a[8]-b[2]*a[12]-b[3]*a[13]-b[8]*a[15] res[8]=b[8]*a[0]+b[11]*a[1]-b[14]*a[4]+b[15]*a[7]+b[0]*a[8]+b[1]*a[11]-b[4]*a[14]+b[7]*a[15] res[9]=b[9]*a[0]+b[12]*a[1]-b[14]*a[3]+b[15]*a[6]+b[0]*a[9]+b[1]*a[12]-b[3]*a[14]+b[6]*a[15] res[10]=b[10]*a[0]+b[13]*a[1]+b[14]*a[2]-b[15]*a[5]+b[0]*a[10]+b[1]*a[13]+b[2]*a[14]-b[5]*a[15] res[11]=b[11]*a[0]+b[15]*a[4]+b[0]*a[11]-b[4]*a[15] res[12]=b[12]*a[0]+b[15]*a[3]+b[0]*a[12]-b[3]*a[15] res[13]=b[13]*a[0]-b[15]*a[2]+b[0]*a[13]+b[2]*a[15] res[14]=b[14]*a[0]+b[15]*a[1]+b[0]*a[14]-b[1]*a[15] res[15]=b[15]*a[0]+b[0]*a[15] return SPACETIME.fromarray(res) def __add__(a,b): """SPACETIME.Add Multivector addition """ if type(b) in (int, float): return a.adds(b) res = a.mvec.copy() res[0] = a[0]+b[0] res[1] = a[1]+b[1] res[2] = a[2]+b[2] res[3] = a[3]+b[3] res[4] = a[4]+b[4] res[5] = a[5]+b[5] res[6] = a[6]+b[6] res[7] = a[7]+b[7] res[8] = a[8]+b[8] res[9] = a[9]+b[9] res[10] = a[10]+b[10] res[11] = a[11]+b[11] res[12] = a[12]+b[12] res[13] = a[13]+b[13] res[14] = a[14]+b[14] res[15] = a[15]+b[15] return SPACETIME.fromarray(res) __radd__=__add__ def __sub__(a,b): """SPACETIME.Sub Multivector subtraction """ if type(b) in (int, float): return a.subs(b) res = a.mvec.copy() res[0] = a[0]-b[0] res[1] = a[1]-b[1] res[2] = a[2]-b[2] res[3] = a[3]-b[3] res[4] = a[4]-b[4] res[5] = a[5]-b[5] res[6] = a[6]-b[6] res[7] = a[7]-b[7] res[8] = a[8]-b[8] res[9] = a[9]-b[9] res[10] = a[10]-b[10] res[11] = a[11]-b[11] res[12] = a[12]-b[12] res[13] = a[13]-b[13] res[14] = a[14]-b[14] res[15] = a[15]-b[15] return SPACETIME.fromarray(res) def __rsub__(a,b): """SPACETIME.Sub Multivector subtraction """ return b + -1 * a def smul(a,b): res = a.mvec.copy() res[0] = a*b[0] res[1] = a*b[1] res[2] = a*b[2] res[3] = a*b[3] res[4] = a*b[4] res[5] = a*b[5] res[6] = a*b[6] res[7] = a*b[7] res[8] = a*b[8] res[9] = a*b[9] res[10] = a*b[10] res[11] = a*b[11] res[12] = a*b[12] res[13] = a*b[13] res[14] = a*b[14] res[15] = a*b[15] return SPACETIME.fromarray(res) def muls(a,b): res = a.mvec.copy() res[0] = a[0]*b res[1] = a[1]*b res[2] = a[2]*b res[3] = a[3]*b res[4] = a[4]*b res[5] = a[5]*b res[6] = a[6]*b res[7] = a[7]*b res[8] = a[8]*b res[9] = a[9]*b res[10] = a[10]*b res[11] = a[11]*b res[12] = a[12]*b res[13] = a[13]*b res[14] = a[14]*b res[15] = a[15]*b return SPACETIME.fromarray(res) def sadd(a,b): res = a.mvec.copy() res[0] = a+b[0] res[1] = b[1] res[2] = b[2] res[3] = b[3] res[4] = b[4] res[5] = b[5] res[6] = b[6] res[7] = b[7] res[8] = b[8] res[9] = b[9] res[10] = b[10] res[11] = b[11] res[12] = b[12] res[13] = b[13] res[14] = b[14] res[15] = b[15] return SPACETIME.fromarray(res) def adds(a,b): res = a.mvec.copy() res[0] = a[0]+b res[1] = a[1] res[2] = a[2] res[3] = a[3] res[4] = a[4] res[5] = a[5] res[6] = a[6] res[7] = a[7] res[8] = a[8] res[9] = a[9] res[10] = a[10] res[11] = a[11] res[12] = a[12] res[13] = a[13] res[14] = a[14] res[15] = a[15] return SPACETIME.fromarray(res) def ssub(a,b): res = a.mvec.copy() res[0] = a-b[0] res[1] = -b[1] res[2] = -b[2] res[3] = -b[3] res[4] = -b[4] res[5] = -b[5] res[6] = -b[6] res[7] = -b[7] res[8] = -b[8] res[9] = -b[9] res[10] = -b[10] res[11] = -b[11] res[12] = -b[12] res[13] = -b[13] res[14] = -b[14] res[15] = -b[15] return SPACETIME.fromarray(res) def subs(a,b): res = a.mvec.copy() res[0] = a[0]-b res[1] = a[1] res[2] = a[2] res[3] = a[3] res[4] = a[4] res[5] = a[5] res[6] = a[6] res[7] = a[7] res[8] = a[8] res[9] = a[9] res[10] = a[10] res[11] = a[11] res[12] = a[12] res[13] = a[13] res[14] = a[14] res[15] = a[15] return SPACETIME.fromarray(res) def norm(a): return abs((a * a.Conjugate())[0])**0.5 def inorm(a): return a.Dual().norm() def normalized(a): return a * (1 / a.norm()) e1 = SPACETIME(1.0, 1) e2 = SPACETIME(1.0, 2) e3 = SPACETIME(1.0, 3) e4 = SPACETIME(1.0, 4) e12 = SPACETIME(1.0, 5) e13 = SPACETIME(1.0, 6) e14 = SPACETIME(1.0, 7) e23 = SPACETIME(1.0, 8) e24 = SPACETIME(1.0, 9) e34 = SPACETIME(1.0, 10) e123 = SPACETIME(1.0, 11) e124 = SPACETIME(1.0, 12) e134 = SPACETIME(1.0, 13) e234 = SPACETIME(1.0, 14) e1234 = SPACETIME(1.0, 15) if __name__ == '__main__': print("e1*e1 :", str(e1*e1)) print("pss :", str(e1234)) print("pss*pss :", str(e1234*e1234))
{ "repo_name": "enkimute/ganja.js", "path": "codegen/python/spacetime.py", "copies": "1", "size": "16879", "license": "mit", "hash": 8925271623927796000, "line_mean": 35.6138828633, "line_max": 226, "alpha_frac": 0.419752355, "autogenerated": false, "ratio": 1.9472773419473928, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.28670296969473924, "avg_score": null, "num_lines": null }
# 3dproj.py # """ Various transforms used for by the 3D code """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six from six.moves import zip import numpy as np import numpy.linalg as linalg def line2d(p0, p1): """ Return 2D equation of line in the form ax+by+c = 0 """ # x + x1 = 0 x0, y0 = p0[:2] x1, y1 = p1[:2] # if x0 == x1: a = -1 b = 0 c = x1 elif y0 == y1: a = 0 b = 1 c = -y1 else: a = (y0-y1) b = (x0-x1) c = (x0*y1 - x1*y0) return a, b, c def line2d_dist(l, p): """ Distance from line to point line is a tuple of coefficients a,b,c """ a, b, c = l x0, y0 = p return abs((a*x0 + b*y0 + c)/np.sqrt(a**2+b**2)) def line2d_seg_dist(p1, p2, p0): """distance(s) from line defined by p1 - p2 to point(s) p0 p0[0] = x(s) p0[1] = y(s) intersection point p = p1 + u*(p2-p1) and intersection point lies within segment if u is between 0 and 1 """ x21 = p2[0] - p1[0] y21 = p2[1] - p1[1] x01 = np.asarray(p0[0]) - p1[0] y01 = np.asarray(p0[1]) - p1[1] u = (x01*x21 + y01*y21)/float(abs(x21**2 + y21**2)) u = np.clip(u, 0, 1) d = np.sqrt((x01 - u*x21)**2 + (y01 - u*y21)**2) return d def mod(v): """3d vector length""" return np.sqrt(v[0]**2+v[1]**2+v[2]**2) def world_transformation(xmin, xmax, ymin, ymax, zmin, zmax): dx, dy, dz = (xmax-xmin), (ymax-ymin), (zmax-zmin) return np.array([ [1.0/dx,0,0,-xmin/dx], [0,1.0/dy,0,-ymin/dy], [0,0,1.0/dz,-zmin/dz], [0,0,0,1.0]]) def view_transformation(E, R, V): n = (E - R) ## new # n /= mod(n) # u = np.cross(V,n) # u /= mod(u) # v = np.cross(n,u) # Mr = np.diag([1.]*4) # Mt = np.diag([1.]*4) # Mr[:3,:3] = u,v,n # Mt[:3,-1] = -E ## end new ## old n = n / mod(n) u = np.cross(V, n) u = u / mod(u) v = np.cross(n, u) Mr = [[u[0],u[1],u[2],0], [v[0],v[1],v[2],0], [n[0],n[1],n[2],0], [0, 0, 0, 1], ] # Mt = [[1, 0, 0, -E[0]], [0, 1, 0, -E[1]], [0, 0, 1, -E[2]], [0, 0, 0, 1]] ## end old return np.dot(Mr, Mt) def persp_transformation(zfront, zback): a = (zfront+zback)/(zfront-zback) b = -2*(zfront*zback)/(zfront-zback) return np.array([[1,0,0,0], [0,1,0,0], [0,0,a,b], [0,0,-1,0] ]) def ortho_transformation(zfront, zback): # note: w component in the resulting vector will be (zback-zfront), not 1 a = -(zfront + zback) b = -(zfront - zback) return np.array([[2,0,0,0], [0,2,0,0], [0,0,-2,0], [0,0,a,b] ]) def proj_transform_vec(vec, M): vecw = np.dot(M, vec) w = vecw[3] # clip here.. txs, tys, tzs = vecw[0]/w, vecw[1]/w, vecw[2]/w return txs, tys, tzs def proj_transform_vec_clip(vec, M): vecw = np.dot(M, vec) w = vecw[3] # clip here. txs, tys, tzs = vecw[0] / w, vecw[1] / w, vecw[2] / w tis = (0 <= vecw[0]) & (vecw[0] <= 1) & (0 <= vecw[1]) & (vecw[1] <= 1) if np.any(tis): tis = vecw[1] < 1 return txs, tys, tzs, tis def inv_transform(xs, ys, zs, M): iM = linalg.inv(M) vec = vec_pad_ones(xs, ys, zs) vecr = np.dot(iM, vec) try: vecr = vecr/vecr[3] except OverflowError: pass return vecr[0], vecr[1], vecr[2] def vec_pad_ones(xs, ys, zs): return np.array([xs, ys, zs, np.ones_like(xs)]) def proj_transform(xs, ys, zs, M): """ Transform the points by the projection matrix """ vec = vec_pad_ones(xs, ys, zs) return proj_transform_vec(vec, M) def proj_transform_clip(xs, ys, zs, M): """ Transform the points by the projection matrix and return the clipping result returns txs,tys,tzs,tis """ vec = vec_pad_ones(xs, ys, zs) return proj_transform_vec_clip(vec, M) transform = proj_transform def proj_points(points, M): return list(zip(*proj_trans_points(points, M))) def proj_trans_points(points, M): xs, ys, zs = list(zip(*points)) return proj_transform(xs, ys, zs, M) def proj_trans_clip_points(points, M): xs, ys, zs = list(zip(*points)) return proj_transform_clip(xs, ys, zs, M) def rot_x(V, alpha): cosa, sina = np.cos(alpha), np.sin(alpha) M1 = np.array([[1,0,0,0], [0,cosa,-sina,0], [0,sina,cosa,0], [0,0,0,1]]) return np.dot(M1, V)
{ "repo_name": "louisLouL/pair_trading", "path": "capstone_env/lib/python3.6/site-packages/mpl_toolkits/mplot3d/proj3d.py", "copies": "2", "size": "4775", "license": "mit", "hash": -638823608366406400, "line_mean": 22.5221674877, "line_max": 77, "alpha_frac": 0.4827225131, "autogenerated": false, "ratio": 2.5039328788673307, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3986655391967331, "avg_score": null, "num_lines": null }
#3D Reconstruct from a tilt series using Direct Fourier Method # #NOTE: Tilt Axis needs to be in the third dimension # #developed as part of the tomviz project (www.tomviz.com) def transform_scalars(dataset): from tomviz import utils import numpy as np #----USER SPECIFIED VARIABLES-----# TILT_AXIS = [] #Specify the tilt axis, if none is specified #it assume it is the smallest dimension ANGLES = [] #Specify the angles used in the tiltseries #For example, ANGLES = np.linspace(0,140,70) #---------------------------------# data_py = utils.get_array(dataset) if data_py is None: raise RuntimeError("No scalars found!") if TILT_AXIS == []: #If tilt axis is not given, find it #Find smallest array dimension, assume it is the tilt angle axis if data_py.ndim == 3: TILT_AXIS = np.argmin( data_py.shape ) elif data_py.ndim == 2: raise RuntimeError("Data Array is 2 dimensions, it should be 3!") else: raise RuntimeError("Data Array is not 2 or 3 dimensions!") if ANGLES == []: #If angles are not given, assume 2 degree tilts angles = np.linspace(0,146,74) dimx = np.size(data_py,0) #IN THE FUTURE THIS SHOULD NOT BE ASSUMED result3D = dfm3(data_py,angles,dimx) # set the result as the new scalars. utils.set_array(dataset, result3D) print('Reconsruction Complete') #dfm3(input,angles,Npad) #3D Direct Fourier Method #Use numpy fft # #Yi Jiang #08/25/2014 #input: aligned data #angles: projection angles #N_pad: size of padded projection. typical choice: twice as the original projection import numpy as np def dfm3(input,angles,Npad): print "You are using 3D direct fourier method, be patient." input = np.double(input) (Nx,Ny,Np) = input.shape angles = np.double(angles) cen = np.floor(Ny/2) cen_pad = np.floor(Npad/2) pad_post = np.ceil((Npad-Ny)/2); pad_pre = np.floor((Npad-Ny)/2) #initialize value and weight matrix print "initialization" Nz = Ny w = np.zeros((Nx,Ny,Nz)) v = np.zeros((Nx,Ny,Nz)) + 1j*np.zeros((Nx,Ny,Nz)) dk = np.double(Ny)/np.double(Npad) *1 for a in range(0,Np): print angles[a] ang = angles[a]*np.pi/180 projection = input[:,:,a] #projection p = np.lib.pad(projection,((0,0),(pad_pre,pad_post)),'constant',constant_values=(0,0)) #pad zeros p = np.fft.ifftshift(p) pF = np.fft.fft2(p) pF = np.fft.fftshift(pF) #bilinear extrapolation for i in range(0, np.int(Npad)): ky = (i-cen_pad)*dk; #kz = 0; ky_new = np.cos(ang)*ky #new coord. after rotation kz_new = np.sin(ang)*ky sy = abs(np.floor(ky_new) - ky_new) #calculate weights sz = abs(np.floor(kz_new) - kz_new) for b in range(1,5): #bilinear extrapolation pz,py,weight = bilinear(kz_new,ky_new,sz,sy,Ny,b) pz = pz + cen; py = py + cen; if (py>=0 and py<Ny and pz>=0 and pz<Nz): w[:,py,pz] = w[:,py,pz] + weight v[:,py,pz] = v[:,py,pz] + weight * pF[:,i] v[w!=0] = v[w!=0]/w[w!=0] v = np.fft.ifftshift(v) recon = np.real(np.fft.ifftn(v)) recon = np.fft.fftshift(recon) return recon def bilinear(kz_new,ky_new,sz,sy,N,p): if p==1: py = np.floor(ky_new) pz = np.floor(kz_new) weight = (1-sy)*(1-sz) elif p==2: py = np.ceil(ky_new) #P2 pz = np.floor(kz_new) weight = sy*(1-sz) elif p==3: py = np.floor(ky_new) #P3 pz = np.ceil(kz_new) weight = (1-sy)*sz elif p==4: py = np.ceil(ky_new) #P4 pz = np.ceil(kz_new) weight = sy*sz if py<0: py = N+py else: py = py return (pz,py,weight)
{ "repo_name": "yijiang1/tomviz", "path": "tomviz/python/Recon_DFT.py", "copies": "2", "size": "3883", "license": "bsd-3-clause", "hash": -9173106542765551000, "line_mean": 30.8278688525, "line_max": 105, "alpha_frac": 0.5717228947, "autogenerated": false, "ratio": 2.9195488721804512, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4491271766880452, "avg_score": null, "num_lines": null }
"""3D renderer module """ # Uses jsc3d: https://github.com/humu2009/jsc3d/tree/master/jsc3d import os import furl from mako.lookup import TemplateLookup from mfr.core import extension from mfr.extensions.jsc3d import settings from mfr.extensions.utils import munge_url_for_localdev, escape_url_for_template class JSC3DRenderer(extension.BaseRenderer): TEMPLATE = TemplateLookup( directories=[ os.path.join(os.path.dirname(__file__), 'templates') ]).get_template('viewer.mako') def render(self): self.metrics.add('needs_export', False) if self.metadata.ext in settings.EXPORT_EXCLUSIONS: download_url = munge_url_for_localdev(self.metadata.download_url) safe_url = escape_url_for_template(download_url.geturl()) return self.TEMPLATE.render( base=self.assets_url, url=safe_url, ext=self.metadata.ext.lower(), ) exported_url = furl.furl(self.export_url) exported_url.args['format'] = settings.EXPORT_TYPE self.metrics.add('needs_export', True) safe_url = escape_url_for_template(exported_url.url) return self.TEMPLATE.render( base=self.assets_url, url=safe_url, ext=settings.EXPORT_TYPE, ) @property def file_required(self): return False @property def cache_result(self): return False
{ "repo_name": "felliott/modular-file-renderer", "path": "mfr/extensions/jsc3d/render.py", "copies": "2", "size": "1455", "license": "apache-2.0", "hash": -6230121727354762000, "line_mean": 29.9574468085, "line_max": 80, "alpha_frac": 0.6336769759, "autogenerated": false, "ratio": 3.6649874055415617, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00026267402153926973, "num_lines": 47 }
#3d room import math memoP = {} memoC = {} memoC[0] = 0 def shortestCuboidPathSq(w, h, l): p1sq = (h+l) * (h+l) + w * w p2sq = (w+h) * (w+h) + l * l p3sq = (w+l) * (w+l) + h * h return min(p1sq, p2sq, p3sq) def isCuboidPathInteger(w, h, l): pathSq = shortestCuboidPathSq(w, h, l) path = math.floor(math.sqrt(pathSq)) return path*path == pathSq def memoPCheck(fn, w, h, l): k = (w,h,l) if k in memoP.keys(): return memoP[k] else: r = fn(w,h,l) memoP[k] = r return r def memoCCheck(fn, k): if k in memoC.keys(): return memoC[k] else: r = fn(k) memoC[k] = r return r # possiveis otimizacoes: # eliminar casos com lados iguais (não pode) # eliminar casos que nao sao primos (deve memoizar se for o caso) ##def countIntegerCuboids(m): ## count = 0 ## for w in range(m, 0, -1): ## for h in range(w, m+1): ## for l in range(h, m+1): ## if memoPCheck(isCuboidPathInteger,w, h, l): ## count += 1 ## return count def countIntegerCuboidsR(m): if m <= 0: return 0 else: count = 0 w = m for h in range(1, w+1): for l in range(1, h+1): if isCuboidPathInteger(w, h, l): count += 1 return count + memoCCheck(countIntegerCuboidsR, m - 1) def firstToExceed(n): m = 1 while True: #c = countIntegerCuboids(m) c = countIntegerCuboidsR(m) #print(m, c) if c > n: print(m, c) return m; m += 1 #w = 6 #h = 3 #l = 5 #print(isCuboidPathInteger(w, h, l)) #print(isCuboidPathInteger(1, 1, 1)) #print(countIntegerCuboids(9)) #print(countIntegerCuboids(99)) def euler86(n): w = 1 while True: for h in range(1, w+1): for l in range(1, h+1): if isCuboidPathInteger(w, h, l): count += 1 print(count, w, h, l) if count > n: return n w += 1 firstToExceed(1000000)
{ "repo_name": "feliposz/project-euler-solutions", "path": "python/euler86.py", "copies": "1", "size": "2126", "license": "mit", "hash": 710832501234180700, "line_mean": 21.1354166667, "line_max": 67, "alpha_frac": 0.4988235294, "autogenerated": false, "ratio": 2.7208706786171577, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.37196942080171574, "avg_score": null, "num_lines": null }
# 3D surface fitting to N random points # using inverse distance weighted averages. # FB - 201003162 from PIL import Image import random import math # image size imgx = 512 imgy = 512 image = Image.new("RGB", (imgx, imgy)) # random color palette coefficients kr = random.randint(1, 7) kg = random.randint(1, 7) kb = random.randint(1, 7) ir = 2**kr ig = 2**kg ib = 2**kb jr = 2**(8-kr) jg = 2**(8-kg) jb = 2**(8-kb) # select n random points n=random.randint(5, 50) arx=[] ary=[] arz=[] for i in range(n): arx.append(random.randint(0, imgx-1)) ary.append(random.randint(0, imgy-1)) arz.append(random.randint(0, 255)) for y in range(imgy): for x in range(imgx): flag=False sumv=0.0 sumw=0.0 for i in range(n): dx=x-arx[i] dy=y-ary[i] if(dx==0 and dy==0): flag=True z=arz[i] break else: # wgh=1.0/math.pow(math.sqrt(dx*dx+dy*dy),1.0) # linear wgh=1.0/math.pow(math.sqrt(dx*dx+dy*dy),2.0) # quadratic # wgh=1.0/math.pow(math.sqrt(dx*dx+dy*dy),3.0) # cubic sumw+=wgh sumv+=(wgh*arz[i]) if flag==False: z=int(sumv/sumw) # z to RGB r = z % ir * jr g = z % ig * jg b = z % ib * jb image.putpixel((x, y), b * 65536 + g * 256 + r) image.save("rndSurface.png", "PNG")
{ "repo_name": "ActiveState/code", "path": "recipes/Python/577119_3d_Surface_fitting_N_random/recipe-577119.py", "copies": "1", "size": "1460", "license": "mit", "hash": -6081211230372909000, "line_mean": 22.1746031746, "line_max": 72, "alpha_frac": 0.5164383562, "autogenerated": false, "ratio": 2.7547169811320753, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8678632663385175, "avg_score": 0.01850453478938018, "num_lines": 63 }
## 3-D tictactoe Ruth Chabay 2000/05 from visual import * from tictacdat import * scene.width=600 scene.height=600 scene.title="3D TicTacToe: 4 in a row" # draw board gray = (1,1,1) yo=2. base=grid (n=4, ds=1, gridcolor=gray) base.pos=base.pos+vector(-0.5, -2., -0.5) second=grid(n=4, ds=1, gridcolor=gray) second.pos=second.pos+vector(-0.5, -1., -0.5) third=grid(n=4, ds=1, gridcolor=gray) third.pos=third.pos+vector(-0.5, 0, -0.5) top=grid(n=4, ds=1, gridcolor=gray) top.pos=top.pos+vector(-0.5, 1., -0.5) # get list of winning combinations wins=win() print("****************************************") print("Drag ball up starting from bottom grid.") print("Release to deposit ball in a square.") print("****************************************") print(" ") # make sliders bars={} balls={} form = '{0[0]} {0[1]} {0[2]}' for x in arange(-2, 2,1): for z in arange(-2, 2,1): cyl=cylinder(pos=(x,-2,z), axis=(0,3,0), radius=0.05, visible=0) loc = (int(round(x)),int(round(-yo)),int(round(z))) bars[form.format(loc)]=cyl # set reasonable viewing angle scene.center=(-.5,-.5,-.5) scene.forward = (0,-0.05,-1) scene.autoscale=0 nballs=0 visbar=None red=(1,0,0) blue=(.3,.3,1) bcolor=red point=None won=None while len(balls) < 4*4*4: while True: rate(100) if scene.mouse.events: p = scene.mouse.getevent() if p.drag: point=p.project(normal=vector(0,1,0),d=-yo) # 'None' if not in plane break if point == None: continue # chose valid square point=(int(round(point[0])), int(round(point[1])), int(round(point[2]))) if not (visbar==None): visbar.visible=0 lookup = form.format(point) if not (lookup in bars): continue visbar=bars[lookup] visbar.visible=1 nballs=nballs+1 b=sphere(pos=point, radius=0.3, color=bcolor) while not scene.mouse.events: rate(100) y=scene.mouse.pos.y if y > 1.: y=1. if y < -yo: y=-yo b.y=y scene.mouse.getevent() # get rid of drop depositing ball bpoint=(int(round(b.x)), int(round(b.y)), int(round(b.z))) lookup = form.format(bpoint) if not(form.format(lookup) in balls): # not already a ball there b.pos=bpoint balls[lookup]=b if bcolor==red: bcolor=blue else:bcolor=red else: ## already a ball there, so abort b.visible=0 visbar.visible=0 visbar=None # check for four in a row for a in wins: a0=a[0] in balls a1=a[1] in balls a2=a[2] in balls a3=a[3] in balls if a0 and a1 and a2 and a3: ccolor=balls[a[0]].color if balls[a[1]].color==balls[a[2]].color==balls[a[3]].color==ccolor: won=ccolor print(" ") if ccolor==red: print("***********") print(" Red wins!") print("***********") else: print("***********") print(" Blue wins!") print("***********") for flash in range(5): sleep(0.1) balls[a[0]].color=(1,1,1) balls[a[1]].color=(1,1,1) balls[a[2]].color=(1,1,1) balls[a[3]].color=(1,1,1) sleep(0.1) balls[a[0]].color=ccolor balls[a[1]].color=ccolor balls[a[2]].color=ccolor balls[a[3]].color=ccolor rate(10) break if not (won==None): break print("game over")
{ "repo_name": "crmathieu/Orbital", "path": "visual/examples/tictac.py", "copies": "1", "size": "3713", "license": "mit", "hash": -4811907296012711000, "line_mean": 27.7829457364, "line_max": 86, "alpha_frac": 0.502827902, "autogenerated": false, "ratio": 3.006477732793522, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4009305634793522, "avg_score": null, "num_lines": null }
# 3D tidal channel demo # ===================== # # .. highlight:: python # # This example demonstrates a 3D barotropic model in a tidal channel with sloping # bathymetry. We also add a constant, passive salinity tracer to demonstrate local # tracer conservation. This simulation uses the ALE moving mesh. # # We begin by defining the 2D mesh as before:: from thetis import * lx = 100e3 ly = 6e3 nx = 33 ny = 2 mesh2d = RectangleMesh(nx, ny, lx, ly) # In this case we define a linearly sloping bathymetry in the x-direction. # The bathymetry function is defined as an # `UFL <http://fenics-ufl.readthedocs.io/en/latest/>`_ expression making use of the # coordinates of the 2D mesh. # The expression is interpolated on the P1 bathymetry field:: P1_2d = FunctionSpace(mesh2d, 'CG', 1) bathymetry_2d = Function(P1_2d, name='Bathymetry') depth_oce = 20.0 depth_riv = 7.0 xy = SpatialCoordinate(mesh2d) bath_ufl_expr = depth_oce - (depth_oce-depth_riv)*xy[0]/lx bathymetry_2d.interpolate(bath_ufl_expr) # Next we create the 3D solver. The 2D mesh will be extruded in the vertical # direction using a constant number of layers:: n_layers = 6 solver_obj = solver.FlowSolver(mesh2d, bathymetry_2d, n_layers) # We then set some options (see :py:class:`~.ModelOptions` for more information):: options = solver_obj.options options.element_family = 'dg-dg' options.timestepper_type = 'SSPRK22' options.use_implicit_vertical_diffusion = False options.use_bottom_friction = False options.use_ale_moving_mesh = True options.use_limiter_for_tracers = True options.simulation_export_time = 900.0 options.simulation_end_time = 24 * 3600 options.fields_to_export = ['uv_2d', 'elev_2d', 'elev_3d', 'uv_3d', 'w_3d', 'w_mesh_3d', 'salt_3d', 'baroc_head_3d', 'uv_dav_2d'] # We set this simulation to be barotropic (i.e. salinity and temperature do not # affect water density), but we still wish to simulate salinity as a passive # tracer:: options.use_baroclinic_formulation = False options.solve_salinity = True options.solve_temperature = False # We also want to see how much the salinity value deviates from its initial # value:: options.check_salinity_overshoot = True # In this simulation we do not set the time step manually but instead use the # automatic time step estimation of Thetis. Time step is estimated based on the # CFL number, used spatial discretization and time integration # method. We only need to define maximal horizontal and vertical velocity scales:: u_max = 0.5 w_max = 2e-4 options.horizontal_velocity_scale = Constant(u_max) options.vertical_velocity_scale = Constant(w_max) # Next we define the boundary conditions. Note that in a 3D model there are # multiple coupled equations, and we need to set boundary conditions to all of # them. # # In this example we impose time dependent normal flux on both the deep (ocean) # and shallow (river) boundaries. We begin by creating python functions that # define the time dependent fluxes. Note that we use a linear ramp-up function on # both boundaries:: ocean_bnd_id = 1 river_bnd_id = 2 un_amp = -0.5 # tidal normal velocity amplitude (m/s) flux_amp = ly*depth_oce*un_amp t_tide = 12 * 3600. # tidal period (s) un_river = -0.05 # constant river flow velocity (m/s) flux_river = ly*depth_riv*un_river t_ramp = 6*3600.0 # use linear ramp up for boundary forcings def ocean_flux_func(t): return (flux_amp*sin(2 * pi * t / t_tide) - flux_river)*min(t/t_ramp, 1.0) def river_flux_func(t): return flux_river*min(t/t_ramp, 1.0) # We then define :py:class:`~.firedrake.constant.Constant` objects for the fluxes and # use them as boundary conditions for the 2D shallow water model:: ocean_flux = Constant(ocean_flux_func(0)) river_flux = Constant(river_flux_func(0)) ocean_funcs = {'flux': ocean_flux} river_funcs = {'flux': river_flux} solver_obj.bnd_functions['shallow_water'] = {ocean_bnd_id: ocean_funcs, river_bnd_id: river_funcs} # The volume fluxes are now defined in the 2D mode, so there's no need to impose # anything in the 3D momentum equation. We therefore only use symmetry condition # for 3D horizontal velocity:: ocean_funcs_3d = {'symm': None} river_funcs_3d = {'symm': None} solver_obj.bnd_functions['momentum'] = {ocean_bnd_id: ocean_funcs_3d, river_bnd_id: river_funcs_3d} # For the salinity, we define a constant value and apply as inflow conditions # at the open boundaries:: salt_init3d = Constant(4.5) ocean_salt_3d = {'value': salt_init3d} river_salt_3d = {'value': salt_init3d} solver_obj.bnd_functions['salt'] = {ocean_bnd_id: ocean_salt_3d, river_bnd_id: river_salt_3d} # As before, all boundaries where boundary conditions are not assigned are # assumed to be impermeable land boundaries. # # We now need to define the callback functions that update all time dependent # forcing fields. As the 2D and 3D modes may be treated separately in the time # integrator we create a different call back for the two modes:: def update_forcings_2d(t_new): """Callback function that updates all time dependent forcing fields for the 2D mode""" ocean_flux.assign(ocean_flux_func(t_new)) river_flux.assign(river_flux_func(t_new)) def update_forcings_3d(t_new): """Callback function that updates all time dependent forcing fields for the 3D mode""" pass # Because the boundary conditions of the 3D equations do not depend on time, the # 3d callback function does nothing (it could be omitted). # # We then assign the constant salinity value as an initial condition:: solver_obj.assign_initial_conditions(salt=salt_init3d) # and run the simulation:: solver_obj.iterate(update_forcings=update_forcings_2d, update_forcings3d=update_forcings_3d) # As you run the simulation, Thetis prints out the normal simulation statistics # and also prints out the over/undershoots in the salinity field: # # .. code-block:: none # # 0 0 T= 0.00 eta norm: 0.0000 u norm: 0.0000 0.00 # salt_3d overshoot 0 0 # 1 5 T= 900.00 eta norm: 15.1764 u norm: 0.0000 1.23 # salt_3d overshoot -1.00586e-11 2.58318e-11 # 2 10 T= 1800.00 eta norm: 83.4282 u norm: 0.0000 0.39 # salt_3d overshoot -3.13083e-11 3.42579e-11 # 3 15 T= 2700.00 eta norm: 229.6974 u norm: 0.0000 0.35 # salt_3d overshoot -6.35199e-11 6.6346e-11 # # Note that here the ``u norm`` is the norm of :math:`\mathbf{u}'`, i.e. the prognostic 3D # horizontal velocity field (3D velocity minus its vertical average). # # This tutorial can be dowloaded as a Python script `here <demo_3d_channel.py>`__.
{ "repo_name": "tkarna/cofs", "path": "demos/demo_3d_channel.py", "copies": "2", "size": "6787", "license": "mit", "hash": -2456392084588889000, "line_mean": 35.4892473118, "line_max": 90, "alpha_frac": 0.6986886695, "autogenerated": false, "ratio": 3.0724309642372116, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47711196337372114, "avg_score": null, "num_lines": null }
'3D visualization tools' # Authors: Afshine Amidi <lastname@mit.edu> # Shervine Amidi <firstname@stanford.edu> # MIT License import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from enzynet.PDB import PDB_backbone from enzynet.volume import adjust_size, coords_to_volume, coords_center_to_zero, weights_to_volume def visualize_pdb(pdb_id, p=5, v_size=32, num=1, weights=None, max_radius=40, noise_treatment=True): 'Plots PDB in a volume and saves it in a file' # Get coordinates pdb = PDB_backbone(pdb_id) pdb.get_coords_extended(p=p) if weights != None: pdb.get_weights_extended(p=p, weights=weights) # Center to 0 coords = coords_center_to_zero(pdb.backbone_coords_ext) # Adjust size coords = adjust_size(coords, v_size, max_radius) if weights == None: # Convert to volume volume = coords_to_volume(coords, v_size, noise_treatment=noise_treatment) else: # Converts to volume of weights volume = weights_to_volume(coords, pdb.backbone_weights_ext, v_size, noise_treatment=noise_treatment) # Plot plot_volume(volume, pdb_id, v_size, num, weights=weights) # 3D plot, sources: http://stackoverflow.com/a/35978146/4124317 # https://dawes.wordpress.com/2014/06/27/publication-ready-3d-figures-from-matplotlib/ def plot_volume(volume, pdb_id, v_size, num, weights=None): 'Plots volume in 3D, interpreting the coordinates as voxels' # Initialization plt.rc('text', usetex=True) plt.rc('font', family='serif') fig = plt.figure(figsize=(4,4)) ax = fig.gca(projection='3d') ax.set_aspect('equal') # Parameters len_vol = volume.shape[0] # Set position of the view ax.view_init(elev=20, azim=135) # Hide tick labels ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_zticklabels([]) # Plot if weights == None: plot_matrix(ax, volume) else: plot_matrix_of_weights(ax, volume) # Tick at every unit ax.set_xticks(np.arange(len_vol)) ax.set_yticks(np.arange(len_vol)) ax.set_zticks(np.arange(len_vol)) # Min and max that can be seen ax.set_xlim(0, len_vol-1) ax.set_ylim(0, len_vol-1) ax.set_zlim(0, len_vol-1) # Clear grid ax.xaxis.pane.set_edgecolor('black') ax.yaxis.pane.set_edgecolor('black') ax.xaxis.pane.fill = False ax.yaxis.pane.fill = False ax.zaxis.pane.fill = False # Change thickness of grid ax.xaxis._axinfo["grid"]['linewidth'] = 0.1 ax.yaxis._axinfo["grid"]['linewidth'] = 0.1 ax.zaxis._axinfo["grid"]['linewidth'] = 0.1 # Change thickness of ticks ax.xaxis._axinfo["tick"]['linewidth'] = 0.1 ax.yaxis._axinfo["tick"]['linewidth'] = 0.1 ax.zaxis._axinfo["tick"]['linewidth'] = 0.1 # Change tick placement ax.xaxis._axinfo['tick']['inward_factor'] = 0 ax.xaxis._axinfo['tick']['outward_factor'] = 0.2 ax.yaxis._axinfo['tick']['inward_factor'] = 0 ax.yaxis._axinfo['tick']['outward_factor'] = 0.2 ax.zaxis._axinfo['tick']['inward_factor'] = 0 ax.zaxis._axinfo['tick']['outward_factor'] = 0.2 ax.zaxis._axinfo['tick']['outward_factor'] = 0.2 # Save plt.savefig('../scripts/volume/' + str(pdb_id) + '_' + str(v_size) + '_' + str(weights) + '_' + str(num) + '.pdf') def cuboid_data(pos, size=(1,1,1)): 'Gets coordinates of cuboid' # Gets the (left, outside, bottom) point o = [a - b / 2 for a, b in zip(pos, size)] # Get the length, width, and height l, w, h = size x = [[o[0], o[0] + l, o[0] + l, o[0], o[0]] for i in range(4)] y = [[o[1], o[1], o[1] + w, o[1] + w, o[1]], [o[1], o[1], o[1] + w, o[1] + w, o[1]], [o[1], o[1], o[1], o[1], o[1]], [o[1] + w, o[1] + w, o[1] + w, o[1] + w, o[1] + w]] z = [[o[2], o[2], o[2], o[2], o[2]], [o[2] + h, o[2] + h, o[2] + h, o[2] + h, o[2] + h], [o[2], o[2], o[2] + h, o[2] + h, o[2]], [o[2], o[2], o[2] + h, o[2] + h, o[2]]] return x, y, z def plot_cube_at(pos=(0,0,0), ax=None): 'Plots a cube element at position pos' if ax != None: X, Y, Z = cuboid_data(pos) ax.plot_surface(X, Y, Z, color='g', rstride=1, cstride=1, alpha=1) def plot_cube_weights_at(pos=(0,0,0), ax=None, color='g'): 'Plots a cube element at position pos' if ax != None: X, Y, Z = cuboid_data(pos) ax.plot_surface(X, Y, Z, color=color, rstride=1, cstride=1, alpha=1) def plot_matrix(ax, matrix): 'Plots cubes from a volumic matrix' for i in range(matrix.shape[0]): for j in range(matrix.shape[1]): for k in range(matrix.shape[2]): if matrix[i,j,k] == 1: plot_cube_at(pos=(i-0.5,j-0.5,k-0.5), ax=ax) def plot_matrix_of_weights(ax, matrix_of_weights): 'Plots cubes from a volumic matrix' # Initialization min_value = np.amin(matrix_of_weights) max_value = np.amax(matrix_of_weights) n_colors = 101 # Check if matrix of weights or not if min_value == max_value == 1: return plot_matrix(ax, matrix_of_weights) # Generate colors cm = plt.get_cmap('seismic') cgen = [cm(1.*i/n_colors) for i in range(n_colors)] # Plot cubes for i in range(matrix_of_weights.shape[0]): for j in range(matrix_of_weights.shape[1]): for k in range(matrix_of_weights.shape[2]): if matrix_of_weights[i,j,k] != 0: # Translate to [0,100] normalized_weight = (matrix_of_weights[i,j,k] - min_value)/ \ (max_value - min_value) normalized_weight = int(100*normalized_weight) # Plot cube with color plot_cube_weights_at(pos=(i-0.5,j-0.5,k-0.5), ax=ax, color=cgen[normalized_weight]) if __name__ == '__main__': visualize_pdb('2Q3Z', p=0, v_size=32, weights=None)
{ "repo_name": "shervinea/enzynet", "path": "enzynet/visualization.py", "copies": "1", "size": "6094", "license": "mit", "hash": -1721245739844582700, "line_mean": 32.8555555556, "line_max": 104, "alpha_frac": 0.5725303577, "autogenerated": false, "ratio": 2.8881516587677725, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8938587731326193, "avg_score": 0.004418857028315789, "num_lines": 180 }
# 3D Volume Graph using Mayavi # 2015-09-09 # By Jay and Cheng # This program reads ascfiles from 'filedir', creates 3d matrix, # uses mayavi display the 3d matrix, and also saves a screenshot in # the working directory. # Notice: Files must be in some format, and the filedir must be specified from os import listdir from os.path import isfile, join import fileinput import numpy as np from mayavi import mlab filedir='/Users/czhang/Desktop/Mayavi/ascfiles2/' # read meta data from the first 6 line of the asc file def metadataforfile(filename): metadata=[None]*6 nrows=ncols=None x=y=None cellsize=None nodata_value=None print filedir+filename for line in fileinput.input([filedir+filename]): arg, val = str.split(line) print arg, val if arg == "nrows": nrows = int(val) metadata[0]=nrows if arg == "ncols": ncols = int(val) metadata[1]=ncols if arg == "xllcorner": x = float(val) metadata[3]=x if arg == "yllcorner": y = float(val) metadata[4]=y if arg == "cellsize": cellsize=float(val) metadata[2]=cellsize if arg == "NODATA_value": nodata_value=float(val) metadata[5]=nodata_value if fileinput.filelineno()>=6: break fileinput.close() return metadata # read data from one file def filedataforfile(filenum): filename=filedir+"tmp_kdeout"+str(filenum)+".asc" nparr=np.loadtxt(filename, skiprows=6) return nparr # load all the data from files and return 3d matrix def loadData(): x = [] onlyfiles = [ f for f in listdir(filedir) if isfile(join(filedir,f)) ] zlength=len(onlyfiles) for i in xrange(zlength): filedat=filedataforfile(i) x.append(filedat) y=np.dstack(x) print "3d shape", y.shape return y # change the ctf and otf property of volume def change_volume_property(vol): color1 = [[0,0,0,0,0], [1,255,255,0,10], [10,255,255,0,50], [100,255,100,0,150], [1000,255,0,0,255]] color2 = [[0,0,0,0,0], [100,0,255,255,10], [1000,0,255,255,50], [10000,0,100,255,150], [100000,0,0,255,255]] color = color1 # Changing the ctf: from tvtk.util.ctf import ColorTransferFunction ctf = ColorTransferFunction() for c in color: ctf.add_rgb_point(c[0], c[1]/255.0, c[2]/255.0, c[3]/255.0) vol._volume_property.set_color(ctf) vol._ctf = ctf vol.update_ctf = True # Changing the otf from enthought.tvtk.util.ctf import PiecewiseFunction otf = PiecewiseFunction() for c in color: otf.add_point(c[0], c[4]/255.0) vol._otf = otf vol._volume_property.set_scalar_opacity(otf) def change_test(vol): from enthought.tvtk.util.ctf import PiecewiseFunction otf = PiecewiseFunction() otf.add_point(0, 0) otf.add_point(1000,1) vol._otf = otf vol._volume_property.set_scalar_opacity(otf) # draw volume def draw_volume(scalars): # filts out low data nmax = np.amax(scalars) nmin = np.amin(scalars) #nptp = nmax - nmin #lowBound = nmin + nptp*0 #for i in np.nditer(scalars, op_flags=['readwrite']): # if i<lowBound: i[...] = 0 # Get the shape of axes shape = scalars.shape # draw fig = mlab.figure(bgcolor=(0,0,0), size=(800,800) ) src = mlab.pipeline.scalar_field(scalars) src.update_image_data = True #src.spacing = [1, 1, 1] vol = mlab.pipeline.volume(src) change_volume_property(vol) #change_test(vol) #vol = mlab.pipeline.image_plane_widget(src,plane_orientation='z_axes', slice_index=shape[2]/2) ax = mlab.axes(nb_labels=5, ranges=(0,shape[0],0,shape[1],0,shape[2])) mlab.savefig("result.jpg") print "nmax =", nmax print "nmin =", nmin viewkeeper = mlab.view() print "View", mlab.view() draw_map(shape[0],shape[1]) mlab.view(viewkeeper[0],viewkeeper[1],viewkeeper[2],viewkeeper[3]) def draw_map(height,width): import pylab as pl im = pl.imread('worldmap.png', format='png') l = [] for i in im: x = [] for j in i: tmp = 0 for k in j: tmp += k x.append(k) l.append(x) ims = mlab.imshow(l, colormap = 'binary') print "Map shape", len(l),len(l[0]) ims.actor.position = [height/2,(width)/2,0] ims.actor.scale = [float(height)/len(l),float(width)/len(l[0]),0] def main(): import pylab as pl s = loadData() draw_volume(s) if __name__ == "__main__": main()
{ "repo_name": "HPCGISLab/STDataViz", "path": "InitialVersion/draw_volume.py", "copies": "1", "size": "4706", "license": "bsd-3-clause", "hash": 5911903450475629000, "line_mean": 26.2080924855, "line_max": 99, "alpha_frac": 0.5960475988, "autogenerated": false, "ratio": 3.085901639344262, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.41819492381442624, "avg_score": null, "num_lines": null }
# 3D Volume Graph using Mayavi # 2016/02/18 # By Jay and Cheng # This program reads ascfiles from 'filedir', creates 3d matrix, # uses mayavi display the 3d matrix, and also saves a screenshot in # the working directory. # Notice: Files must be in some format, and the filedir must be specified from os import listdir from os.path import isfile, join import fileinput import numpy as np from mayavi import mlab import pylab as pl def metadataforfile(filename,filedir): '''read meta data from the first 6 line of the asc file ''' metadata=[None]*6 nrows=ncols=None x=y=None cellsize=None nodata_value=None print filedir+filename for line in fileinput.input([filedir+filename]): arg, val = str.split(line) print arg, val if arg == "nrows": nrows = int(val) metadata[0]=nrows if arg == "ncols": ncols = int(val) metadata[1]=ncols if arg == "xllcorner": x = float(val) metadata[3]=x if arg == "yllcorner": y = float(val) metadata[4]=y if arg == "cellsize": cellsize=float(val) metadata[2]=cellsize if arg == "NODATA_value": nodata_value=float(val) metadata[5]=nodata_value if fileinput.filelineno()>=6: break fileinput.close() return metadata def loadData(fileDir): '''load all the data from files from one directory Parameters ---------- fileDir : str Directory of the data files Returns ------- 3d np arry ''' x = [] files = [join(fileDir,f) for f in listdir(fileDir) if isfile(join(fileDir,f)) ] for f in files: x.append(np.loadtxt(f,skiprows=6) ) y=np.dstack(x) print "3d shape", y.shape return y def changeVolumeColormap(vol,color): '''change the ctf and otf property of volume Parameters ---------- vol : mlab.volume color : [[]] For each color [datavalue, R, G, B, A] R,G,B,A in range(0.0,255.0) inclusive ''' # Changing the ctf: from tvtk.util.ctf import ColorTransferFunction ctf = ColorTransferFunction() for c in color: ctf.add_rgb_point(float(c[0]), float(c[1])/255.0, float(c[2])/255.0, float(c[3])/255.0) vol._volume_property.set_color(ctf) vol._ctf = ctf vol.update_ctf = True # Changing the otf from enthought.tvtk.util.ctf import PiecewiseFunction otf = PiecewiseFunction() for c in color: otf.add_point(float(c[0]), float(c[4])/255.0) vol._otf = otf vol._volume_property.set_scalar_opacity(otf) def changeTest(vol): ''' Test for vol change ''' from enthought.tvtk.util.ctf import PiecewiseFunction otf = PiecewiseFunction() otf.add_point(0, 0) otf.add_point(1000,1) vol._otf = otf vol._volume_property.set_scalar_opacity(otf) def drawVolume(mlab,scalars): ''' 3d Visualization of the data Parameters ---------- mlab : mlab scalars : 3d np array Returns ------- volume object ''' # filts out low data nmax = np.amax(scalars) nmin = np.amin(scalars) #nptp = nmax - nmin #lowBound = nmin + nptp*0 #for i in np.nditer(scalars, op_flags=['readwrite']): # if i<lowBound: i[...] = 0 # Get the shape of axes shape = scalars.shape # draw src = mlab.pipeline.scalar_field(scalars) src.update_image_data = True #src.spacing = [1, 1, 1] vol = mlab.pipeline.volume(src) #vol = mlab.pipeline.image_plane_widget(src,plane_orientation='z_axes', slice_index=shape[2]/2) ax = mlab.axes(nb_labels=5, ranges=(0,shape[0],0,shape[1],0,shape[2])) mlab.savefig("result.jpg") print "nmax =", nmax print "nmin =", nmin viewkeeper = mlab.view() print "View", mlab.view() mlab.view(viewkeeper[0],viewkeeper[1],viewkeeper[2],viewkeeper[3]) return vol def drawMap(mlab, scalars, mapFile): ''' 3d Visualization of the data Parameters ---------- mlab : mlab scalars : 3d np array mapFile : str Returns ------- imshow object ''' # Get the shape of axes shape = scalars.shape height = shape[0] width = shape[1] im = pl.imread(mapFile, format = 'png') l = [] for i in im: x = [] for j in i: tmp = 0 for k in j: tmp += k x.append(tmp) l.append(x) #ims = mlab.imshow(l, colormap = 'binary') ims = mlab.imshow(l) print "Map shape", len(l),len(l[0]) ims.actor.position = [height/2,(width)/2,0] ims.actor.scale = [float(height)/len(l),float(width)/len(l[0]),0] return ims def changeToBestView(mlab): mlab.view(45.0, 54.735610317245346, 1477.5179822379857, [ 147. , 352.5, 38. ]) def readColorFile(filename): f = open(filename, "r") return [ [int(x) for x in lines.split(' ')] for lines in f ] def main(): fileDir='./ascfiles2' mapFile = './maps/worldmap.png' colorFile = './colormaps/color1.txt' # color map used for test color1 = [[0,0,0,0,0], [1,255,255,0,10], [10,255,255,0,50], [100,255,100,0,150], [1000,255,0,0,255]] color2 = [[0,0,0,0,0], [100,0,255,255,10], [1000,0,255,255,50], [10000,0,100,255,150], [100000,0,0,255,255]] s = loadData(fileDir) mlab.figure(bgcolor=(0,0,0), size=(800,800) ) vol = drawVolume(mlab,s) colormap = readColorFile(colorFile) changeVolumeColormap(vol,colormap) drawMap(mlab, s, mapFile) changeToBestView(mlab) if __name__ == "__main__": main()
{ "repo_name": "HPCGISLab/STDataViz", "path": "WorkingVersion/draw_volume.py", "copies": "1", "size": "5795", "license": "bsd-3-clause", "hash": -8505266946312206000, "line_mean": 24.875, "line_max": 99, "alpha_frac": 0.5746333046, "autogenerated": false, "ratio": 3.201657458563536, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4276290763163536, "avg_score": null, "num_lines": null }
## 3. Exercise: Dynamic Arrays ## # Retrieving an item in an array by index retrieval_by_index = "constant" # Searching for a value in an unordered array search = "linear" # Deleting an item from an array, and filling the gap # by shifting all later items back by one deletion = "linear" # Inserting an item into the array, and shifting forward # every item that comes after it insertion = "linear" ## 4. Exercise: Practice Inserting Into an Array ## players = ["Reggie Jackson"] print(players) players.insert(1, "C.J. Watson") print(players) players.insert(0, "Jeff Adrien") print(players) players.remove("Reggie Jackson") print(players) players.insert(0, "Quincy Acy") players.insert(2, "Evan Turner") print(players) ## 6. 2D Array Implementation ## red_pieces = 0 black_pieces = 0 # Find how many red and black pieces there are for values in checker_board: for x in values: if x == "black": black_pieces += 1 if x == "red": red_pieces += 1 ## 9. Dictionary Access ## # Population of Rio de Janeiro rio_population = city_populations["Rio de Janeiro"] boston_population = city_populations["Boston"] paris_population = city_populations["Paris"] city_populations["Boston"] = city_populations["Boston"] -1 city_populations["Beijing"] = city_populations["Beijing"] +1 ## 12. Exercise: Choosing a Data Structure ## # Scenario A: You need to keep track of people sitting in an auditorium for a play. You'll have to identify which seats are empty, and sell tickets until the auditorium is completely full. How will you store the names of who's sitting where? scenario_A_data_structure = "2d array" # Scenario B: You're in charge of maintaining a guest list for a wedding. You're only concerned with a list of who's coming to the party. You have to add someone's name whenever they RSVP that they'll be attending the wedding. scenario_B_data_structure = "dynamic array" # Scenario C: Now every person who RSVPs for the wedding indicates which meal they want. You have to keep track of both the person and the meal order. You need to be able to find out what meal a particular person ordered quickly, so the waiters don't delay too long when it comes time to eat. scenario_C_data_structure = "hash table"
{ "repo_name": "vipmunot/Data-Analysis-using-Python", "path": "Data Structures & Algorithms/Data Structures-94.py", "copies": "1", "size": "2263", "license": "mit", "hash": 6250929031577893000, "line_mean": 35.5161290323, "line_max": 292, "alpha_frac": 0.7277949624, "autogenerated": false, "ratio": 3.3675595238095237, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45953544862095236, "avg_score": null, "num_lines": null }