input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
= len(temp_array) - 1 # Lower bound is 0
# Counter for a, starts at the end this time
j = a[1]
gallop_thresh = min_gallop
while True:
a_count = 0 # number of times a win in a row
b_count = 0 # number of times b win in a row
# Linear merge, taking note of how many times a and b wins in a row.
# If a_count or b_count > threshold, switch to gallop
while i >= 0 and j >= a[0]:
if temp_array[i] > lst[j]:
lst[k] = temp_array[i]
k -= 1
i -= 1
a_count = 0
b_count += 1
# If b runs out during linear merge
if i < 0:
while j >= a[0]:
lst[k] = lst[j]
k -= 1
j -= 1
return
if b_count >= gallop_thresh:
break
else:
lst[k] = lst[j]
k -= 1
j -= 1
a_count += 1
b_count = 0
# If a runs out during linear merge
if j < a[0]:
while i >= 0:
lst[k] = temp_array[i]
k -= 1
i -= 1
return
if a_count >= gallop_thresh:
break
# i, j, k are DECREMENTED in this case
while True:
# Look for the position of b[i] in a[0, j + 1]
# ltr = False -> uses bisect_right()
a_adv = gallop(lst, temp_array[i], a[0], j + 1, False)
# Copy the elements from a_adv -> j to merge area
# Go backwards to the index a_adv
for x in range(j, a_adv - 1, -1):
lst[k] = lst[x]
k -= 1
# # Update the a_count to check successfulness of galloping
a_count = j - a_adv + 1
# Decrement index j
j = a_adv - 1
# If run a runs out:
if j < a[0]:
while i >= 0:
lst[k] = temp_array[i]
k -= 1
i -= 1
return
# Copy the b[i] into the merge area
lst[k] = temp_array[i]
k -= 1
i -= 1
# If a runs out:
if i < 0:
while j >= a[0]:
lst[k] = lst[j]
k -= 1
j -= 1
return
# -------------------------------------------------
# Look for the position of A[j] in B:
b_adv = gallop(temp_array, lst[j], 0, i + 1, False)
for y in range(i, b_adv - 1, -1):
lst[k] = temp_array[y]
k -= 1
b_count = i - b_adv + 1
i = b_adv - 1
# If b runs out:
if i < 0:
while j >= a[0]:
lst[k] = lst[j]
k -= 1
j -= 1
return
# Copy the a[j] back to the merge area
lst[k] = lst[j]
k -= 1
j -= 1
# If a runs out:
if j < a[0]:
while i >= 0:
lst[k] = temp_array[i]
k -= 1
i -= 1
return
# if galloping proves to be unsuccessful, return to linear
if a_count < gallop_thresh and b_count < gallop_thresh:
break
# punishment for leaving galloping
gallop_thresh += 1
def merge_collapse(lst, stack):
"""The last three runs in the stack is A, B, C.
Maintains invariants so that their lengths: A > B + C, B > C
Translated to stack positions:
stack[-3] > stack[-2] + stack[-1]
stack[-2] > stack[-1]
Takes a stack that holds many lists of type [s, e, bool, length]"""
# This loops keeps running until stack has one element
# or the invariant holds.
while len(stack) > 1:
if len(stack) >= 3 and stack[-3][3] <= stack[-2][3] + stack[-1][3]:
if stack[-3][3] < stack[-1][3]:
# merge -3 and -2, merge at -3
merge(lst, stack, -3)
else:
# merge -2 and -1, merge at -2
merge(lst, stack, -2)
elif stack[-2][3] <= stack[-1][3]:
# merge -2 and -1, merge at -2
merge(lst, stack, -2)
else:
break
def merge_force_collapse(lst, stack):
"""When the invariant holds and there are > 1 run
in the stack, this function finishes the merging"""
while len(stack) > 1:
# Only merges at -2, because when the invariant holds,
# merging would be balanced
merge(lst, stack, -2)
# Starting index
s = 0
# Ending index
e = len(lst) - 1
# The stack
stack = []
# Compute min_run using size of lst
min_run = merge_compute_minrun(len(lst))
while s <= e:
# Find a run, return [start, end, bool, length]
run = count_run(lst, s)
# If decreasing, reverse
if run[2] == False:
reverse(lst, run[0], run[1])
# Change bool to True
run[2] = True
# If length of the run is less than min_run
if run[3] < min_run:
# The number of indices by which we want to extend the run
# either by the distance to the end of the lst
# or by the length difference between run and minrun
extend = min(min_run - run[3], e - run[1])
# Extend the run using binary insertion sort
bin_sort(lst, run[0], run[1], extend)
# Update last index of the run
run[1] = run[1] + extend
# Update the run length
run[3] = run[3] + extend
# Push the run into the stack
stack.append(run)
# Start merging to maintain the invariant
merge_collapse(lst, stack)
# Update starting position to find the next run
# If run[1] == end of the lst, s > e, loop exits
s = run[1] + 1
# Some runs might be left in the stack, complete the merging.
merge_force_collapse(lst, stack)
return lst
def quickSort(array): # in-place | not-stable
"""
Best : O(nlogn) Time | O(logn) Space
Average : O(nlogn) Time | O(logn) Space
Worst : O(nlogn) Time | O(logn) Space
"""
if len(array) <= 1:
return array
smaller, equal, larger = [], [], []
pivot = array[randrange(0, len(array))]
for x in array:
if x < pivot:
smaller.append(x)
elif x == pivot:
equal.append(x)
else:
larger.append(x)
return quickSort(smaller) + equal + quickSort(larger)
def quickSortHoare(array, low=0, high=None): # in-place | not-stable
"""
QuickSort using tail recursive + insertion sort + hoare
Best : O(nlogn) Time | O(1) Space
Average : O(nlogn) Time | O(1) Space
Worst : O(nlogn) Time | O(1) Space
"""
def insertSort(array, low=0, high=None):
if high is None:
high = len(array) - 1
for i in range(low + 1, high + 1):
j = i
while j > 0 and array[j] < array[j - 1]:
array[j], array[j - 1] = array[j - 1], array[j]
j -= 1
return array
if high is None:
high = len(array) - 1
while low < high and high - low > 16:
q = partition(array, low, high)
quickSortHoare(array, low, q)
low = q + 1
return insertSort(array, low, high)
def quickSortHeap(array, low=0, high=None, depth=None):
"""
QuickSort using tail recursive + insertion sort + heap sort + hoare + median of three killer
"""
def medianOf3(array, lowIdx, midIdx, highIdx):
if (array[lowIdx] - array[midIdx]) * (array[highIdx] - array[lowIdx]) >= 0:
return array[lowIdx]
elif (array[midIdx] - array[lowIdx]) * (array[highIdx] - array[midIdx]) >= 0:
return array[midIdx]
else:
return array[highIdx]
def partition(array, low, high):
pivot = medianOf3(array, low, (low + high) // 2, high)
i = low - 1
j = high + 1
while True:
i += 1
while array[i] < pivot:
i += 1
j -= 1
while array[j] > pivot:
j -= 1
if i >= j:
return j
array[i], array[j] = array[j], array[i]
def insertSort(array, low=0, high=None):
if high is None:
high = len(array) - 1
for i in range(low + 1, high + 1):
j = i
while j > 0 and array[j] < array[j - 1]:
array[j], array[j - 1] = array[j - 1], array[j]
j -= 1
return array
if high is None:
high = len(array) - 1
if depth is None:
depth = 2 * (len(array).bit_length() - 1)
if depth == 0:
return heapSort2(array)
else:
while high - low > 16:
q = partition(array, low, high)
quickSortHeap(array, low, q)
low = q + 1
return insertSort(array, low, high)
def partition(array, low, high):
pivot = array[(high + low) // 2]
# pivot | |
m.x769 - m.x770 - m.x771 - m.x772 - m.x773 - m.x774 - m.x775 - m.x776 - m.x777 - m.x778
- m.x779 - m.x780 - m.x781 - m.x782 - m.x783 - m.x784 + m.x1130 >= 0)
m.c307 = Constraint(expr= - m.x785 - m.x786 - m.x787 - m.x788 - m.x789 - m.x790 - m.x791 - m.x792 - m.x793 - m.x794
- m.x795 - m.x796 - m.x797 - m.x798 - m.x799 - m.x800 + m.x1131 >= 0)
m.c308 = Constraint(expr= - m.x801 - m.x802 - m.x803 - m.x804 - m.x805 - m.x806 - m.x807 - m.x808 - m.x809 - m.x810
- m.x811 - m.x812 - m.x813 - m.x814 - m.x815 - m.x816 + m.x1132 >= 0)
m.c309 = Constraint(expr= - m.x817 - m.x818 - m.x819 - m.x820 - m.x821 - m.x822 - m.x823 - m.x824 - m.x825 - m.x826
- m.x827 - m.x828 - m.x829 - m.x830 - m.x831 - m.x832 + m.x1133 >= 0)
m.c310 = Constraint(expr= - m.x833 - m.x834 - m.x835 - m.x836 - m.x837 - m.x838 - m.x839 - m.x840 - m.x841 - m.x842
- m.x843 - m.x844 - m.x845 - m.x846 - m.x847 - m.x848 + m.x1134 >= 0)
m.c311 = Constraint(expr= - m.x849 - m.x850 - m.x851 - m.x852 - m.x853 - m.x854 - m.x855 - m.x856 - m.x857 - m.x858
- m.x859 - m.x860 - m.x861 - m.x862 - m.x863 - m.x864 + m.x1135 >= 0)
m.c312 = Constraint(expr= - m.x865 - m.x866 - m.x867 - m.x868 - m.x869 - m.x870 - m.x871 - m.x872 - m.x873 - m.x874
- m.x875 - m.x876 - m.x877 - m.x878 - m.x879 - m.x880 + m.x1136 >= 0)
m.c313 = Constraint(expr= - m.x881 - m.x882 - m.x883 - m.x884 - m.x885 - m.x886 - m.x887 - m.x888 - m.x889 - m.x890
- m.x891 - m.x892 - m.x893 - m.x894 - m.x895 - m.x896 + m.x1137 >= 0)
m.c314 = Constraint(expr= - m.x897 - m.x898 - m.x899 - m.x900 - m.x901 - m.x902 - m.x903 - m.x904 - m.x905 - m.x906
- m.x907 - m.x908 - m.x909 - m.x910 - m.x911 - m.x912 + m.x1138 >= 0)
m.c315 = Constraint(expr= - m.x913 - m.x914 - m.x915 - m.x916 - m.x917 - m.x918 - m.x919 - m.x920 - m.x921 - m.x922
- m.x923 - m.x924 - m.x925 - m.x926 - m.x927 - m.x928 + m.x1139 >= 0)
m.c316 = Constraint(expr= - m.x929 - m.x930 - m.x931 - m.x932 - m.x933 - m.x934 - m.x935 - m.x936 - m.x937 - m.x938
- m.x939 - m.x940 - m.x941 - m.x942 - m.x943 - m.x944 + m.x1140 >= 0)
m.c317 = Constraint(expr= - m.x945 - m.x946 - m.x947 - m.x948 - m.x949 - m.x950 - m.x951 - m.x952 - m.x953 - m.x954
- m.x955 - m.x956 - m.x957 - m.x958 - m.x959 - m.x960 + m.x1141 >= 0)
m.c318 = Constraint(expr=137*m.x1082*m.b961 - 137*m.b961*m.x1021 + m.x1082*m.x1021 <= 0)
m.c319 = Constraint(expr=505*m.x1083*m.b962 - 505*m.b962*m.x1022 + m.x1083*m.x1022 <= 0)
m.c320 = Constraint(expr=427*m.x1084*m.b963 - 427*m.b963*m.x1023 + m.x1084*m.x1023 <= 0)
m.c321 = Constraint(expr=559*m.x1085*m.b964 - 559*m.b964*m.x1024 + m.x1085*m.x1024 <= 0)
m.c322 = Constraint(expr=137*m.x1086*m.b965 - 137*m.b965*m.x1025 + m.x1086*m.x1025 <= 0)
m.c323 = Constraint(expr=196*m.x1087*m.b966 - 196*m.b966*m.x1026 + m.x1087*m.x1026 <= 0)
m.c324 = Constraint(expr=341*m.x1088*m.b967 - 341*m.b967*m.x1027 + m.x1088*m.x1027 <= 0)
m.c325 = Constraint(expr=263*m.x1089*m.b968 - 263*m.b968*m.x1028 + m.x1089*m.x1028 <= 0)
m.c326 = Constraint(expr=245*m.x1090*m.b969 - 245*m.b969*m.x1029 + m.x1090*m.x1029 <= 0)
m.c327 = Constraint(expr=196*m.x1091*m.b970 - 196*m.b970*m.x1030 + m.x1091*m.x1030 <= 0)
m.c328 = Constraint(expr=346*m.x1092*m.b971 - 346*m.b971*m.x1031 + m.x1092*m.x1031 <= 0)
m.c329 = Constraint(expr=361*m.x1093*m.b972 - 361*m.b972*m.x1032 + m.x1093*m.x1032 <= 0)
m.c330 = Constraint(expr=179*m.x1094*m.b973 - 179*m.b973*m.x1033 + m.x1094*m.x1033 <= 0)
m.c331 = Constraint(expr=505*m.x1095*m.b974 - 505*m.b974*m.x1034 + m.x1095*m.x1034 <= 0)
m.c332 = Constraint(expr=341*m.x1096*m.b975 - 341*m.b975*m.x1035 + m.x1096*m.x1035 <= 0)
m.c333 = Constraint(expr=160*m.x1097*m.b976 - 160*m.b976*m.x1036 + m.x1097*m.x1036 <= 0)
m.c334 = Constraint(expr=389*m.x1098*m.b977 - 389*m.b977*m.x1037 + m.x1098*m.x1037 <= 0)
m.c335 = Constraint(expr=153*m.x1099*m.b978 - 153*m.b978*m.x1038 + m.x1099*m.x1038 <= 0)
m.c336 = Constraint(expr=164*m.x1100*m.b979 - 164*m.b979*m.x1039 + m.x1100*m.x1039 <= 0)
m.c337 = Constraint(expr=427*m.x1101*m.b980 - 427*m.b980*m.x1040 + m.x1101*m.x1040 <= 0)
m.c338 = Constraint(expr=389*m.x1102*m.b981 - 389*m.b981*m.x1041 + m.x1102*m.x1041 <= 0)
m.c339 = Constraint(expr=513*m.x1103*m.b982 - 513*m.b982*m.x1042 + m.x1103*m.x1042 <= 0)
m.c340 = Constraint(expr=353*m.x1104*m.b983 - 353*m.b983*m.x1043 + m.x1104*m.x1043 <= 0)
m.c341 = Constraint(expr=305*m.x1105*m.b984 - 305*m.b984*m.x1044 + m.x1105*m.x1044 <= 0)
m.c342 = Constraint(expr=346*m.x1106*m.b985 - 346*m.b985*m.x1045 + m.x1106*m.x1045 <= 0)
m.c343 = Constraint(expr=463*m.x1107*m.b986 - 463*m.b986*m.x1046 + m.x1107*m.x1046 <= 0)
m.c344 = Constraint(expr=511*m.x1108*m.b987 - 511*m.b987*m.x1047 + m.x1108*m.x1047 <= 0)
m.c345 = Constraint(expr=361*m.x1109*m.b988 - 361*m.b988*m.x1048 + m.x1109*m.x1048 <= 0)
m.c346 = Constraint(expr=513*m.x1110*m.b989 - 513*m.b989*m.x1049 + m.x1110*m.x1049 <= 0)
m.c347 = Constraint(expr=218*m.x1111*m.b990 - 218*m.b990*m.x1050 + m.x1111*m.x1050 <= 0)
m.c348 = Constraint(expr=338*m.x1112*m.b991 - 338*m.b991*m.x1051 + m.x1112*m.x1051 <= 0)
m.c349 = Constraint(expr=153*m.x1113*m.b992 - 153*m.b992*m.x1052 + m.x1113*m.x1052 <= 0)
m.c350 = Constraint(expr=439*m.x1114*m.b993 - 439*m.b993*m.x1053 + m.x1114*m.x1053 <= 0)
m.c351 = Constraint(expr=194*m.x1115*m.b994 - 194*m.b994*m.x1054 + m.x1115*m.x1054 <= 0)
m.c352 = Constraint(expr=353*m.x1116*m.b995 - 353*m.b995*m.x1055 + m.x1116*m.x1055 <= 0)
m.c353 = Constraint(expr=415*m.x1117*m.b996 - 415*m.b996*m.x1056 + m.x1117*m.x1056 <= 0)
m.c354 = Constraint(expr=559*m.x1118*m.b997 - 559*m.b997*m.x1057 + m.x1118*m.x1057 <= 0)
m.c355 = Constraint(expr=439*m.x1119*m.b998 - 439*m.b998*m.x1058 + m.x1119*m.x1058 <= 0)
m.c356 = Constraint(expr=415*m.x1120*m.b999 - 415*m.b999*m.x1059 + m.x1120*m.x1059 <= 0)
m.c357 = Constraint(expr=421*m.x1121*m.b1000 - 421*m.b1000*m.x1060 + m.x1121*m.x1060 <= 0)
m.c358 = Constraint(expr=179*m.x1122*m.b1001 - 179*m.b1001*m.x1061 + m.x1122*m.x1061 <= 0)
m.c359 = Constraint(expr=463*m.x1123*m.b1002 - 463*m.b1002*m.x1062 + m.x1123*m.x1062 <= 0)
m.c360 = Constraint(expr=534*m.x1124*m.b1003 - 534*m.b1003*m.x1063 + m.x1124*m.x1063 <= 0)
m.c361 = Constraint(expr=218*m.x1125*m.b1004 - 218*m.b1004*m.x1064 + m.x1125*m.x1064 <= 0)
m.c362 = Constraint(expr=534*m.x1126*m.b1005 - 534*m.b1005*m.x1065 + m.x1126*m.x1065 <= 0)
m.c363 = Constraint(expr=425*m.x1127*m.b1006 - 425*m.b1006*m.x1066 + m.x1127*m.x1066 <= 0)
m.c364 = Constraint(expr=263*m.x1128*m.b1007 - 263*m.b1007*m.x1067 + m.x1128*m.x1067 <= 0)
m.c365 = Constraint(expr=160*m.x1129*m.b1008 - 160*m.b1008*m.x1068 + m.x1129*m.x1068 <= 0)
m.c366 = Constraint(expr=511*m.x1130*m.b1009 - 511*m.b1009*m.x1069 + m.x1130*m.x1069 <= 0)
m.c367 = Constraint(expr=421*m.x1131*m.b1010 - 421*m.b1010*m.x1070 + m.x1131*m.x1070 <= 0)
m.c368 = Constraint(expr=497*m.x1132*m.b1011 - 497*m.b1011*m.x1071 + m.x1132*m.x1071 <= 0)
m.c369 = Constraint(expr=245*m.x1133*m.b1012 - 245*m.b1012*m.x1072 + m.x1133*m.x1072 <= 0)
m.c370 = Constraint(expr=305*m.x1134*m.b1013 - 305*m.b1013*m.x1073 + m.x1134*m.x1073 <= 0)
m.c371 = Constraint(expr=194*m.x1135*m.b1014 - 194*m.b1014*m.x1074 + m.x1135*m.x1074 <= 0)
m.c372 = Constraint(expr=425*m.x1136*m.b1015 - 425*m.b1015*m.x1075 + m.x1136*m.x1075 <= 0)
m.c373 = Constraint(expr=497*m.x1137*m.b1016 - 497*m.b1016*m.x1076 + m.x1137*m.x1076 <= 0)
m.c374 = Constraint(expr=552*m.x1138*m.b1017 - 552*m.b1017*m.x1077 + m.x1138*m.x1077 <= 0)
m.c375 = Constraint(expr=164*m.x1139*m.b1018 - 164*m.b1018*m.x1078 + m.x1139*m.x1078 <= 0)
m.c376 = Constraint(expr=338*m.x1140*m.b1019 - 338*m.b1019*m.x1079 + m.x1140*m.x1079 <= 0)
m.c377 = Constraint(expr=552*m.x1141*m.b1020 - 552*m.b1020*m.x1080 + m.x1141*m.x1080 <= 0)
m.c378 = Constraint(expr= m.x1021 + m.x1022 + m.x1023 + m.x1024 + m.x1025 + m.x1026 + m.x1027 + m.x1028 + m.x1029
+ m.x1030 + m.x1031 + m.x1032 + m.x1033 + m.x1034 + m.x1035 + m.x1036 + m.x1037 + m.x1038
+ m.x1039 + m.x1040 + m.x1041 + m.x1042 + m.x1043 + m.x1044 + m.x1045 + m.x1046 + m.x1047
+ m.x1048 + m.x1049 + m.x1050 + m.x1051 + m.x1052 + m.x1053 + m.x1054 + m.x1055 + m.x1056
+ m.x1057 + m.x1058 + m.x1059 + m.x1060 + m.x1061 + m.x1062 + m.x1063 + m.x1064 + m.x1065
+ m.x1066 + m.x1067 + m.x1068 + m.x1069 + m.x1070 + m.x1071 + m.x1072 + m.x1073 + m.x1074
+ m.x1075 + m.x1076 + m.x1077 + m.x1078 + m.x1079 + m.x1080 <= 14012)
m.c379 = Constraint(expr= m.x1 + m.x2 + m.x3 + m.x4 + m.x5 + m.x6 + m.x7 + m.x8 + m.x9 + m.x10 + m.x11 + m.x12 + m.x13
+ m.x14 + m.x15 + m.x16 - 137*m.b961 <= 0)
m.c380 = Constraint(expr= m.x17 + m.x18 + m.x19 + m.x20 + m.x21 + m.x22 + m.x23 + m.x24 + m.x25 + m.x26 + m.x27
+ m.x28 + m.x29 + m.x30 + m.x31 + m.x32 - 505*m.b962 <= 0)
m.c381 = Constraint(expr= m.x33 + m.x34 + m.x35 + m.x36 + m.x37 + m.x38 + m.x39 + m.x40 + m.x41 + m.x42 + m.x43
+ m.x44 + m.x45 + m.x46 + m.x47 + m.x48 - 427*m.b963 <= 0)
m.c382 = Constraint(expr= m.x49 + m.x50 + m.x51 + m.x52 + m.x53 + m.x54 + m.x55 + m.x56 + m.x57 + m.x58 + m.x59
+ m.x60 + m.x61 + m.x62 + m.x63 + m.x64 - 559*m.b964 <= 0)
m.c383 = Constraint(expr= m.x65 + m.x66 + m.x67 + m.x68 + m.x69 + m.x70 + m.x71 + m.x72 + m.x73 + m.x74 + m.x75
+ m.x76 + m.x77 + m.x78 + m.x79 + m.x80 - 137*m.b965 <= 0)
m.c384 = Constraint(expr= m.x81 + m.x82 + m.x83 + m.x84 + m.x85 + m.x86 + m.x87 + m.x88 + m.x89 + m.x90 + m.x91
+ m.x92 + m.x93 + m.x94 + m.x95 + m.x96 - 196*m.b966 <= 0)
m.c385 = Constraint(expr= | |
#!/usr/bin/env python
import sys, os, binascii, base64, json, re, subprocess
from collections import OrderedDict
try:
import Tkinter as tk
import ttk
import tkFileDialog as fd
import tkMessageBox as mb
from tkFont import Font, families
from tkColorChooser import askcolor as ac
except:
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import filedialog as fd
from tkinter import messagebox as mb
from tkinter.font import Font, families
from tkinter.colorchooser import askcolor as ac
try:
unicode
except NameError: # Python 3
unicode = str
# Add this script's dir to the local PATH var - may improve import consistency
sys.path.append(os.path.abspath(os.path.dirname(os.path.realpath(__file__))))
from Scripts import plist, plistwindow
class ProperTree:
def __init__(self, plists = []):
# Create the new tk object
self.tk = tk.Tk()
self.tk.withdraw() # Try to remove before it's drawn
self.tk.title("Convert Values")
self.tk.minsize(width=640,height=130)
self.tk.resizable(True, False)
self.tk.columnconfigure(2,weight=1)
self.tk.columnconfigure(3,weight=1)
# Build the Hex <--> Base64 converter
f_label = tk.Label(self.tk, text="From:")
f_label.grid(row=0,column=0,padx=10,pady=10)
t_label = tk.Label(self.tk, text="To:")
t_label.grid(row=1,column=0,padx=10,pady=10)
# Create the settings window
self.settings_window = tk.Toplevel(self.tk)
self.settings_window.withdraw() # Try to remove before it's drawn
self.settings_window.title("ProperTree Settings")
self.settings_window.resizable(False, False)
self.settings_window.columnconfigure(0,weight=1)
self.settings_window.columnconfigure(1,weight=1)
self.settings_window.columnconfigure(3,weight=1)
self.settings_window.columnconfigure(4,weight=1)
# Set the default max undo/redo steps to retain
self.max_undo = 200
# Left side - functional elements:
# Let's add some checkboxes and stuffs
sep_func = ttk.Separator(self.settings_window,orient="horizontal")
sep_func.grid(row=0,column=1,columnspan=1,sticky="we",padx=10,pady=10)
func_label = tk.Label(self.settings_window,text="Functionality Options:")
func_label.grid(row=0,column=0,sticky="w",padx=10,pady=10)
self.expand_on_open = tk.IntVar()
self.use_xcode_data = tk.IntVar()
self.sort_dict_keys = tk.IntVar()
self.comment_ignore_case = tk.IntVar()
self.comment_check_string = tk.IntVar()
self.force_schema = tk.IntVar()
self.expand_check = tk.Checkbutton(self.settings_window,text="Expand Children When Opening Plist",variable=self.expand_on_open,command=self.expand_command)
self.xcode_check = tk.Checkbutton(self.settings_window,text="Use Xcode-Style <data> Tags (Inline) in XML Plists",variable=self.use_xcode_data,command=self.xcode_command)
self.sort_check = tk.Checkbutton(self.settings_window,text="Ignore Dictionary Key Order",variable=self.sort_dict_keys,command=self.sort_command)
self.ignore_case_check = tk.Checkbutton(self.settings_window,text="Ignore Case When Stripping Comments",variable=self.comment_ignore_case,command=self.ignore_case_command)
self.check_string_check = tk.Checkbutton(self.settings_window,text="Check String Values When Stripping Comments",variable=self.comment_check_string,command=self.check_string_command)
self.expand_check.grid(row=1,column=0,columnspan=2,sticky="w",padx=10)
self.xcode_check.grid(row=2,column=0,columnspan=2,sticky="w",padx=10)
self.sort_check.grid(row=3,column=0,columnspan=2,sticky="w",padx=10)
self.ignore_case_check.grid(row=4,column=0,columnspan=2,sticky="w",padx=10)
self.check_string_check.grid(row=5,column=0,columnspan=2,sticky="w",padx=10)
comment_prefix_label = tk.Label(self.settings_window,text="Comment Prefix (default is #):")
comment_prefix_label.grid(row=6,column=0,sticky="w",padx=10)
self.comment_prefix_text = tk.Entry(self.settings_window)
self.comment_prefix_text.grid(row=6,column=1,sticky="we",padx=10)
self.plist_type_string = tk.StringVar(self.settings_window)
self.plist_type_menu = tk.OptionMenu(self.settings_window, self.plist_type_string, "XML","Binary", command=self.change_plist_type)
plist_label = tk.Label(self.settings_window,text="Default New Plist Type:")
plist_label.grid(row=7,column=0,sticky="w",padx=10)
self.plist_type_menu.grid(row=7,column=1,sticky="we",padx=10)
self.data_type_string = tk.StringVar(self.settings_window)
self.data_type_menu = tk.OptionMenu(self.settings_window, self.data_type_string, "Hex","Base64", command=self.change_data_type)
data_label = tk.Label(self.settings_window,text="Data Display Default:")
data_label.grid(row=8,column=0,sticky="w",padx=10)
self.data_type_menu.grid(row=8,column=1,sticky="we",padx=10)
self.int_type_string = tk.StringVar(self.settings_window)
self.int_type_menu = tk.OptionMenu(self.settings_window, self.int_type_string, "Decimal", "Hex", command=self.change_int_type)
int_label = tk.Label(self.settings_window,text="Integer Display Default:")
int_label.grid(row=9,column=0,sticky="w",padx=10)
self.int_type_menu.grid(row=9,column=1,sticky="we",padx=10)
self.bool_type_string = tk.StringVar(self.settings_window)
self.bool_type_menu = tk.OptionMenu(self.settings_window, self.bool_type_string, "True/False", "YES/NO", "On/Off", "1/0", command=self.change_bool_type)
bool_label = tk.Label(self.settings_window,text="Boolean Display Default:")
bool_label.grid(row=10,column=0,sticky="w",padx=10)
self.bool_type_menu.grid(row=10,column=1,sticky="we",padx=10)
self.snapshot_string = tk.StringVar(self.settings_window)
self.snapshot_menu = tk.OptionMenu(self.settings_window, self.snapshot_string, "Latest", command=self.change_snapshot_version)
snapshot_label = tk.Label(self.settings_window,text="Snapshot OC Version:")
snapshot_label.grid(row=11,column=0,sticky="w",padx=10)
self.snapshot_menu.grid(row=11,column=1,sticky="we",padx=10)
self.schema_check = tk.Checkbutton(self.settings_window,text="Force Update Snapshot Schema",variable=self.force_schema,command=self.schema_command)
self.schema_check.grid(row=12,column=0,columnspan=2,sticky="w",padx=10)
self.drag_label = tk.Label(self.settings_window,text="Drag Dead Zone (1-100 pixels):")
self.drag_label.grid(row=13,column=0,sticky="w",padx=10)
self.drag_scale = tk.Scale(self.settings_window,from_=1,to=100,orient=tk.HORIZONTAL)
self.drag_scale.grid(row=13,column=1,sticky="we",padx=10)
undo_max_label = tk.Label(self.settings_window,text="Max Undo (0=unlim, {}=default):".format(self.max_undo))
undo_max_label.grid(row=14,column=0,sticky="w",padx=10)
self.undo_max_text = tk.Entry(self.settings_window)
self.undo_max_text.grid(row=14,column=1,sticky="we",padx=10)
# Left/right separator:
sep = ttk.Separator(self.settings_window,orient="vertical")
sep.grid(row=1,column=2,rowspan=13,sticky="ns",padx=10)
# Right side - theme elements:
t_func = ttk.Separator(self.settings_window,orient="horizontal")
t_func.grid(row=0,column=4,columnspan=1,sticky="we",padx=10,pady=10)
tfunc_label = tk.Label(self.settings_window,text="Appearance Options:")
tfunc_label.grid(row=0,column=3,sticky="w",padx=10,pady=10)
r4_label = tk.Label(self.settings_window,text="Highlight Color:")
r4_label.grid(row=1,column=3,sticky="w",padx=10)
self.hl_canvas = tk.Canvas(self.settings_window, height=20, width=30, background="black", relief="groove", bd=2)
self.hl_canvas.grid(row=1,column=4,sticky="we",padx=10)
r1_label = tk.Label(self.settings_window,text="Alternating Row Color #1:")
r1_label.grid(row=2,column=3,sticky="w",padx=10)
self.r1_canvas = tk.Canvas(self.settings_window, height=20, width=30, background="black", relief="groove", bd=2)
self.r1_canvas.grid(row=2,column=4,sticky="we",padx=10)
r2_label = tk.Label(self.settings_window,text="Alternating Row Color #2:")
r2_label.grid(row=3,column=3,sticky="w",padx=10)
self.r2_canvas = tk.Canvas(self.settings_window, height=20, width=30, background="black", relief="groove", bd=2)
self.r2_canvas.grid(row=3,column=4,sticky="we",padx=10)
r3_label = tk.Label(self.settings_window,text="Column Header/BG Color:")
r3_label.grid(row=4,column=3,sticky="w",padx=10)
self.bg_canvas = tk.Canvas(self.settings_window, height=20, width=30, background="black", relief="groove", bd=2)
self.bg_canvas.grid(row=4,column=4,sticky="we",padx=10)
self.ig_bg_check = tk.IntVar()
self.ig_bg = tk.Checkbutton(self.settings_window,text="Header Text Ignores BG Color",variable=self.ig_bg_check,command=self.check_ig_bg_command)
self.ig_bg.grid(row=5,column=3,sticky="w",padx=10)
self.bg_inv_check = tk.IntVar()
self.bg_inv = tk.Checkbutton(self.settings_window,text="Invert Header Text Color",variable=self.bg_inv_check,command=self.check_bg_invert_command)
self.bg_inv.grid(row=5,column=4,sticky="w",padx=10)
self.r1_inv_check = tk.IntVar()
self.r1_inv = tk.Checkbutton(self.settings_window,text="Invert Row #1 Text Color",variable=self.r1_inv_check,command=self.check_r1_invert_command)
self.r1_inv.grid(row=6,column=4,sticky="w",padx=10)
self.r2_inv_check = tk.IntVar()
self.r2_inv = tk.Checkbutton(self.settings_window,text="Invert Row #2 Text Color",variable=self.r2_inv_check,command=self.check_r2_invert_command)
self.r2_inv.grid(row=7,column=4,sticky="w",padx=10)
self.hl_inv_check = tk.IntVar()
self.hl_inv = tk.Checkbutton(self.settings_window,text="Invert Highlight Text Color",variable=self.hl_inv_check,command=self.check_hl_invert_command)
self.hl_inv.grid(row=8,column=4,sticky="w",padx=10)
self.default_font = Font(font='TkTextFont')
self.custom_font = tk.IntVar()
self.font_check = tk.Checkbutton(self.settings_window,text="Use Custom Font Size",variable=self.custom_font,command=self.font_command)
self.font_string = tk.StringVar()
self.font_spinbox = tk.Spinbox(self.settings_window,from_=1,to=128,textvariable=self.font_string)
self.font_string.trace("w",self.update_font)
self.font_check.grid(row=9,column=3,sticky="w",padx=10)
self.font_spinbox.grid(row=9,column=4,sticky="we",padx=10)
# Custom font picker - wacky implementation.
self.font_var = tk.IntVar()
self.font_family = tk.StringVar()
self.font_custom_check = tk.Checkbutton(self.settings_window,text="Use Custom Font",variable=self.font_var,command=self.font_select)
self.font_custom = ttk.Combobox(self.settings_window,state="readonly",textvariable=self.font_family,values=sorted(families()))
self.font_custom.bind('<<ComboboxSelected>>',self.font_pick)
self.font_family.trace("w",self.update_font_family)
self.font_custom_check.grid(row=10,column=3,stick="w",padx=10)
self.font_custom.grid(row=10,column=4,sticky="we",padx=10)
r5_label = tk.Label(self.settings_window,text="Restore Default Colors:")
r5_label.grid(row=11,column=3,sticky="w",padx=10)
dt_func = ttk.Separator(self.settings_window,orient="horizontal")
dt_func.grid(row=11,column=4,columnspan=1,sticky="we",padx=10)
default_high = tk.Button(self.settings_window,text="Highlight Color",command=lambda:self.swap_colors("highlight"))
default_high.grid(row=12,column=4,sticky="we",padx=10)
default_light = tk.Button(self.settings_window,text="Light Mode Colors",command=lambda:self.swap_colors("light"))
default_light.grid(row=13,column=4,sticky="we",padx=10)
default_dark = tk.Button(self.settings_window,text="Dark Mode Colors",command=lambda:self.swap_colors("dark"))
default_dark.grid(row=14,column=4,sticky="we",padx=10)
sep_theme = ttk.Separator(self.settings_window,orient="horizontal")
sep_theme.grid(row=15,column=0,columnspan=5,sticky="we",padx=10,pady=(10,0))
reset_settings = tk.Button(self.settings_window,text="Restore All Defaults",command=self.reset_settings)
reset_settings.grid(row=16,column=4,sticky="we",padx=10,pady=10)
# Setup the color picker click methods
self.r1_canvas.bind("<ButtonRelease-1>",lambda x:self.pick_color("alternating_color_1",self.r1_canvas))
self.r2_canvas.bind("<ButtonRelease-1>",lambda x:self.pick_color("alternating_color_2",self.r2_canvas))
self.hl_canvas.bind("<ButtonRelease-1>",lambda x:self.pick_color("highlight_color",self.hl_canvas))
self.bg_canvas.bind("<ButtonRelease-1>",lambda x:self.pick_color("background_color",self.bg_canvas))
# Setup some canvas connections
self.canvas_connect = {
self.bg_canvas: {"invert":self.bg_inv_check},
self.r1_canvas: {"invert":self.r1_inv_check},
self.r2_canvas: {"invert":self.r2_inv_check},
self.hl_canvas: {"invert":self.hl_inv_check}
}
self.default_dark = {
"alternating_color_1":"#161616",
"alternating_color_2":"#202020",
"highlight_color":"#1E90FF",
"background_color":"#161616",
"invert_background_text_color":False,
"invert_row1_text_color":False,
"invert_row2_text_color":False
}
self.default_light = {
"alternating_color_1":"#F0F1F1",
"alternating_color_2":"#FEFEFE",
"highlight_color":"#1E90FF",
"background_color":"#FEFEFE",
"invert_background_text_color":False,
"invert_row1_text_color":False,
"invert_row2_text_color":False
}
# Setup the from/to option menus
self.f_title = tk.StringVar(self.tk)
self.t_title = tk.StringVar(self.tk)
f_option = tk.OptionMenu(self.tk, self.f_title, "Ascii", "Base64", "Decimal", "Hex", command=self.change_from_type)
t_option = tk.OptionMenu(self.tk, self.t_title, "Ascii", "Base64", "Decimal", "Hex", command=self.change_to_type)
f_option.grid(row=0,column=1,sticky="we")
t_option.grid(row=1,column=1,sticky="we")
self.f_text = tk.Entry(self.tk)
self.f_text.delete(0,tk.END)
self.f_text.insert(0,"")
self.f_text.grid(row=0,column=2,columnspan=2,sticky="we",padx=10,pady=10)
self.t_text = tk.Entry(self.tk)
self.t_text.configure(state='normal')
self.t_text.delete(0,tk.END)
self.t_text.insert(0,"")
self.t_text.configure(state='readonly')
self.t_text.grid(row=1,column=2,columnspan=2,sticky="we",padx=10,pady=10)
self.c_button = tk.Button(self.tk, text="Convert", command=self.convert_values)
self.c_button.grid(row=2,column=3,sticky="e",padx=10,pady=10)
self.s_button = tk.Button(self.tk, text="To <--> From", command=self.swap_convert)
self.s_button.grid(row=2,column=0,sticky="w",padx=10,pady=10)
self.f_text.bind("<Return>", self.convert_values)
self.f_text.bind("<KP_Enter>", self.convert_values)
self.start_window = None
# Regex to find the processor serial numbers when
# opened from the Finder
self.regexp = re.compile(r"^-psn_[0-9]+_[0-9]+$")
# Setup the menu-related keybinds - and change the app name if needed
key="Control"
sign = "Ctrl+"
self.use_dark = self.get_dark()
if str(sys.platform) == "darwin":
# Remap the quit function to our own
self.tk.createcommand('::tk::mac::Quit', self.quit)
self.tk.createcommand("::tk::mac::OpenDocument", self.open_plist_from_app)
self.tk.createcommand("::tk::mac::ShowPreferences", lambda:self.show_window(self.settings_window))
# Import the needed modules to change the bundle name and force focus
try:
from Foundation import NSBundle
from Cocoa import NSRunningApplication, NSApplicationActivateIgnoringOtherApps
app = NSRunningApplication.runningApplicationWithProcessIdentifier_(os.getpid())
app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)
bundle = NSBundle.mainBundle()
if bundle:
info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
if info and info['CFBundleName'] == 'Python':
info['CFBundleName'] = "ProperTree"
except:
pass
key="Command"
sign=key+"+"
self.tk.protocol("WM_DELETE_WINDOW", self.close_window)
self.settings_window.protocol("WM_DELETE_WINDOW", self.close_window)
self.default_windows = (self.tk,self.settings_window)
self.recent_menu = None
if str(sys.platform) == "darwin":
# Setup the top level menu
file_menu = tk.Menu(self.tk)
main_menu = tk.Menu(self.tk)
self.recent_menu = tk.Menu(self.tk)
main_menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="New (Cmd+N)", command=self.new_plist)
file_menu.add_command(label="Open (Cmd+O)", command=self.open_plist)
file_menu.add_cascade(label="Open Recent", menu=self.recent_menu)
file_menu.add_command(label="Save (Cmd+S)", command=self.save_plist)
file_menu.add_command(label="Save As... (Cmd+Shift+S)", command=self.save_plist_as)
file_menu.add_command(label="Duplicate (Cmd+D)", command=self.duplicate_plist)
file_menu.add_command(label="Reload From Disk (Cmd+L)", command=self.reload_from_disk)
file_menu.add_separator()
file_menu.add_command(label="OC Snapshot (Cmd+R)", command=self.oc_snapshot)
file_menu.add_command(label="OC Clean Snapshot (Cmd+Shift+R)", command=self.oc_clean_snapshot)
file_menu.add_separator()
file_menu.add_command(label="Convert Window (Cmd+T)", command=lambda:self.show_window(self.tk))
file_menu.add_command(label="Strip Comments (Cmd+M)", command=self.strip_comments)
file_menu.add_command(label="Strip Disabled Entries (Cmd+E)", command=self.strip_disabled)
file_menu.add_separator()
file_menu.add_command(label="Settings (Cmd+,)",command=lambda:self.show_window(self.settings_window))
file_menu.add_separator()
file_menu.add_command(label="Toggle Find/Replace Pane (Cmd+F)",command=self.hide_show_find)
file_menu.add_command(label="Toggle Plist/Data/Int Type Pane (Cmd+P)",command=self.hide_show_type)
file_menu.add_separator()
file_menu.add_command(label="Quit (Cmd+Q)", command=self.quit)
self.tk.config(menu=main_menu)
# Set bindings
# on at least macOS, tk 8.5 works with <Command-Z>, but 8.6 requires <Shift-Command-z>
# Can be bypassed by including both Shift and the capital letter
self.tk.bind("<{}-w>".format(key), self.close_window)
self.settings_window.bind("<{}-w>".format(key), self.close_window)
self.tk.bind_all("<{}-n>".format(key), self.new_plist)
self.tk.bind_all("<{}-o>".format(key), self.open_plist)
self.tk.bind_all("<{}-s>".format(key), self.save_plist)
self.tk.bind_all("<{}-Shift-S>".format(key), self.save_plist_as)
self.tk.bind_all("<{}-d>".format(key), self.duplicate_plist)
self.tk.bind_all("<{}-t>".format(key), lambda event, x=self.tk: self.show_window(x))
self.tk.bind_all("<{}-z>".format(key), self.undo)
self.tk.bind_all("<{}-Shift-Z>".format(key), self.redo)
self.tk.bind_all("<{}-m>".format(key), self.strip_comments)
self.tk.bind_all("<{}-e>".format(key), self.strip_disabled)
self.tk.bind_all("<{}-r>".format(key), self.oc_snapshot)
self.tk.bind_all("<{}-Shift-R>".format(key), self.oc_clean_snapshot)
self.tk.bind_all("<{}-l>".format(key), self.reload_from_disk)
if not str(sys.platform) == "darwin":
# Rewrite the default Command-Q command
self.tk.bind_all("<{}-q>".format(key), self.quit)
self.tk.bind_all("<{}-comma>".format(key), lambda event, x=self.settings_window:self.show_window(x))
cwd = os.getcwd()
os.chdir(os.path.dirname(os.path.realpath(__file__)))
#
# Load the settings - current available settings are:
#
# last_window_width: width value (default is 640)
# last_window_height: height value (default is 480)
# expand_all_items_on_open: bool
# sort_dict: bool, false = OrderedDict
# xcode_data: bool, true = <data>XXXX</data>, false = different lines
# comment_strip_prefix: string, defaults to #
# comment_strip_ignore_case: bool, true = ignore case when stripping comments
# comment_strip_check_string: bool, true = consider string values as well as keys
# new_plist_default_type: string, XML/Binary
# display_data_as: string, Hex/Base64
# display_int_as: string, Decimal/Hex
# snapshot_version: string, X.X.X version number, or Latest
# force_snapshot_schema: bool
# alternating_color_1: string, Dark: #161616 - Light: #F0F1F1
# alternating_color_2: string, Dark: #202020 - Light: #FEFEFE
# highlight_color: string, Dark: #1E90FF - Light: #1E90FF
# background_color: string, Dark: #161616 - Light: #FEFEFE
# header_text_ignore_bg_color: bool
# invert_background_text_color: bool
# invert_row1_text_color: bool
# invert_row2_text_color: bool
# invert_hl_text_color: bool
# drag_dead_zone: pixel distance before drag starts (default is 20)
# open_recent: list, paths recently opened
# recent_max: int, max number of recent items
# max_undo: int, max undo history - 0 = unlimited
#
self.settings = {}
if os.path.exists("Scripts/settings.json"):
try:
self.settings = json.load(open("Scripts/settings.json"))
except:
pass
# Also load the snapshot defaults
self.snapshot_data = {}
if os.path.exists("Scripts/snapshot.plist"):
try:
with open("Scripts/snapshot.plist","rb") as f:
self.snapshot_data = plist.load(f)
except:
pass
os.chdir(cwd)
# Setup the settings page to reflect our settings.json file
self.allowed_types = ("XML","Binary")
self.allowed_data = ("Hex","Base64")
self.allowed_int = ("Decimal","Hex")
self.allowed_bool = ("True/False","YES/NO","On/Off","1/0")
self.allowed_conv = ("Ascii","Base64","Decimal","Hex")
self.update_settings()
self.case_insensitive = self.get_case_insensitive()
# Normalize the pathing for Open Recents
self.normpath_recents()
if str(sys.platform) == "darwin": self.update_recents()
self.check_dark_mode()
# Prior implementations tried to wait 250ms to | |
"""
Tensor based implementation of f-statistics to
simultaneously calculate many comparisons.
Works on VCF files.
For memory efficiency, weighted block-jackknifing is
currently done across whole chromosomes.
F-test was compared to previous implementation (which was checked
against Admixtols). Results were extremely close, e.g.: D +- 0.25%
To run map function of these classes with ipython parallel or
multiprocessing, one might need to use a pickling tool other than
the standard pickling module. The module dill works fine for me.
#!!! NAN HAndling breaks F4ratio!!!!
# make sure that the same rows are removed in all subsamples!
"""
import logging
import numpy as np
import pandas as pd
import os
#local modules
import vcfpandas as vp
import treetools
logger = logging.getLogger()
logging.basicConfig(
format='%(levelname)-8s %(asctime)s %(filename) %(message)s')
#logging.basicConfig(format='%(levelname)-8s %(asctime)s %(funcName)20s() %(message)s')
logger.setLevel(logging.WARNING)
class Test(object):
x = 'Test'
def test(self, i):
return i + self.x
#ACCOUNT FOR NA here?
def run_parallel(self, rc):
rc[:].push({'x': 22})
rc[:].use_cloudpickle()
lv = rc.load_balanced_view()
m = lv.map_async(lambda c: x, range(5))
#return m.result
return m.result
class Ftest(object):
"""
This is the base class for f-tests. Specific
test classes such as Dtest, F3test, F4test, ...
derive from it.
Performs tests for all combinations of h1, h2, h3, (h4).
------------------
Parameters:
vcf_filename : vcf.gz filename. Should be tabix indexed
for random access.
ind_to_pop : dictionary that maps individuals to populations
if each individual is its on population this can also
be a list of individuals
reduce_dim : If true, remove dimensions with length 1 (not implemented).
TODO:
Samples should be defined from the h1s, h2s etc
so that samples in ind_to_pop that are not needed are ignored...
"""
ftype = None
def __init__(self, vcf_filename,
ind_to_pop=None,
result_filebase=None,
reduce_dim=False, haploid=False):
self.vcf_filename = vcf_filename
try:
self.samples = ind_to_pop.keys()
except AttributeError:
ind_to_pop = {k:k for k in ind_to_pop}
self.samples = ind_to_pop.keys()
self.ind_to_pop = ind_to_pop
self.result_filebase = result_filebase
self.haploid = haploid
@staticmethod
def get_hap_df(t0, t1):
"""
Takes 0/1 DataFrames for two haplotpyes
per individual and combines them to per
population allele frequencies.
"""
# if len(t0):
# t0.columns = pd.MultiIndex.from_arrays(
# [t0.columns, [0] * len(t0.columns)])
# if len(t1):
# t1.columns = pd.MultiIndex.from_arrays(
# [t1.columns, [1] * len(t1.columns)])
hap_df = pd.concat([t0, t1], axis=1).sortlevel(axis=1)
#it is enought to drop nas in the allele frequency!
#hap_df = hap_df.dropna(axis=0)
return hap_df
#THINK ABOUT NA handling for this functions
@staticmethod
def get_af(hap_df, ind_to_pop):
if len(hap_df):
af = hap_df.groupby(level=0, axis=1).mean()
af = af.groupby(ind_to_pop, axis=1).mean()
else:
af = pd.DataFrame(columns=set(ind_to_pop.values()))
return af#dropna()
@staticmethod
def get_ac(hap_df, ind_to_pop):
if len(hap_df):
ac = hap_df.groupby(level=0, axis=1).sum()
ac = ac.groupby(ind_to_pop, axis=1).sum()
else:
ac = pd.DataFrame(columns=set(ind_to_pop.values()))
return ac#.dropna()
@staticmethod
def get_n(hap_df, ind_to_pop):
"""
Get the number of haplotypes per population.
"""
if len(hap_df):
#ACCOUNT FOR NA
n = hap_df.groupby(level=0, axis=1).apply(lambda df: df.notnull().sum(axis=1))
n = n.groupby(ind_to_pop).sum()
else:
n = pd.Series(index=set(ind_to_pop.values()))
return n.dropna()
@staticmethod
def fly_reduce_fun(chunk_res, result=None):
if result is None:
return chunk_res
else:
return result + chunk_res
def map(self, chromosomes, start=None, end=None,
map_fun=map, get_result_fun=lambda r:r, chunksize=50000,
return_result=True, save_result=False):
"""
chromosomes : list of chromosome names as in the vcf file
to run the analysis on
stat : Start at this position at each chromosome
end : End at this position at each chromosomes
If start and end are not given, the whole chromosome
is used.
map_fun : The mapping function that will be used
to map calculations to chromosomes.
Could for instance be multiprocessing.map_async
or ipython parallel map_async. Default: map
get_result_fun : The function that receives the result
from the output of the mapping function
For map this would simply be the identity (default)
or for ipython parallel lv.map_async it is
lambda r: r.result() (or lambda r: r.result for older versions)
chunksize : Number of lines in the input vcf to read per chunk
if jackknife_levels is 'chunk' this also determines
the block-jackknife block.
return_result : Whether to return the result for each chromosme
to the mapping function. For very large results
it can be more stable and memory efficient to
set return_result=False and save_result=True
save_result : whether or not to save the result for each chromosome
to disk
"""
assert return_result or save_result
if save_result:
assert self.result_filebase is not None
result_filebase = self.result_filebase
self.chromosomes = chromosomes
self.get_result_fun = get_result_fun
#calc_stat = lambda chunk1, chunk2: self.calc_stat_static(chunk1, chunk2, ind_to_pop, h1s, h2s, h3s, h4s)
#params = {'vcf_filename':self.vcf_filename,
# 'calc_stat':calc_stat, 'ind_to_pop': self.ind_to_pop, 'h1s':self.h1s,
# 'h2s':self.h2s, 'h3s': self.h3s, 'h4s': self.h4s,
# 'samples':self.samples,'fly_reduce_fun':self.fly_reduce_fun,
# 'chunksize':self.chunksize,'mr_haplo_fun':vp.map_fly_reduce_haplo}
vcf_filename = self.vcf_filename
ind_to_pop = self.ind_to_pop
samples = self.samples
fly_reduce_fun = self.fly_reduce_fun
mr_haplo_fun = vp.map_fly_reduce_haplo
calc_stat = self.get_calc_stat(*self.calc_params)
def calc_fstat_fun(chrom):
r = mr_haplo_fun(vcf_filename.format(str(chrom)), calc_stat,
samples_h0=samples,
samples_h1=samples if not self.haploid else None,
chrom=str(chrom), start=start, end=end,
fly_reduce_fun=fly_reduce_fun,
chunksize=chunksize)
if save_result:
np.save(result_filebase+'_'+str(chrom), r)
#return_result = True
if return_result:
return r
self.map_result = map_fun(calc_fstat_fun, chromosomes)
#self.map_result = 'bla'
return self.map_result
def progress(self):
return self.map_result.progress
def load_result_chrom(self, chrom):
r = np.load(self.result_filebase+'_'+str(chrom)+'.npy')
return r
def load_result(self):
res = np.array([self.load_result_chrom(c) for c in self.chromosomes])
return res
def get_result(self):
#try:
# se.result(1)
#except TimeoutError:
# logger.INFO('Not finished, status is: {}'.format({i:s.count(i) for i in set(s)}))
# return
try:
res = np.array(self.get_result_fun(self.map_result))
except AttributeError:
res = self.load_result()
if res[0] is None:
res = self.load_result()
stat = self.get_stat(res)
zscores = self.get_zscores(res, stat)
stat_df = self.get_stat_df(stat, zscores)
self.stat_df = stat_df
return stat_df
class PairwiseDiff(Ftest):
"""
Parameters:
hs1s : list of sample names to use as h1
hs2s : list of sample names to use as h2
vcf_filename : vcf.gz filename. Should be tabix indexed
for random access.
ind_to_pop : dictionary that maps individuals to populations
if each individual is its on population this can also
be a list of individuals
reduce_dim : If true, remove dimensions with length 1 (not implemented).
"""
ftype = 'pwd'
def __init__(self, vcf_filename, ind_to_pop, h1s, **kwa):
self.h1s = h1s
self.h2s = None
self.h3s = None
self.h4s = None
try:
to_delete = []
for k,v in ind_to_pop.iteritems():
if v not in h1s:
to_delete.append(k)
for k in to_delete:
del ind_to_pop[k]
except AttributeError:
pass
Ftest.__init__(self, vcf_filename, ind_to_pop, **kwa)
self.calc_params = (self.ind_to_pop, self.h1s)
@staticmethod
def fly_reduce_fun(chunk_res, result=None):
"""
Function that reduces on the fly by summing
"""
if result is None:
return chunk_res
else:
return result + chunk_res
@staticmethod
def calc_stat_static(chunk1, chunk2, ind_to_pop, h1s, *args):
hap_df = Ftest.get_hap_df(chunk1, chunk2)
if len(hap_df):
groups = hap_df.groupby(ind_to_pop, axis=1, level=0)
#ids = groups.apply(lambda df:np.nan).index.values
return calc.divergence(groups)
else:
return np.zeros((len(groups),
len(groups)))
@staticmethod
def get_calc_stat(*args):
def calc_stat(chunk1, chunk2):
return PairwiseDiff.calc_stat_static(chunk1, chunk2, *args)
return calc_stat
@staticmethod
def jackknife(res, i):
return np.sum(res[np.arange(len(res))!=i, 0], axis=0)/np.sum(res[np.arange(len(res))!=i, 1], axis=0)
@staticmethod
def get_stat(res):
return np.sum(res, axis=0)
@staticmethod
def get_zscores(res, pwd):
return None
@staticmethod
def get_stat_df_static(pwd, ind_to_pop):
s = sorted(set(ind_to_pop.values()))
return pd.DataFrame(pwd, index=s, columns=s)
def get_stat_df(self, stat, zscores):
return self.get_stat_df_static(stat, self.ind_to_pop)
class F3test(Ftest):
"""
Parameters:
hs3s : list of sample names to use as h3
This is the branch called 'C' in
Patterson et al. 2012 Genetics
hs1s : list of sample names to use as h1
hs2s : list of sample names to use as h2
vcf_filename : vcf.gz filename. Should be tabix indexed
for random access.
ind_to_pop : dictionary that maps individuals to populations
if each individual is its on population this can also
be a list of individuals
reduce_dim : If true, remove dimensions with length 1 (not implemented).
"""
ftype = 'F3'
def __init__(self, vcf_filename, ind_to_pop, h3s, h1s, h2s, do_drop_self_comparisons=False, **kwa):
self.h1s = h1s
self.h2s = h2s
self.h3s = h3s
self.do_drop_self_comparisons = do_drop_self_comparisons
Ftest.__init__(self, vcf_filename, ind_to_pop, **kwa)
self.calc_params = (self.ind_to_pop, self.h1s, self.h2s, self.h3s)
@staticmethod
def fly_reduce_fun(chunk_res, result=None):
"""
Function that reduces on the fly by summing
"""
if result is None:
return chunk_res
else:
return result + chunk_res
@staticmethod
def calc_stat_static(chunk1, chunk2, ind_to_pop, h1s, h2s, h3s, *args):
hap_df = Ftest.get_hap_df(chunk1, chunk2)
af = Ftest.get_af(hap_df, ind_to_pop)
ac = Ftest.get_ac(hap_df, ind_to_pop)
n = Ftest.get_n(hap_df, ind_to_pop)
if len(af):
return calc.f3(ac[h3s], n[h3s], af[h1s], af[h2s])
else:
return np.zeros((len(h3s),len(h1s), len(h2s)))
@staticmethod
def get_calc_stat(*args):
def calc_stat(chunk1, chunk2):
return F3test.calc_stat_static(chunk1, chunk2, *args)
return calc_stat
@staticmethod
def jackknife(res, i):
return np.sum(res[np.arange(len(res))!=i, 0], axis=0)/np.sum(res[np.arange(len(res))!=i, 1], axis=0)
@staticmethod
def get_stat(res):
return np.sum(res, axis=0)
@staticmethod
def get_zscores(res, pwd):
return None
@staticmethod
def drop_self_comparisons_static(stat_df, h1s, h2s, | |
import itertools
import math
import random
import warnings
import numpy as np
from scipy.interpolate import griddata
from sklearn.decomposition import PCA
import src.multi_agent.elements.mobile_camera as mobileCam
from src import constants
from src.multi_agent.elements.target import TargetType
from src.multi_agent.tools.configuration import Configuration, bound
from src.my_utils import constant_class
from src.my_utils.my_math.line import Line, distance_btw_two_point
from src.multi_agent.tools.potential_field_method import compute_potential_gradient, \
convert_target_list_to_potential_field_input, compute_potential_field_cam, plot_potential_field_dynamic, HeatMaps
class Angle_configuration:
PARALLEL_TO_COMPUTED_DIRECTION = 0
PERPENDICULAR_TO_COMPUTED_DIRECTION = 1
class PCA_track_points_possibilites:
MEANS_POINTS = "mean points"
MEDIAN_POINTS = "median points"
def check_heat_maps(n_target, camera):
if n_target == 1:
return [HeatMaps.HEAT_MAP_ONE_TARGET_CENTER(camera.field_depth)]
elif n_target == 2:
return [HeatMaps.HEAT_MAP_TWO_TARGET_CENTER(camera.field_depth, camera.beta),
HeatMaps.HEAT_MAP_TWO_TARGET_FAR(camera.field_depth, camera.field_depth, 1),
HeatMaps.HEAT_MAP_TWO_TARGET_FAR(camera.field_depth, camera.field_depth, 2)]
def get_configuration_based_on_seen_target(camera, target_representation_list, room,
point_to_track_choice=PCA_track_points_possibilites.MEDIAN_POINTS,
memory_objectives=None,
memory_point_to_reach=None, virtual=False, no_target_behaviour=False):
"""Default values"""
xt = camera.xc
yt = camera.yc
alpha = camera.alpha
beta = camera.beta
angle_in_room_representation = 0
distance_to_keep_to_target = camera.field_depth * constants.DISTANCE_TO_KEEP_FROM_TARGET
y_to_compute_beta = 0
point_to_be_close_x = camera.xc
point_to_be_close_y = camera.yc
placement_choice = None
number_of_target = len(target_representation_list)
all_fix = True
are_target_fix = [target.target_type == TargetType.FIX for target in target_representation_list]
for item in are_target_fix:
if not item:
all_fix = False
if all_fix and target_representation_list:
return Configuration(xt, yt, camera.xc, camera.yc, camera.alpha, camera.beta, camera.field_depth, virtual)
"""-----------------------------------------------------------------------------------------------------------------
IN TERMS OF THE TARGET NUMBER
-----------------------------------------------------------------------------------------------------------------"""
if number_of_target < 0:
warnings.warn("Agent ", camera.id, "sees a negative number of targets...")
elif number_of_target == 0 or no_target_behaviour:
configuration = Configuration(camera.xc, camera.yc, camera.xc, camera.yc, camera.alpha,
camera.beta, camera.field_depth, virtual)
# all types rotate
if camera.camera_type != mobileCam.MobileCameraType.FIX:
no_targets_rotation_behaviour(configuration, camera)
# rails and free cameras actually move
if camera.camera_type == mobileCam.MobileCameraType.RAIL or \
camera.camera_type == mobileCam.MobileCameraType.FREE:
no_target_movement_behaviour(configuration, camera)
configuration.track_target_list = []
configuration.configuration_score = 0
return configuration
elif number_of_target == 1:
"In this case PCA is not possible, we chose to focus on the target itself"
target = target_representation_list[0]
xt = target.xc
yt = target.yc
delta_x = camera.xc - xt
delta_y = camera.yc - yt
if target.target_type == TargetType.FIX or target.target_type == TargetType.SET_FIX:
angle_in_room_representation = camera.alpha
else:
angle_in_room_representation = math.atan(delta_y / delta_x)
y_to_compute_beta = target.radius
placement_choice = Angle_configuration.PARALLEL_TO_COMPUTED_DIRECTION
elif number_of_target >= 2:
"Principle Component Analysis"
xt, yt, angle_in_room_representation, y_to_compute_beta, variance_min_ratio = get_angle_alpha_beta_PCA_method(
target_representation_list,
point_to_track_choice)
placement_choice = Angle_configuration.PERPENDICULAR_TO_COMPUTED_DIRECTION
if number_of_target == 2:
target1 = target_representation_list[0]
target2 = target_representation_list[1]
distance = distance_btw_two_point(target1.xc, target1.yc, target2.xc, target2.yc)
if distance > 2 * distance_to_keep_to_target * camera.field_depth * math.tan(beta / 2):
placement_choice = Angle_configuration.PARALLEL_TO_COMPUTED_DIRECTION
elif number_of_target == 3:
"We want to be closer from the 3rd target"
distance_max = -1
distance_max_and_ids = (-1, [-1, -1])
for targets in itertools.combinations(target_representation_list, 2):
target1, target2 = targets
distance_to_compute = distance_btw_two_point(target1.xc, target1.yc, target2.xc, target2.yc)
if distance_max < distance_to_compute:
distance_max = distance_to_compute
distance_max_and_ids = (distance_max, [target1.id, target2.id])
for target in target_representation_list:
if target.id not in distance_max_and_ids[1]:
point_to_be_close_x = 2 * xt - math.fabs(target.xc)
point_to_be_close_y = 2 * yt - math.fabs(target.yc)
"""-----------------------------------------------------------------------------------------------------------------
IN TERMS OF THE CAMERA TYPE
-----------------------------------------------------------------------------------------------------------------"""
angle_in_room_representation = modify_angle(angle_in_room_representation, placement_choice)
"""Camera has to moove in a different way"""
if camera.camera_type == mobileCam.MobileCameraType.FIX or \
camera.camera_type == mobileCam.MobileCameraType.ROTATIVE:
_, _, alpha = define_xc_yc_alpha(camera, xt, yt, distance_to_keep_to_target, angle_in_room_representation,
memory_objectives, memory_point_to_reach, virtual)
xc = camera.xc
yc = camera.yc
elif camera.camera_type == mobileCam.MobileCameraType.RAIL:
xc, yc, alpha = define_xc_yc_alpha(camera, xt, yt, distance_to_keep_to_target, angle_in_room_representation,
memory_objectives, memory_point_to_reach, virtual)
elif camera.camera_type == mobileCam.MobileCameraType.FREE:
xc1, yc1, alpha1 = define_xc_yc_alpha(camera, xt, yt, distance_to_keep_to_target, angle_in_room_representation,
memory_objectives, memory_point_to_reach, virtual)
xc2, yc2, alpha2 = define_xc_yc_alpha(camera, xt, yt, distance_to_keep_to_target,
angle_in_room_representation + math.pi,
memory_objectives, memory_point_to_reach, virtual)
distance1 = distance_btw_two_point(xc1, yc1, point_to_be_close_x, point_to_be_close_y)
distance2 = distance_btw_two_point(xc2, yc2, point_to_be_close_x, point_to_be_close_y)
delta_distance = distance1 - distance2
chose_pt_1 = True
if math.fabs(delta_distance) > 0.1 and delta_distance > 0:
chose_pt_1 = False
if chose_pt_1:
xc = xc1
yc = yc1
alpha = alpha1
else:
xc = xc2
yc = yc2
alpha = alpha2
if not virtual:
memory_point_to_reach.append([(xc, yc, 0), (point_to_be_close_x, point_to_be_close_y, 0)])
else:
xc = -1
yc = -1
print("camera_type not recognize")
"""Same computation for the beta for every case"""
distance_to_target = distance_btw_two_point(camera.xc, camera.yc, xt, yt)
beta = define_beta(distance_to_target, y_to_compute_beta)
field_depth = camera.compute_field_depth_variation_for_a_new_beta(beta)
"""Create a new configuration and make it match with the camera limitation"""
configuration = Configuration(xt, yt, xc, yc, alpha, beta, field_depth, virtual)
configuration.bound_to_camera_limitation(camera)
configuration.track_target_list = target_representation_list
configuration.compute_configuration_score()
return configuration
def define_xc_yc_alpha(camera, xt, yt, distance_to_keep_to_target, angle_in_room_coordinate, memory_objectives=None,
memory_point_to_reach=None, virtual=False):
"""Finding were the camera should move in terms of its type, fix and rotative cannot move"""
memory_objectives.append((xt, yt, angle_in_room_coordinate))
xc, yc = (camera.default_xc, camera.default_yc)
if camera.camera_type == mobileCam.MobileCameraType.RAIL:
line_we_want_to_be_align_with = Line(xt, yt, xt + math.cos(angle_in_room_coordinate),
yt + math.sin(angle_in_room_coordinate))
index = camera.trajectory.trajectory_index
(xi, yi, new_index) = camera.trajectory.find_closest_intersection(line_we_want_to_be_align_with, index)
if virtual:
xc = xi
yc = yi
else:
xc, yc = camera.trajectory.compute_distance_for_point_x_y(xi, yi, new_index)
"Save data"
if not virtual:
memory_point_to_reach.append([(xi, yi, new_index)])
elif camera.camera_type == mobileCam.MobileCameraType.FREE:
xc = xt + math.cos(angle_in_room_coordinate) * distance_to_keep_to_target
yc = yt + math.sin(angle_in_room_coordinate) * distance_to_keep_to_target
xc = bound(xc, camera.xc_min, camera.xc_max)
yc = bound(yc, camera.yc_min, camera.yc_max)
if virtual:
alpha = math.atan2(yt - yc, xt - xc)
else:
alpha = math.atan2(yt - camera.yc, xt - camera.xc)
return xc, yc, alpha
def define_beta(distance, radius):
beta = constants.SECURITY_MARGIN_BETA * math.atan2(radius, distance)
return beta
def modify_angle(angle_in_room_coordinate, alignement_choice=Angle_configuration.PERPENDICULAR_TO_COMPUTED_DIRECTION):
"""Modification from this angle to slightly improve the results"""
if alignement_choice == Angle_configuration.PERPENDICULAR_TO_COMPUTED_DIRECTION:
angle_in_room_coordinate = angle_in_room_coordinate + math.pi / 2
elif alignement_choice == Angle_configuration.PARALLEL_TO_COMPUTED_DIRECTION:
angle_in_room_coordinate = angle_in_room_coordinate # angle_prec
else:
print("modify_angle in behaviour_agent.py error, choice not found")
angle_in_room_coordinate = 0
return angle_in_room_coordinate
def get_angle_alpha_beta_PCA_method(target_representation_list,
point_to_track_choice=PCA_track_points_possibilites.MEDIAN_POINTS):
(xt, yt, mean, explained_variance_, explained_variance_ratio_, components_) = pca_methode_2D_plan(
target_representation_list,
point_to_track_choice)
eigen_vector = components_
eigen_value_ = explained_variance_
eigen_value_ratio = explained_variance_ratio_
"""Finding highest highest value"""
if eigen_value_[1] < eigen_value_[0]:
vector = eigen_vector[0]
lambda_min = eigen_value_[0]
lambda_max = eigen_value_[1]
coeff_corrector = eigen_value_ratio[0]
else:
vector = eigen_vector[1]
lambda_min = eigen_value_[1]
lambda_max = eigen_value_[0]
coeff_corrector = eigen_value_ratio[1]
"""Angle to give to the camera to get a good orrientation"""
angle_in_room_coordinate = math.atan(vector[1] / vector[0])
"""Angle beta - field opening"""
radius_for_beta = 0
if point_to_track_choice == PCA_track_points_possibilites.MEANS_POINTS:
radius_for_beta = 2 * np.sqrt(max(eigen_value_[0], eigen_value_[1]))
elif point_to_track_choice == PCA_track_points_possibilites.MEDIAN_POINTS:
# TODO A CHANGER ici si on sait qu'on ne prends de toute façon pas tous les points en prenant la mediane, peut être réapliquer les pca
# TODO avec la moyenne pour obtenir l'orrientation et la variance maximale sur les targets qui sont réellement vus.
radius_for_beta = 2 * np.sqrt(max(eigen_value_[0], eigen_value_[1]))
return xt, yt, angle_in_room_coordinate, radius_for_beta, coeff_corrector
def get_angle_beta_command_based_on_target_pos(camera, xt, yt, radius):
(xt_in_camera_frame, yt_in_camera_frame) = camera.coordinate_change_from_world_frame_to_camera_frame(xt, yt)
"We suppose we are centering on the target using get_angle_alpha_command_based_on_target_pos => yt_in_camera_frame is almost = 0 "
error_y = yt_in_camera_frame
angle_beta = math.atan2((radius + error_y), xt_in_camera_frame)
return 1.2 * angle_beta
def pca_methode_2D_plan(target_representation_list, point_to_track_choice=PCA_track_points_possibilites.MEDIAN_POINTS):
""""""
"""List used"""
sample = []
all_x = []
all_y = []
"""Formating data to the method fit"""
for target_representation in target_representation_list:
sample.append([target_representation.xc, target_representation.yc])
if not int(target_representation.target_type) == int(TargetType.SET_FIX):
all_x.append(target_representation.xc)
all_y.append(target_representation.yc)
if len(sample) > 0:
"""Compute the PCA analysis"""
pca = PCA(n_components=2)
pca.fit(sample)
"""To possibilities to choose were to place the PCA origin"""
if len(all_x) <= 0 or len(all_y) <= 0:
xt = pca.mean_[0]
yt = pca.mean_[1]
elif point_to_track_choice == PCA_track_points_possibilites.MEANS_POINTS:
xt = np.mean(all_x)
yt = np.mean(all_y)
elif point_to_track_choice == PCA_track_points_possibilites.MEDIAN_POINTS:
xt = np.median(all_x)
yt = np.median(all_y)
else:
print("pca method not defined")
return None, None, None, None
return xt, yt, pca.mean_, pca.explained_variance_, pca.explained_variance_ratio_, pca.components_
else:
print("no samples")
return None, None, None, None
def are_all_points_in_room(points_list):
return all([is_point_in_room(point) for point in points_list])
def is_point_in_room(point):
x_in_length = 0 <= point[0] <= constants.ROOM_DIMENSION_X
y_in_width = 0 <= point[1] <= constants.ROOM_DIMENSION_Y
return x_in_length and y_in_width
def intersection_fov_room(camera):
"""Finds the intersectino between the field of view of a camera with the edges of the room."""
from src.my_utils.my_math.line import Line
points_of_intersection = []
corners_of_room = [(0, 0), (0, constants.ROOM_DIMENSION_Y), (constants.ROOM_DIMENSION_X, constants.ROOM_DIMENSION_Y),
(constants.ROOM_DIMENSION_X, 0), (0, 0)]
for idx in range(len(corners_of_room) - 1):
# define the 4 Lines of the room
room_edge = Line(corners_of_room[idx][0], corners_of_room[idx][1],
corners_of_room[idx + 1][0], corners_of_room[idx + 1][1])
# define the circle constructed from the field depth and the center of the camera & find intersections
fov_intersection = room_edge.find_intersection_btw_line_circle(camera.field_depth, camera.xc, camera.yc)
if fov_intersection is not None:
x1, y1, x2, y2 = fov_intersection
points_of_intersection.append((x1, y1))
points_of_intersection.append((x2, y2))
# return all intersections (if more than 2, there is a problem... sort of...)
return points_of_intersection
def chose_point_of_intersection(intersection_points, rotation_direction):
"""From the intersection points, finds the one that will be touched if the points are outside of the room and
the camera rotates | |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
# -----------------------------------------------------------------------------
try:
basestring # Python 3
except NameError:
basestring = str # Python 2
import base64
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidAddress
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
class max(Exchange):
def describe(self):
return self.deep_extend(super(max, self).describe(), {
'id': 'max',
'name': 'Max',
'countries': ['TW'],
'version': 'v2',
'enableRateLimit': False,
'rateLimit': 1200,
'certified': False,
'has': {
'cancelAllOrders': True,
'cancelOrder': True,
'cancelOrders': False,
'CORS': True,
'createDepositAddress': True,
'createLimitOrder': True,
'createMarketOrder': True,
'createOrder': True,
'deposit': False,
'editOrder': 'emulated',
'fetchBalance': True,
'fetchBidsAsks': False,
'fetchClosedOrders': True,
'fetchCurrencies': True,
'fetchDepositAddress': True,
'fetchDeposits': False,
'fetchFundingFees': False,
'fetchL2OrderBook': False,
'fetchLedger': False,
'fetchMarkets': True,
'fetchMyTrades': True,
'fetchOHLCV': True,
'fetchOpenOrders': True,
'fetchOrder': True,
'fetchOrderBook': True,
'fetchOrderBooks': False,
'fetchOrders': True,
'fetchStatus': 'emulated',
'fetchTicker': True,
'fetchTickers': True,
'fetchTime': True,
'fetchTrades': True,
'fetchTradingFee': False,
'fetchTradingFees': False,
'fetchTradingLimits': False,
'fetchTransactions': False,
'fetchWithdrawals': True,
'privateAPI': True,
'publicAPI': True,
'withdraw': False,
},
'urls': {
'logo': '',
'api': {
'web': 'https://max.maicoin.com',
'wapi': '',
'public': 'https://max-api.maicoin.com',
'private': 'https://max-api.maicoin.com',
},
'www': 'https://max.maicoin.com',
'doc': 'https://max.maicoin.com/documents/api',
'fees': 'https://max.maicoin.com/docs/fees',
},
'api': {
'web': {
},
'wapi': {
},
'public': {
'get': [
'markets',
'currencies',
'tickers/{market_id}',
'tickers',
'withdrawal/constraint',
'depth',
'trades',
'k',
'timestamp',
],
},
'private': {
'get': [
'members/profile',
'members/accounts/{currency_id}',
'members/accounts',
'members/me',
'deposits',
'deposit',
'deposit_addresses',
'withdrawals',
'withdrawal',
'withdrawal_addresses',
'orders',
'order',
'trades/my/of_order',
'trades/my',
'internal_transfers',
'internal_transfer',
'rewards/{reward_type}',
'rewards',
'max_rewards/yesterday',
],
'post': [
'deposit_addresses',
'orders/clear',
'orders',
'orders/multi',
'order/delete',
],
},
},
'timeframes': {
'1m': '1',
'5m': '5',
'15m': '15',
'30m': '30',
'1h': '60',
'2h': '120',
'4h': '240',
'6h': '360',
'12h': '720',
'1d': '1440',
'3d': '4320',
'1w': '10080',
},
'fees': {
'trading': {
'maker': 0.05 / 100,
'taker': 0.15 / 100,
},
'funding': {
'withdraw': {},
'deposit': {},
},
},
'commonCurrencies': {
},
'options': {
'timeDifference': 0, # the difference between system clock and Max clock
'adjustForTimeDifference': False, # controls the adjustment logic upon instantiation
},
'exceptions': {
'2002': InvalidOrder, # Order volume too small
'2003': OrderNotFound, # Failed to cancel order
'2004': OrderNotFound, # Order doesn't exist
'2005': AuthenticationError, # Signature is incorrect.
'2006': AuthenticationError, # The nonce has already been used by access key.
'2007': AuthenticationError, # The nonce is invalid.(30 secconds difference from server time)
'2008': AuthenticationError, # The access key does not exist.
'2009': AuthenticationError, # The access key is disabled.
'2011': AuthenticationError, # Requested API is out of access key scopes.
'2014': AuthenticationError, # Payload is not consistent with body or wrong path in payload.
'2015': AuthenticationError, # Payload is invalid
'2016': InvalidOrder, # amount_too_small
'2018': InsufficientFunds, # cannot lock funds
},
})
def fetch_time(self, params={}):
response = self.publicGetTimestamp()
return int(response, 10) * 1000
def nonce(self):
return self.milliseconds() - self.options['timeDifference']
def load_time_difference(self):
serverTimestamp = self.fetch_time()
after = self.milliseconds()
self.options['timeDifference'] = after - serverTimestamp
return self.options['timeDifference']
def insert_objects_property_by(self, a, keyA, b, keyB, insertKey):
result = {}
for i in range(0, len(a)):
entry = a[i]
index = entry[keyA]
result[index] = entry
for i in range(0, len(b)):
entry = b[i]
index = entry[keyB]
if result[index]:
result[index][insertKey] = entry
values = []
resultKeys = list(result.keys())
for i in range(0, len(resultKeys)):
values.append(result[resultKeys[i]])
return values
def fetch_currencies(self, params={}):
currenciesResponse = self.publicGetCurrencies(params)
withdrawalResponse = self.publicGetWithdrawalConstraint()
response = self.insert_objects_property_by(
currenciesResponse,
'id',
withdrawalResponse,
'currency',
'withdrawal'
)
result = {}
for i in range(0, len(response)):
currency = response[i]
id = currency['id']
code = self.safe_currency_code(id)
fiat = id is True if 'twd' else False
withdrawal = self.safe_value(currency, 'withdrawal')
withdrawalFee = self.safe_value(withdrawal, 'fee')
withdrawalLimit = self.safe_value(withdrawal, 'min_amount')
result[code] = {
'id': id,
'code': code,
'name': code,
'active': True,
'fiat': fiat,
'precision': self.safe_integer(currency, 'precision'),
'limits': {
'amount': {
'min': None,
'max': None,
},
'price': {
'min': None,
'max': None,
},
'deposit': {
'min': None,
'max': None,
},
'withdraw': {
'min': withdrawalLimit,
'max': None,
},
},
'funding': {
'withdraw': {
'fee': withdrawalFee,
},
'deposit': {
'fee': None,
},
},
'info': currency,
}
return result
def fetch_markets(self, params={}):
markets = self.publicGetMarkets()
if self.options['adjustForTimeDifference']:
self.load_time_difference()
result = []
for i in range(0, len(markets)):
market = markets[i]
id = market['id']
baseId = market['base_unit']
quoteId = market['quote_unit']
base = self.safe_currency_code(baseId)
quote = self.safe_currency_code(quoteId)
symbol = base + '/' + quote
precision = {
'amount': market['base_unit_precision'],
'price': market['quote_unit_precision'],
}
active = True
entry = {
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'info': market,
'active': active,
'precision': precision,
'limits': {
'amount': {
'min': None,
'max': None,
},
'price': {
'min': None,
'max': None,
},
'cost': {
'min': None,
'max': None,
},
},
}
result.append(entry)
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privateGetMembersAccounts(params)
result = {'info': response}
for i in range(0, len(response)):
balance = response[i]
currency = balance['currency']
if currency in self.currencies_by_id:
currency = self.currencies_by_id[currency]['code']
account = self.account()
account['free'] = self.safe_float(balance, 'balance')
account['used'] = self.safe_float(balance, 'locked')
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return self.parse_balance(result)
def fetch_order_book(self, symbol, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
request = {
'market': market['id'],
}
if limit is not None:
request['limit'] = limit # default = 300
response = self.publicGetDepth(self.extend(request, params))
timestamp = self.safe_timestamp(response, 'timestamp')
orderbook = self.parse_order_book(response, timestamp)
return orderbook
def parse_ticker(self, ticker, market=None):
timestamp = self.safe_timestamp(ticker, 'at')
symbol = None
marketId = self.safe_string(ticker, 'symbol')
if marketId in self.markets_by_id:
market = self.markets_by_id[marketId]
if market is not None:
symbol = market['symbol']
last = self.safe_float(ticker, 'last')
open = self.safe_float(ticker, 'open')
change = last - open
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': self.safe_float(ticker, 'high'),
'low': self.safe_float(ticker, 'low'),
'bid': self.safe_float(ticker, 'buy'),
'bidVolume': None,
'ask': self.safe_float(ticker, 'sell'),
'askVolume': None,
'vwap': None,
'open': open,
'close': last,
'last': last,
'previousClose': None,
'change': change,
'percentage': (change / open) * 100,
'average': None,
'baseVolume': self.safe_float(ticker, 'vol'),
'quoteVolume': None,
'info': ticker,
}
def fetch_ticker(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTickersMarketId(self.extend({
'market_id': market['id'],
}, params))
response['symbol'] = market['id']
return self.parse_ticker(response, market)
def fetch_tickers(self, symbols=None, params={}):
self.load_markets()
response = self.publicGetTickers(params)
tickerKeys = list(response.keys())
result = {}
for i in range(0, len(tickerKeys)):
key = tickerKeys[i]
response[key]['symbol'] = key
ticker = self.parse_ticker(response[key])
if symbols is None or symbols.includes(ticker['symbol']):
result[ticker['symbol']] = ticker
return result
def parse_ohlcv(self, ohlcv, market=None, timeframe='1m', since=None, limit=None):
return [
int(ohlcv[0]) * 1000,
float(ohlcv[1]),
float(ohlcv[2]),
float(ohlcv[3]),
float(ohlcv[4]),
float(ohlcv[5]),
]
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
request = {
'market': market['id'],
'period': self.timeframes[timeframe],
}
if since is not None:
request['timestamp'] = int(since) / 1000
if limit is not None:
request['limit'] = limit # default = 30
response = self.publicGetK(self.extend(request, params))
return self.parse_ohlcvs(response, market, timeframe, since, limit)
def parse_deposit_address(self, code, response):
if len(response) < 1:
raise InvalidAddress(self.id + ' fetchDepositAddress ' + code + ' returned empty address.')
depositAddress = response[0]
address = self.safe_string(depositAddress, 'address')
if address == 'suspended':
raise InvalidAddress(self.id + ' fetchDepositAddress ' + code + ' returned an suspended address.')
tag = None
if code == 'XRP' and address:
splitted = address.split('?dt=')
address = splitted[0]
tag = splitted[1]
self.check_address(address)
return {
'info': response,
'currency': code,
'address': address,
'tag': tag,
}
def create_deposit_address(self, code, params={}):
self.load_markets()
currency = self.currency(code)
request = {
'currency': currency['id'],
}
response = self.privatePostDepositAddresses(self.extend(request, params))
return self.parse_deposit_address(code, response)
def fetch_deposit_address(self, code, params={}):
self.load_markets()
currency = self.currency(code)
request = {
'currency': currency['id'],
}
response = self.privateGetDepositAddresses(self.extend(request, params))
return self.parse_deposit_address(code, response)
def parse_transaction_status_by_type(self, status, type=None):
if type is None:
return status
statuses = {
'deposit': {
'submitting': 'pending',
'cancelled': 'canceled',
'submitted': 'pending',
'suspended': 'pending',
'rejected': 'failed',
'accepted': 'ok',
'refunded': 'failed',
'suspect': 'pending',
'refund_cancelled': 'ok',
},
'withdrawal': {
'submitting': 'pending',
'submitted': 'pending',
'rejected': 'failed',
'accepted': 'pending',
'suspect': 'pending',
'approved': 'pending',
'processing': 'pending',
'retryable': 'pending',
'sent': 'pending',
'canceled': 'canceled',
'failed': 'failed',
'pending': 'pending',
'confirmed': 'ok',
'kgi_manually_processing': 'pending',
'kgi_instruction_sent': 'pending',
'kgi_manually_confirmed': 'ok',
'kgi_possible_failed': 'pending',
},
}
return statuses[type][status] if (status in statuses[type]) else status
def parse_transaction(self, transaction, currency=None):
id = self.safe_string(transaction, 'uuid')
txid = self.safe_string(transaction, 'txid')
currencyId = self.safe_string(transaction, 'currency')
code = self.safe_currency_code(currencyId, currency)
timestamp = self.safe_timestamp(transaction, 'created_at')
updated = self.safe_timestamp(transaction, 'updated_at')
amount = self.safe_float(transaction, 'amount')
feeCurrencyId | |
data.preprocess_notesequence(
note_sequence, self._presplit_on_time_changes)
results = []
for ns in note_sequences:
results.append(
super(BaseHierarchicalNoteSequenceConverter, self).to_tensors(ns))
return self._combine_to_tensor_results(results)
def _to_items(self, samples, controls=None):
"""Python method that decodes samples into list of NoteSequences."""
if controls is None:
return self._to_notesequences(samples)
else:
return self._to_notesequences(samples, controls)
class MultiInstrumentPerformanceConverter(
BaseHierarchicalNoteSequenceConverter):
"""Converts to/from multiple-instrument metric performances.
Args:
num_velocity_bins: Number of velocity bins.
max_tensors_per_notesequence: The maximum number of outputs to return
for each NoteSequence.
hop_size_bars: How many bars each sequence should be.
chunk_size_bars: Chunk size used for hierarchically decomposing sequence.
steps_per_quarter: Number of time steps per quarter note.
quarters_per_bar: Number of quarter notes per bar.
min_num_instruments: Minimum number of instruments per sequence.
max_num_instruments: Maximum number of instruments per sequence.
min_total_events: Minimum total length of all performance tracks, in events.
max_events_per_instrument: Maximum length of a single-instrument
performance, in events.
first_subsequence_only: If True, only use the very first hop and discard all
sequences longer than the hop size.
chord_encoding: An instantiated OneHotEncoding object to use for encoding
chords on which to condition, or None if not conditioning on chords.
"""
def __init__(self,
num_velocity_bins=0,
max_tensors_per_notesequence=None,
hop_size_bars=1,
chunk_size_bars=1,
steps_per_quarter=24,
quarters_per_bar=4,
min_num_instruments=2,
max_num_instruments=8,
min_total_events=8,
max_events_per_instrument=64,
min_pitch=performance_lib.MIN_MIDI_PITCH,
max_pitch=performance_lib.MAX_MIDI_PITCH,
first_subsequence_only=False,
chord_encoding=None):
max_shift_steps = (performance_lib.DEFAULT_MAX_SHIFT_QUARTERS *
steps_per_quarter)
self._performance_encoding = mm.PerformanceOneHotEncoding(
num_velocity_bins=num_velocity_bins, max_shift_steps=max_shift_steps,
min_pitch=min_pitch, max_pitch=max_pitch)
self._chord_encoding = chord_encoding
self._num_velocity_bins = num_velocity_bins
self._hop_size_bars = hop_size_bars
self._chunk_size_bars = chunk_size_bars
self._steps_per_quarter = steps_per_quarter
self._steps_per_bar = steps_per_quarter * quarters_per_bar
self._min_num_instruments = min_num_instruments
self._max_num_instruments = max_num_instruments
self._min_total_events = min_total_events
self._max_events_per_instrument = max_events_per_instrument
self._min_pitch = min_pitch
self._max_pitch = max_pitch
self._first_subsequence_only = first_subsequence_only
self._max_num_chunks = hop_size_bars // chunk_size_bars
self._max_steps_truncate = (
steps_per_quarter * quarters_per_bar * hop_size_bars)
# Each encoded track will begin with a program specification token
# (with one extra program for drums).
num_program_tokens = mm.MAX_MIDI_PROGRAM - mm.MIN_MIDI_PROGRAM + 2
end_token = self._performance_encoding.num_classes + num_program_tokens
depth = end_token + 1
max_lengths = [
self._max_num_chunks, max_num_instruments, max_events_per_instrument]
if chord_encoding is None:
control_depth = 0
control_pad_token = None
else:
control_depth = chord_encoding.num_classes
control_pad_token = chord_encoding.encode_event(mm.NO_CHORD)
super(MultiInstrumentPerformanceConverter, self).__init__(
input_depth=depth,
input_dtype=np.bool,
output_depth=depth,
output_dtype=np.bool,
control_depth=control_depth,
control_dtype=np.bool,
control_pad_token=control_pad_token,
end_token=end_token,
max_lengths=max_lengths,
max_tensors_per_notesequence=max_tensors_per_notesequence)
def _quantized_subsequence_to_tensors(self, quantized_subsequence):
# Reject sequences with out-of-range pitches.
if any(note.pitch < self._min_pitch or note.pitch > self._max_pitch
for note in quantized_subsequence.notes):
return [], []
# Extract all instruments.
tracks, _ = mm.extract_performances(
quantized_subsequence,
max_steps_truncate=self._max_steps_truncate,
num_velocity_bins=self._num_velocity_bins,
split_instruments=True)
# Reject sequences with too few instruments.
if not (self._min_num_instruments <= len(tracks) <=
self._max_num_instruments):
return [], []
# Sort tracks by program, with drums at the end.
tracks = sorted(tracks, key=lambda t: (t.is_drum, t.program))
chunk_size_steps = self._steps_per_bar * self._chunk_size_bars
chunks = [[] for _ in range(self._max_num_chunks)]
total_length = 0
for track in tracks:
# Make sure the track is the proper number of time steps.
track.set_length(self._max_steps_truncate)
# Split this track into chunks.
def new_performance(quantized_sequence, start_step, track=track):
steps_per_quarter = (
self._steps_per_quarter if quantized_sequence is None else None)
return performance_lib.MetricPerformance(
quantized_sequence=quantized_sequence,
steps_per_quarter=steps_per_quarter,
start_step=start_step,
num_velocity_bins=self._num_velocity_bins,
program=track.program, is_drum=track.is_drum)
track_chunks = split_performance(
track, chunk_size_steps, new_performance, clip_tied_notes=True)
assert len(track_chunks) == self._max_num_chunks
track_chunk_lengths = [len(track_chunk) for track_chunk in track_chunks]
# Each track chunk needs room for program token and end token.
if not all(l <= self._max_events_per_instrument - 2
for l in track_chunk_lengths):
return [], []
if not all(mm.MIN_MIDI_PROGRAM <= t.program <= mm.MAX_MIDI_PROGRAM
for t in track_chunks if not t.is_drum):
return [], []
total_length += sum(track_chunk_lengths)
# Aggregate by chunk.
for i, track_chunk in enumerate(track_chunks):
chunks[i].append(track_chunk)
# Reject sequences that are too short (in events).
if total_length < self._min_total_events:
return [], []
num_programs = mm.MAX_MIDI_PROGRAM - mm.MIN_MIDI_PROGRAM + 1
chunk_tensors = []
chunk_chord_tensors = []
for chunk_tracks in chunks:
track_tensors = []
for track in chunk_tracks:
# Add a special token for program at the beginning of each track.
track_tokens = [self._performance_encoding.num_classes + (
num_programs if track.is_drum else track.program)]
# Then encode the performance events.
for event in track:
track_tokens.append(self._performance_encoding.encode_event(event))
# Then add the end token.
track_tokens.append(self.end_token)
encoded_track = data.np_onehot(
track_tokens, self.output_depth, self.output_dtype)
track_tensors.append(encoded_track)
if self._chord_encoding:
# Extract corresponding chords for each track. The chord sequences may
# be different for different tracks even though the underlying chords
# are the same, as the performance event times will generally be
# different.
try:
track_chords = chords_lib.event_list_chords(
quantized_subsequence, chunk_tracks)
except chords_lib.CoincidentChordsError:
return [], []
track_chord_tensors = []
try:
# Chord encoding for all tracks is inside this try block. If any
# track fails we need to skip the whole subsequence.
for chords in track_chords:
# Start with a pad token corresponding to the track program token.
track_chord_tokens = [self._control_pad_token]
# Then encode the chords.
for chord in chords:
track_chord_tokens.append(
self._chord_encoding.encode_event(chord))
# Then repeat the final chord for the track end token.
track_chord_tokens.append(track_chord_tokens[-1])
encoded_track_chords = data.np_onehot(
track_chord_tokens, self.control_depth, self.control_dtype)
track_chord_tensors.append(encoded_track_chords)
except (mm.ChordSymbolError, mm.ChordEncodingError):
return [], []
chunk_chord_tensors.append(track_chord_tensors)
chunk_tensors.append(track_tensors)
return chunk_tensors, chunk_chord_tensors
def _to_tensors(self, note_sequence):
# Performance sequences require sustain to be correctly interpreted.
note_sequence = sequences_lib.apply_sustain_control_changes(note_sequence)
if self._chord_encoding and not any(
ta.annotation_type == CHORD_SYMBOL
for ta in note_sequence.text_annotations):
try:
# Quantize just for the purpose of chord inference.
# TODO(iansimon): Allow chord inference in unquantized sequences.
quantized_sequence = mm.quantize_note_sequence(
note_sequence, self._steps_per_quarter)
if (mm.steps_per_bar_in_quantized_sequence(quantized_sequence) !=
self._steps_per_bar):
return data.ConverterTensors()
# Infer chords in quantized sequence.
mm.infer_chords_for_sequence(quantized_sequence)
except (mm.BadTimeSignatureError, mm.NonIntegerStepsPerBarError,
mm.NegativeTimeError, mm.ChordInferenceError):
return data.ConverterTensors()
# Copy inferred chords back to original sequence.
for qta in quantized_sequence.text_annotations:
if qta.annotation_type == CHORD_SYMBOL:
ta = note_sequence.text_annotations.add()
ta.annotation_type = CHORD_SYMBOL
ta.time = qta.time
ta.text = qta.text
if note_sequence.tempos:
quarters_per_minute = note_sequence.tempos[0].qpm
else:
quarters_per_minute = mm.DEFAULT_QUARTERS_PER_MINUTE
quarters_per_bar = self._steps_per_bar / self._steps_per_quarter
hop_size_quarters = quarters_per_bar * self._hop_size_bars
hop_size_seconds = 60.0 * hop_size_quarters / quarters_per_minute
# Split note sequence by bar hop size (in seconds).
subsequences = sequences_lib.split_note_sequence(
note_sequence, hop_size_seconds)
if self._first_subsequence_only and len(subsequences) > 1:
return data.ConverterTensors()
sequence_tensors = []
sequence_chord_tensors = []
for subsequence in subsequences:
# Quantize this subsequence.
try:
quantized_subsequence = mm.quantize_note_sequence(
subsequence, self._steps_per_quarter)
if (mm.steps_per_bar_in_quantized_sequence(quantized_subsequence) !=
self._steps_per_bar):
return data.ConverterTensors()
except (mm.BadTimeSignatureError, mm.NonIntegerStepsPerBarError,
mm.NegativeTimeError):
return data.ConverterTensors()
# Convert the quantized subsequence to tensors.
tensors, chord_tensors = self._quantized_subsequence_to_tensors(
quantized_subsequence)
if tensors:
sequence_tensors.append(tensors)
if self._chord_encoding:
sequence_chord_tensors.append(chord_tensors)
return data.ConverterTensors(
inputs=sequence_tensors, outputs=sequence_tensors,
controls=sequence_chord_tensors)
def _to_single_notesequence(self, samples, controls):
qpm = mm.DEFAULT_QUARTERS_PER_MINUTE
seconds_per_step = 60.0 / (self._steps_per_quarter * qpm)
chunk_size_steps = self._steps_per_bar * self._chunk_size_bars
seq = music_pb2.NoteSequence()
seq.tempos.add().qpm = qpm
seq.ticks_per_quarter = mm.STANDARD_PPQ
tracks = [[] for _ in range(self._max_num_instruments)]
all_timed_chords = []
for chunk_index, encoded_chunk in enumerate(samples):
chunk_step_offset = chunk_index * chunk_size_steps
# Decode all tracks in this chunk into performance representation.
# We don't immediately convert to NoteSequence as we first want to group
# by track and concatenate.
for instrument, encoded_track in enumerate(encoded_chunk):
track_tokens = np.argmax(encoded_track, axis=-1)
# Trim to end token.
if self.end_token in track_tokens:
idx = track_tokens.tolist().index(self.end_token)
track_tokens = track_tokens[:idx]
# Handle program token. If there are extra program tokens, just use the
# first one.
program_tokens = [token for token in track_tokens
if token >= self._performance_encoding.num_classes]
track_token_indices = [idx for idx, t in enumerate(track_tokens)
if t < self._performance_encoding.num_classes]
track_tokens = [track_tokens[idx] for idx in track_token_indices]
if not program_tokens:
program = 0
is_drum = False
else:
program = program_tokens[0] - self._performance_encoding.num_classes
if program == mm.MAX_MIDI_PROGRAM + 1:
# This is the drum program.
program = 0
is_drum = True
else:
is_drum = False
# Decode the tokens into a performance track.
track = performance_lib.MetricPerformance(
quantized_sequence=None,
steps_per_quarter=self._steps_per_quarter,
start_step=0,
num_velocity_bins=self._num_velocity_bins,
program=program,
is_drum=is_drum)
for token in track_tokens:
track.append(self._performance_encoding.decode_event(token))
if controls is not None:
# Get the corresponding chord and time for each event in the track.
# This is a little tricky since we removed extraneous program tokens
# when constructing the track.
track_chord_tokens = np.argmax(controls[chunk_index][instrument],
axis=-1)
track_chord_tokens = [track_chord_tokens[idx]
for idx in track_token_indices]
chords = [self._chord_encoding.decode_event(token)
for token in track_chord_tokens]
chord_times = [(chunk_step_offset + step) * seconds_per_step
for step in track.steps if step < chunk_size_steps]
all_timed_chords += zip(chord_times, chords)
# Make sure the track has the proper length in time steps.
track.set_length(chunk_size_steps)
# Aggregate by instrument.
tracks[instrument].append(track)
# Concatenate all of the track chunks for each instrument.
for instrument, track_chunks in enumerate(tracks):
if track_chunks:
track = track_chunks[0]
for t in track_chunks[1:]:
for e in t:
track.append(e)
track_seq = track.to_sequence(instrument=instrument, qpm=qpm)
seq.notes.extend(track_seq.notes)
# Set total | |
{}) # type: Dict[str, Any]
if metadata is not None:
_header_parameters['x-ms-meta'] = _SERIALIZER.header("metadata", metadata, '{str}')
_header_parameters['x-ms-version'] = _SERIALIZER.header("version", version, 'str')
if lease_id is not None:
_header_parameters['x-ms-lease-id'] = _SERIALIZER.header("lease_id", lease_id, 'str')
_header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PUT",
url=_url,
params=_query_parameters,
headers=_header_parameters,
**kwargs
)
def build_acquire_lease_request(
url, # type: str
**kwargs # type: Any
):
# type: (...) -> HttpRequest
comp = kwargs.pop('comp', "lease") # type: str
action = kwargs.pop('action', "acquire") # type: str
version = kwargs.pop('version', "2021-04-10") # type: str
timeout = kwargs.pop('timeout', None) # type: Optional[int]
duration = kwargs.pop('duration', None) # type: Optional[int]
proposed_lease_id = kwargs.pop('proposed_lease_id', None) # type: Optional[str]
request_id_parameter = kwargs.pop('request_id_parameter', None) # type: Optional[str]
accept = "application/xml"
# Construct URL
_url = kwargs.pop("template_url", "{url}/{shareName}/{directory}/{fileName}")
path_format_arguments = {
"url": _SERIALIZER.url("url", url, 'str', skip_quote=True),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
_query_parameters['comp'] = _SERIALIZER.query("comp", comp, 'str')
if timeout is not None:
_query_parameters['timeout'] = _SERIALIZER.query("timeout", timeout, 'int', minimum=0)
# Construct headers
_header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
_header_parameters['x-ms-lease-action'] = _SERIALIZER.header("action", action, 'str')
if duration is not None:
_header_parameters['x-ms-lease-duration'] = _SERIALIZER.header("duration", duration, 'int')
if proposed_lease_id is not None:
_header_parameters['x-ms-proposed-lease-id'] = _SERIALIZER.header("proposed_lease_id", proposed_lease_id, 'str')
_header_parameters['x-ms-version'] = _SERIALIZER.header("version", version, 'str')
if request_id_parameter is not None:
_header_parameters['x-ms-client-request-id'] = _SERIALIZER.header("request_id_parameter", request_id_parameter, 'str')
_header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PUT",
url=_url,
params=_query_parameters,
headers=_header_parameters,
**kwargs
)
def build_release_lease_request(
url, # type: str
**kwargs # type: Any
):
# type: (...) -> HttpRequest
comp = kwargs.pop('comp', "lease") # type: str
action = kwargs.pop('action', "release") # type: str
version = kwargs.pop('version', "2021-04-10") # type: str
lease_id = kwargs.pop('lease_id') # type: str
timeout = kwargs.pop('timeout', None) # type: Optional[int]
request_id_parameter = kwargs.pop('request_id_parameter', None) # type: Optional[str]
accept = "application/xml"
# Construct URL
_url = kwargs.pop("template_url", "{url}/{shareName}/{directory}/{fileName}")
path_format_arguments = {
"url": _SERIALIZER.url("url", url, 'str', skip_quote=True),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
_query_parameters['comp'] = _SERIALIZER.query("comp", comp, 'str')
if timeout is not None:
_query_parameters['timeout'] = _SERIALIZER.query("timeout", timeout, 'int', minimum=0)
# Construct headers
_header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
_header_parameters['x-ms-lease-action'] = _SERIALIZER.header("action", action, 'str')
_header_parameters['x-ms-lease-id'] = _SERIALIZER.header("lease_id", lease_id, 'str')
_header_parameters['x-ms-version'] = _SERIALIZER.header("version", version, 'str')
if request_id_parameter is not None:
_header_parameters['x-ms-client-request-id'] = _SERIALIZER.header("request_id_parameter", request_id_parameter, 'str')
_header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PUT",
url=_url,
params=_query_parameters,
headers=_header_parameters,
**kwargs
)
def build_change_lease_request(
url, # type: str
**kwargs # type: Any
):
# type: (...) -> HttpRequest
comp = kwargs.pop('comp', "lease") # type: str
action = kwargs.pop('action', "change") # type: str
version = kwargs.pop('version', "2021-04-10") # type: str
lease_id = kwargs.pop('lease_id') # type: str
timeout = kwargs.pop('timeout', None) # type: Optional[int]
proposed_lease_id = kwargs.pop('proposed_lease_id', None) # type: Optional[str]
request_id_parameter = kwargs.pop('request_id_parameter', None) # type: Optional[str]
accept = "application/xml"
# Construct URL
_url = kwargs.pop("template_url", "{url}/{shareName}/{directory}/{fileName}")
path_format_arguments = {
"url": _SERIALIZER.url("url", url, 'str', skip_quote=True),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
_query_parameters['comp'] = _SERIALIZER.query("comp", comp, 'str')
if timeout is not None:
_query_parameters['timeout'] = _SERIALIZER.query("timeout", timeout, 'int', minimum=0)
# Construct headers
_header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
_header_parameters['x-ms-lease-action'] = _SERIALIZER.header("action", action, 'str')
_header_parameters['x-ms-lease-id'] = _SERIALIZER.header("lease_id", lease_id, 'str')
if proposed_lease_id is not None:
_header_parameters['x-ms-proposed-lease-id'] = _SERIALIZER.header("proposed_lease_id", proposed_lease_id, 'str')
_header_parameters['x-ms-version'] = _SERIALIZER.header("version", version, 'str')
if request_id_parameter is not None:
_header_parameters['x-ms-client-request-id'] = _SERIALIZER.header("request_id_parameter", request_id_parameter, 'str')
_header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PUT",
url=_url,
params=_query_parameters,
headers=_header_parameters,
**kwargs
)
def build_break_lease_request(
url, # type: str
**kwargs # type: Any
):
# type: (...) -> HttpRequest
comp = kwargs.pop('comp', "lease") # type: str
action = kwargs.pop('action', "break") # type: str
version = kwargs.pop('version', "2021-04-10") # type: str
timeout = kwargs.pop('timeout', None) # type: Optional[int]
lease_id = kwargs.pop('lease_id', None) # type: Optional[str]
request_id_parameter = kwargs.pop('request_id_parameter', None) # type: Optional[str]
accept = "application/xml"
# Construct URL
_url = kwargs.pop("template_url", "{url}/{shareName}/{directory}/{fileName}")
path_format_arguments = {
"url": _SERIALIZER.url("url", url, 'str', skip_quote=True),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
_query_parameters['comp'] = _SERIALIZER.query("comp", comp, 'str')
if timeout is not None:
_query_parameters['timeout'] = _SERIALIZER.query("timeout", timeout, 'int', minimum=0)
# Construct headers
_header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
_header_parameters['x-ms-lease-action'] = _SERIALIZER.header("action", action, 'str')
if lease_id is not None:
_header_parameters['x-ms-lease-id'] = _SERIALIZER.header("lease_id", lease_id, 'str')
_header_parameters['x-ms-version'] = _SERIALIZER.header("version", version, 'str')
if request_id_parameter is not None:
_header_parameters['x-ms-client-request-id'] = _SERIALIZER.header("request_id_parameter", request_id_parameter, 'str')
_header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PUT",
url=_url,
params=_query_parameters,
headers=_header_parameters,
**kwargs
)
def build_upload_range_request(
url, # type: str
**kwargs # type: Any
):
# type: (...) -> HttpRequest
comp = kwargs.pop('comp', "range") # type: str
version = kwargs.pop('version', "2021-04-10") # type: str
content_type = kwargs.pop('content_type', None) # type: Optional[str]
range = kwargs.pop('range') # type: str
content_length = kwargs.pop('content_length') # type: int
timeout = kwargs.pop('timeout', None) # type: Optional[int]
file_range_write = kwargs.pop('file_range_write', "update") # type: Union[str, "_models.FileRangeWriteType"]
content_md5 = kwargs.pop('content_md5', None) # type: Optional[bytearray]
lease_id = kwargs.pop('lease_id', None) # type: Optional[str]
accept = "application/xml"
# Construct URL
_url = kwargs.pop("template_url", "{url}/{shareName}/{directory}/{fileName}")
path_format_arguments = {
"url": _SERIALIZER.url("url", url, 'str', skip_quote=True),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
_query_parameters['comp'] = _SERIALIZER.query("comp", comp, 'str')
if timeout is not None:
_query_parameters['timeout'] = _SERIALIZER.query("timeout", timeout, 'int', minimum=0)
# Construct headers
_header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
_header_parameters['x-ms-range'] = _SERIALIZER.header("range", range, 'str')
_header_parameters['x-ms-write'] = _SERIALIZER.header("file_range_write", file_range_write, 'str')
_header_parameters['Content-Length'] = _SERIALIZER.header("content_length", content_length, 'long')
if content_md5 is not None:
_header_parameters['Content-MD5'] = _SERIALIZER.header("content_md5", content_md5, 'bytearray')
_header_parameters['x-ms-version'] = _SERIALIZER.header("version", version, 'str')
if lease_id is not None:
_header_parameters['x-ms-lease-id'] = _SERIALIZER.header("lease_id", lease_id, 'str')
if content_type is not None:
_header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
_header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PUT",
url=_url,
params=_query_parameters,
headers=_header_parameters,
**kwargs
)
def build_upload_range_from_url_request(
url, # type: str
**kwargs # type: Any
):
# type: (...) -> HttpRequest
comp = kwargs.pop('comp', "range") # type: str
file_range_write_from_url = kwargs.pop('file_range_write_from_url', "update") # type: str
version = kwargs.pop('version', "2021-04-10") # type: str
range = kwargs.pop('range') # type: str
copy_source = kwargs.pop('copy_source') # type: str
content_length = kwargs.pop('content_length') # type: int
timeout = kwargs.pop('timeout', None) # type: Optional[int]
source_range = kwargs.pop('source_range', None) # type: Optional[str]
source_content_crc64 = kwargs.pop('source_content_crc64', None) # type: Optional[bytearray]
source_if_match_crc64 = kwargs.pop('source_if_match_crc64', None) # type: Optional[bytearray]
source_if_none_match_crc64 = kwargs.pop('source_if_none_match_crc64', None) # type: Optional[bytearray]
lease_id = kwargs.pop('lease_id', None) # type: Optional[str]
copy_source_authorization = kwargs.pop('copy_source_authorization', None) # type: Optional[str]
accept = "application/xml"
# Construct URL
_url = kwargs.pop("template_url", "{url}/{shareName}/{directory}/{fileName}")
path_format_arguments = {
"url": _SERIALIZER.url("url", url, 'str', skip_quote=True),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
_query_parameters['comp'] = _SERIALIZER.query("comp", comp, 'str')
if timeout is not None:
_query_parameters['timeout'] = _SERIALIZER.query("timeout", timeout, 'int', minimum=0)
# Construct headers
_header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
_header_parameters['x-ms-range'] = _SERIALIZER.header("range", range, 'str')
_header_parameters['x-ms-copy-source'] = _SERIALIZER.header("copy_source", copy_source, 'str')
if source_range is not None:
_header_parameters['x-ms-source-range'] = _SERIALIZER.header("source_range", source_range, 'str')
_header_parameters['x-ms-write'] = _SERIALIZER.header("file_range_write_from_url", file_range_write_from_url, 'str')
_header_parameters['Content-Length'] = _SERIALIZER.header("content_length", content_length, 'long')
if source_content_crc64 is not None:
_header_parameters['x-ms-source-content-crc64'] = _SERIALIZER.header("source_content_crc64", source_content_crc64, 'bytearray')
if source_if_match_crc64 is not None:
_header_parameters['x-ms-source-if-match-crc64'] = _SERIALIZER.header("source_if_match_crc64", source_if_match_crc64, 'bytearray')
if source_if_none_match_crc64 is not None:
_header_parameters['x-ms-source-if-none-match-crc64'] = _SERIALIZER.header("source_if_none_match_crc64", source_if_none_match_crc64, 'bytearray')
_header_parameters['x-ms-version'] = _SERIALIZER.header("version", version, 'str')
if lease_id is not None:
_header_parameters['x-ms-lease-id'] = _SERIALIZER.header("lease_id", lease_id, 'str')
if copy_source_authorization is not None:
_header_parameters['x-ms-copy-source-authorization'] = _SERIALIZER.header("copy_source_authorization", copy_source_authorization, 'str')
_header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="PUT",
url=_url,
params=_query_parameters,
headers=_header_parameters,
**kwargs
)
def build_get_range_list_request(
url, # type: str
**kwargs # type: Any
):
# type: (...) -> HttpRequest
comp = kwargs.pop('comp', "rangelist") # type: str
version = kwargs.pop('version', "2021-04-10") # type: str
sharesnapshot = kwargs.pop('sharesnapshot', None) # type: Optional[str]
prevsharesnapshot = kwargs.pop('prevsharesnapshot', None) # type: Optional[str]
timeout = kwargs.pop('timeout', None) # type: Optional[int]
range = kwargs.pop('range', None) # type: Optional[str]
lease_id = kwargs.pop('lease_id', None) # type: Optional[str]
accept = "application/xml"
# Construct URL
_url = kwargs.pop("template_url", "{url}/{shareName}/{directory}/{fileName}")
path_format_arguments = {
"url": _SERIALIZER.url("url", url, 'str', skip_quote=True),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
_query_parameters['comp'] = _SERIALIZER.query("comp", comp, 'str')
if sharesnapshot is not None:
_query_parameters['sharesnapshot'] = _SERIALIZER.query("sharesnapshot", sharesnapshot, 'str')
if prevsharesnapshot | |
# Copyright 2019 IBM Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from lale import helpers
from abc import ABC, abstractmethod
import importlib
import enum
import os
import itertools
from lale import schema2enums as enum_gen
import numpy as np
import lale.datasets.data_schemas
from typing import AbstractSet, Any, Dict, Generic, Iterable, Iterator, List, Tuple, TypeVar, Optional, Union
import warnings
import copy
from lale.util.VisitorMeta import AbstractVisitorMeta
from lale.search.PGO import remove_defaults_dict
import inspect
import copy
from lale.schemas import Schema
import jsonschema
import lale.pretty_print
class MetaModel(ABC):
"""Abstract base class for LALE operators states: MetaModel, Planned, Trainable, and Trained.
"""
@abstractmethod
def auto_arrange(self, planner):
"""Auto arrange the operators to make a new plan.
Parameters
----------
TBD
"""
pass
@abstractmethod
def arrange(self, *args, **kwargs):
"""Given composable operators, create a plan. TBD.
"""
pass
class Planned(MetaModel):
"""Base class to tag an operator's state as Planned.
Warning: This class is not to be used directly by users/developers.
"""
@abstractmethod
def configure(self, *args, **kwargs)->'Trainable':
"""Abstract method to configure an operator to make it Trainable.
Parameters
----------
args, kwargs:
The parameters are used to configure an operator in a Planned
state to bind hyper-parameter values such that it becomes Trainable.
"""
pass
@abstractmethod
def __call__(self, *args, **kwargs)->'Trainable':
"""Abstract method to make Planned objects callable.
Operators in a Planned states are made callable by overriding
the __call__ method (https://docs.python.org/3/reference/datamodel.html#special-method-names).
It is supposed to return an operator in a Trainable state.
Parameters
----------
args, kwargs:
The parameters are used to configure an operator in a Planned
state to bind hyper-parameter values such that it becomes Trainable.
"""
pass
@abstractmethod
def auto_configure(self, X, y = None, optimizer = None)->'Trainable':
"""Abstract method to use an hyper-param optimizer.
Automatically select hyper-parameter values using an optimizer.
This will return an operator in a Trainable state.
Parameters
----------
TBD
"""
pass
class Trainable(Planned):
"""Base class to tag an operator's state as Trainable.
Warning: This class is not to be used directly by users/developers.
"""
@abstractmethod
def fit(self, X, y=None, **fit_params)->'Trained':
"""Abstract fit method to be overriden by all trainable operators.
Parameters
----------
X :
The type of X is as per input_fit schema of the operator.
y : optional
The type of y is as per input_fit schema of the operator. Default is None.
fit_params: Dictionary, optional
A dictionary of keyword parameters to be used during training.
"""
pass
class Trained(Trainable):
"""Base class to tag an operator's state as Trained.
Warning: This class is not to be used directly by users/developers.
"""
@abstractmethod
def predict(self, X):
"""Abstract predict method to be overriden by trained operators as applicable.
Parameters
----------
X :
The type of X is as per input_predict schema of the operator.
"""
pass
@abstractmethod
def transform(self, X, y = None):
"""Abstract transform method to be overriden by trained operators as applicable.
Parameters
----------
X :
The type of X is as per input_predict schema of the operator.
"""
pass
@abstractmethod
def predict_proba(self, X):
"""Abstract predict method to be overriden by trained operators as applicable.
Parameters
----------
X :
The type of X is as per input_predict schema of the operator.
"""
pass
class Operator(metaclass=AbstractVisitorMeta):
"""Abstract base class for a LALE operator.
Pipelines and individual operators extend this.
"""
def __and__(self, other:'Operator')->'Operator':
"""Overloaded `and` operator.
Creates a union of the two operators.
TODO:Explain more.
Parameters
----------
other : Operator
Returns
-------
Pipeline
Returns a pipeline that consists of union of self and other.
"""
return make_union_no_concat(self, other)
def __rand__(self, other:'Operator')->'Operator':
return make_union_no_concat(other, self)
def __rshift__(self, other:'Operator')->'Operator':
"""Overloaded `>>` operator.
Creates a pipeline of the two operators, current operator followed
by the operator passed as parameter.
Parameters
----------
other : Operator
Returns
-------
Pipeline
Returns a pipeline that contains `self` followed by `other`.
"""
return make_pipeline(self, other)
def __rrshift__(self, other:'Operator')->'Operator':
return make_pipeline(other, self)
def __or__(self, other:'Operator')->'Operator':
"""Overloaded `or` operator.
Creates an OperatorChoice consisting of the two operators, current operator followed
by the operator passed as parameter.
Parameters
----------
other : Operator
Returns
-------
OperatorChoice
Returns an OperatorChoice object that contains `self` and `other`.
"""
return make_choice(self, other)
def __ror__(self, other:'Operator')->'Operator':
return make_choice(other, self)
@abstractmethod
def name(self)->str:
"""Returns the name of the operator.
"""
pass
@abstractmethod
def to_json(self):
"""Returns the json representation of the operator.
"""
pass
@abstractmethod
def has_same_impl(self, other:'Operator')->bool:
"""Checks if the type of the operator imnplementations are compatible
"""
pass
class MetaModelOperator(Operator, MetaModel):
pass
class PlannedOperator(MetaModelOperator, Planned):
@abstractmethod
def __call__(self, *args, **kwargs)->'TrainableOperator':
pass
class TrainableOperator(PlannedOperator, Trainable):
@abstractmethod
def fit(self, X, y=None, **fit_params)->'TrainedOperator':
"""Abstract fit method to be overriden by all trainable operators.
Parameters
----------
X :
The type of X is as per input_fit schema of the operator.
y : optional
The type of y is as per input_fit schema of the operator. Default is None.
fit_params: Dictionary, optional
A dictionary of keyword parameters to be used during training.
"""
pass
@abstractmethod
def is_supervised(self)->bool:
"""Checks if the this operator needs labeled data for learning (the `y' parameter for fit)
"""
pass
class TrainedOperator(TrainableOperator, Trained):
@abstractmethod
def is_transformer(self)->bool:
""" Checks if the operator is a transformer
"""
pass
class IndividualOp(MetaModelOperator):
"""
This is a concrete class that can instantiate a new individual
operator and provide access to its metadata.
"""
_name:str
_impl:Any
def __init__(self, name:str, impl, schemas) -> None:
"""Create a new IndividualOp.
Parameters
----------
name : String
Name of the operator.
impl :
An instance of operator implementation class. This is a class that
contains fit, predict/transform methods implementing an underlying
algorithm.
schemas : dict
This is a dictionary of json schemas for the operator.
"""
self._impl = impl
self._name = name
schemas = schemas if schemas is not None else helpers.get_lib_schema(impl)
if schemas:
self._schemas = schemas
else:
self._schemas = {
'$schema': 'http://json-schema.org/draft-04/schema#',
'description':
'Combined schema for expected data and hyperparameters.',
'type': 'object',
'properties': {
'input_fit': {},
'input_predict': {},
'output': {},
'hyperparams': {
'allOf': [
{'type': 'object',
'properties': {}}]
}
}}
# Add enums from the hyperparameter schema to the object as fields
# so that their usage looks like LogisticRegression.penalty.l1
enum_gen.addSchemaEnumsAsFields(self, self.hyperparam_schema())
def get_schema_maybe(self, schema_kind:str, default:Any=None)->Dict[str, Any]:
"""Return a schema of the operator or a given default if the schema is unspecified
Parameters
----------
schema_kind : string, 'input_fit' or 'input_predict' or 'output' or 'hyperparams'
Type of the schema to be returned.
Returns
-------
dict
The python object containing the json schema of the operator.
For all the schemas currently present, this would be a dictionary.
"""
return self._schemas.get('properties',{}).get(schema_kind, default)
def get_schema(self, schema_kind:str)->Dict[str, Any]:
"""Return a schema of the operator.
Parameters
----------
schema_kind : string, 'input_fit' or 'input_predict' or 'output' or 'hyperparams'
Type of the schema to be returned.
Returns
-------
dict
The python object containing the json schema of the operator.
For all the schemas currently present, this would be a dictionary.
"""
return self.get_schema_maybe(schema_kind, {})
def get_tags(self)->Dict[str, List[str]]:
"""Return the tags of an operator.
Returns
-------
list
A list of tags describing the operator.
"""
return self._schemas.get('tags', {})
def has_tag(self, tag:str)->bool:
"""Check the presence of a tag for an operator.
Parameters
----------
tag : string
Returns
-------
boolean
Flag indicating the presence or absence of the given tag
in this operator's schemas.
"""
tags = [t for l in self.get_tags().values() for t in l]
return tag in tags
def input_schema_fit(self):
"""Returns the schema for fit method's input.
Returns
-------
dict
Logical schema describing input required by | |
<reponame>David-Durst/aetherling<filename>tests/haskell/test_downsampleStencil_big.py<gh_stars>1-10
from aetherling.modules.reduce import ReduceSequential, ReduceParallel, ReducePartiallyParallel, renameCircuitForReduce
from magma.backend.coreir_ import CoreIRBackend
from magma.bitutils import *
from coreir.context import *
from magma.simulator.coreir_simulator import CoreIRSimulator
import coreir
from magma.scope import Scope
from mantle.coreir.arith import *
from mantle.coreir import DefineCoreirConst
import fault
from aetherling.helpers.fault_helpers import print_start_clock, print_end_clock, \
print_nd_int_array_port, print_nd_bit_array_port, get_fault_log
int_width = 8
# this computes the convlution that is computed at different throughputs by the
# differently scheduled Aetherling pipelines
num_rows = 256
num_cols = 256
image_matrix = [[row * num_rows + col for col in range(num_cols)] for row in range(num_rows)]
stencil = [[1,2],[3,4]]
# since this is a 2x2 stencil, the right most column and bottom most row are invalid data to be ignored
# these are only emitted so that the rate doesn't have any ugly constants
valid_in_rows = [x for x in range(0,num_rows - 1,2)]
valid_in_cols = [x for x in range(0,num_cols - 1,2)]
valid_after_first_conv_rows = [x for x in range(0,num_rows // 2 - 1,2)]
valid_after_first_conv_cols = [x for x in range(0,num_cols // 2 - 1,2)]
valid_after_second_conv_rows = [x for x in range(0,num_rows // 4 - 1,2)]
valid_after_second_conv_cols = [x for x in range(0,num_cols // 4 - 1,2)]
def do_convolution_at_point(row, col, input_matrix):
return ((stencil[0][0] * input_matrix[row][col] + stencil[0][1] * input_matrix[row][col+1] +
stencil[1][0] * input_matrix[row+1][col] + stencil[1][1] * input_matrix[row+1][col+1]) % 256 // 4)
firstResults = [[do_convolution_at_point(row,col, image_matrix) for col in valid_in_cols] for row in valid_in_rows]
secondResults = [[do_convolution_at_point(row,col, firstResults) for col in valid_after_first_conv_cols] for row in valid_after_first_conv_rows]
thirdResults = [[do_convolution_at_point(row,col, secondResults) for col in valid_after_second_conv_cols] for row in valid_after_second_conv_rows]
flattenedThirdResults = [element for sublist in thirdResults for element in sublist]
valid_out_rows = [x for x in range(len(thirdResults))]
valid_out_cols = [x for x in range(len(thirdResults[0]))]
num_valid_out_rows = len(valid_out_rows)
num_valid_out_cols = len(valid_out_rows)
# note: the reason these tests don't have to worr about extra invalid values at end of output that are marked as valid
# is that, for a 2x2 window, only the last window is invalid. Since downsampleing by 2 in x dimension, that never
# gets emitted and only valid outputs are emitted.
def test_downsample_256x256_to_32x32_1px_in_per_clk():
from .downsample_256x256_to_32x32_1px_in_per_clk import downsample_256x256_to_32x32_1px_in_per_clk as testcircuit
magma.compile("vBuild/" + testcircuit.name, testcircuit, output="coreir-verilog",
passes=["rungenerators", "wireclocks-coreir", "verifyconnectivity --noclkrst", "flattentypes", "flatten", "verifyconnectivity --noclkrst", "deletedeadinstances"],
namespaces=["aetherlinglib", "commonlib", "mantle", "coreir", "global"])
tester = fault.Tester(testcircuit, testcircuit.CLK)
tester.poke(testcircuit.valid_data_in, 1)
tester.poke(testcircuit.ready_data_out, 1)
tester.poke(testcircuit.CE, 1)
# these check the outputs, as there is a delay between feeding inputs in and getting the results back
for row in range(num_rows+20):
for col in range(0,num_cols):
# a necessary adjustment as running tests for multiple clocks after inputting full image
# to get rest of the outputs
if row < num_rows:
tester.poke(testcircuit.I0, image_matrix[row][col])
tester.eval()
tester.step(2)
tester.eval()
print_start_clock(tester)
print_nd_bit_array_port(tester, testcircuit.valid_data_out, "valid")
print_nd_int_array_port(tester, testcircuit.O0, "O0")
print_end_clock(tester)
tester.compile_and_run(target="verilator", skip_compile=True, directory="vBuild/")
with open(get_fault_log(__file__, testcircuit.name)) as file:
results = eval("[" + file.read() + "]")
filtered_results = [x['O0'] for x in results if x['valid'] == 1]
if len(filtered_results) >= len(flattenedThirdResults):
assert filtered_results[0:len(flattenedThirdResults)] == [element for sublist in thirdResults for element in sublist]
else:
assert filtered_results == [element for sublist in thirdResults for element in sublist]
def test_downsample_256x256_to_32x32_2px_in_per_clk():
from .downsample_256x256_to_32x32_2px_in_per_clk import downsample_256x256_to_32x32_2px_in_per_clk as testcircuit
magma.compile("vBuild/" + testcircuit.name, testcircuit, output="coreir-verilog",
passes=["rungenerators", "wireclocks-coreir", "verifyconnectivity --noclkrst", "flattentypes", "flatten", "verifyconnectivity --noclkrst", "deletedeadinstances"],
namespaces=["aetherlinglib", "commonlib", "mantle", "coreir", "global"])
tester = fault.Tester(testcircuit, testcircuit.CLK)
tester.poke(testcircuit.valid_data_in, 1)
tester.poke(testcircuit.ready_data_out, 1)
tester.poke(testcircuit.CE, 1)
# these check the outputs, as there is a delay between feeding inputs in and getting the results back
for row in range(num_rows+20):
for col in range(0,num_cols,2):
# a necessary adjustment as running tests for multiple clocks after inputting full image
# to get rest of the outputs
if row < num_rows:
tester.poke(testcircuit.I0, image_matrix[row][col])
tester.poke(testcircuit.I1, image_matrix[row][col+1])
tester.eval()
tester.step(2)
tester.eval()
print_start_clock(tester)
print_nd_bit_array_port(tester, testcircuit.valid_data_out, "valid")
print_nd_int_array_port(tester, testcircuit.O0, "O0")
print_end_clock(tester)
tester.compile_and_run(target="verilator", skip_compile=True, directory="vBuild/")
with open(get_fault_log(__file__, testcircuit.name)) as file:
results = eval("[" + file.read() + "]")
filtered_results = [x['O0'] for x in results if x['valid'] == 1]
if len(filtered_results) >= len(flattenedThirdResults):
assert filtered_results[0:len(flattenedThirdResults)] == [element for sublist in thirdResults for element in sublist]
else:
assert filtered_results == [element for sublist in thirdResults for element in sublist]
def test_downsample_256x256_to_32x32_4px_in_per_clk():
from .downsample_256x256_to_32x32_4px_in_per_clk import downsample_256x256_to_32x32_4px_in_per_clk as testcircuit
magma.compile("vBuild/" + testcircuit.name, testcircuit, output="coreir-verilog",
passes=["rungenerators", "wireclocks-coreir", "verifyconnectivity --noclkrst", "flattentypes", "flatten", "verifyconnectivity --noclkrst", "deletedeadinstances"],
namespaces=["aetherlinglib", "commonlib", "mantle", "coreir", "global"])
tester = fault.Tester(testcircuit, testcircuit.CLK)
tester.poke(testcircuit.valid_data_in, 1)
tester.poke(testcircuit.ready_data_out, 1)
tester.poke(testcircuit.CE, 1)
# these check the outputs, as there is a delay between feeding inputs in and getting the results back
for row in range(num_rows+20):
for col in range(0,num_cols,4):
# a necessary adjustment as running tests for multiple clocks after inputting full image
# to get rest of the outputs
if row < num_rows:
tester.poke(testcircuit.I0, image_matrix[row][col])
tester.poke(testcircuit.I1, image_matrix[row][col+1])
tester.poke(testcircuit.I2, image_matrix[row][col+2])
tester.poke(testcircuit.I3, image_matrix[row][col+3])
tester.eval()
tester.step(2)
tester.eval()
print_start_clock(tester)
print_nd_bit_array_port(tester, testcircuit.valid_data_out, "valid")
print_nd_int_array_port(tester, testcircuit.O0, "O0")
print_end_clock(tester)
tester.compile_and_run(target="verilator", skip_compile=True, directory="vBuild/")
with open(get_fault_log(__file__, testcircuit.name)) as file:
results = eval("[" + file.read() + "]")
filtered_results = [x['O0'] for x in results if x['valid'] == 1]
if len(filtered_results) >= len(flattenedThirdResults):
assert filtered_results[0:len(flattenedThirdResults)] == [element for sublist in thirdResults for element in sublist]
else:
assert filtered_results == [element for sublist in thirdResults for element in sublist]
def test_downsample_256x256_to_32x32_8px_in_per_clk():
from .downsample_256x256_to_32x32_8px_in_per_clk import downsample_256x256_to_32x32_8px_in_per_clk as testcircuit
magma.compile("vBuild/" + testcircuit.name, testcircuit, output="coreir-verilog",
passes=["rungenerators", "wireclocks-coreir", "verifyconnectivity --noclkrst", "flattentypes", "flatten", "verifyconnectivity --noclkrst", "deletedeadinstances"],
namespaces=["aetherlinglib", "commonlib", "mantle", "coreir", "global"])
tester = fault.Tester(testcircuit, testcircuit.CLK)
tester.poke(testcircuit.valid_data_in, 1)
tester.poke(testcircuit.ready_data_out, 1)
tester.poke(testcircuit.CE, 1)
# these check the outputs, as there is a delay between feeding inputs in and getting the results back
for row in range(num_rows+20):
for col in range(0,num_cols,8):
# a necessary adjustment as running tests for multiple clocks after inputting full image
# to get rest of the outputs
if row < num_rows:
tester.poke(testcircuit.I0, image_matrix[row][col])
tester.poke(testcircuit.I1, image_matrix[row][col+1])
tester.poke(testcircuit.I2, image_matrix[row][col+2])
tester.poke(testcircuit.I3, image_matrix[row][col+3])
tester.poke(testcircuit.I4, image_matrix[row][col+4])
tester.poke(testcircuit.I5, image_matrix[row][col+5])
tester.poke(testcircuit.I6, image_matrix[row][col+6])
tester.poke(testcircuit.I7, image_matrix[row][col+7])
tester.eval()
tester.step(2)
tester.eval()
print_start_clock(tester)
print_nd_bit_array_port(tester, testcircuit.valid_data_out, "valid")
print_nd_int_array_port(tester, testcircuit.O0, "O0")
print_end_clock(tester)
tester.compile_and_run(target="verilator", skip_compile=True, directory="vBuild/")
with open(get_fault_log(__file__, testcircuit.name)) as file:
results = eval("[" + file.read() + "]")
filtered_results = [x['O0'] for x in results if x['valid'] == 1]
if len(filtered_results) >= len(flattenedThirdResults):
assert filtered_results[0:len(flattenedThirdResults)] == [element for sublist in thirdResults for element in sublist]
else:
assert filtered_results == [element for sublist in thirdResults for element in sublist]
def test_downsample_256x256_to_32x32_16px_in_per_clk():
from .downsample_256x256_to_32x32_16px_in_per_clk import downsample_256x256_to_32x32_16px_in_per_clk as testcircuit
magma.compile("vBuild/" + testcircuit.name, testcircuit, output="coreir-verilog",
passes=["rungenerators", "wireclocks-coreir", "verifyconnectivity --noclkrst", "flattentypes", "flatten", "verifyconnectivity --noclkrst", "deletedeadinstances"],
namespaces=["aetherlinglib", "commonlib", "mantle", "coreir", "global"])
tester = fault.Tester(testcircuit, testcircuit.CLK)
tester.poke(testcircuit.valid_data_in, 1)
tester.poke(testcircuit.ready_data_out, 1)
tester.poke(testcircuit.CE, 1)
# these check the outputs, as there is a delay between feeding inputs in and getting the results back
for row in range(num_rows+20):
for col in range(0,num_cols,16):
# a necessary adjustment as running tests for multiple clocks after inputting full image
# to get rest of the outputs
if row < num_rows:
tester.poke(testcircuit.I0, image_matrix[row][col])
tester.poke(testcircuit.I1, image_matrix[row][col+1])
tester.poke(testcircuit.I2, image_matrix[row][col+2])
tester.poke(testcircuit.I3, image_matrix[row][col+3])
tester.poke(testcircuit.I4, image_matrix[row][col+4])
tester.poke(testcircuit.I5, image_matrix[row][col+5])
tester.poke(testcircuit.I6, image_matrix[row][col+6])
tester.poke(testcircuit.I7, image_matrix[row][col+7])
tester.poke(testcircuit.I8, image_matrix[row][col+8])
tester.poke(testcircuit.I9, image_matrix[row][col+9])
tester.poke(testcircuit.I10, image_matrix[row][col+10])
tester.poke(testcircuit.I11, image_matrix[row][col+11])
tester.poke(testcircuit.I12, image_matrix[row][col+12])
tester.poke(testcircuit.I13, image_matrix[row][col+13])
tester.poke(testcircuit.I14, image_matrix[row][col+14])
tester.poke(testcircuit.I15, image_matrix[row][col+15])
tester.eval()
tester.step(2)
tester.eval()
print_start_clock(tester)
print_nd_bit_array_port(tester, testcircuit.valid_data_out, "valid")
print_nd_int_array_port(tester, testcircuit.O0, "O0")
print_end_clock(tester)
tester.compile_and_run(target="verilator", skip_compile=True, directory="vBuild/")
with open(get_fault_log(__file__, testcircuit.name)) as file:
results = eval("[" + file.read() + "]")
filtered_results = [x['O0'] for x in results if x['valid'] == 1]
if len(filtered_results) >= len(flattenedThirdResults):
assert filtered_results[0:len(flattenedThirdResults)] == [element for sublist in thirdResults for element in sublist]
else:
assert filtered_results == [element for sublist in thirdResults for element in sublist]
def test_downsample_256x256_to_32x32_32px_in_per_clk():
from .downsample_256x256_to_32x32_32px_in_per_clk import downsample_256x256_to_32x32_32px_in_per_clk as testcircuit
magma.compile("vBuild/" + testcircuit.name, testcircuit, output="coreir-verilog",
passes=["rungenerators", "wireclocks-coreir", "verifyconnectivity --noclkrst", "flattentypes", "flatten", "verifyconnectivity --noclkrst", "deletedeadinstances"],
namespaces=["aetherlinglib", "commonlib", "mantle", "coreir", "global"])
tester = fault.Tester(testcircuit, testcircuit.CLK)
tester.poke(testcircuit.valid_data_in, 1)
tester.poke(testcircuit.ready_data_out, 1)
tester.poke(testcircuit.CE, 1)
# these check the outputs, as there is a delay between feeding inputs in and getting the results back
for row in range(num_rows+20):
for col in range(0,num_cols,32):
# a necessary adjustment as running tests for multiple clocks after inputting full image
# to get rest of the outputs
if row < num_rows:
tester.poke(testcircuit.I0, image_matrix[row][col])
tester.poke(testcircuit.I1, image_matrix[row][col+1])
tester.poke(testcircuit.I2, image_matrix[row][col+2])
tester.poke(testcircuit.I3, image_matrix[row][col+3])
tester.poke(testcircuit.I4, image_matrix[row][col+4])
tester.poke(testcircuit.I5, image_matrix[row][col+5])
tester.poke(testcircuit.I6, image_matrix[row][col+6])
tester.poke(testcircuit.I7, image_matrix[row][col+7])
tester.poke(testcircuit.I8, image_matrix[row][col+8])
tester.poke(testcircuit.I9, image_matrix[row][col+9])
tester.poke(testcircuit.I10, image_matrix[row][col+10])
tester.poke(testcircuit.I11, image_matrix[row][col+11])
tester.poke(testcircuit.I12, image_matrix[row][col+12])
tester.poke(testcircuit.I13, image_matrix[row][col+13])
tester.poke(testcircuit.I14, image_matrix[row][col+14])
tester.poke(testcircuit.I15, image_matrix[row][col+15])
tester.poke(testcircuit.I16, image_matrix[row][col+16])
tester.poke(testcircuit.I17, image_matrix[row][col+17])
tester.poke(testcircuit.I18, image_matrix[row][col+18])
tester.poke(testcircuit.I19, image_matrix[row][col+19])
tester.poke(testcircuit.I20, image_matrix[row][col+20])
tester.poke(testcircuit.I21, image_matrix[row][col+21])
tester.poke(testcircuit.I22, image_matrix[row][col+22])
tester.poke(testcircuit.I23, image_matrix[row][col+23])
tester.poke(testcircuit.I24, image_matrix[row][col+24])
tester.poke(testcircuit.I25, image_matrix[row][col+25])
tester.poke(testcircuit.I26, image_matrix[row][col+26])
tester.poke(testcircuit.I27, image_matrix[row][col+27])
tester.poke(testcircuit.I28, image_matrix[row][col+28])
tester.poke(testcircuit.I29, image_matrix[row][col+29])
tester.poke(testcircuit.I30, image_matrix[row][col+30])
| |
# -*- coding: utf-8 -*-
# (c) 2014 <NAME>, MIT licensed
# (c) 2018-2019 <NAME>, MIT licensed
import logging
from collections import OrderedDict
log = logging.getLogger(__name__)
class DwdCdcKnowledge(object):
"""
Knowledge about the data layout on the DWD Climate Data Centers (CDC) server.
"""
class climate:
# The different measurements for climate data
measurements = [
{"key": "KL", "name": "daily_observations", "folder": "kl"},
{"key": "TU", "name": "air_temperature"},
{"key": "CS", "name": "cloud_type"},
{"key": "N", "name": "cloudiness"},
{"key": "TD", "name": "dew_point"},
{"key": "TX", "name": "extreme_temperature"},
{"key": "FX", "name": "extreme_wind"},
{"key": "RR", "name": "precipitation"},
{"key": "P0", "name": "pressure"},
{"key": "EB", "name": "soil_temperature"},
{"key": "ST", "name": "solar"},
{"key": "SD", "name": "sun"},
{"key": "VV", "name": "visibility"},
{"key": "FF", "name": "wind"},
{"key": "F", "name": "wind_synop"},
]
# The different resolutions for climate data
class resolutions:
"""
Quality information
The quality level "Qualitätsniveau" (QN) given here applies
to the respective columns and describes the method of quality control.
Quality level (column header: QN_X)::
1 only formal control during decoding and import
2 controlled with individually defined criteria
3 automatic control and correction (with QUALIMET and QCSY)
5 historic, subjective procedures
7 second control, not yet corrected
8 quality control, outside ROUTINE
9 quality control, not all parameters corrected
10 quality control finished, all corrections finished
Erroneous or suspicious values are identified and set to -999.
"""
# Temporal resolution: daily
class daily:
# Which data set / resolution subfolder to use.
__folder__ = "daily"
# Which format does the timestamp of this resolution have?
__timestamp_format__ = "%Y%m%d"
"""
==================
Daily observations
==================
Recent daily station observations (temperature, pressure, precipitation,
sunshine duration, etc.) for Germany, quality control not completed yet.
Documentation
-------------
- Recent
- Temporal coverage: rolling: 500 days before yesterday - until yesterday
- Temporal resolution: daily
- https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/daily/kl/recent/DESCRIPTION_obsgermany_climate_daily_kl_recent_en.pdf
- Historical
- Temporal coverage: 01.01.1781 - 31.12.2017
- Temporal resolution: daily
- https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/daily/kl/historical/DESCRIPTION_obsgermany_climate_daily_kl_historical_en.pdf
Fields
------
::
Field Description Format or unit
STATIONS_ID Station identification number Integer
MESS_DATUM Measurement time YYYYMMDD
QN_3 quality level of next columns Integer: 1-10 and -999, for coding see paragraph "Quality information" in PDF.
FX daily maximum of wind gust m/s
FM daily mean of wind velocity m/s
QN_4 quality level of next columns Integer: 1-10 and -999, for coding see paragraph "Quality information" in PDF.
RSK daily precipitation height mm
RSKF precipitation form 0, 1, 4, 6, 7, 8, 9
SDK daily sunshine duration h
SHK_TAG daily snow depth cm
NM daily mean of cloud cover 1/8
VPM daily mean of vapor pressure hPa
PM daily mean of pressure hPa
TMK daily mean of temperature °C
UPM daily mean of relative humidity %
TXK daily maximum of temperature
at 2m height °C
TNK daily minimum of temperature
at 2m height °C
TGK daily minimum of air temperature
at 5cm above ground °C
eor End of record, can be ignored
Missing values are marked as -999. All dates given are in UTC.
Form of precipitation:
0 No precipitation (conventional or automatic measurement),
relates to WMO code 10
1 Only rain (before 1979)
4 Unknown form of recorded precipitation
6 Only rain; only liquid precipitation at automatic stations,
relates to WMO code 11
7 Only snow; only solid precipitation at automatic stations,
relates to WMO code 12
8 Rain and snow (and/or "Schneeregen"); liquid and solid precipitation
at automatic stations, relates to WMO code 13
9 Error or missing value or no automatic determination of precipitation form,
relates to WMO code 15
"""
daily_observations = (
("daily_quality_level_3", "int"),
("wind_gust_max", "real"),
("wind_velocity_mean", "real"),
("daily_quality_level_4", "int"),
("precipitation_height", "real"),
("precipitation_form", "int"),
("sunshine_duration", "real"),
("snow_depth", "real"),
("cloud_cover", "real"),
("vapor_pressure", "real"),
("pressure", "real"),
("temperature", "real"),
("humidity", "real"),
("temperature_max_200", "real"),
("temperature_min_200", "real"),
("temperature_min_005", "real"),
)
"""
================
Soil temperature
================
Documentation
-------------
- Recent
- Temporal coverage: rolling: 500 days before yesterday - until yesterday
- Temporal resolution: daily
- https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/daily/soil_temperature/recent/DESCRIPTION_obsgermany_climate_daily_soil_temperature_recent_en.pdf
- Historical
- Temporal coverage: 01.01.1949 - 31.12.2017
- Temporal resolution: daily
- https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/daily/soil_temperature/historical/DESCRIPTION_obsgermany_climate_daily_soil_temperature_historical_en.pdf
Fields
------
::
Field Description Format or unit
STATIONS_ID Station identification number Integer
MESS_DATUM Measurement time YYYYMMDDHH
QN_2 Quality level Integer: 1-10 and -999, for coding see paragraph "Quality information" in PDF.
V_TE002 Soil temperature in 2 cm depth °C
V_TE005 Soil temperature in 5 cm depth °C
V_TE010 Soil temperature in 10 cm depth °C
V_TE020 Soil temperature in 20 cm depth °C
V_TE050 Soil temperature in 50 cm depth °C
V_TE100 Soil temperature in 100 cm depth °C
eor End of record, can be ignored
Missing values are marked as -999. All dates given are in UTC.
"""
soil_temperature = (
("soil_temperature_quality_level", "int"), # Quality level
("soil_temperature_002", "real"), # Soil temperature 2cm
("soil_temperature_005", "real"), # Soil temperature 5cm
("soil_temperature_010", "real"), # Soil temperature 10cm
("soil_temperature_020", "real"), # Soil temperature 20cm
("soil_temperature_050", "real"), # Soil temperature 50cm
#("soil_temperature_100", "real"), # Soil temperature 100cm
)
"""
=====
Solar
=====
Documentation
-------------
- Description: Daily station observations of solar incoming (total/diffuse) and longwave downward radiation for Germany
- Temporal coverage: 01.01.1937 - month before last month
- Temporal resolution: daily
- https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/daily/solar/DESCRIPTION_obsgermany_climate_daily_solar_en.pdf
Fields
------
::
Field Description Format or unit
STATIONS_ID Station identification number Integer
MESS_DATUM Measurement time YYYYMMDDHH
QN_592 Quality level Integer: 1-10 and -999, for coding see paragraph "Quality information" in PDF.
ATMO_STRAHL Hourly sum of longwave J/cm^2
downward radiation
FD_STRAHL Hourly sum of diffuse J/cm^2
solar radiation
FG_STRAHL Hourly sum of solar J/cm^2
incoming radiation
SD_STRAHL Hourly sum of min
sunshine duration
eor End of record, can be ignored
Missing values are marked as -999. All dates given are in UTC.
"""
solar = (
("solar_quality_level", "int"), # Quality information
("solar_atmosphere", "real"), # Hourly sum of longwave downward radiation
("solar_dhi", "real"), # Hourly sum of Diffuse Horizontal Irradiance (DHI)
("solar_ghi", "real"), # Hourly sum of Global Horizontal Irradiance (GHI)
("solar_sunshine", "real"), # Hourly sum of sunshine duration
)
# Temporal resolution: hourly
class hourly:
# Which data set / resolution subfolder to use.
__folder__ = "hourly"
# Which format does the timestamp of this resolution have?
__timestamp_format__ = "%Y%m%d%H"
"""
===============
Air temperature
===============
Documentation
-------------
- Recent
- Temporal coverage: rolling: 500 days before yesterday - until yesterday
- Temporal resolution: hourly
- https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/hourly/air_temperature/recent/DESCRIPTION_obsgermany_climate_hourly_tu_recent_en.pdf
- Historical
- Temporal coverage: 01.01.1893 - 31.12.2016
- Temporal resolution: hourly
- https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/hourly/air_temperature/historical/DESCRIPTION_obsgermany_climate_hourly_tu_historical_en.pdf
Fields
------
::
Field Description Format or unit
STATIONS_ID Station identification number Integer
MESS_DATUM Measurement time YYYYMMDDHH
QN_9 Quality level Integer: 1-10 and -999, for coding see paragraph "Quality information" in PDF.
TT_TU Air temperature 2m °C
RF_TU Relative humidity 2m %
eor End of record, can be ignored
Missing values are marked as -999. All dates given are in UTC.
"""
air_temperature = (
("air_temperature_quality_level", "int"), # Quality level
("air_temperature_200", "real"), # Air temperature 2m
("relative_humidity_200", "real"), # Relative humidity 2m
)
"""
================
Soil temperature
================
Documentation
-------------
- Recent
- Temporal coverage: rolling: 500 days before yesterday - until yesterday
- Temporal resolution: several times a day
- https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/hourly/soil_temperature/recent/DESCRIPTION_obsgermany_climate_hourly_soil_temperature_recent_en.pdf
- Historical
- Temporal coverage: 01.01.1949 - 31.12.2016
- Temporal resolution: several times a day
- https://opendata.dwd.de/climate_environment/CDC/observations_germany/climate/hourly/soil_temperature/historical/DESCRIPTION_obsgermany_climate_hourly_soil_temperature_historical_en.pdf
Fields
------
::
Field Description Format or unit
STATIONS_ID Station identification number Integer
MESS_DATUM Measurement time YYYYMMDDHH
QN_2 Quality level Integer: 1-10 and -999, for coding see paragraph "Quality information" in PDF.
V_TE002 Soil temperature in 2 cm depth °C
V_TE005 Soil temperature in 5 cm depth °C
V_TE010 Soil temperature in 10 cm depth °C
V_TE020 Soil temperature in 20 cm depth °C
V_TE050 Soil temperature in 50 cm depth °C
V_TE100 Soil temperature in 100 cm depth °C
eor End of record, can be ignored
Missing values are marked as -999. All dates given are in UTC.
"""
soil_temperature = (
("soil_temperature_quality_level", "int"), # Quality level
("soil_temperature_002", "real"), # Soil temperature 2cm
("soil_temperature_005", "real"), # Soil temperature 5cm
("soil_temperature_010", "real"), # Soil temperature 10cm
("soil_temperature_020", "real"), # Soil temperature 20cm
| |
model parameters if not already done so.
Parameters
----------
t_eval : numeric type, optional
The times (in seconds) at which to compute the solution. Can be
provided as an array of times at which to return the solution, or as a
list `[t0, tf]` where `t0` is the initial time and `tf` is the final time.
If provided as a list the solution is returned at 100 points within the
interval `[t0, tf]`.
If not using an experiment or running a drive cycle simulation (current
provided as data) `t_eval` *must* be provided.
If running an experiment the values in `t_eval` are ignored, and the
solution times are specified by the experiment.
If None and the parameter "Current function [A]" is read from data
(i.e. drive cycle simulation) the model will be solved at the times
provided in the data.
solver : :class:`pybamm.BaseSolver`
The solver to use to solve the model.
check_model : bool, optional
If True, model checks are performed after discretisation (see
:meth:`pybamm.Discretisation.process_model`). Default is True.
**kwargs
Additional key-word arguments passed to `solver.solve`.
See :meth:`pybamm.BaseSolver.solve`.
"""
# Setup
self.build(check_model=check_model)
if solver is None:
solver = self.solver
if self.operating_mode in ["without experiment", "drive cycle"]:
if self.operating_mode == "without experiment":
if t_eval is None:
raise pybamm.SolverError(
"'t_eval' must be provided if not using an experiment or "
"simulating a drive cycle. 't_eval' can be provided as an "
"array of times at which to return the solution, or as a "
"list [t0, tf] where t0 is the initial time and tf is the "
"final time. "
"For a constant current (dis)charge the suggested 't_eval' "
"is [0, 3700/C] where C is the C-rate. "
"For example, run\n\n"
"\tsim.solve([0, 3700])\n\n"
"for a 1C discharge."
)
elif self.operating_mode == "drive cycle":
# For drive cycles (current provided as data) we perform additional
# tests on t_eval (if provided) to ensure the returned solution
# captures the input.
time_data = self._parameter_values["Current function [A]"].x[0]
# If no t_eval is provided, we use the times provided in the data.
if t_eval is None:
pybamm.logger.info("Setting t_eval as specified by the data")
t_eval = time_data
# If t_eval is provided we first check if it contains all of the
# times in the data to within 10-12. If it doesn't, we then check
# that the largest gap in t_eval is smaller than the smallest gap in
# the time data (to ensure the resolution of t_eval is fine enough).
# We only raise a warning here as users may genuinely only want
# the solution returned at some specified points.
elif (
set(np.round(time_data, 12)).issubset(set(np.round(t_eval, 12)))
) is False:
warnings.warn(
"""
t_eval does not contain all of the time points in the data
set. Note: passing t_eval = None automatically sets t_eval
to be the points in the data.
""",
pybamm.SolverWarning,
)
dt_data_min = np.min(np.diff(time_data))
dt_eval_max = np.max(np.diff(t_eval))
if dt_eval_max > dt_data_min + sys.float_info.epsilon:
warnings.warn(
"""
The largest timestep in t_eval ({}) is larger than
the smallest timestep in the data ({}). The returned
solution may not have the correct resolution to accurately
capture the input. Try refining t_eval. Alternatively,
passing t_eval = None automatically sets t_eval to be the
points in the data.
""".format(
dt_eval_max, dt_data_min
),
pybamm.SolverWarning,
)
self._solution = solver.solve(self.built_model, t_eval, **kwargs)
elif self.operating_mode == "with experiment":
if t_eval is not None:
pybamm.logger.warning(
"Ignoring t_eval as solution times are specified by the experiment"
)
# Re-initialize solution, e.g. for solving multiple times with different
# inputs without having to build the simulation again
self._solution = None
previous_num_subsolutions = 0
# Step through all experimental conditions
inputs = kwargs.get("inputs", {})
pybamm.logger.info("Start running experiment")
timer = pybamm.Timer()
all_cycle_solutions = []
idx = 0
num_cycles = len(self.experiment.cycle_lengths)
for cycle_num, cycle_length in enumerate(self.experiment.cycle_lengths):
pybamm.logger.info(
f"Cycle {cycle_num+1}/{num_cycles} ({timer.time()} elapsed) "
+ "-" * 20
)
steps = []
cycle_solution = None
for step_num in range(cycle_length):
exp_inputs = self._experiment_inputs[idx]
dt = self._experiment_times[idx]
# Use 1-indexing for printing cycle number as it is more
# human-intuitive
pybamm.logger.info(
f"Cycle {cycle_num+1}/{num_cycles}, "
f"step {step_num+1}/{cycle_length}: "
f"{self.experiment.operating_conditions_strings[idx]}"
)
inputs.update(exp_inputs)
kwargs["inputs"] = inputs
# Make sure we take at least 2 timesteps
npts = max(int(round(dt / exp_inputs["period"])) + 1, 2)
self.step(dt, solver=solver, npts=npts, **kwargs)
# Extract the new parts of the solution
# to construct the entire "step"
sol = self.solution
new_num_subsolutions = len(sol.sub_solutions)
diff_num_subsolutions = (
new_num_subsolutions - previous_num_subsolutions
)
previous_num_subsolutions = new_num_subsolutions
step_solution = pybamm.Solution(
sol.all_ts[-diff_num_subsolutions:],
sol.all_ys[-diff_num_subsolutions:],
sol.model,
sol.all_inputs[-diff_num_subsolutions:],
sol.t_event,
sol.y_event,
sol.termination,
)
step_solution.solve_time = 0
step_solution.integration_time = 0
steps.append(step_solution)
# Construct cycle solutions (a list of solutions corresponding to
# cycles) from sub_solutions
if step_num == 0:
cycle_solution = step_solution
else:
cycle_solution = cycle_solution + step_solution
# Only allow events specified by experiment
if not (
self._solution.termination == "final time"
or "[experiment]" in self._solution.termination
):
pybamm.logger.warning(
"\n\n\tExperiment is infeasible: '{}' ".format(
self._solution.termination
)
+ "was triggered during '{}'. ".format(
self.experiment.operating_conditions_strings[idx]
)
+ "Try reducing current, shortening the time interval, "
"or reducing the period.\n\n"
)
break
# Increment index for next iteration
idx += 1
# At the final step of the inner loop we save the cycle
cycle_solution.steps = steps
all_cycle_solutions.append(cycle_solution)
self.solution.cycles = all_cycle_solutions
pybamm.logger.notice(
"Finish experiment simulation, took {}".format(timer.time())
)
return self.solution
def step(self, dt, solver=None, npts=2, save=True, **kwargs):
"""
A method to step the model forward one timestep. This method will
automatically build and set the model parameters if not already done so.
Parameters
----------
dt : numeric type
The timestep over which to step the solution
solver : :class:`pybamm.BaseSolver`
The solver to use to solve the model.
npts : int, optional
The number of points at which the solution will be returned during
the step dt. Default is 2 (returns the solution at t0 and t0 + dt).
save : bool
Turn on to store the solution of all previous timesteps
**kwargs
Additional key-word arguments passed to `solver.solve`.
See :meth:`pybamm.BaseSolver.step`.
"""
self.build()
if solver is None:
solver = self.solver
self._solution = solver.step(
self._solution, self.built_model, dt, npts=npts, save=save, **kwargs
)
return self.solution
def plot(self, output_variables=None, quick_plot_vars=None, **kwargs):
"""
A method to quickly plot the outputs of the simulation. Creates a
:class:`pybamm.QuickPlot` object (with keyword arguments 'kwargs') and
then calls :meth:`pybamm.QuickPlot.dynamic_plot`.
Parameters
----------
output_variables: list, optional
A list of the variables to plot.
quick_plot_vars: list, optional
A list of the variables to plot. Deprecated, use output_variables instead.
**kwargs
Additional keyword arguments passed to
:meth:`pybamm.QuickPlot.dynamic_plot`.
For a list of all possible keyword arguments see :class:`pybamm.QuickPlot`.
"""
if quick_plot_vars is not None:
raise NotImplementedError(
"'quick_plot_vars' has been deprecated. Use 'output_variables' instead."
)
if self._solution is None:
raise ValueError(
"Model has not been solved, please solve the model before plotting."
)
if output_variables is None:
output_variables = self.output_variables
self.quick_plot = pybamm.dynamic_plot(
self._solution, output_variables=output_variables, **kwargs
)
@property
def model(self):
return self._model
@model.setter
def model(self, model):
self._model = copy.copy(model)
self._model_class = model.__class__
@property
def model_with_set_params(self):
return self._model_with_set_params
@property
def built_model(self):
return self._built_model
@property
def geometry(self):
return self._geometry
@geometry.setter
def geometry(self, geometry):
self._geometry = geometry.copy()
@property
def parameter_values(self):
return self._parameter_values
@parameter_values.setter
def parameter_values(self, parameter_values):
self._parameter_values = parameter_values.copy()
@property
def submesh_types(self):
return self._submesh_types
@submesh_types.setter
def submesh_types(self, submesh_types):
self._submesh_types = submesh_types.copy()
@property
def mesh(self):
return self._mesh
@property
def var_pts(self):
return self._var_pts
@var_pts.setter
def var_pts(self, var_pts):
self._var_pts = var_pts.copy()
@property
def spatial_methods(self):
return self._spatial_methods
@spatial_methods.setter
def spatial_methods(self, spatial_methods):
self._spatial_methods = spatial_methods.copy()
@property
def solver(self):
return self._solver
@solver.setter
def solver(self, solver):
self._solver = solver.copy()
@property
def output_variables(self):
return self._output_variables
@output_variables.setter
def output_variables(self, output_variables):
self._output_variables = copy.copy(output_variables)
@property
def solution(self):
return self._solution
def specs(
self,
geometry=None,
parameter_values=None,
submesh_types=None,
var_pts=None,
spatial_methods=None,
solver=None,
output_variables=None,
C_rate=None,
):
"Deprecated method for setting specs"
raise NotImplementedError(
"The 'specs' method has been deprecated. "
"Create a new simulation for each different case instead."
)
def save(self, filename):
"""Save simulation using pickle"""
if self.model.convert_to_format == "python":
# We currently cannot save models in the 'python' format
raise | |
<gh_stars>1-10
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import itertools
from edgedb.lang import edgeql
from edgedb.lang.edgeql import ast as qlast
from edgedb.lang.edgeql import errors as ql_errors
from . import delta as sd
from . import error as s_errors
from . import expr as s_expr
from . import functions as s_func
from . import inheriting
from . import name as sn
from . import named
from . import objects as so
from . import referencing
class CumulativeBoolExpr(s_expr.ExpressionText):
@classmethod
def merge_values(cls, ours, theirs, schema):
if ours and theirs and ours != theirs:
result = '({}) and ({})'.format(ours, theirs)
elif not ours and theirs:
result = theirs
else:
result = ours
return result
class Constraint(inheriting.InheritingObject):
_type = 'constraint'
expr = so.Field(s_expr.ExpressionText, default=None, compcoef=0.909,
coerce=True)
subjectexpr = so.Field(s_expr.ExpressionText,
default=None, compcoef=0.833, coerce=True)
localfinalexpr = so.Field(CumulativeBoolExpr, default=None,
coerce=True, hashable=False, inheritable=False,
ephemeral=True)
finalexpr = so.Field(CumulativeBoolExpr, default=None,
coerce=True, hashable=False, compcoef=0.909)
subject = so.Field(so.Object, default=None, inheritable=False)
paramnames = so.Field(so.StringList, default=None, coerce=True,
compcoef=0.4)
paramtypes = so.Field(so.TypeList, default=None, coerce=True,
compcoef=0.857)
# Number of the variadic parameter (+1)
varparam = so.Field(int, default=None, compcoef=0.4)
args = so.Field(s_expr.ExpressionList,
default=None, coerce=True, inheritable=False,
compcoef=0.875)
errmessage = so.Field(str, default=None, compcoef=0.971)
def generic(self):
return self.subject is None
def merge_localexprs(self, obj, schema):
self.localfinalexpr = CumulativeBoolExpr.merge_values(
self.localfinalexpr, obj.localfinalexpr, schema=schema)
def init_derived(self, schema, source, *qualifiers,
as_copy, mark_derived=False, add_to_schema=False,
merge_bases=None, attrs=None,
dctx=None, **kwargs):
if attrs is None:
attrs = {}
attrs['subject'] = source
return super().init_derived(
schema, source, *qualifiers, as_copy=as_copy,
mark_derived=mark_derived, add_to_schema=add_to_schema,
merge_bases=merge_bases, attrs=attrs, dctx=dctx, **kwargs)
@classmethod
def _dummy_subject(cls):
from . import scalars as s_scalars
# Point subject placeholder to a dummy pointer to make EdgeQL
# pipeline happy.
return s_scalars.ScalarType(name=sn.Name('std::_subject_tgt'))
@classmethod
def _normalize_constraint_expr(
cls, schema, module_aliases, expr, subject, *,
inline_anchors=False):
from edgedb.lang.edgeql import parser as edgeql_parser
from edgedb.lang.edgeql import utils as edgeql_utils
if isinstance(expr, str):
tree = edgeql_parser.parse(expr, module_aliases)
else:
tree = expr
ir, edgeql_tree, _ = edgeql_utils.normalize_tree(
tree, schema, modaliases=module_aliases,
anchors={qlast.Subject: subject}, inline_anchors=inline_anchors)
return edgeql_tree.result, ir.expr.expr.result
@classmethod
def normalize_constraint_expr(
cls, schema, module_aliases, expr, *,
subject=None, constraint, expr_context=None,
enforce_boolean=False):
from edgedb.lang.ir import utils as irutils
if subject is None:
subject = cls._dummy_subject()
edgeql_tree, ir_result = cls._normalize_constraint_expr(
schema, module_aliases, expr, subject)
if enforce_boolean:
bool_t = schema.get('std::bool')
expr_type = irutils.infer_type(ir_result, schema)
if not expr_type.issubclass(bool_t):
raise s_errors.SchemaDefinitionError(
f'{constraint.displayname} constraint expression expected '
f'to return a bool value, got {expr_type.name.name!r}',
context=expr_context
)
expr = edgeql.generate_source(edgeql_tree, pretty=False)
# XXX: check that expr has boolean result
return expr
@classmethod
def process_specialized_constraint(cls, schema, constraint, params=None):
from edgedb.lang.edgeql import utils as edgeql_utils
from edgedb.lang.edgeql import parser as edgeql_parser
assert constraint.subject is not None
module_aliases = {}
# check to make sure that the specialized constraint doesn't redefine
# an already defined subjectexpr
if constraint.subjectexpr is not None:
for base in constraint.bases:
base_se = base.get_field_value('subjectexpr')
if base_se and base_se != constraint.subjectexpr:
raise s_errors.InvalidConstraintDefinitionError(
'subjectexpr is already defined for ' +
f'{constraint.name!r}')
subject = constraint.subject
subjectexpr = constraint.get_field_value('subjectexpr')
if subjectexpr:
_, subject = cls._normalize_constraint_expr(
schema, {}, subjectexpr, subject)
expr = constraint.get_field_value('expr')
if not expr:
raise s_errors.InvalidConstraintDefinitionError(
f'missing constraint expression in {constraint.name!r}')
expr_ql = edgeql_parser.parse(expr, module_aliases)
if params:
args = params
else:
args = constraint.get_field_value('args')
args_map = None
if args:
if constraint.varparam is not None:
varparam = constraint.varparam
else:
varparam = None
args_ql = [
edgeql_parser.parse(arg, module_aliases) for arg in args
]
args_map = edgeql_utils.index_parameters(
args_ql, varparam=varparam)
edgeql_utils.inline_parameters(expr_ql, args_map)
args_map = {f'${name}': edgeql.generate_source(val, pretty=False)
for name, val in args_map.items()}
constraint.errmessage = constraint.errmessage.format(
__subject__='{__subject__}', **args_map)
args = list(args_map.values())
if expr == '__subject__':
expr_context = \
constraint.get_attribute_source_context('subjectexpr')
else:
expr_context = \
constraint.get_attribute_source_context('expr')
expr_text = cls.normalize_constraint_expr(
schema, module_aliases, expr_ql, subject=subject,
constraint=constraint, enforce_boolean=True,
expr_context=expr_context)
constraint.expr = expr_text
constraint.localfinalexpr = expr_text
constraint.finalexpr = expr_text
constraint.args = args or None
def format_error_message(self):
errmsg = self.errmessage
subjtitle = self.subject.title
if not subjtitle:
try:
subjname = self.subject.shortname
except AttributeError:
subjname = self.subject.name
subjtitle = subjname.name
formatted = errmsg.format(__subject__=subjtitle)
return formatted
@classmethod
def get_root_classes(cls):
return (
sn.Name(module='std', name='constraint'),
)
@classmethod
def get_default_base_name(self):
return sn.Name('std::constraint')
class ConsistencySubject(referencing.ReferencingObject):
constraints = referencing.RefDict(ref_cls=Constraint, compcoef=0.887)
@classmethod
def inherit_pure(cls, schema, item, source, *, dctx=None):
item = super().inherit_pure(schema, item, source, dctx=dctx)
if any(c.is_abstract for c in item.constraints.values()):
# Have abstract constraints, cannot go pure inheritance,
# must create a derived Object with materialized
# constraints.
generic = item.bases[0]
item = generic.derive(schema, source=source, add_to_schema=True,
merge_bases=[item], dctx=dctx)
return item
def begin_classref_dict_merge(self, schema, bases, attr):
if attr == 'constraints':
# Make sure abstract constraints from parents are mixed in
# properly.
constraints = set(self.constraints)
inherited = itertools.chain.from_iterable(
getattr(b, 'constraints', {}).values()
for b in bases)
constraints.update(c.shortname
for c in inherited if c.is_abstract)
return constraints
else:
return super().begin_classref_dict_merge(schema, bases, attr)
def finish_classref_dict_merge(self, schema, bases, attr):
super().finish_classref_dict_merge(schema, bases, attr)
if attr == 'constraints':
# Materialize unmerged abstract constraints
for cn, constraint in self.constraints.items():
if constraint.is_abstract and cn not in self.local_constraints:
constraint = constraint.derive_copy(
schema, self, add_to_schema=True,
attrs=dict(is_abstract=False))
self.add_constraint(constraint)
def add_constraint(self, constraint, replace=False):
self.add_classref('constraints', constraint, replace=replace)
def del_constraint(self, constraint_name, schema):
self.del_classref('constraints', constraint_name, schema)
@classmethod
def delta_constraints(cls, set1, set2, delta, context=None):
oldconstraints = set(set1)
newconstraints = set(set2)
for constraint in oldconstraints - newconstraints:
d = set1[constraint].delta(None, reverse=True, context=context)
delta.add(d)
for constraint in newconstraints - oldconstraints:
d = set2[constraint].delta(None, context=context)
delta.add(d)
for constraint in newconstraints & oldconstraints:
oldconstr = set1[constraint]
newconstr = set2[constraint]
if newconstr.compare(oldconstr, context=context) != 1.0:
d = newconstr.delta(oldconstr, context=context)
delta.add(d)
def delta_all_constraints(self, old, new, delta, context):
oldconstraints = old.local_constraints if old else {}
newconstraints = new.local_constraints if new else {}
self.delta_constraints(oldconstraints, newconstraints, delta, context)
class ConsistencySubjectCommandContext:
# context mixin
pass
class ConsistencySubjectCommand(referencing.ReferencingObjectCommand):
pass
class ConstraintCommandContext(sd.ObjectCommandContext):
pass
class ConstraintCommand(
referencing.ReferencedInheritingObjectCommand,
schema_metaclass=Constraint, context_class=ConstraintCommandContext,
referrer_context_class=ConsistencySubjectCommandContext):
def add_constraint(self, constraint, parent, schema):
parent.add_constraint(constraint)
def delete_constraint(self, constraint_name, parent, schema):
parent.del_constraint(constraint_name, schema)
def _create_begin(self, schema, context):
super()._create_begin(schema, context)
referrer_ctx = self.get_referrer_context(context)
if referrer_ctx is not None and self.scls.finalexpr is None:
Constraint.process_specialized_constraint(schema, self.scls)
def _alter_begin(self, schema, context, scls):
super()._alter_begin(schema, context, scls)
@classmethod
def _validate_subcommands(cls, astnode):
# check that 'subject' and 'subjectexpr' are not set as attributes
for command in astnode.commands:
if cls._is_special_name(command.name):
raise s_errors.SchemaDefinitionError(
f'{command.name.name} is not a valid constraint attribute',
context=command.context)
@classmethod
def _is_special_name(cls, astnode):
# check that 'subject' and 'subjectexpr' are not set as attributes
return (astnode.name in {'subject', 'subjectexpr'} and
not astnode.module)
class CreateConstraint(ConstraintCommand,
referencing.CreateReferencedInheritingObject,
s_func.FunctionCommandMixin):
astnode = [qlast.CreateConcreteConstraint, qlast.CreateConstraint]
referenced_astnode = qlast.CreateConcreteConstraint
@classmethod
def _cmd_tree_from_ast(cls, astnode, context, schema):
cmd = super()._cmd_tree_from_ast(astnode, context, schema)
if isinstance(astnode, qlast.CreateConcreteConstraint):
if astnode.args:
args = []
for arg in astnode.args:
arg_expr = s_expr.ExpressionText(
edgeql.generate_source(arg.arg, pretty=False))
args.append(arg_expr)
cmd.add(
sd.AlterObjectProperty(
property='args',
new_value=args
)
)
elif isinstance(astnode, qlast.CreateConstraint):
if astnode.args:
paramnames, paramdefaults, paramtypes, paramkinds, variadic = \
s_func.parameters_from_ast(
astnode, context.modaliases, schema)
if variadic is not None:
cmd.add(sd.AlterObjectProperty(
property='varparam',
new_value=variadic
))
for pname, pdefault, ptype in zip(paramnames, paramdefaults,
paramtypes):
if pname is not None:
raise ql_errors.EdgeQLError(
'constraints do not support named parameters',
context=astnode.context)
if pdefault is not None:
raise ql_errors.EdgeQLError(
'constraints do not support parameters '
'with defaults',
context=astnode.context)
if ptype is None:
raise ql_errors.EdgeQLError(
'untyped parameter', context=astnode.context)
cmd.add(sd.AlterObjectProperty(
property='paramtypes',
new_value=paramtypes
))
# 'subject' can be present in either astnode type
if astnode.subject:
subjectexpr = s_expr.ExpressionText(
edgeql.generate_source(astnode.subject, pretty=False))
cmd.add(sd.AlterObjectProperty(
property='subjectexpr',
new_value=subjectexpr
))
cls._validate_subcommands(astnode)
return cmd
def _apply_field_ast(self, context, node, op):
if op.property == 'is_derived':
pass
elif op.property == 'is_abstract':
node.is_abstract = op.new_value
elif op.property == 'subject':
pass
else:
super()._apply_field_ast(context, node, op)
class RenameConstraint(ConstraintCommand, named.RenameNamedObject):
pass
class AlterConstraint(ConstraintCommand, named.AlterNamedObject):
astnode = [qlast.AlterConcreteConstraint, qlast.AlterConstraint]
referenced_astnode = qlast.AlterConcreteConstraint
@classmethod
def _cmd_tree_from_ast(cls, astnode, context, schema):
cmd = super()._cmd_tree_from_ast(astnode, context, schema)
if isinstance(astnode, qlast.AlterConcreteConstraint):
subject_ctx = context.get(ConsistencySubjectCommandContext)
new_subject_name = None
for op in subject_ctx.op.get_subcommands(
type=named.RenameNamedObject):
new_subject_name = op.new_name
if new_subject_name is not None:
cmd.add(
sd.AlterObjectProperty(
property='subject',
new_value=so.ObjectRef(
classname=new_subject_name
)
)
)
new_name = None
for op in cmd.get_subcommands(type=RenameConstraint):
new_name = op.new_name
if new_name is not None:
| |
fields:
return ast_pb2.MakeCond(
op, fields[possible_field], [], [], phase_name=phase_name)
elif unquoted_value in fields: # Look for that field with any value.
return ast_pb2.MakeCond(op, fields[unquoted_value], [], [])
else: # Look for any label with that prefix.
return ast_pb2.MakeCond(op, fields['label'], [unquoted_value], [])
# Search entries with certain gates.
if prefix == 'gate':
return ast_pb2.MakeCond(op, fields['gate'], quick_or_vals, [])
# Determine hotlist query type.
# If prefix is not 'hotlist', quick_or_vals is empty, or qov
# does not contain ':', is_fields will remain True
is_fields = True
if prefix == 'hotlist':
try:
if ':' not in quick_or_vals[0]:
is_fields = False
except IndexError:
is_fields = False
phase_name = None
if '.' in prefix and is_fields:
split_prefix = prefix.split('.', 1)
if split_prefix[1] in fields:
phase_name, prefix = split_prefix
# search built-in and custom fields. E.g., summary.
if prefix in fields and is_fields:
# Note: if first matching field is date-type, we assume they all are.
# TODO(jrobbins): better handling for rare case where multiple projects
# define the same custom field name, and one is a date and another is not.
first_field = fields[prefix][0]
if first_field.field_type == DATE:
date_values = [_ParseDateValue(val, now=now) for val in quick_or_vals]
return ast_pb2.MakeCond(op, fields[prefix], [], date_values)
elif first_field.field_type == APPROVAL and prefix.endswith(SET_ON_SUFFIX):
date_values = [_ParseDateValue(val, now=now) for val in quick_or_vals]
return ast_pb2.MakeCond(
op,
fields[prefix], [],
date_values,
key_suffix=SET_ON_SUFFIX,
phase_name=phase_name)
else:
quick_or_ints = []
for qov in quick_or_vals:
try:
quick_or_ints.append(int(qov))
except ValueError:
pass
if first_field.field_type == APPROVAL:
for approval_suffix in _APPROVAL_SUFFIXES:
if prefix.endswith(approval_suffix):
return ast_pb2.MakeCond(op, fields[prefix], quick_or_vals,
quick_or_ints, key_suffix=approval_suffix,
phase_name=phase_name)
return ast_pb2.MakeCond(op, fields[prefix], quick_or_vals,
quick_or_ints, phase_name=phase_name)
# Since it is not a field, treat it as labels, E.g., Priority.
quick_or_labels = ['%s-%s' % (prefix, v) for v in quick_or_vals]
# Convert substring match to key-value match if user typed 'foo:bar'.
if op == TEXT_HAS:
op = KEY_HAS
return ast_pb2.MakeCond(op, fields['label'], quick_or_labels, [])
def _ExtractConds(query, warnings):
# type: (str, Sequence[str]) -> Sequence[str]
"""Parse a query string into a list of individual condition strings.
Args:
query: UTF-8 encoded search query string.
warnings: list to accumulate warning messages.
Returns:
A list of query condition strings.
"""
# Convert to unicode then search for distinct terms.
term_matches = TERM_RE.findall(query)
terms = []
for (phrase, word_label, _op1, phrase_label, _op2,
word) in term_matches:
# Case 1: Quoted phrases, e.g., ["hot dog"].
if phrase_label or phrase:
terms.append(phrase_label or phrase)
# Case 2: Comparisons
elif word_label:
special_prefixes_match = any(
word_label.startswith(p) for p in NON_OP_PREFIXES)
match = OP_RE.match(word_label)
if match and not special_prefixes_match:
label = match.group('prefix')
op = match.group('op')
word = match.group('value')
terms.append('%s%s"%s"' % (label, op, word))
else:
# It looked like a key:value cond, but not exactly, so treat it
# as fulltext search. It is probably a tiny bit of source code.
terms.append('"%s"' % word_label)
# Case 3: Simple words.
elif word:
terms.append(word)
else: # pragma: no coverage
warnings.append('Unparsable search term')
return terms
def _ParseDateValue(val, now=None):
# type: (str, int) -> int
"""Convert the user-entered date into timestamp."""
# Support timestamp value such as opened>1437671476
try:
return int(val)
except ValueError:
pass
# TODO(jrobbins): future: take timezones into account.
# TODO(jrobbins): for now, explain to users that "today" is
# actually now: the current time, not 12:01am in their timezone.
# In fact, it is not very useful because everything in the system
# happened before the current time.
if val == 'today':
return _CalculatePastDate(0, now=now)
elif val.startswith('today-'):
try:
days_ago = int(val.split('-')[1])
except ValueError:
raise InvalidQueryError('Could not parse date: ' + val)
return _CalculatePastDate(days_ago, now=now)
try:
if '/' in val:
year, month, day = [int(x) for x in val.split('/')]
elif '-' in val:
year, month, day = [int(x) for x in val.split('-')]
else:
raise InvalidQueryError('Could not parse date: ' + val)
except ValueError:
raise InvalidQueryError('Could not parse date: ' + val)
try:
return int(time.mktime(datetime.datetime(year, month, day).timetuple()))
except ValueError:
raise InvalidQueryError('Could not parse date: ' + val)
def _CalculatePastDate(days_ago, now=None):
# type: (int, int) -> int
"""Calculates the timestamp N days ago from now."""
if now is None:
now = int(time.time())
ts = now - days_ago * 24 * 60 * 60
return ts
def QueryToSubqueries(query):
# type (str) -> Sequence[str]
"""Splits a query into smaller queries based on Monorail's search syntax.
This function handles parsing parentheses and OR statements in Monorail's
search syntax. By doing this parsing for OR statements and parentheses up
front in FrontendSearchPipeline, we are able to convert complex queries
with lots of ORs into smaller, more easily cacheable query terms.
These outputted subqueries should collectively return the same query results
as the initial input query without containing any ORs or parentheses,
allowing later search layers to parse queries without worrying about ORs
or parentheses.
Some examples of possible queries and their expected output:
- '(A OR B) (C OR D) OR (E OR F)' -> ['A C', 'A D', 'B C', 'B D', 'E', 'F']
- '(A) OR (B)' -> ['A', 'B']
- '(A ((C) OR (D OR (E OR F))))' -> ['A C', 'A D', 'A E', 'A F']
Where A, B, C, D, etc could be any list of conjunctions. ie: "owner:me",
"Pri=1", "hello world Hotlist=test", "label!=a11y", etc
Note: Monorail implicitly ANDs any query terms separated by a space. For
the most part, AND functionality is handled at a later layer in search
processing. However, this case becomes important here when considering the
fact that a prentheses group can either be ANDed or ORed with terms that
surround it.
The _MultiplySubqueries helper is used to AND the results of different
groups together whereas concatenating lists is used to OR subqueries
together.
Args:
query: The initial query that was sent to the search.
Returns:
List of query fragments to be independently processed as search terms.
Raises:
InvalidQueryError if parentheses are unmatched.
"""
tokens = _ValidateAndTokenizeQuery(query)
# Using an iterator allows us to keep our current loop position across
# helpers. This makes recursion a lot easier.
token_iterator = PeekIterator(tokens)
subqueries = _ParseQuery(token_iterator)
if not len(subqueries):
# Several cases, such as an empty query or a query with only parentheses
# will result in an empty set of subqueries. In these cases, we still want
# to give the search pipeline a single empty query to process.
return ['']
return subqueries
def _ParseQuery(token_iterator):
# type (Sequence[proto.ast_pb2.QueryToken]) -> Sequence[str]
"""Recursive helper to convert query tokens into a list of subqueries.
Parses a Query based on the following grammar (EBNF):
Query := OrGroup { [OrOperator] OrGroup }
OrGroup := AndGroup { AndGroup }
AndGroup := Subquery | ParenthesesGroup
ParenthesesGroup := "(" Query ")"
Subquery := /.+/
OrOperator := " OR "
An important nuance is that two groups can be next to each other, separated
only by a word boundary (ie: space or parentheses). In this case, they are
implicitly ANDed. In practice, because unparenthesized fragments ANDed by
spaces are stored as single tokens, we only need to handle the AND case when
a parentheses group is implicitly ANDed with an adjacent group.
Order of precedence is implemented by recursing through OR groups before
recursing through AND groups.
Args:
token_iterator: Iterator over a list of query tokens.
Returns:
List of query fragments to be processed as search terms.
Raises:
InvalidQueryError if tokens were inputted in a format that does not follow
our search grammar.
"""
subqueries = []
try:
if token_iterator.peek().token_type == OR:
# Edge case: Ignore empty OR groups at the starte of a ParenthesesGroup.
# ie: "(OR A)" will be processed as "A"
next(token_iterator)
subqueries = _ParseOrGroup(token_iterator)
while token_iterator.peek().token_type == OR:
# Consume the OR tokens without doing anything with it.
next(token_iterator)
next_token = token_iterator.peek()
if next_token.token_type == RIGHT_PAREN:
# Edge case: Ignore empty OR groups at the end of a ParenthesesGroup.
# ie: "(A OR)" will be processed as "A"
return subqueries
next_subqueries = _ParseOrGroup(token_iterator)
# Concatenate results of OR groups together.
subqueries = subqueries + next_subqueries
except StopIteration:
pass
# Return | |
2
# finalize
self.filemask = filemask
self.order = order
self.fshape = fshape
self.__setdimandshape__() # set ndim and shape attributes
def __fcopy__(self, order):
"""
Create a copy
"""
n = pipe_3d(self.filemask, order)
return n
def __fgetitem__(self, slices):
"""
Return ndarray of selected values
(sZ, sY, sX) is a well formatted tuple of slices
"""
sZ, sY, sX = slices
# determine which objects should be selected
lenZ, lenY, lenX = self.fshape
xch = range(lenX)[sX]
ych = range(lenY)[sY]
zch = range(lenZ)[sZ]
# create an empty array to store the selected slice
out = np.empty((len(zch), len(ych), len(xch)), dtype=self.dtype)
# read in the data file by file and trace by trace
for zi, z in enumerate(zch):
# open the Z axis file
f = open(self.filemask % (z + 1), 'rb')
for yi, y in enumerate(ych):
ntrace = y
trace = get_trace(f, ntrace, lenX, self.bswap, self.cplex)
out[zi, yi] = trace[sX]
f.close()
return out
class pipestream_3d(fileiobase.data_nd):
"""
Emulate a ndarray objects without loading data into memory for low memory
reading of 3D NMRPipe data stream files (one file data sets).
* slicing operations return ndarray objects.
* can iterate over with expected results.
* transpose and swapaxes methods create a new objects with correct axes
ordering.
* has ndim, shape, and dtype attributes.
Parameters
----------
filename : str
Filename of 3D NMRPipe stream file.
order : tuple
Ordering of axes against file.
"""
def __init__(self, filename, order=(0, 1, 2)):
"""
Create and set up object
"""
# read and parse the NMRPipe header
fdata = get_fdata(filename) # get the header data
if fdata[2] - 2.345 > 1e-6: # check if byteswapping will be necessary
self.bswap = True
else:
self.bswap = False
dic = fdata2dic(fdata) # create the dictionary
fshape = list(find_shape(dic))
# check last axis quadrature
fn = "FDF" + str(int(dic["FDDIMORDER1"]))
if dic[fn + "QUADFLAG"] == 1.0:
self.cplex = False
self.dtype = np.dtype('float32')
else:
self.cplex = True
self.dtype = np.dtype('complex64')
fshape[2] = fshape[2] // 2
# finalize
self.filename = filename
self.order = order
self.fshape = tuple(fshape)
self.__setdimandshape__() # set ndim and shape attributes
def __fcopy__(self, order):
"""
Create a copy
"""
n = pipestream_3d(self.filename, order)
return n
def __fgetitem__(self, slices):
"""
Return ndarray of selected values
(sZ, sY, sX) is a well formatted tuple of slices
"""
sZ, sY, sX = slices
f = open(self.filename, 'rb') # open the file for reading
# determine which objects should be selected
lenZ, lenY, lenX = self.fshape
xch = range(lenX)[sX]
ych = range(lenY)[sY]
zch = range(lenZ)[sZ]
# create an empty array to store the selected slice
out = np.empty((len(zch), len(ych), len(xch)), dtype=self.dtype)
# read in the data trace by trace
for zi, z in enumerate(zch):
for yi, y in enumerate(ych):
ntrace = y + z * lenY
trace = get_trace(f, ntrace, lenX, self.bswap, self.cplex)
out[zi, yi] = trace[sX]
f.close()
return out
# There are three types of NMRPipe 4D files:
# 1) streams which are single file data sets made with xyz2pipe.
# 2) single index multiple file data sets, named test%03d.ft4, etc.
# 3) two index muttuple file data sets, named test%02d%03d.ft2, made with
# pipe2xyz and conversion binary.
# Low memory objects exist for all three, choose the correct one, or let read
# do it for you.
class pipe_4d(fileiobase.data_nd):
"""
Emulate a ndarray objects without loading data into memory for low memory
reading of single/two index 4D NMRPipe data files.
* slicing operations return ndarray objects.
* can iterate over with expected results.
* transpose and swapaxes methods create a new objects with correct axes
ordering.
* has ndim, shape, and dtype attributes.
Parameters
----------
filemask : str
Filename of 4D NMRPipe file with one or two formatter (%) operators.
order : tuple
Ordering of axes against file.
fcheck : bool, optional.
True to perform a basic check to see if all files expected for the data
set exist. Raises a IOError if files are missing. Default is False.
"""
def __init__(self, filemask, order=(0, 1, 2, 3), fcheck=False):
"""
Create and set up object, check that files exist if fcheck is True
"""
if filemask.count("%") == 1:
self.singleindex = True
filename = filemask % (1)
elif filemask.count("%") == 2:
self.singleindex = False
filename = filemask % (1, 1)
else:
raise ValueError("bad filemask")
# read and parse the NMRPipe header in the first file of the 3D
fdata = get_fdata(filename) # get the header data
if fdata[2] - 2.345 > 1e-6: # check if byteswapping will be necessary
self.bswap = True
else:
self.bswap = False
# find the shape of the first two dimensions
dic = fdata2dic(fdata) # create the dictionary
fshape = list(find_shape(dic))[-2:]
# find the length of the third dimension
f3 = "FDF" + str(int(dic["FDDIMORDER3"]))
quadrature_factor = [2, 1][int(dic[f3 + 'QUADFLAG'])]
if dic[f3 + 'QUADFLAG']:
lenZ = int(dic[f3 + 'FTSIZE'] * quadrature_factor)
else:
lenZ = int(dic[f3 + 'TDSIZE'] * quadrature_factor)
fshape.insert(0, lenZ) # insert as leading size of fshape
# find the length of the fourth dimension
f4 = "FDF" + str(int(dic["FDDIMORDER4"]))
quadrature_factor = [2, 1][int(dic[f4 + 'QUADFLAG'])]
if dic[f4 + 'QUADFLAG']:
lenA = int(dic[f4 + 'FTSIZE'] * quadrature_factor)
else:
lenA = int(dic[f4 + 'TDSIZE'] * quadrature_factor)
fshape.insert(0, lenA) # insert as leading size of fshape
# check that all files exist if fcheck is set
if fcheck:
for ai in range(1, lenA + 1):
for zi in range(1, lenZ + 1):
if self.singleindex:
fname = filemask % (ai * lenZ + zi + 1)
else:
fname = filemask % (ai + 1, zi + 1)
if os.path.exists(fname) is False:
raise IOError("File not found: " + str(fname))
# check last axis quadrature
fn = "FDF" + str(int(dic["FDDIMORDER1"]))
if dic[fn + "QUADFLAG"] == 1.0:
self.cplex = False
self.dtype = np.dtype('float32')
else:
self.cplex = True
self.dtype = np.dtype('complex64')
fshape[3] = fshape[3] // 2
# finalize
self.filemask = filemask
self.order = order
self.fshape = fshape
self.__setdimandshape__() # set ndim and shape attributes
def __fcopy__(self, order):
"""
Create a copy
"""
n = pipe_4d(self.filemask, order)
return n
def __fgetitem__(self, slices):
"""
Return ndarray of selected values
(sZ, sY, sX) is a well formatted tuple of slices
"""
sA, sZ, sY, sX = slices
# determine which objects should be selected
lenA, lenZ, lenY, lenX = self.fshape
xch = range(lenX)[sX]
ych = range(lenY)[sY]
zch = range(lenZ)[sZ]
ach = range(lenA)[sA]
# create an empty array to store the selected slice
out = np.empty((len(ach), len(zch), len(ych), len(xch)),
dtype=self.dtype)
# read in the data file by file, trace by trace
for ai, a in enumerate(ach):
for zi, z in enumerate(zch):
if self.singleindex: # single index
f = open(self.filemask % (a * lenZ + z + 1), 'rb')
else: # two index
f = open(self.filemask % (a + 1, z + 1), 'rb')
for yi, y in enumerate(ych):
ntrace = y
trace = get_trace(f, ntrace, lenX, self.bswap, self.cplex)
out[ai, zi, yi] = trace[sX]
f.close()
return out
class pipestream_4d(fileiobase.data_nd):
"""
Emulate a ndarray objects without loading data into memory for low memory
reading of 4D NMRPipe data streams (one file 4D data sets).
* slicing operations return ndarray objects.
* can iterate over with expected results.
* transpose and swapaxes methods create a new objects with correct axes
ordering.
* has ndim, shape, and dtype attributes.
Parameters
----------
filename : str
Filename of 4D NMRPipe stream file.
order : tuple
Ordering of axes against file.
"""
def __init__(self, filename, order=(0, 1, 2, 3)):
"""
Create and set up object
"""
# read and parse the NMRPipe header
fdata = get_fdata(filename) # get the header data
if fdata[2] - 2.345 > 1e-6: # check if byteswapping will be necessary
self.bswap = True
else:
self.bswap = False
dic = fdata2dic(fdata) # create the dictionary
fshape = list(find_shape(dic))
# set object attributes
self.filename = filename
self.order = order
# check last axis quadrature
fn = "FDF" + str(int(dic["FDDIMORDER1"]))
if dic[fn + "QUADFLAG"] == 1.0:
self.cplex = False
self.dtype | |
<gh_stars>0
# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from abc import ABCMeta, abstractmethod
import six
from six.moves import cPickle as pickle
import importlib
from pkg_resources import resource_filename
import os
from .validator import Validator
from .backend import Backend
@six.python_2_unicode_compatible
class ConfigPropertyObject(object):
def __init__(self, name, data=None, help_str=None, description=None):
"""
Args:
name(str): Name of the property object. Will be come the Key of the object when nested in a dict
data(dict): Dictionary of properties to initialize with
help_str(dict(str)): Dictionary of help strings that map to keys in data
description(str): A description of this instance
"""
if data:
if not isinstance(data, dict):
raise ValueError("'data' must be a dictionary of properties to add")
self.__dict__ = data
if help_str:
if not isinstance(data, dict):
raise ValueError("'help_str' must be a dictionary of help strings which correspond to 'data' keys")
self.__help_str = help_str
self.__object_name = name
self.__object_description = description
def __iter__(self):
for x in self.get_properties():
yield self.__dict__[x]
def __str__(self):
return self.__object_name
def add_property(self, prop_name, prop_value, help_text=None):
"""
Method to add a property
Args:
prop_name(str): name of the property
prop_value: property value. can be anything that can be a dictionary value
help_text(str): string of help information
Returns:
None
"""
self.__dict__[prop_name] = prop_value
if help_text:
self.__help_str[prop_name] = help_text
def add_property_object(self, prop_obj, help_text=None):
"""
Method to add a property
Args:
prop_obj(ConfigPropertyObject): The property object to add
help_text(str): String containing help information
Returns:
None
"""
self.__dict__[prop_obj.get_name()] = prop_obj
if help_text:
self.__help_str[prop_obj.get_name()] = help_text
def get_name(self):
"""Method to return the object name since we are mangling the object name so it doesn't get encoded"""
return self.__object_name
def get_description(self):
"""Method to return the object description since we are mangling the object name so it doesn't get encoded"""
return self.__object_description
def get_properties(self):
"""Method to return a list of property names contained in object
Returns:
(list(str)): List of property names
"""
props = []
for prop in [x for x in self.__dict__ if "__" not in x]:
props.append(prop)
return props
def get_help_str(self, property_name):
"""Method to return the help string for a specific property
Args:
property_name(str): The name of the property
Returns:
(str): Help string
"""
return self.__help_str[property_name]
def explain(self):
"""Method to print help information for this configuration object
Returns:
None
"""
print("\n\n### {} ###".format(self.__object_name))
if self.__object_description:
print(self.__object_description)
print("")
for prop in self.get_properties():
print(" - {}: {}".format(prop, self.get_help_str(prop)))
print("\n")
def to_dict(self):
"""Method to recursively encode as a dictionary."""
output = {}
for prop in [x for x in self.__dict__ if "__" not in x]:
if isinstance(self.__dict__[prop], ConfigPropertyObject):
output.update(self.__dict__[prop].to_dict())
else:
# An actual property
output[prop] = self.__dict__[prop]
return {self.__object_name: output}
@six.add_metaclass(ABCMeta)
class ConfigurationGenerator(object):
def __init__(self):
self.config = ConfigPropertyObject("ROOT")
self.name = "Base Config"
self.description = ""
# Setup the config
self.setup()
def load(self, file_path):
"""Method to pre-populate the class
Args:
file_path(str): Absolute path to the saved instance
Returns:
None
"""
with open(file_path, 'rb') as file_handle:
self.__dict__ = pickle.load(file_handle)
def save(self, file_path):
"""
Args:
file_path(str): Absolute path to the file for saving a copy of the instance
Returns:
None
"""
with open(file_path, 'wb') as file_handle:
if six.PY3:
pickle.dump(self.__dict__, file_handle, 2, fix_imports=True)
else:
pickle.dump(self.__dict__, file_handle, 2)
@abstractmethod
def setup(self):
"""Method to setup in instance by populating the correct data/property objects"""
raise NotImplemented
def to_json(self, file_path):
"""Method to serialize to json
Args:
file_path(str): Absolute path to the file for saving the instance as JSON
Returns:
None
"""
config_dict = {}
for obj in self.config:
config_dict.update(obj.to_dict())
with open(file_path, 'wt') as file_handle:
json.dump(config_dict, file_handle)
def explain(self):
"""Method to print help information for creating configuration
Returns:
None
"""
print("\n\n### {} ###".format(self.name))
if self.description:
print(self.description)
print("")
for prop in self.config:
print(" - {}: {}".format(prop.get_name(), prop.get_description()))
print("\n")
def add_property_object(self, prop_obj, help_text=None):
"""
Method to add a property
Args:
prop_obj(ConfigPropertyObject): The property object to add
help_text(str): String containing help information
Returns:
None
"""
if not isinstance(prop_obj, ConfigPropertyObject):
raise ValueError("Must add ConfigPropertyObject instance type")
self.config.add_property_object(prop_obj, help_text=help_text)
class BossConfigurationGenerator(ConfigurationGenerator):
def __init__(self):
ConfigurationGenerator.__init__(self)
self.name = "Boss Ingest v0.1"
self.description = "Configuration Generator for the Boss ingest service v0.1"
def setup(self):
"""Method to setup instance by populating the correct data/property objects"""
# Schema section
schema = ConfigPropertyObject("schema",
{"version": "0.1",
"name": "boss",
"validator": "BossValidatorV01"},
{"version": "Ingest service version number",
"name": "Ingest service type",
"validator": "The validator class to use to validate the schema"},
"Schema properties for validation"
)
# Client Section
client_backend = ConfigPropertyObject("backend",
{"name": "boss",
"class": "BossBackend",
"host": "api.theboss.io",
"protocol": "https"},
{"name": "the backend name",
"class": "the class to load for handling this backend",
"host": "the domain name for the ingest server",
"protocol": "https or http"},
"Properties for the backend service"
)
client_tile_processor = ConfigPropertyObject("tile_processor",
{"class": "",
"params": None},
{"class": "The name of the class to load for tile processing",
"params": "Custom properties in a dictionary"},
"Properties for the custom tile processor class"
)
client_file_processor = ConfigPropertyObject("file_processor",
{"class": "",
"params": None},
{"class": "The name of the class to load for file processing",
"params": "Custom properties in a dictionary"},
"Properties for the custom file processor class"
)
client = ConfigPropertyObject("client",
{"backend": client_backend,
"tile_processor": client_tile_processor,
"file_processor": client_file_processor},
{"backend": "Properties for the backend service",
"tile_processor": "Ingest service type",
"file_processor": "The validator class to use to validate the schema"},
"Ingest client properties"
)
database = ConfigPropertyObject("database",
{"collection": "",
"experiment": "",
"channel": ""},
{"collection": "The collection name containing the experiment and channel where data will be written",
"experiment": "The experiment name containing the channel where data will be written",
"channel": "The channel name where data will be written"},
"Properties describing where in the database data should be written"
)
# Ingest Job Section
ingest_job_extent = ConfigPropertyObject("extent",
{"x": [0, 1],
"y": [0, 1],
"z": [0, 1],
"t": [0, 1]},
{"x": "The spatial extent (in pixels) in the x-dimension. Python convention - start inclusive, stop exclusive",
"y": "The spatial extent (in pixels) in the y-dimension. Python convention - start inclusive, stop exclusive",
"z": "The spatial extent (in pixels) in the z-dimension. Python convention - start inclusive, stop exclusive",
"t": "The spatial extent (in pixels) in the t-dimension. Python convention - start inclusive, stop exclusive"},
"The spatial extent of the data to be uploaded. This does not have to be the entire dataset."
)
ingest_job_tile_size = ConfigPropertyObject("tile_size",
{"x": 4096,
"y": 4096,
"z": 1,
"t": 0},
{"x": "The size (in pixels) in the x-dimension of an individual image file",
"y": "The size (in pixels) in the y-dimension of an individual image file",
"z": "The size (in pixels) in the z-dimension of an individual image file",
"t": "The number of time samples in a single file"},
"The dimensions of the individual image data files that will be uploaded to the Boss"
)
ingest_job = ConfigPropertyObject("ingest_job",
{"resolution": 0,
"extent": ingest_job_extent,
"tile_size": ingest_job_tile_size},
{"extent": "The spatial extent of the data to be uploaded. This does not have to be the entire dataset.",
"resolution": "The resolution level to ingest data. Default is 0 which represents native resolution",
"tile_size": "The dimensions of the individual image data files that will be uploaded to the Boss"},
"The properties defining what part of the dataset will be ingested"
)
self.add_property_object(schema)
self.add_property_object(client)
self.add_property_object(database)
self.add_property_object(ingest_job)
class ConfigFileError(Exception):
"""Custom error to catch config file errors upstream in the client"""
pass
class Configuration(object):
def __init__(self, config_data=None):
"""
A class to store configuration information and parameters for an ingest job
Args:
config_data(dict): The configuration dictionary
"""
self.config_data = None
self.schema = None
self.tile_processor_class = None
self.path_processor_class = None
# If a configuration file was provided, load it now
if config_data:
self.load(config_data)
def load(self, config_data):
"""
Method to load the configuration file, the configuration schema, and select the correct validator | |
<reponame>subhylahiri/numpy_linalg_extras<filename>numpy_linalg/convert.py
# -*- coding: utf-8 -*-
"""Helpers for writing __array_ufunc__ and __array_function__ methods.
Routine Listings
----------------
Converters that process inputs/`out` parameter in an `__array_ufunc__` method:
conv_in_attr
Process inputs/`out` parameter using an attribute.
conv_in_view
Process inputs/`out` parameter using a view method.
Converters that process outputs from an `__array_ufunc__` method:
conv_out_attr
Process outputs using an attribute.
conv_out_init
Process outputs using a constructor.
conv_out_view
Process outputs using a view method.
Converters that take a callback function as a parameter:
conv_input
Process inputs to a `ufunc`.
conv_in_out
Process `out` argument of a `ufunc`.
conv_out
Process outputs from a `ufunc`.
Creators of callback functions to convert a single iput/output:
prepare_via_attr
Create a callback to process inputs using an attribute.
prepare_via_view
Create a callback to process inputs using a view method.
restore_via_attr
Create a callback to process an output using an attribute.
restore_via_init
Create a callback to process an output using a constructor.
restore_via_view
Create a callback to process an output using a view method.
Example
-------
```
import numpy_linalg.convert as cv
class MyClass():
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
'''Handling ufunce with MyClass
'''
args, _ = cv.conv_in_attr('attr', MyClass, inputs)
conv = [True] + [False] * (ufunc.nout-1)
outputs, conv = cv.conv_in_attr('attr', MyClass, kwargs, conv)
results = self.attr.__array_ufunc__(ufunc, method, *args, **kwargs)
return cv.conv_out_attr(self, 'attr', results, outputs, conv)
```
"""
from __future__ import annotations
import itertools as _itertools
import typing as _ty
import operator as _op
import numpy as _np
# =============================================================================
# Inputs
# =============================================================================
def conv_input(converter: Preparer[MyArray, BaseArray],
obj_typ: _ty.Type[MyArray],
args: ArgTuple[MyArray]
) -> _ty.Tuple[ArrayTuple[BaseArray], BoolList]:
"""Process inputs in an __array_ufunc__ method.
Parameters
----------
converter : Callable[MyArray -> ndarray]
Function to convert specified type to `ndarray`s.
obj_typ : Type[MyArray]
The type of object that needs converting.
args : Tuple[ndarray|MyArray, ...]
Tuple of inputs to ufunc (or ``out`` argument)
Returns
-------
out : Tuple[ndarray|MyArray, ...]
New tuple of inputs to ufunc (or ``out`` argument) with conversions.
conv : List[bool]
List of bools telling us if each input was converted.
"""
out = []
conv = []
for obj in args:
if isinstance(obj, obj_typ):
out.append(converter(obj))
conv.append(True)
else:
out.append(obj)
conv.append(False)
return tuple(out), conv
def conv_in_out(converter: Preparer[MyArray, BaseArray],
obj_typ: _ty.Type[MyArray],
kwds: ArgDict,
cv_out: BoolList) -> _ty.Tuple[OutTuple[BaseArray], BoolList]:
"""Process the out keyword in an __array_ufunc__ method.
Parameters
----------
converter : Callable[MyArray -> ndarray]
Function to convert specified type to `ndarray`s.
obj_typ : Type[MyArray]
The type of object that needs converting.
kwds : Dict[str, Any]
Dict of key word inputs to ufunc
cv_out : List[bool]
List of bools for converting outputs. Should have the correct length.
Returns
-------
out : Tuple[ndarray|None, ...]
New tuple of inputs to ufunc (or ``out`` argument) with conversions.
cv_out : List[bool]
List of bools telling us if each output was converted.
"""
outputs = kwds.pop('out', None)
if outputs:
if not isinstance(outputs, tuple):
outputs = (outputs,)
out_args, cv_out = conv_input(converter, obj_typ, outputs)
kwds['out'] = tuple(out_args)
else:
outputs = (None,) * len(cv_out)
return outputs, cv_out
def _conv_in(converter: Preparer[MyArray, BaseArray],
obj_typ: _ty.Type[MyArray],
tup: ArgsIn,
*cv_out) -> _ty.Tuple[OutTuple[BaseArray], BoolList]:
"""Call one of conv_input or conv_in_out"""
if isinstance(tup, (tuple, list)):
return conv_input(converter, obj_typ, tup)
return conv_in_out(converter, obj_typ, tup, *cv_out)
def prepare_via_view(std_array: _ty.Type[BaseArray] = _np.ndarray
) -> Preparer[MyArray, BaseArray]:
"""Create function to convert object to an array using view method.
Returns
-------
converter : Callable[MyArray -> ndarray]
Function to convert specified type to `ndarray`s.
"""
return _op.methodcaller('view', std_array)
def prepare_via_attr(attr: str) -> Preparer[MyArray, BaseArray]:
"""Create function to convert object to an array using an attribute.
Parameters
----------
attr: str
The name of the ``obj_typ`` attribute to use in place of class.
Returns
-------
converter : Callable[MyArray -> ndarray]
Function to convert specified type to `ndarray`s.
"""
return _op.attrgetter(attr)
def conv_in_view(obj_typ: _ty.Type[MyArray],
tup: ArgsIn[MyArray],
*cv_out) -> _ty.Tuple[OutTuple[_np.ndarray], BoolList]:
"""Process inputs in an __array_ufunc__ method using view method.
If the second argument is a tuple, we assume we are processing the ufunc's
inputs. If it is a dict, we are processing the `out` keyword.
Parameters
----------
obj_typ : Type[MyArray]
The type of object that needs converting via ``view`` method.
tup : Tuple[ndarray|MyArray, ...], Dict[str, Any]
Tuple of inputs to ufunc (or ``out`` argument)
Dict of key word inputs to ufunc
cv_out : Sequence[bool], optional
List of bools for converting outputs. Should have the correct length.
Returns
-------
out : Tuple[ndarray|None, ...]
New tuple of inputs to ufunc (or ``out`` argument) with conversions.
conv : List[bool]
List of bools telling us if each input was converted.
"""
return _conv_in(prepare_via_view(), obj_typ, tup, *cv_out)
def conv_in_attr(attr: str,
obj_typ: _ty.Type[MyArray],
tup: ArgsIn[MyArray],
*cv_out: bool) -> _ty.Tuple[OutTuple[BaseArray], BoolList]:
"""Process inputs in an __array_ufunc__ method using an attribute.
If the third argument is a tuple, we assume we are processing the ufunc's
inputs. If it is a dict, we are processing the `out` keyword.
Parameters
----------
attr : str, None
The name of the ``obj_typ`` attribute to use in place of class.
obj_typ : Type[MyArray]
The type of object that needs converting with its ``attr`` attribute.
tup : Tuple[ndarray|MyArray, ...], Dict[str, Any]
Tuple of inputs to ufunc (or ``out`` argument)
Dict of key word inputs to ufunc
cv_out : Sequence[bool], optional
List of bools for converting outputs. Should have the correct length.
Returns
-------
out : Tuple[ndarray|None]
New tuple of inputs to ufunc (or ``out`` argument) with conversions.
conv : List[bool]
List of bools telling us if each input was converted.
"""
return _conv_in(prepare_via_attr(attr), obj_typ, tup, *cv_out)
# ======================================================================
# Outputs
# ======================================================================
def conv_out(converter: Restorer[BaseArray, MyArray],
results: ArrayTuple[BaseArray],
outputs: OutTuple[BaseArray],
conv: _ty.Sequence[bool] = ()) -> ArgTuple[MyArray]:
"""Process outputs in an __array_ufunc__ method.
Parameters
----------
converter : Callable[ndarray -> MyArray]
Function to perform conversions back from `ndarray` to specified type.
results : Tuple[ndarray]
Tuple of outputs from ufunc
outputs : Tuple[ndarray|None]
``out`` argument of ufunc, or tuple of ``None``.
conv : Sequence[bool], default: ()
Sequence of bools telling us if each output should be converted.
Replaced with itertools.repeat(True) if bool(conv) == False (default)
Returns
-------
results : Tuple[ndarray|MyArray, ...]
New tuple of results from ufunc with conversions.
"""
if results is NotImplemented:
return NotImplemented
if not isinstance(results, tuple):
results = (results,)
if not outputs:
outputs = _itertools.repeat(None)
if not conv:
conv = _itertools.repeat(True)
results_out = []
for result, output, cout in zip(results, outputs, conv):
if output is not None:
results_out.append(output)
elif cout and isinstance(result, _np.ndarray):
results_out.append(converter(result))
else:
results_out.append(result)
if len(results_out) == 1:
return results_out[0]
return tuple(results_out)
def restore_via_attr(obj: MyArray, attr: str) -> Restorer[BaseArray, MyArray]:
"""Create function to convert arrays by setting obj.attr.
Parameters
----------
obj : MyArray
The template object for conversions.
attr: str, None
The name of the ``type(obj)`` attribute returned in place of class.
It will try to use ``obj.copy(attr=result)``. If that fails, it will
use ``obj.copy()`` followed by ``setattr(newobj, attr, result)``.
Returns
-------
converter : Callable[ndarray -> MyArray]
Function to perform conversions back from `ndarray` to specified type.
"""
def converter(thing: BaseArray) -> MyArray:
"""convert arrays by setting obj.attr
"""
try:
return obj.copy(**{attr: thing})
except TypeError:
pass
thing_out = obj.copy()
setattr(thing_out, attr, thing)
return thing_out
return converter
def restore_via_init(objt: _ty.Type[MyArray]) -> Restorer[BaseArray, MyArray]:
"""Create function to convert arrays using objt.__init__.
Parameters
----------
objt : Type[MyArray]
The type of object to converst to.
Returns
-------
converter : Callable[ndarray -> MyArray]
Function to perform conversions back from `ndarray` to specified type.
"""
return objt
def restore_via_view(objt: _ty.Type[MyArray]) -> Restorer[BaseArray, MyArray]:
"""Create function to convert arrays using array.view.
Parameters
----------
objt : Type[MyArray]
The type of object to converst to.
Returns
-------
converter : Callable[ndarray -> MyArray]
Function to perform conversions back from `ndarray` to specified type.
"""
return _op.methodcaller('view', objt)
def conv_out_attr(obj: MyArray,
attr: str,
results: ArrayTuple[BaseArray],
outputs: OutTuple[BaseArray],
conv: _ty.Sequence[bool] = ()) -> ArgTuple[MyArray]:
"""Process outputs in an __array_ufunc__ method using an attribute.
Makes a copy of ``obj`` with ``obj.attr = result``.
Parameters
----------
obj : MyArray
The template object for conversions.
attr : str
The name of the ``type(obj)`` attribute returned in place of class.
results : Tuple[ndarray]
Tuple of outputs from ufunc
outputs : Tuple[ndarray|None]
``out`` argument of ufunc, or tuple of ``None``.
conv : Sequence[bool], default: ()
Sequence of bools telling us if each output should be converted.
Converted to itertools.repeat(True) if bool(conv) == False | |
m.b3011 <= 0)
m.c1612 = Constraint(expr= m.x1611 - m.b3011 <= 0)
m.c1613 = Constraint(expr= m.x1612 - m.b3011 <= 0)
m.c1614 = Constraint(expr= m.x1613 - m.b3011 <= 0)
m.c1615 = Constraint(expr= m.x1614 - m.b3011 <= 0)
m.c1616 = Constraint(expr= m.x1615 - m.b3011 <= 0)
m.c1617 = Constraint(expr= m.x1616 - m.b3011 <= 0)
m.c1618 = Constraint(expr= m.x1617 - m.b3011 <= 0)
m.c1619 = Constraint(expr= m.x1618 - m.b3011 <= 0)
m.c1620 = Constraint(expr= m.x1619 - m.b3011 <= 0)
m.c1621 = Constraint(expr= m.x1620 - m.b3011 <= 0)
m.c1622 = Constraint(expr= m.x1621 - m.b3011 <= 0)
m.c1623 = Constraint(expr= m.x1622 - m.b3011 <= 0)
m.c1624 = Constraint(expr= m.x1623 - m.b3011 <= 0)
m.c1625 = Constraint(expr= m.x1624 - m.b3011 <= 0)
m.c1626 = Constraint(expr= m.x1625 - m.b3011 <= 0)
m.c1627 = Constraint(expr= m.x1626 - m.b3011 <= 0)
m.c1628 = Constraint(expr= m.x1627 - m.b3011 <= 0)
m.c1629 = Constraint(expr= m.x1628 - m.b3011 <= 0)
m.c1630 = Constraint(expr= m.x1629 - m.b3011 <= 0)
m.c1631 = Constraint(expr= m.x1630 - m.b3011 <= 0)
m.c1632 = Constraint(expr= m.x1631 - m.b3011 <= 0)
m.c1633 = Constraint(expr= m.x1632 - m.b3011 <= 0)
m.c1634 = Constraint(expr= m.x1633 - m.b3011 <= 0)
m.c1635 = Constraint(expr= m.x1634 - m.b3011 <= 0)
m.c1636 = Constraint(expr= m.x1635 - m.b3011 <= 0)
m.c1637 = Constraint(expr= m.x1636 - m.b3011 <= 0)
m.c1638 = Constraint(expr= m.x1637 - m.b3011 <= 0)
m.c1639 = Constraint(expr= m.x1638 - m.b3011 <= 0)
m.c1640 = Constraint(expr= m.x1639 - m.b3011 <= 0)
m.c1641 = Constraint(expr= m.x1640 - m.b3011 <= 0)
m.c1642 = Constraint(expr= m.x1641 - m.b3011 <= 0)
m.c1643 = Constraint(expr= m.x1642 - m.b3011 <= 0)
m.c1644 = Constraint(expr= m.x1643 - m.b3011 <= 0)
m.c1645 = Constraint(expr= m.x1644 - m.b3011 <= 0)
m.c1646 = Constraint(expr= m.x1645 - m.b3011 <= 0)
m.c1647 = Constraint(expr= m.x1646 - m.b3011 <= 0)
m.c1648 = Constraint(expr= m.x1647 - m.b3011 <= 0)
m.c1649 = Constraint(expr= m.x1648 - m.b3011 <= 0)
m.c1650 = Constraint(expr= m.x1649 - m.b3011 <= 0)
m.c1651 = Constraint(expr= m.x1650 - m.b3011 <= 0)
m.c1652 = Constraint(expr= m.x1651 - m.b3012 <= 0)
m.c1653 = Constraint(expr= m.x1652 - m.b3012 <= 0)
m.c1654 = Constraint(expr= m.x1653 - m.b3012 <= 0)
m.c1655 = Constraint(expr= m.x1654 - m.b3012 <= 0)
m.c1656 = Constraint(expr= m.x1655 - m.b3012 <= 0)
m.c1657 = Constraint(expr= m.x1656 - m.b3012 <= 0)
m.c1658 = Constraint(expr= m.x1657 - m.b3012 <= 0)
m.c1659 = Constraint(expr= m.x1658 - m.b3012 <= 0)
m.c1660 = Constraint(expr= m.x1659 - m.b3012 <= 0)
m.c1661 = Constraint(expr= m.x1660 - m.b3012 <= 0)
m.c1662 = Constraint(expr= m.x1661 - m.b3012 <= 0)
m.c1663 = Constraint(expr= m.x1662 - m.b3012 <= 0)
m.c1664 = Constraint(expr= m.x1663 - m.b3012 <= 0)
m.c1665 = Constraint(expr= m.x1664 - m.b3012 <= 0)
m.c1666 = Constraint(expr= m.x1665 - m.b3012 <= 0)
m.c1667 = Constraint(expr= m.x1666 - m.b3012 <= 0)
m.c1668 = Constraint(expr= m.x1667 - m.b3012 <= 0)
m.c1669 = Constraint(expr= m.x1668 - m.b3012 <= 0)
m.c1670 = Constraint(expr= m.x1669 - m.b3012 <= 0)
m.c1671 = Constraint(expr= m.x1670 - m.b3012 <= 0)
m.c1672 = Constraint(expr= m.x1671 - m.b3012 <= 0)
m.c1673 = Constraint(expr= m.x1672 - m.b3012 <= 0)
m.c1674 = Constraint(expr= m.x1673 - m.b3012 <= 0)
m.c1675 = Constraint(expr= m.x1674 - m.b3012 <= 0)
m.c1676 = Constraint(expr= m.x1675 - m.b3012 <= 0)
m.c1677 = Constraint(expr= m.x1676 - m.b3012 <= 0)
m.c1678 = Constraint(expr= m.x1677 - m.b3012 <= 0)
m.c1679 = Constraint(expr= m.x1678 - m.b3012 <= 0)
m.c1680 = Constraint(expr= m.x1679 - m.b3012 <= 0)
m.c1681 = Constraint(expr= m.x1680 - m.b3012 <= 0)
m.c1682 = Constraint(expr= m.x1681 - m.b3012 <= 0)
m.c1683 = Constraint(expr= m.x1682 - m.b3012 <= 0)
m.c1684 = Constraint(expr= m.x1683 - m.b3012 <= 0)
m.c1685 = Constraint(expr= m.x1684 - m.b3012 <= 0)
m.c1686 = Constraint(expr= m.x1685 - m.b3012 <= 0)
m.c1687 = Constraint(expr= m.x1686 - m.b3012 <= 0)
m.c1688 = Constraint(expr= m.x1687 - m.b3012 <= 0)
m.c1689 = Constraint(expr= m.x1688 - m.b3012 <= 0)
m.c1690 = Constraint(expr= m.x1689 - m.b3012 <= 0)
m.c1691 = Constraint(expr= m.x1690 - m.b3012 <= 0)
m.c1692 = Constraint(expr= m.x1691 - m.b3012 <= 0)
m.c1693 = Constraint(expr= m.x1692 - m.b3012 <= 0)
m.c1694 = Constraint(expr= m.x1693 - m.b3012 <= 0)
m.c1695 = Constraint(expr= m.x1694 - m.b3012 <= 0)
m.c1696 = Constraint(expr= m.x1695 - m.b3012 <= 0)
m.c1697 = Constraint(expr= m.x1696 - m.b3012 <= 0)
m.c1698 = Constraint(expr= m.x1697 - m.b3012 <= 0)
m.c1699 = Constraint(expr= m.x1698 - m.b3012 <= 0)
m.c1700 = Constraint(expr= m.x1699 - m.b3012 <= 0)
m.c1701 = Constraint(expr= m.x1700 - m.b3012 <= 0)
m.c1702 = Constraint(expr= m.x1701 - m.b3012 <= 0)
m.c1703 = Constraint(expr= m.x1702 - m.b3012 <= 0)
m.c1704 = Constraint(expr= m.x1703 - m.b3012 <= 0)
m.c1705 = Constraint(expr= m.x1704 - m.b3012 <= 0)
m.c1706 = Constraint(expr= m.x1705 - m.b3012 <= 0)
m.c1707 = Constraint(expr= m.x1706 - m.b3012 <= 0)
m.c1708 = Constraint(expr= m.x1707 - m.b3012 <= 0)
m.c1709 = Constraint(expr= m.x1708 - m.b3012 <= 0)
m.c1710 = Constraint(expr= m.x1709 - m.b3012 <= 0)
m.c1711 = Constraint(expr= m.x1710 - m.b3012 <= 0)
m.c1712 = Constraint(expr= m.x1711 - m.b3012 <= 0)
m.c1713 = Constraint(expr= m.x1712 - m.b3012 <= 0)
m.c1714 = Constraint(expr= m.x1713 - m.b3012 <= 0)
m.c1715 = Constraint(expr= m.x1714 - m.b3012 <= 0)
m.c1716 = Constraint(expr= m.x1715 - m.b3012 <= 0)
m.c1717 = Constraint(expr= m.x1716 - m.b3012 <= 0)
m.c1718 = Constraint(expr= m.x1717 - m.b3012 <= 0)
m.c1719 = Constraint(expr= m.x1718 - m.b3012 <= 0)
m.c1720 = Constraint(expr= m.x1719 - m.b3012 <= 0)
m.c1721 = Constraint(expr= m.x1720 - m.b3012 <= 0)
m.c1722 = Constraint(expr= m.x1721 - m.b3012 <= 0)
m.c1723 = Constraint(expr= m.x1722 - m.b3012 <= 0)
m.c1724 = Constraint(expr= m.x1723 - m.b3012 <= 0)
m.c1725 = Constraint(expr= m.x1724 - m.b3012 <= 0)
m.c1726 = Constraint(expr= m.x1725 - m.b3012 <= 0)
m.c1727 = Constraint(expr= m.x1726 - m.b3012 <= 0)
m.c1728 = Constraint(expr= m.x1727 - m.b3012 <= 0)
m.c1729 = Constraint(expr= m.x1728 - m.b3012 <= 0)
m.c1730 = Constraint(expr= m.x1729 - m.b3012 <= 0)
m.c1731 = Constraint(expr= m.x1730 - m.b3012 <= 0)
m.c1732 = Constraint(expr= m.x1731 - m.b3012 <= 0)
m.c1733 = Constraint(expr= m.x1732 - m.b3012 <= 0)
m.c1734 = Constraint(expr= m.x1733 - m.b3012 <= 0)
m.c1735 = Constraint(expr= m.x1734 - m.b3012 <= 0)
m.c1736 = Constraint(expr= m.x1735 - m.b3012 <= 0)
m.c1737 = Constraint(expr= m.x1736 - m.b3012 <= 0)
m.c1738 = Constraint(expr= m.x1737 - m.b3012 <= 0)
m.c1739 = Constraint(expr= m.x1738 - m.b3012 <= 0)
m.c1740 = Constraint(expr= m.x1739 - m.b3012 <= 0)
m.c1741 = Constraint(expr= m.x1740 - m.b3012 <= 0)
m.c1742 = Constraint(expr= m.x1741 - m.b3012 <= 0)
m.c1743 = Constraint(expr= m.x1742 - m.b3012 <= 0)
m.c1744 = Constraint(expr= m.x1743 - m.b3012 <= 0)
m.c1745 = Constraint(expr= m.x1744 - m.b3012 <= 0)
m.c1746 = Constraint(expr= m.x1745 - m.b3012 <= 0)
m.c1747 = Constraint(expr= m.x1746 - m.b3012 <= 0)
m.c1748 = Constraint(expr= m.x1747 - m.b3012 <= 0)
m.c1749 = Constraint(expr= m.x1748 - m.b3012 <= 0)
m.c1750 = Constraint(expr= m.x1749 - m.b3012 <= 0)
m.c1751 = Constraint(expr= m.x1750 - m.b3012 <= 0)
m.c1752 = Constraint(expr= m.x1751 - m.b3012 <= 0)
m.c1753 = Constraint(expr= m.x1752 - m.b3012 <= 0)
m.c1754 = Constraint(expr= m.x1753 - m.b3012 <= 0)
m.c1755 = Constraint(expr= m.x1754 - m.b3012 <= 0)
m.c1756 = Constraint(expr= m.x1755 - m.b3012 <= 0)
m.c1757 = Constraint(expr= m.x1756 - m.b3012 <= 0)
m.c1758 = Constraint(expr= m.x1757 - m.b3012 <= 0)
m.c1759 = Constraint(expr= m.x1758 - m.b3012 <= 0)
m.c1760 = Constraint(expr= m.x1759 - m.b3012 <= 0)
m.c1761 = Constraint(expr= m.x1760 - m.b3012 <= 0)
m.c1762 = Constraint(expr= m.x1761 - m.b3012 <= 0)
m.c1763 = Constraint(expr= m.x1762 - m.b3012 <= 0)
m.c1764 = Constraint(expr= m.x1763 - m.b3012 <= 0)
m.c1765 = Constraint(expr= m.x1764 - m.b3012 <= 0)
m.c1766 = Constraint(expr= m.x1765 - m.b3012 <= 0)
m.c1767 = Constraint(expr= m.x1766 - m.b3012 <= 0)
m.c1768 = Constraint(expr= m.x1767 - m.b3012 <= 0)
m.c1769 = Constraint(expr= m.x1768 - m.b3012 <= 0)
m.c1770 = Constraint(expr= m.x1769 - m.b3012 <= 0)
m.c1771 = Constraint(expr= m.x1770 - m.b3012 <= 0)
m.c1772 = Constraint(expr= m.x1771 - m.b3012 <= 0)
m.c1773 = Constraint(expr= m.x1772 - m.b3012 <= 0)
m.c1774 = Constraint(expr= m.x1773 - m.b3012 <= 0)
m.c1775 = Constraint(expr= m.x1774 - m.b3012 <= 0)
m.c1776 = Constraint(expr= m.x1775 - m.b3012 <= 0)
m.c1777 = Constraint(expr= m.x1776 - m.b3012 <= 0)
m.c1778 = Constraint(expr= m.x1777 - m.b3012 <= 0)
m.c1779 = Constraint(expr= m.x1778 - m.b3012 <= 0)
m.c1780 = Constraint(expr= m.x1779 - m.b3012 <= 0)
m.c1781 = Constraint(expr= m.x1780 - m.b3012 <= 0)
m.c1782 = Constraint(expr= m.x1781 - m.b3012 <= 0)
m.c1783 = Constraint(expr= m.x1782 - m.b3012 <= 0)
m.c1784 = Constraint(expr= m.x1783 - m.b3012 <= 0)
m.c1785 = Constraint(expr= m.x1784 - m.b3012 <= 0)
m.c1786 = Constraint(expr= m.x1785 - m.b3012 <= 0)
m.c1787 = Constraint(expr= m.x1786 - m.b3012 <= 0)
m.c1788 = Constraint(expr= m.x1787 - m.b3012 <= 0)
m.c1789 = Constraint(expr= m.x1788 - m.b3012 <= 0)
m.c1790 = Constraint(expr= m.x1789 - m.b3012 <= 0)
m.c1791 = Constraint(expr= m.x1790 - m.b3012 <= 0)
m.c1792 = Constraint(expr= m.x1791 - m.b3012 <= 0)
m.c1793 = Constraint(expr= m.x1792 - m.b3012 <= 0)
m.c1794 = Constraint(expr= m.x1793 | |
sage: p.order_of_rauzy_action('bottom', 'left')
3
"""
winner = interval_conversion(winner)
side = side_conversion(side)
if side == -1:
return self.length(winner) - self._twin[winner][-1] - 1
elif side == 0:
return self._twin[winner][0]
def erase_marked_points(self):
r"""
Returns a permutation equivalent to self but without marked points.
EXAMPLES::
sage: a = iet.Permutation('a b1 b2 c d', 'd c b1 b2 a')
sage: a.erase_marked_points()
a b1 c d
d c b1 a
"""
res = copy(self)
l = res.list()
left_corner = ((l[1][0], l[0][0]), 'L')
right_corner = ((l[0][-1], l[1][-1]), 'R')
s = res.separatrix_diagram(side=True)
lengths = [len(_) for _ in s]
while 2 in lengths:
if lengths == [2]:
return res
i = lengths.index(2)
t = s[i]
if t[0] == left_corner or t[0] == right_corner:
letter = t[1][0]
else:
letter = t[0][0]
res = res.erase_letter(letter)
l = res.list()
s = res.separatrix_diagram(side=True)
lengths = [len(_) for _ in s]
return res
def is_hyperelliptic(self):
r"""
Returns True if the permutation is in the class of the symmetric
permutations (with eventual marked points).
This is equivalent to say that the suspension lives in an hyperelliptic
stratum of Abelian differentials H_hyp(2g-2) or H_hyp(g-1, g-1) with
some marked points.
EXAMPLES::
sage: iet.Permutation('a b c d','d c b a').is_hyperelliptic()
True
sage: iet.Permutation('0 1 2 3 4 5','5 2 1 4 3 0').is_hyperelliptic()
False
REFERENCES:
<NAME>, "Echanges d'intervalles et transformations induites",
Acta Arith. 34, no. 3, 203-212, 1980
<NAME>, <NAME> "Connected components of the moduli space
of Abelian differentials with prescripebd singularities" Invent. math.
153, 631-678 (2003)
"""
test = self.erase_marked_points()
n = test.length_top()
cylindric = test.cylindric()
return cylindric._twin[0] == range(n-1,-1,-1)
def cylindric(self):
r"""
Returns a permutation in the Rauzy class such that
twin[0][-1] == 0
twin[1][-1] == 0
TESTS::
sage: p = iet.Permutation('a b c','c b a')
sage: p.cylindric() == p
True
sage: p = iet.Permutation('a b c d','b d a c')
sage: q = p.cylindric()
sage: q[0][0] == q[1][-1]
True
sage: q[1][0] == q[1][0]
True
"""
tmp = copy(self)
n = self.length(0)
a0 = tmp._twin[0][-1]
a1 = tmp._twin[1][-1]
p_min = min(a0,a1)
while p_min > 0:
if p_min == a0:
k_min = min(tmp._twin[1][a0+1:])
k = n - tmp._twin[1].index(k_min) - 1
tmp = tmp.rauzy_move(0, iteration=k)
else:
k_min = min(tmp._twin[0][a1+1:])
k = n - tmp._twin[0].index(k_min) - 1
tmp = tmp.rauzy_move(1, iteration=k)
a0 = tmp._twin[0][-1]
a1 = tmp._twin[1][-1]
p_min = min(a0,a1)
if a0 == 0:
k = n - tmp._twin[1].index(0) - 1
tmp = tmp.rauzy_move(0, iteration = k)
else:
k = n - tmp._twin[0].index(0) - 1
tmp = tmp.rauzy_move(1, iteration=k)
return tmp
def is_cylindric(self):
r"""
Returns True if the permutation is Rauzy_1n.
A permutation is cylindric if 1 and n are exchanged.
EXAMPLES::
sage: iet.Permutation('1 2 3','3 2 1').is_cylindric()
True
sage: iet.Permutation('1 2 3','2 1 3').is_cylindric()
False
"""
return self._twin[0][-1] == 0 and self._twin[1][-1] == 0
def to_permutation(self):
r"""
Returns the permutation as an element of the symmetric group.
EXAMPLES::
sage: p = iet.Permutation('a b c','c b a')
sage: p.to_permutation()
[3, 2, 1]
::
sage: p = Permutation([2,4,1,3])
sage: q = iet.Permutation(p)
sage: q.to_permutation() == p
True
"""
from sage.combinat.permutation import Permutation
return Permutation([x+1 for x in self._twin[1]])
class PermutationLI(Permutation):
r"""
Template for quadratic permutation.
.. WARNING::
Internal class! Do not use directly!
AUTHOR:
- <NAME> (2008-12-20): initial version
"""
def _init_twin(self,a):
r"""
Initialization of the twin data.
TEST::
sage: p = iet.GeneralizedPermutation('a a','b b',reduced=True) #indirect doctest
sage: p._twin
[[(0, 1), (0, 0)], [(1, 1), (1, 0)]]
"""
# creation of the twin
self._twin = [[],[]]
l = [[(0,j) for j in range(len(a[0]))],[(1,j) for j in range(len(a[1]))]]
for i in range(2) :
for j in range(len(l[i])) :
if l[i][j] == (i,j) :
if a[i][j] in a[i][j+1:] :
# two up or two down
j2 = (a[i][j+1:]).index(a[i][j]) + j + 1
l[i][j] = (i,j2)
l[i][j2] = (i,j)
else :
# one up, one down (here i=0)
j2 = a[1].index(a[i][j])
l[0][j] = (1,j2)
l[1][j2] = (0,j)
self._twin[0] = l[0]
self._twin[1] = l[1]
def _init_alphabet(self, intervals) :
r"""
Intialization procedure of the alphabet of self from intervals list
TEST::
sage: p = iet.GeneralizedPermutation('a a','b b') #indirect doctest
sage: p.alphabet()
{'a', 'b'}
"""
tmp_alphabet = []
for letter in intervals[0] + intervals[1] :
if letter not in tmp_alphabet :
tmp_alphabet.append(letter)
self._alphabet = Alphabet(tmp_alphabet)
def is_irreducible(self, return_decomposition=False):
r"""
Test of reducibility
A quadratic (or generalized) permutation is *reducible* if there exists
a decomposition
.. math::
A1 u B1 | ... | B1 u A2
A1 u B2 | ... | B2 u A2
where no corners is empty, or exactly one corner is empty
and it is on the left, or two and they are both on the
right or on the left. The definition is due to [BL08]_ where they prove
that the property of being irreducible is stable under Rauzy induction.
INPUT:
- ``return_decomposition`` - boolean (default: False) - if True, and
the permutation is reducible, returns also the blocs A1 u B1, B1 u
A2, A1 u B2 and B2 u A2 of a decomposition as above.
OUTPUT:
If return_decomposition is True, returns a 2-uple
(test,decomposition) where test is the preceding test and
decomposition is a 4-uple (A11,A12,A21,A22) where:
A11 = A1 u B1
A12 = B1 u A2
A21 = A1 u B2
A22 = B2 u A2
EXAMPLES::
sage: GP = iet.GeneralizedPermutation
sage: GP('a a','b b').is_irreducible()
False
sage: GP('a a b','b c c').is_irreducible()
True
sage: GP('1 2 3 4 5 1','5 6 6 4 3 2').is_irreducible()
True
TESTS:
Test reducible permutations with no empty corner::
sage: GP('1 4 1 3','4 2 3 2').is_irreducible(True)
(False, (['1', '4'], ['1', '3'], ['4', '2'], ['3', '2']))
Test reducible permutations with one left corner empty::
sage: GP('1 2 2 3 1','4 4 3').is_irreducible(True)
(False, (['1'], ['3', '1'], [], ['3']))
sage: GP('4 4 3','1 2 2 3 1').is_irreducible(True)
(False, ([], ['3'], ['1'], ['3', '1']))
Test reducible permutations with two left corners empty::
sage: GP('1 1 2 3','4 2 4 3').is_irreducible(True)
(False, ([], ['3'], [], ['3']))
Test reducible permutations with two right corners empty::
sage: GP('1 2 2 3 3','1 4 4').is_irreducible(True)
(False, (['1'], [], ['1'], []))
sage: GP('1 2 2','1 3 3').is_irreducible(True)
(False, (['1'], [], ['1'], []))
sage: GP('1 2 3 3','2 1 4 4 5 5').is_irreducible(True)
(False, (['1', '2'], [], ['2', '1'], []))
AUTHORS:
- <NAME> (2008-12-20)
"""
l0 = self.length_top()
l1 = self.length_bottom()
s0,s1 = self.list()
# testing two corners empty on the right (i12 = i22 = 0)
A11, A21, A12, A22 = [],[],[],[]
for i11 in range(1, l0):
if s0[i11-1] in A11:
break
A11 = s0[:i11]
for i21 in range(1, l1):
if s1[i21-1] in A21:
break
A21 = s1[:i21]
if sorted(A11) == sorted(A21):
if return_decomposition:
return False,(A11,A12,A21,A22)
return False
A21 = []
# testing no corner empty but one or two on the left
A11, A12, A21, A22 = [], [], [], []
for i11 in range(0, l0):
if i11 > 0 and s0[i11-1] in A11:
break
A11 = s0[:i11]
for i21 in xrange(0, l1) :
if i21 > 0 and s1[i21-1] in A21:
break
A21 = s1[:i21]
for i12 in xrange(l0 - 1, i11 - 1, -1) :
if s0[i12] in A12 or s0[i12] in A21:
break
A12 = s0[i12:]
for i22 in xrange(l1 - 1, i21 - 1, -1) :
if s1[i22] in A22 or s1[i22] in A11:
break
A22 = s1[i22:]
if sorted(A11 + A22) == sorted(A12 + A21) :
if return_decomposition :
return False, (A11,A12,A21,A22)
return False
A22 = []
A12 = []
A21 = []
if return_decomposition:
return True, ()
return True
def has_right_rauzy_move(self, winner):
r"""
Test of Rauzy movability (with an eventual specified choice of winner)
A quadratic (or generalized) permutation is rauzy_movable type
depending on the possible length of the last interval. It's
dependent of the length equation.
INPUT:
- ``winner`` - the integer 'top' or 'bottom'
EXAMPLES::
sage: p = iet.GeneralizedPermutation('a a','b b')
sage: p.has_right_rauzy_move('top')
False
sage: p.has_right_rauzy_move('bottom')
False
::
sage: p = iet.GeneralizedPermutation('a | |
# -*- coding: utf-8 -*-
'''
CRISPResso2 - <NAME> and <NAME> 2018
Software pipeline for the analysis of genome editing outcomes from deep sequencing data
(c) 2018 The General Hospital Corporation. All Rights Reserved.
'''
import os
from copy import deepcopy
import sys
import argparse
import re
import traceback
import json
from CRISPResso2 import CRISPRessoShared
from CRISPResso2 import CRISPRessoPlot
from CRISPResso2 import CRISPRessoMultiProcessing
from CRISPResso2 import CRISPRessoReport
running_python3 = False
if sys.version_info > (3, 0):
running_python3 = True
if running_python3:
import pickle as cp #python 3
else:
import cPickle as cp #python 2.7
import logging
logging.basicConfig(level=logging.INFO,
format='%(levelname)-5s @ %(asctime)s:\n\t %(message)s \n',
datefmt='%a, %d %b %Y %H:%M:%S',
stream=sys.stderr,
filemode="w"
)
error = logging.critical
warn = logging.warning
debug = logging.debug
info = logging.info
_ROOT = os.path.abspath(os.path.dirname(__file__))
####Support functions###
def propagate_options(cmd,options,params,paramInd):
####
# cmd - the command to run
# options - list of options to propagate e.g. crispresso options
# params - df from excel parser e.g. params['amplicon_name'] = ['name1','name2','name3'] where each item corresponds to a different run in the batch
# paramInd - index in dict - this is the run number in the batch
for option in options :
if option:
if option in params:
val = params.loc[paramInd,option]
if val is None:
pass
elif str(val) == "True":
cmd+=' --%s' % option
elif str(val) =="False":
pass
elif type(val)==str:
if val != "":
if " " in val or "-" in val:
cmd+=' --%s "%s"' % (option,str(val)) # quotes for options with spaces
else:
cmd+=' --%s %s' % (option,str(val))
elif type(val)==bool:
if val:
cmd+=' --%s' % option
else:
cmd+=' --%s %s' % (option,str(val))
# print("cmd is " + str(cmd))
return cmd
def check_library(library_name):
try:
return __import__(library_name)
except:
error('You need to install %s module to use CRISPRessoMeta!' % library_name)
sys.exit(1)
pd=check_library('pandas')
np=check_library('numpy')
def main():
try:
description = ['~~~CRISPRessoMeta~~~','-Analysis of CRISPR/Cas9 outcomes from deep sequencing data using a metadata file-']
meta_string = r'''
________________________________________
| _________ ______ _______ ______ |
| | | | | | \ | | | | | | | | |
| | | | | | | | |---- | | | |__| | |
| |_| |_| |_| |_|____ |_| |_| |_| |
|________________________________________|
'''
print(CRISPRessoShared.get_crispresso_header(description,meta_string))
parser = CRISPRessoShared.getCRISPRessoArgParser(parserTitle = 'CRISPRessoMeta Parameters')
#batch specific params
parser.add_argument('--metadata', type=str, help='Metadata file according to NIST specification',required=True)
parser.add_argument('-mo','--meta_output_folder', help='Directory where analysis output will be stored')
parser.add_argument('-p','--n_processes',type=int, help='Specify the number of processes to use for quantification.\
Please use with caution since increasing this parameter will increase the memory required to run CRISPResso.',default=1)
parser.add_argument('--crispresso_command', help='CRISPResso command to call',default='CRISPResso')
args = parser.parse_args()
debug_flag = args.debug
crispresso_options = CRISPRessoShared.get_crispresso_options()
options_to_ignore = set(['name','output_folder'])
crispresso_options_for_meta = list(crispresso_options-options_to_ignore)
CRISPRessoShared.check_file(args.metadata)
meta_params = pd.DataFrame(columns=['name','guide_seq','amplicon_seq'])
with open(args.metadata) as metadata_file:
metadata = json.load(metadata_file)
exp = metadata['Experiment']
for guide in data['Experiment']:
print('Guide: ' + guide['name'])
print('Sequence: ' + guide['sequence'])
print('Amplicon: ' + guide['amplicon'])
print('Fastq_R1: ' + guide['fastq_r1'])
print('Fastq_R2: ' + guide['fastq_r2'])
meta_params.append({'name':guide['name'],'guide_seq':guide['sequence'],'amplicon_seq':guide['amplicon'],'fastq_r1':guide['fastq_r1'],'fastq_r2':guide['fastq_r2']})
print('table:')
print(meta_params)
#rename column "a" to "amplicon_seq", etc
meta_params.rename(index=str,columns=CRISPRessoShared.get_crispresso_options_lookup(),inplace=True)
meta_count = meta_params.shape[0]
meta_params.index = range(meta_count)
if 'fastq_r1' not in meta_params:
raise CRISPRessoShared.BadParameterException("fastq_r1 must be specified in the meta settings file. Current headings are: "
+ str(meta_params.columns.values))
#add args from the command line to meta_params
for arg in vars(args):
if arg not in meta_params:
meta_params[arg] = getattr(args,arg)
else:
if (getattr(args,arg) is not None):
meta_params[arg].fillna(value=getattr(args,arg), inplace=True)
#assert that all names are unique
#and clean names
for i in range(meta_count):
if meta_params.loc[i,'name'] == '':
meta_params.at[i,'name'] = i
meta_params.at[i,'name'] = CRISPRessoShared.clean_filename(meta_params.loc[i,'name'])
if meta_params.drop_duplicates('name').shape[0] != meta_params.shape[0]:
raise CRISPRessoShared.BadParameterException('Sample input names must be unique. The given names are not unique: ' + str(meta_params.loc[:,'name']))
quantification_window_center = -3 #default value
if args.quantification_window_center is not None:
quantification_window_center = args.quantification_window_center
plot_window_size = 20 #default value
if args.plot_window_size is not None:
plot_window_size = args.plot_window_size
#Check files
meta_params["sgRNA_intervals"] = '' #create empty array for sgRNA intervals
meta_params["sgRNA_intervals"] = meta_params["sgRNA_intervals"].apply(list)
meta_params["cut_point_include_idx"] = '' #create empty array for cut point intervals for each batch based on sgRNA
meta_params["cut_point_include_idx"] = meta_params["cut_point_include_idx"].apply(list)
for idx,row in meta_params.iterrows():
if row.fastq_r1 is None:
raise CRISPRessoShared.BadParameterException("At least one fastq file must be given as a command line parameter or be specified in the meta settings file with the heading 'fastq_r1' (fastq_r1 on row %s '%s' is invalid)"%(int(idx)+1,row.fastq_r1))
CRISPRessoShared.check_file(row.fastq_r1)
if row.fastq_r2 != "":
CRISPRessoShared.check_file(row.fastq_r2)
if args.auto:
continue
curr_amplicon_seq_str = row.amplicon_seq
if curr_amplicon_seq_str is None:
raise CRISPRessoShared.BadParameterException("Amplicon sequence must be given as a command line parameter or be specified in the meta settings file with the heading 'amplicon_seq' (Amplicon seq on row %s '%s' is invalid)"%(int(idx)+1,curr_amplicon_seq_str))
guides_are_in_amplicon = {} #dict of whether a guide is in at least one amplicon sequence
#iterate through amplicons
for curr_amplicon_seq in curr_amplicon_seq_str.split(','):
this_include_idxs=[] #mask for bp to include for this amplicon seq, as specified by sgRNA cut points
this_sgRNA_intervals = []
wrong_nt=CRISPRessoShared.find_wrong_nt(curr_amplicon_seq)
if wrong_nt:
raise CRISPRessoShared.NTException('The amplicon sequence in row %d (%s) contains incorrect characters:%s' % (idx+1,curr_amplicon_seq_str,' '.join(wrong_nt)))
#iterate through guides
curr_guide_seq_string = row.guide_seq
if curr_guide_seq_string is not None and curr_guide_seq_string != "":
guides = curr_guide_seq_string.strip().upper().split(',')
for curr_guide_seq in guides:
wrong_nt=CRISPRessoShared.find_wrong_nt(curr_guide_seq)
if wrong_nt:
raise CRISPRessoShared.NTException('The sgRNA sequence in row %d (%s) contains incorrect characters:%s' % (idx+1,curr_guide_seq, ' '.join(wrong_nt)))
(this_sgRNA_sequences, this_sgRNA_intervals, this_cut_points, this_include_idxs,
this_exclude_idxs, this_plot_idxs) = CRISPRessoShared.get_amplicon_info_for_guides(curr_amplicon_seq,guides,row.quantification_window_center,
row.quantification_window_size,row.quantification_window_coordinates,row.exclude_bp_from_left,row.exclude_bp_from_right,row.plot_window_size)
for guide_seq in this_sgRNA_sequences:
guides_are_in_amplicon[guide_seq] = 1
meta_params.ix[idx,"cut_point_include_idx"].append(this_include_idxs)
meta_params.ix[idx,"sgRNA_intervals"].append(this_sgRNA_intervals)
for guide_seq in guides_are_in_amplicon:
if guides_are_in_amplicon[guide_seq] != 1:
warn('\nThe guide sequence provided on row %d (%s) is not present in any amplicon sequence:%s! \nNOTE: The guide will be ignored for the analysis. Please check your input!' % (idx+1,row.guide_seq,curr_amplicon_seq))
meta_folder_name = os.path.splitext(os.path.basename(args.metadata))[0]
if args.name and args.name != "":
meta_folder_name = args.name
output_folder_name='CRISPRessoMeta_on_%s' % meta_folder_name
OUTPUT_DIRECTORY=os.path.abspath(output_folder_name)
if args.meta_output_folder:
OUTPUT_DIRECTORY=os.path.join(os.path.abspath(args.meta_output_folder),output_folder_name)
_jp=lambda filename: os.path.join(OUTPUT_DIRECTORY,filename) #handy function to put a file in the output directory
try:
info('Creating Folder %s' % OUTPUT_DIRECTORY)
os.makedirs(OUTPUT_DIRECTORY)
except:
warn('Folder %s already exists.' % OUTPUT_DIRECTORY)
log_filename=_jp('CRISPRessoMeta_RUNNING_LOG.txt')
logging.getLogger().addHandler(logging.FileHandler(log_filename))
with open(log_filename,'w+') as outfile:
outfile.write('[Command used]:\n%s\n\n[Execution log]:\n' % ' '.join(sys.argv))
crispresso2Meta_info_file = os.path.join(OUTPUT_DIRECTORY,'CRISPResso2Meta_info.pickle')
crispresso2_info = {} #keep track of all information for this run to be pickled and saved at the end of the run
crispresso2_info['version'] = CRISPRessoShared.__version__
crispresso2_info['args'] = deepcopy(args)
crispresso2_info['log_filename'] = os.path.basename(log_filename)
crispresso_cmds = []
meta_names_arr = []
meta_input_names = {}
for idx,row in meta_params.iterrows():
metaName = CRISPRessoShared.slugify(row["name"])
meta_names_arr.append(metaName)
meta_input_names[metaName] = row["name"]
crispresso_cmd= args.crispresso_command + ' -o %s --name %s' % (OUTPUT_DIRECTORY,metaName)
crispresso_cmd=propagate_options(crispresso_cmd,crispresso_options_for_meta,meta_params,idx)
crispresso_cmds.append(crispresso_cmd)
crispresso2_info['meta_names_arr'] = meta_names_arr
crispresso2_info['meta_input_names'] = meta_input_names
CRISPRessoMultiProcessing.run_crispresso_cmds(crispresso_cmds,args.n_processes,'meta',args.skip_failed)
run_datas = [] #crispresso2 info from each row
all_amplicons = set()
amplicon_names = {}
amplicon_counts = {}
completed_meta_arr = []
for idx,row in meta_params.iterrows():
metaName = CRISPRessoShared.slugify(row["name"])
folder_name = os.path.join(OUTPUT_DIRECTORY,'CRISPResso_on_%s' % metaName)
run_data_file = os.path.join(folder_name,'CRISPResso2_info.pickle')
if os.path.isfile(run_data_file) is False:
info("Skipping folder '%s'. Cannot find run data at '%s'."%(folder_name,run_data_file))
run_datas.append(None)
continue
run_data = cp.load(open(run_data_file,'rb'))
run_datas.append(run_data)
for ref_name in run_data['ref_names']:
ref_seq = run_data['refs'][ref_name]['sequence']
all_amplicons.add(ref_seq)
#if this amplicon is called something else in another sample, just call it the amplicon
if ref_name in amplicon_names and amplicon_names[ref_seq] != ref_name:
amplicon_names[ref_seq] = ref_seq
else:
amplicon_names[ref_seq] = ref_name
if ref_seq not in amplicon_counts:
amplicon_counts[ref_seq] = 0
amplicon_counts[ref_seq]+= 1
completed_meta_arr.append(metaName)
crispresso2_info['completed_meta_arr'] = completed_meta_arr
#make sure amplicon names aren't super long
for amplicon in all_amplicons:
if len(amplicon_names[amplicon]) > 20:
amplicon_names[amplicon] = amplicon_names[amplicon][0:20]
#make sure no duplicate names (same name for the different amplicons)
seen_names = {}
for amplicon in all_amplicons:
suffix_counter = 2
while amplicon_names[amplicon] in seen_names:
amplicon_names[amplicon] = amplicon_names[amplicon]+"_"+str(suffix_counter)
suffix_counter += 1
seen_names[amplicon_names[amplicon]] = 1
save_png = True
if args.suppress_report:
save_png = False
#summarize amplicon modifications
with open(_jp('CRISPRessoBatch_quantification_of_editing_frequency.txt'),'w') as outfile:
wrote_header = False
for idx,row in meta_params.iterrows():
metaName = CRISPRessoShared.slugify(row["name"])
folder_name = os.path.join(OUTPUT_DIRECTORY,'CRISPResso_on_%s' % metaName)
run_data = run_datas[idx]
if run_data is None:
continue
amplicon_modification_file=os.path.join(folder_name,run_data['quant_of_editing_freq_filename'])
with open(amplicon_modification_file,'r') as infile:
file_head = infile.readline()
if not wrote_header:
outfile.write('Batch\t' + file_head)
wrote_header = True
for line in infile:
outfile.write(metaName + "\t" + line)
#summarize alignment
with open(_jp('CRISPRessoBatch_mapping_statistics.txt'),'w') as outfile:
wrote_header = False
for idx,row in meta_params.iterrows():
metaName = CRISPRessoShared.slugify(row["name"])
folder_name = os.path.join(OUTPUT_DIRECTORY,'CRISPResso_on_%s' % metaName)
run_data = run_datas[idx]
if run_data is None:
continue
amplicon_modification_file=os.path.join(folder_name,run_data['mapping_stats_filename'])
with open(amplicon_modification_file,'r') as infile:
file_head = infile.readline()
if not wrote_header:
outfile.write('Batch\t' + file_head)
wrote_header = True
for line in infile:
outfile.write(metaName + "\t" + line)
if not args.suppress_report:
if (args.place_report_in_output_folder):
report_name = _jp("CRISPResso2Meta_report.html")
else:
report_name = OUTPUT_DIRECTORY+'.html'
CRISPRessoReport.make_meta_report_from_folder(report_name,crispresso2_info,OUTPUT_DIRECTORY,_ROOT)
crispresso2_info['report_location'] = report_name
crispresso2_info['report_filename'] = os.path.basename(report_name)
cp.dump(crispresso2_info, open(crispresso2Meta_info_file, 'wb' ) )
info('Analysis Complete!')
print(CRISPRessoShared.get_crispresso_footer())
sys.exit(0)
except Exception as e:
debug_flag = False
if 'args' in vars() | |
lines[1].split()
vals.append(vals.pop(0))
del vals[-1]
# If chosen, apply initial reference for the protein backbone restraints
if (stage == 'fe' and comp != 'c' and comp != 'w' and comp != 'f'):
if (bb_equil == 'yes'):
shutil.copy('../../../../equil/'+pose+'/assign.dat', './assign-eq.dat')
else:
shutil.copy('./assign.dat', './assign-eq.dat')
with open('./assign-eq.dat') as fin:
lines = (line.rstrip() for line in fin)
lines = list(line for line in lines if line) # Non-blank lines in a list
valse = lines[1].split()
valse.append(valse.pop(0))
del valse[-1]
# Define spring constants based on stage and weight
if stage == 'equil':
if bb_equil == 'yes':
rdhf = rest[0]
else:
rdhf = 0
rdsf = rest[1]
ldf = weight*rest[2]/100
laf = weight*rest[3]/100
ldhf = weight*rest[4]/100
rcom = rest[5]
elif comp == 'l' or comp == 'c':
rdhf = rest[0]
rdsf = rest[1]
ldf = 0
laf = 0
ldhf = weight*rest[4]/100
rcom = rest[5]
elif comp == 'a' or comp == 'r':
rdhf = weight*rest[0]/100
rdsf = weight*rest[1]/100
ldf = 0
laf = 0
ldhf = 0
rcom = rest[5]
elif comp == 't':
rdhf = rest[0]
rdsf = rest[1]
ldf = weight*rest[2]/100
laf = weight*rest[3]/100
ldhf = rest[4]
rcom = rest[5]
elif comp == 'v' or comp == 'e' or comp == 'w' or comp == 'f':
rdhf = rest[0]
rdsf = rest[1]
ldf = rest[2]
laf = rest[3]
ldhf = rest[4]
rcom = rest[5]
lcom = rest[6]
# Write AMBER restraint file for the full system
if (comp != 'c' and comp != 'r' and comp != 'w' and comp != 'f'):
disang_file = open('disang.rest', 'w')
disang_file.write('%s %s %s %s %s %s %s %s %s \n'%('# Anchor atoms', P1, P2, P3, L1, L2, L3, 'stage = '+stage, 'weight = '+str(weight)))
for i in range(0, len(rst)):
data = rst[i].split()
# Protein conformation (P1-P3 distance restraints)
if i < 3:
if (stage != 'equil'):
if len(data) == 2:
nums = str(atm_num.index(data[0]))+','+str(atm_num.index(data[1]))+','
disang_file.write('%s %-23s '%('&rst iat=', nums))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(0.0), float(valse[i]), float(valse[i]), float(999.0), rdsf, rdsf, recep_c))
else:
if len(data) == 2:
nums = str(atm_num.index(data[0]))+','+str(atm_num.index(data[1]))+','
disang_file.write('%s %-23s '%('&rst iat=', nums))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(0.0), float(vals[i]), float(vals[i]), float(999.0), rdsf, rdsf, recep_c))
# Protein conformation (backbone restraints)
elif i >= 3 and i < 3+nd:
if (stage != 'equil'):
if len(data) == 4:
nums = str(atm_num.index(data[0]))+','+str(atm_num.index(data[1]))+','+str(atm_num.index(data[2]))+','+str(atm_num.index(data[3]))+','
disang_file.write('%s %-23s '%('&rst iat=', nums))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(valse[i]) - 180, float(valse[i]), float(valse[i]), float(valse[i]) + 180 , rdhf, rdhf, recep_d))
else:
if len(data) == 4:
nums = str(atm_num.index(data[0]))+','+str(atm_num.index(data[1]))+','+str(atm_num.index(data[2]))+','+str(atm_num.index(data[3]))+','
disang_file.write('%s %-23s '%('&rst iat=', nums))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(vals[i]) - 180, float(vals[i]), float(vals[i]), float(vals[i]) + 180 , rdhf, rdhf, recep_d))
# Ligand translational/rotational restraints
elif i >= 3+nd and i < 9+nd and comp != 'a':
if len(data) == 2:
nums = str(atm_num.index(data[0]))+','+str(atm_num.index(data[1]))+','
disang_file.write('%s %-23s '%('&rst iat=', nums))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(0.0), float(vals[i]), float(vals[i]), float(999.0), ldf, ldf, lign_tr))
elif len(data) == 3:
nums = str(atm_num.index(data[0]))+','+str(atm_num.index(data[1]))+','+str(atm_num.index(data[2]))+','
disang_file.write('%s %-23s '%('&rst iat=', nums))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(0.0), float(vals[i]), float(vals[i]), float(180.0), laf, laf, lign_tr))
elif len(data) == 4:
nums = str(atm_num.index(data[0]))+','+str(atm_num.index(data[1]))+','+str(atm_num.index(data[2]))+','+str(atm_num.index(data[3]))+','
disang_file.write('%s %-23s '%('&rst iat=', nums))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(vals[i]) - 180, float(vals[i]), float(vals[i]), float(vals[i]) + 180, laf, laf, lign_tr))
if comp == 'e':
if i == (3+nd):
nums2 = str(atm_num.index(data[0]))+','+str(atm_num.index(data[1])+vac_atoms)+','
disang_file.write('%s %-23s '%('&rst iat=', nums2))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(0.0), float(vals[i]), float(vals[i]), float(999.0), ldf, ldf, lign_tr))
if i == (4+nd):
nums2 = str(atm_num.index(data[0]))+','+str(atm_num.index(data[1]))+','+str(atm_num.index(data[2])+vac_atoms)+','
disang_file.write('%s %-23s '%('&rst iat=', nums2))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(0.0), float(vals[i]), float(vals[i]), float(180.0), laf, laf, lign_tr))
if i == (5+nd):
nums2 = str(atm_num.index(data[0]))+','+str(atm_num.index(data[1]))+','+str(atm_num.index(data[2]))+','+str(atm_num.index(data[3])+vac_atoms)+','
disang_file.write('%s %-23s '%('&rst iat=', nums2))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(vals[i]) - 180, float(vals[i]), float(vals[i]), float(vals[i]) + 180, laf, laf, lign_tr))
if i == (6+nd):
nums2 = str(atm_num.index(data[0]))+','+str(atm_num.index(data[1])+vac_atoms)+','+str(atm_num.index(data[2])+vac_atoms)+','
disang_file.write('%s %-23s '%('&rst iat=', nums2))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(0.0), float(vals[i]), float(vals[i]), float(180.0), laf, laf, lign_tr))
if i == (7+nd):
nums2 = str(atm_num.index(data[0]))+','+str(atm_num.index(data[1]))+','+str(atm_num.index(data[2])+vac_atoms)+','+str(atm_num.index(data[3])+vac_atoms)+','
disang_file.write('%s %-23s '%('&rst iat=', nums2))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(vals[i]) - 180, float(vals[i]), float(vals[i]), float(vals[i]) + 180, laf, laf, lign_tr))
if i == (8+nd):
nums2 = str(atm_num.index(data[0]))+','+str(atm_num.index(data[1])+vac_atoms)+','+str(atm_num.index(data[2])+vac_atoms)+','+str(atm_num.index(data[3])+vac_atoms)+','
disang_file.write('%s %-23s '%('&rst iat=', nums2))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(vals[i]) - 180, float(vals[i]), float(vals[i]), float(vals[i]) + 180, laf, laf, lign_tr))
# Ligand conformation (non-hydrogen dihedrals)
elif i >= 9+nd and comp != 'a':
if len(data) == 4:
nums = str(atm_num.index(data[0]))+','+str(atm_num.index(data[1]))+','+str(atm_num.index(data[2]))+','+str(atm_num.index(data[3]))+','
disang_file.write('%s %-23s '%('&rst iat=', nums))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(vals[i]) - 180, float(vals[i]), float(vals[i]), float(vals[i]) + 180, ldhf, ldhf, lign_d))
if comp == 'v' and dec_method == 'sdr':
nums2 = str(atm_num.index(data[0])+vac_atoms)+','+str(atm_num.index(data[1])+vac_atoms)+','+str(atm_num.index(data[2])+vac_atoms)+','+str(atm_num.index(data[3])+vac_atoms)+','
disang_file.write('%s %-23s '%('&rst iat=', nums2))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(vals[i]) - 180, float(vals[i]), float(vals[i]), float(vals[i]) + 180, ldhf, ldhf, lign_d))
if comp == 'e':
nums2 = str(atm_num.index(data[0])+vac_atoms)+','+str(atm_num.index(data[1])+vac_atoms)+','+str(atm_num.index(data[2])+vac_atoms)+','+str(atm_num.index(data[3])+vac_atoms)+','
disang_file.write('%s %-23s '%('&rst iat=', nums2))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(vals[i]) - 180, float(vals[i]), float(vals[i]), float(vals[i]) + 180, ldhf, ldhf, lign_d))
if (dec_method == 'sdr'):
nums3 = str(atm_num.index(data[0])+2*vac_atoms)+','+str(atm_num.index(data[1])+2*vac_atoms)+','+str(atm_num.index(data[2])+2*vac_atoms)+','+str(atm_num.index(data[3])+2*vac_atoms)+','
disang_file.write('%s %-23s '%('&rst iat=', nums3))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(vals[i]) - 180, float(vals[i]), float(vals[i]), float(vals[i]) + 180, ldhf, ldhf, lign_d))
nums4 = str(atm_num.index(data[0])+3*vac_atoms)+','+str(atm_num.index(data[1])+3*vac_atoms)+','+str(atm_num.index(data[2])+3*vac_atoms)+','+str(atm_num.index(data[3])+3*vac_atoms)+','
disang_file.write('%s %-23s '%('&rst iat=', nums4))
disang_file.write('r1= %10.4f, r2= %10.4f, r3= %10.4f, r4= %10.4f, rk2= %11.7f, rk3= %11.7f, &end %s \n' % (float(vals[i]) - 180, float(vals[i]), float(vals[i]), float(vals[i]) + 180, ldhf, ldhf, lign_d))
# COM restraints
cv_file = open('cv.in', 'w')
cv_file.write('cv_file \n')
cv_file.write('&colvar \n')
cv_file.write(' cv_type = \'COM_DISTANCE\' \n')
cv_file.write(' cv_ni = %s, cv_i = 1,0,' % str(len(hvy_h)+2))
for i in range(0, len(hvy_h)):
cv_file.write(hvy_h[i])
cv_file.write(',')
cv_file.write('\n')
cv_file.write(' anchor_position = %10.4f, %10.4f, %10.4f, %10.4f \n' % (float(0.0), float(0.0), float(0.0), float(999.0)))
cv_file.write(' anchor_strength = %10.4f, %10.4f, \n' % (rcom, rcom))
cv_file.write('/ \n')
if dec_method == 'sdr':
if comp == 'e' or comp == 'v':
cv_file.write('&colvar \n')
cv_file.write(' cv_type = \'COM_DISTANCE\' \n')
cv_file.write(' cv_ni = %s, cv_i = 2,0,' % str(len(hvy_g)+2))
for i in range(0, len(hvy_g)):
cv_file.write(hvy_g[i])
cv_file.write(',')
cv_file.write('\n')
cv_file.write(' anchor_position = %10.4f, %10.4f, %10.4f, %10.4f \n' % (float(0.0), float(0.0), float(0.0), float(999.0)))
cv_file.write(' anchor_strength = %10.4f, %10.4f, \n' % (lcom, lcom))
cv_file.write('/ \n')
cv_file.close()
# Analysis of simulations
if (comp != 'l' and comp != 'a'):
restraints_file = open('restraints.in', 'w')
restraints_file.write('%s %s %s %s %s %s %s %s \n'%('# Anchor atoms', P1, P2, P3, L1, L2, L3, 'stage = '+stage))
restraints_file.write('noexitonerror\n')
restraints_file.write('parm vac.prmtop\n')
for i in range(2,11):
restraints_file.write('trajin md%02.0f.nc\n' % i)
for i in range(3+nd, 9+nd):
arr = rst[i].split()
if len(arr) == 2:
restraints_file.write('%s %s %s'%('distance d'+str(i), rst[i], 'noimage out restraints.dat\n'))
if len(arr) == 3:
restraints_file.write('%s %s %s'%('angle a'+str(i), rst[i], 'out restraints.dat\n'))
if len(arr) == 4:
restraints_file.write('%s %s %s'%('dihedral a'+str(i), rst[i], 'out restraints.dat\n'))
elif (comp == 'a'):
restraints_file = open('restraints.in', 'w')
restraints_file.write('%s %s %s %s %s %s %s %s \n'%('# Anchor atoms', P1, P2, | |
m.x614 + m.x628 - m.x656 + m.x712 + m.x726 - m.x754 + m.x810 + m.x824 - m.x852 + m.x908
+ m.x922 - m.x950 + m.x1006 + m.x1020 - m.x1048 + m.x1104 + m.x1118 - m.x1146 + m.x1202
+ m.x1216 - m.x1244 + m.x1300 + m.x1314 - m.x1342 <= 100)
m.c3981 = Constraint(expr= m.x615 + m.x629 - m.x657 + m.x713 + m.x727 - m.x755 + m.x811 + m.x825 - m.x853 + m.x909
+ m.x923 - m.x951 + m.x1007 + m.x1021 - m.x1049 + m.x1105 + m.x1119 - m.x1147 + m.x1203
+ m.x1217 - m.x1245 + m.x1301 + m.x1315 - m.x1343 <= 100)
m.c3982 = Constraint(expr= m.x616 + m.x630 - m.x658 + m.x714 + m.x728 - m.x756 + m.x812 + m.x826 - m.x854 + m.x910
+ m.x924 - m.x952 + m.x1008 + m.x1022 - m.x1050 + m.x1106 + m.x1120 - m.x1148 + m.x1204
+ m.x1218 - m.x1246 + m.x1302 + m.x1316 - m.x1344 <= 70)
m.c3983 = Constraint(expr= m.x617 + m.x631 - m.x659 + m.x715 + m.x729 - m.x757 + m.x813 + m.x827 - m.x855 + m.x911
+ m.x925 - m.x953 + m.x1009 + m.x1023 - m.x1051 + m.x1107 + m.x1121 - m.x1149 + m.x1205
+ m.x1219 - m.x1247 + m.x1303 + m.x1317 - m.x1345 <= 100)
m.c3984 = Constraint(expr= 12*m.b16 + 12*m.b19 - m.x128 - m.x131 + m.x338 + m.x341 <= 12)
m.c3985 = Constraint(expr= 12*m.b16 + 12*m.b20 - m.x128 - m.x132 + m.x338 + m.x342 <= 12)
m.c3986 = Constraint(expr= 12*m.b17 + 12*m.b21 - m.x129 - m.x133 + m.x339 + m.x343 <= 12)
m.c3987 = Constraint(expr= 12*m.b17 + 12*m.b22 - m.x129 - m.x134 + m.x339 + m.x344 <= 12)
m.c3988 = Constraint(expr= 12*m.b17 + 12*m.b23 - m.x129 - m.x135 + m.x339 + m.x345 <= 12)
m.c3989 = Constraint(expr= 12*m.b18 + 12*m.b24 - m.x130 - m.x136 + m.x340 + m.x346 <= 12)
m.c3990 = Constraint(expr= 12*m.b18 + 12*m.b25 - m.x130 - m.x137 + m.x340 + m.x347 <= 12)
m.c3991 = Constraint(expr= 12*m.b19 + 12*m.b26 - m.x131 - m.x138 + m.x341 + m.x348 <= 12)
m.c3992 = Constraint(expr= 12*m.b21 + 12*m.b26 - m.x133 - m.x138 + m.x343 + m.x348 <= 12)
m.c3993 = Constraint(expr= 12*m.b23 + 12*m.b29 - m.x135 - m.x141 + m.x345 + m.x351 <= 12)
m.c3994 = Constraint(expr= 12*m.b25 + 12*m.b29 - m.x137 - m.x141 + m.x347 + m.x351 <= 12)
m.c3995 = Constraint(expr= 12*m.b26 + 12*m.b27 - m.x138 - m.x139 + m.x348 + m.x349 <= 12)
m.c3996 = Constraint(expr= 12*m.b28 + 12*m.b29 - m.x140 - m.x141 + m.x350 + m.x351 <= 12)
m.c3997 = Constraint(expr= 12*m.b16 + 12*m.b17 + 12*m.b18 - m.x128 - m.x129 - m.x130 + m.x338 + m.x339 + m.x340 <= 12)
m.c3998 = Constraint(expr= 12*m.b20 + 12*m.b27 + 12*m.b28 - m.x132 - m.x139 - m.x140 + m.x342 + m.x349 + m.x350 <= 12)
m.c3999 = Constraint(expr= 12*m.b22 + 12*m.b27 + 12*m.b28 - m.x134 - m.x139 - m.x140 + m.x344 + m.x349 + m.x350 <= 12)
m.c4000 = Constraint(expr= 12*m.b24 + 12*m.b27 + 12*m.b28 - m.x136 - m.x139 - m.x140 + m.x346 + m.x349 + m.x350 <= 12)
m.c4001 = Constraint(expr= 12*m.b30 + 12*m.b33 - m.x142 - m.x145 + m.x240 + m.x243 + m.x338 + m.x341 <= 12)
m.c4002 = Constraint(expr= 12*m.b30 + 12*m.b34 - m.x142 - m.x146 + m.x240 + m.x244 + m.x338 + m.x342 <= 12)
m.c4003 = Constraint(expr= 12*m.b31 + 12*m.b35 - m.x143 - m.x147 + m.x241 + m.x245 + m.x339 + m.x343 <= 12)
m.c4004 = Constraint(expr= 12*m.b31 + 12*m.b36 - m.x143 - m.x148 + m.x241 + m.x246 + m.x339 + m.x344 <= 12)
m.c4005 = Constraint(expr= 12*m.b31 + 12*m.b37 - m.x143 - m.x149 + m.x241 + m.x247 + m.x339 + m.x345 <= 12)
m.c4006 = Constraint(expr= 12*m.b32 + 12*m.b38 - m.x144 - m.x150 + m.x242 + m.x248 + m.x340 + m.x346 <= 12)
m.c4007 = Constraint(expr= 12*m.b32 + 12*m.b39 - m.x144 - m.x151 + m.x242 + m.x249 + m.x340 + m.x347 <= 12)
m.c4008 = Constraint(expr= 12*m.b33 + 12*m.b40 - m.x145 - m.x152 + m.x243 + m.x250 + m.x341 + m.x348 <= 12)
m.c4009 = Constraint(expr= 12*m.b35 + 12*m.b40 - m.x147 - m.x152 + m.x245 + m.x250 + m.x343 + m.x348 <= 12)
m.c4010 = Constraint(expr= 12*m.b37 + 12*m.b43 - m.x149 - m.x155 + m.x247 + m.x253 + m.x345 + m.x351 <= 12)
m.c4011 = Constraint(expr= 12*m.b39 + 12*m.b43 - m.x151 - m.x155 + m.x249 + m.x253 + m.x347 + m.x351 <= 12)
m.c4012 = Constraint(expr= 12*m.b40 + 12*m.b41 - m.x152 - m.x153 + m.x250 + m.x251 + m.x348 + m.x349 <= 12)
m.c4013 = Constraint(expr= 12*m.b42 + 12*m.b43 - m.x154 - m.x155 + m.x252 + m.x253 + m.x350 + m.x351 <= 12)
m.c4014 = Constraint(expr= 12*m.b30 + 12*m.b31 + 12*m.b32 - m.x142 - m.x143 - m.x144 + m.x240 + m.x241 + m.x242
+ m.x338 + m.x339 + m.x340 <= 12)
m.c4015 = Constraint(expr= 12*m.b34 + 12*m.b41 + 12*m.b42 - m.x146 - m.x153 - m.x154 + m.x244 + m.x251 + m.x252
+ m.x342 + m.x349 + m.x350 <= 12)
m.c4016 = Constraint(expr= 12*m.b36 + 12*m.b41 + 12*m.b42 - m.x148 - m.x153 - m.x154 + m.x246 + m.x251 + m.x252
+ m.x344 + m.x349 + m.x350 <= 12)
m.c4017 = Constraint(expr= 12*m.b38 + 12*m.b41 + 12*m.b42 - m.x150 - m.x153 - m.x154 + m.x248 + m.x251 + m.x252
+ m.x346 + m.x349 + m.x350 <= 12)
m.c4018 = Constraint(expr= 12*m.b44 + 12*m.b47 - m.x156 - m.x159 + m.x240 + m.x243 + m.x254 + m.x257 + m.x338 + m.x341
<= 12)
m.c4019 = Constraint(expr= 12*m.b44 + 12*m.b48 - m.x156 - m.x160 + m.x240 + m.x244 + m.x254 + m.x258 + m.x338 + m.x342
<= 12)
m.c4020 = Constraint(expr= 12*m.b45 + 12*m.b49 - m.x157 - m.x161 + m.x241 + m.x245 + m.x255 + m.x259 + m.x339 + m.x343
<= 12)
m.c4021 = Constraint(expr= 12*m.b45 + 12*m.b50 - m.x157 - m.x162 + m.x241 + m.x246 + m.x255 + m.x260 + m.x339 + m.x344
<= 12)
m.c4022 = Constraint(expr= 12*m.b45 + 12*m.b51 - m.x157 - m.x163 + m.x241 + m.x247 + m.x255 + m.x261 + m.x339 + m.x345
<= 12)
m.c4023 = Constraint(expr= 12*m.b46 + 12*m.b52 - m.x158 - m.x164 + m.x242 + m.x248 + m.x256 + m.x262 + m.x340 + m.x346
<= 12)
m.c4024 = Constraint(expr= 12*m.b46 + 12*m.b53 - m.x158 - m.x165 + m.x242 + m.x249 + m.x256 + m.x263 + m.x340 + m.x347
<= 12)
m.c4025 = Constraint(expr= 12*m.b47 + 12*m.b54 - m.x159 - m.x166 + m.x243 + m.x250 + m.x257 + m.x264 + m.x341 + m.x348
<= 12)
m.c4026 = Constraint(expr= 12*m.b49 + 12*m.b54 - m.x161 - m.x166 + m.x245 + m.x250 + m.x259 + m.x264 + m.x343 + m.x348
<= 12)
m.c4027 = Constraint(expr= 12*m.b51 + 12*m.b57 - m.x163 - m.x169 + m.x247 + m.x253 + m.x261 + m.x267 + m.x345 + m.x351
<= 12)
m.c4028 = Constraint(expr= 12*m.b53 + 12*m.b57 - m.x165 - m.x169 + m.x249 + m.x253 + m.x263 + m.x267 + m.x347 + m.x351
<= 12)
m.c4029 = Constraint(expr= 12*m.b54 + 12*m.b55 - m.x166 - m.x167 + m.x250 + m.x251 + m.x264 + m.x265 + m.x348 + m.x349
<= 12)
m.c4030 = Constraint(expr= 12*m.b56 + 12*m.b57 - m.x168 - m.x169 + m.x252 + m.x253 + m.x266 + m.x267 + m.x350 + m.x351
<= 12)
m.c4031 = Constraint(expr= 12*m.b44 + 12*m.b45 + 12*m.b46 - m.x156 - m.x157 - m.x158 + m.x240 + m.x241 + m.x242
+ m.x254 + m.x255 + m.x256 + m.x338 + m.x339 + m.x340 <= 12)
m.c4032 = Constraint(expr= 12*m.b48 + 12*m.b55 + 12*m.b56 - m.x160 - m.x167 - m.x168 + m.x244 + m.x251 + m.x252
+ m.x258 + m.x265 + m.x266 + m.x342 + m.x349 + m.x350 <= 12)
m.c4033 = Constraint(expr= 12*m.b50 + 12*m.b55 + 12*m.b56 - m.x162 - m.x167 - m.x168 + m.x246 + m.x251 + m.x252
+ m.x260 + m.x265 + m.x266 + m.x344 + m.x349 + m.x350 <= 12)
m.c4034 = Constraint(expr= 12*m.b52 + 12*m.b55 + 12*m.b56 - m.x164 - m.x167 - m.x168 + m.x248 + m.x251 + m.x252
+ m.x262 + m.x265 + m.x266 + m.x346 + m.x349 + m.x350 <= 12)
m.c4035 = Constraint(expr= 12*m.b58 + 12*m.b61 - m.x170 - m.x173 + m.x240 + m.x243 | |
start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = QuietTestResultHandler(test_count=1)
result = TestResult.from_test_case(
case, TestCompletionStatus.skipped, expected_duration,
message='reason')
# When
handler(result)
# Then
output = stderr.getvalue()
self.assertEqual(output, '')
@patch('sys.stderr', new_callable=StringIO)
def test_no_output_on_expected_fail(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = QuietTestResultHandler(test_count=1)
with self.exc_info(RuntimeError) as exc_info:
result = TestResult.from_test_case(
case, TestCompletionStatus.expected_failure, expected_duration,
exception=exc_info)
# When
handler(result)
# Then
output = stderr.getvalue()
self.assertEqual(output, '')
@patch('sys.stderr', new_callable=StringIO)
def test_no_output_on_unexpected_success(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = QuietTestResultHandler(test_count=1)
result = TestResult.from_test_case(
case, TestCompletionStatus.unexpected_success, expected_duration)
# When
handler(result)
# Then
output = stderr.getvalue()
self.assertEqual(output, '')
@patch('sys.stderr', new_callable=StringIO)
def test_no_output_with_error_on_stop_test_run(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = QuietTestResultHandler(test_count=1)
handler.start_test_run()
with self.exc_info(RuntimeError) as exc_info:
result = TestResult.from_test_case(
case, TestCompletionStatus.error, expected_duration,
exception=exc_info)
# When
handler(result)
handler.stop_test_run()
# Then
output = stderr.getvalue().replace('\n', '')
description = handler.get_test_description(
case,).replace('(', r'\(').replace(')', r'\)')
self.assertRegexpMatches(
output, '{0}.*?Traceback.*?RuntimeError'.format(
description))
@patch('sys.stderr', new_callable=StringIO)
def test_no_output_with_failure_on_stop_test_run(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = QuietTestResultHandler(test_count=1)
handler.start_test_run()
with self.failure_exc_info() as exc_info:
result = TestResult.from_test_case(
case, TestCompletionStatus.failure, expected_duration,
exception=exc_info)
# When
handler(result)
handler.stop_test_run()
# Then
output = stderr.getvalue().replace('\n', '')
description = handler.get_test_description(
case,).replace('(', r'\(').replace(')', r'\)').replace('\n', '')
self.assertRegexpMatches(
output, '{0}.*?Traceback.*?AssertionError'.format(
description))
# The contents of unittest.TestCase should not be in the traceback
self.assertNotIn('raise', output)
class TestStandardResultHandler(ExcInfoFixture, unittest.TestCase):
@patch('sys.stderr', new_callable=StringIO)
def test_no_output_start_test_run(self, stderr):
# Given
handler = StandardTestResultHandler(test_count=1)
# When
handler.start_test_run()
# Then
output = stderr.getvalue()
self.assertEqual(output, '')
@patch('sys.stderr', new_callable=StringIO)
def test_output_stop_test_run(self, stderr):
# Given
handler = StandardTestResultHandler(test_count=1)
handler.start_test_run()
# When
handler.stop_test_run()
# Then
output = stderr.getvalue()
self.assertTrue(output.startswith('\n' + handler.separator2))
self.assertTrue(output.endswith('OK\n'))
self.assertRegexpMatches(
output.replace('\n', ''), r'--+.*?Ran 0 tests.*?OK')
@patch('sys.stderr', new_callable=StringIO)
def test_no_output_start_test(self, stderr):
# Given
handler = StandardTestResultHandler(test_count=1)
case = _test_cases.TestCase('test_method')
# When
handler.start_test(case)
# Then
output = stderr.getvalue()
self.assertEqual(output, '')
@patch('sys.stderr', new_callable=StringIO)
def test_no_output_stop_test(self, stderr):
# Given
handler = StandardTestResultHandler(test_count=1)
case = _test_cases.TestCase('test_method')
# When
handler.stop_test(case)
# Then
output = stderr.getvalue()
self.assertEqual(output, '')
@patch('sys.stderr', new_callable=StringIO)
def test_no_output_on_error(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = StandardTestResultHandler(test_count=1)
with self.exc_info(RuntimeError) as exc_info:
result = TestResult.from_test_case(
case, TestCompletionStatus.error, expected_duration,
exception=exc_info)
# When
handler(result)
# Then
output = stderr.getvalue()
self.assertEqual(output, 'E')
@patch('sys.stderr', new_callable=StringIO)
def test_no_output_on_failure(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = StandardTestResultHandler(test_count=1)
with self.failure_exc_info() as exc_info:
result = TestResult.from_test_case(
case, TestCompletionStatus.failure, expected_duration,
exception=exc_info)
# When
handler(result)
# Then
output = stderr.getvalue()
self.assertEqual(output, 'F')
@patch('sys.stderr', new_callable=StringIO)
def test_no_output_on_success(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = StandardTestResultHandler(test_count=1)
result = TestResult.from_test_case(
case, TestCompletionStatus.success, expected_duration)
# When
handler(result)
# Then
output = stderr.getvalue()
self.assertEqual(output, '.')
@patch('sys.stderr', new_callable=StringIO)
def test_no_output_on_skip(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = StandardTestResultHandler(test_count=1)
result = TestResult.from_test_case(
case, TestCompletionStatus.skipped, expected_duration,
message='reason')
# When
handler(result)
# Then
output = stderr.getvalue()
self.assertEqual(output, 's')
@patch('sys.stderr', new_callable=StringIO)
def test_no_output_on_expected_fail(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = StandardTestResultHandler(test_count=1)
with self.exc_info(RuntimeError) as exc_info:
result = TestResult.from_test_case(
case, TestCompletionStatus.expected_failure, expected_duration,
exception=exc_info)
# When
handler(result)
# Then
output = stderr.getvalue()
self.assertEqual(output, 'x')
@patch('sys.stderr', new_callable=StringIO)
def test_no_output_on_unexpected_success(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = StandardTestResultHandler(test_count=1)
result = TestResult.from_test_case(
case, TestCompletionStatus.unexpected_success, expected_duration)
# When
handler(result)
# Then
output = stderr.getvalue()
self.assertEqual(output, 'u')
@patch('sys.stderr', new_callable=StringIO)
def test_no_output_with_error_on_stop_test_run(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = StandardTestResultHandler(test_count=1)
handler.start_test_run()
with self.exc_info(RuntimeError) as exc_info:
result = TestResult.from_test_case(
case, TestCompletionStatus.error, expected_duration,
exception=exc_info)
# When
handler(result)
handler.stop_test_run()
# Then
output = stderr.getvalue().replace('\n', '')
description = handler.get_test_description(
case).replace('(', r'\(').replace(')', r'\)')
self.assertRegexpMatches(
output, '{0}.*?Traceback.*?RuntimeError'.format(
description))
@patch('sys.stderr', new_callable=StringIO)
def test_no_output_with_failure_on_stop_test_run(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = StandardTestResultHandler(test_count=1)
handler.start_test_run()
with self.failure_exc_info() as exc_info:
result = TestResult.from_test_case(
case, TestCompletionStatus.failure, expected_duration,
exception=exc_info)
# When
handler(result)
handler.stop_test_run()
# Then
output = stderr.getvalue().replace('\n', '')
description = handler.get_test_description(
case).replace('(', r'\(').replace(')', r'\)').replace('\n', '')
self.assertRegexpMatches(
output, '{0}.*?Traceback.*?AssertionError'.format(
description))
# The contents of unittest.TestCase should not be in the traceback
self.assertNotIn('raise', output)
class TestVerboseResultHandler(ExcInfoFixture, unittest.TestCase):
@patch('sys.stderr', new_callable=StringIO)
def test_output_start_test_run(self, stderr):
# Given
handler = VerboseTestResultHandler(test_count=1)
# When
handler.start_test_run()
# Then
output = stderr.getvalue()
self.assertEqual(output, '')
@patch('sys.stderr', new_callable=StringIO)
def test_no_output_stop_test_run(self, stderr):
# Given
handler = VerboseTestResultHandler(test_count=1)
handler.start_test_run()
# When
handler.stop_test_run()
# Then
output = stderr.getvalue()
self.assertTrue(output.startswith('\n' + handler.separator2))
self.assertTrue(output.endswith('OK\n'))
self.assertRegexpMatches(
output.replace('\n', ''), r'--+.*?Ran 0 tests.*?OK')
@patch('time.ctime')
@patch('sys.stderr', new_callable=StringIO)
def test_output_start_test(self, stderr, mock_ctime):
# Given
case = _test_cases.TestCase('test_method')
handler = VerboseTestResultHandler(test_count=1)
mock_ctime.return_value = expected_time = ctime()
expected_description = handler.get_test_description(case)
# When
handler.start_test(case)
# Then
output = stderr.getvalue()
self.assertEqual(
output, '[{0}] (1/1) {1} ... '.format(
expected_time, expected_description))
@patch('sys.stderr', new_callable=StringIO)
def test_no_output_stop_test(self, stderr):
# Given
handler = VerboseTestResultHandler(test_count=1)
case = _test_cases.TestCase('test_method')
# When
handler.stop_test(case)
# Then
output = stderr.getvalue()
self.assertEqual(output, '')
@patch('sys.stderr', new_callable=StringIO)
def test_output_on_error(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = VerboseTestResultHandler(test_count=1)
with self.exc_info(RuntimeError) as exc_info:
result = TestResult.from_test_case(
case, TestCompletionStatus.error, expected_duration,
exception=exc_info)
# When
handler(result)
# Then
output = stderr.getvalue()
self.assertEqual(output, 'ERROR\n')
@patch('sys.stderr', new_callable=StringIO)
def test_output_on_failure(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = VerboseTestResultHandler(test_count=1)
with self.failure_exc_info() as exc_info:
result = TestResult.from_test_case(
case, TestCompletionStatus.failure, expected_duration,
exception=exc_info)
# When
handler(result)
# Then
output = stderr.getvalue()
self.assertEqual(output, 'FAIL\n')
@patch('sys.stderr', new_callable=StringIO)
def test_output_on_success(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = VerboseTestResultHandler(test_count=1)
result = TestResult.from_test_case(
case, TestCompletionStatus.success, expected_duration)
# When
handler(result)
# Then
output = stderr.getvalue()
self.assertEqual(output, 'ok\n')
@patch('sys.stderr', new_callable=StringIO)
def test_output_on_skip(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = VerboseTestResultHandler(test_count=1)
result = TestResult.from_test_case(
case, TestCompletionStatus.skipped, expected_duration,
message='reason')
# When
handler(result)
# Then
output = stderr.getvalue()
self.assertEqual(output, 'skipped \'reason\'\n')
@patch('sys.stderr', new_callable=StringIO)
def test_output_on_expected_fail(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = VerboseTestResultHandler(test_count=1)
with self.exc_info(RuntimeError) as exc_info:
result = TestResult.from_test_case(
case, TestCompletionStatus.expected_failure, expected_duration,
exception=exc_info)
# When
handler(result)
# Then
output = stderr.getvalue()
self.assertEqual(output, 'expected failure\n')
@patch('sys.stderr', new_callable=StringIO)
def test_output_on_unexpected_success(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = TestDuration(start_time, end_time)
case = _test_cases.TestCase('test_method')
handler = VerboseTestResultHandler(test_count=1)
result = TestResult.from_test_case(
case, TestCompletionStatus.unexpected_success, expected_duration)
# When
handler(result)
# Then
output = stderr.getvalue()
self.assertEqual(output, 'unexpected success\n')
@patch('sys.stderr', new_callable=StringIO)
def test_output_with_error_on_stop_test_run(self, stderr):
# Given
start_time = datetime(2015, 12, 23, 8, 14, 12)
duration = timedelta(seconds=10)
end_time = start_time + duration
expected_duration = | |
# -*- coding: utf-8 -*-
###############################################################################
# Copyright (c), Forschungszentrum Jülich GmbH, IAS-1/PGI-1, Germany. #
# All rights reserved. #
# This file is part of the Masci-tools package. #
# (Material science tools) #
# #
# The code is hosted on GitHub at https://github.com/judftteam/masci-tools. #
# For further information on the license, see the LICENSE.txt file. #
# For further information please visit http://judft.de/. #
# #
###############################################################################
from masci_tools.io.common_functions import open_general
"""
In this module you find the kkrparams class that helps defining the KKR input parameters
Also some defaults for the parameters are defined.
"""
__copyright__ = ('Copyright (c), 2017, Forschungszentrum Jülich GmbH,' 'IAS-1/PGI-1, Germany. All rights reserved.')
__license__ = 'MIT license, see LICENSE.txt file'
__version__ = '1.8.7'
__contributors__ = '<NAME>'
# This defines the default parameters for KKR used in the aiida plugin:
__kkr_default_params__ = {
'LMAX': 3, # lmax-cutoff
'INS': 1, # use shape corrections (full potential)
'KSHAPE': 2, # basically the same information as INS (KSHAPE=2*INS should always hold!)
'NSPIN': 2, # spin-polarized calculation (but by default not automatically initialized with external field)
'RMAX': 10., # Madelung sum real-space cutoff
'GMAX': 100., # Madelung sum reciprocal-space cutoff
'RCLUSTZ': 2.3 # size of screening cluster (in alat units)
}
# prevent kkrparams to add brackets around these keywords automatically
__forbid_brackets__ = ['use_input_alat']
class kkrparams:
"""
Class for creating and handling the parameter input for a KKR calculation
Optional keyword arguments are passed to init and stored in values dictionary.
Example usage: params = kkrparams(LMAX=3, BRAVAIS=array([[1,0,0], [0,1,0], [0,0,1]]))
Alternatively values can be set afterwards either individually with
params.set_value('LMAX', 3)
or multiple keys at once with
params.set_multiple_values(EMIN=-0.5, EMAX=1)
Other useful functions
- print the description of a keyword: params.get_description([key]) where [key] is a string for a keyword in params.values
- print a list of mandatory keywords: params.get_all_mandatory()
- print a list of keywords that are set including their value: params.get_set_values()
.. note:
KKR-units (e.g. atomic units with energy in Ry, length in a_Bohr) are assumed
except for the keys'<RBLEFT>', '<RBRIGHT>', 'ZPERIODL', and 'ZPERIODR' which should be given in Ang. units!
"""
def __init__(self, **kwargs):
"""
Initialize class instance with containing the attribute values that also have
a format, mandatory flags (defaults for KKRcode, changed for example via params_type='voronoi' keyword) and a description.
"""
# keywords for KKRhost and voronoi (all allowed keys for inputcard)
self._DEFAULT_KEYWORDS_KKR = dict([ # complete list of keywords, detault all that are not mandatory to None
# lattice
('ALATBASIS', [
None, '%f', True,
'Description of lattice: Length unit in Bohr radii usually conventional lattice parameter'
]),
('BRAVAIS', [
None, '%f %f %f\n%f %f %f\n%f %f %f', True,
'Description of lattice: Bravais vectors in units of [ALATBASIS]'
]),
('NAEZ', [None, '%i', True, 'Description of lattice: Number of sites in unit cell']),
('<RBASIS>', [None, '%f %f %f', True, 'Description of lattice: Positions of sites in unit cell']),
('CARTESIAN', [
None, '%l', False,
'Description of lattice: Interpret the basis vector coordinates as reduced (w. respect to bravais) or as cartesian (in lattice constant units)'
]),
('INTERFACE', [None, '%l', False, 'Description of lattice, 2D mode: needs to be TRUE for 2D calculation']),
('<NLBASIS>', [
None, '%i', False,
'Description of lattice, 2D mode: Number of basis sites forming the half-infinite lattice to the lower (=left) part of the slab.'
]),
('<RBLEFT>', [
None, '%f %f %f', False,
'Description of lattice, 2D mode: Positions of sites forming the basis sites of the half-infinite lattice to the lower (=left) part of the slab.'
]),
('ZPERIODL', [
None, '%f %f %f', False,
'Description of lattice, 2D mode: Lattice vector describing the periodicity perpendicular to the slab-plane for the half-infinite lattice to the lower (=left) part of the slab (plays the role of the 3rd Bravais vector for this half-infinite lattice). The <RBLEFT> vectors are periodically repeated by the ZPERIODL vector.'
]),
('<NRBASIS>', [
None, '%i', False,
'Description of lattice, 2D mode: Number of basis sites forming the half-infinite lattice to the upper (=right) part of the slab.'
]),
('<RBRIGHT>', [
None, '%f %f %f', False,
'Description of lattice, 2D mode: Positions of sites forming the basis sites of the half-infinite lattice to the upper (=right) part of the slab.'
]),
('ZPERIODR', [
None, '%f %f %f', False,
'Description of lattice, 2D mode: Lattice vector describing the periodicity perpendicular to the slab-plane for the half-infinite lattice to the upper (=right) part of the slab (plays the role of the 3rd Bravais vector for this half-infinite lattice). The <RBRIGHT> vectors are periodically repeated by the ZPERIODR vector.'
]),
('KSHAPE', [
None, '%i', False,
'Description of lattice, shape functions: 0 for ASA ([INS]=0), 2 for full potential ([INS]=1)'
]),
('<SHAPE>', [
None, '%i', False,
'Description of lattice, shape functions: Indexes which shape function from the shape-function file to use in which atom. Default is that each atom has its own shape function.'
]),
# chemistry
('<ZATOM>', [
None, '%f', True,
'Chemistry, Atom types: Nuclear charge per atom. Negative value signals to use value read in from the potential file.'
]),
('NSPIN',
[None, '%i', True, 'Chemistry, Atom types: Number of spin directions in potential. Values 1 or 2']),
('KVREL', [
None, '%i', False,
'Chemistry, Atom types: Relativistic treatment of valence electrons. Takes values 0 (Schroedinger), 1 (Scalar relativistic), 2 (Dirac ; works only in ASA mode)'
]),
('<SOCSCL>', [
None, '%f', False,
'Chemistry, Atom types: Spin-orbit coupling scaling per atom. Takes values between 0. (no spin-orbit) and 1. (full spin-orbit). Works only in combination with the Juelich spin orbit solver (runoption NEWSOSOL)'
]),
('KEXCOR', [
None, '%i', False,
'Chemistry, Exchange-correlation: Type of exchange correlation potential. Takes values 0 (LDA, Moruzzi-Janak-Williams), 1 (LDA, von Barth-Hedin), 2 (LDA, Vosko-Wilk-Nussair), 3 (GGA, Perdew-Wang 91), 4 (GGA, PBE), 5 (GGA, PBEsol)'
]),
('LAMBDA_XC', [
None, '%f', False,
'Chemistry, Exchange-correlation: Scale the magnetic part of the xc-potential and energy. Takes values between 0. (fully suppressed magnetisc potential) and 1. (normal magnetic potential).'
]),
('NAT_LDAU',
[None, '%i', False, 'Chemistry, Exchange-correlation: Numer of atoms where LDA+U will be used']),
('LDAU_PARA', [
None, '%i %i %f %f %f', False,
'Chemistry, Exchange-correlation: For each atom where LDA+U should be used, the entries are: [atom type] [angular mom. to apply LDA+U] [Ueff] [Jeff] [Eref] where [atom type] is between 1...[NATYP].'
]),
('KREADLDAU', [
None, '%i', False,
"Chemistry, Exchange-correlation: Takes values 0 or 1; if [KREADLDAU]=1 then read previously calculated LDA+U matrix elements from file 'ldaupot'."
]),
('NATYP', [
None, '%i', False,
'Chemistry, CPA mode: Number of atom types; CPA is triggered by setting [NATYP]>[NAEZ].'
]),
('<SITE>', [
None, '%i', False,
'Chemistry, CPA mode: Takes values 1 < [<SITE>] < [NAEZ] Assigns the position (given by [<RBASIS>]) where the atom-dependent read-in potential is situated. E.g., if the 3rd-in-the-row potential should be positioned at the 2nd <RBASIS> vector, then the 3rd entry of the <SITE> list should have the value 2.'
]),
('<CPA-CONC>', [
None, '%f', False,
'Chemistry, CPA mode: Takes values 0. < [<CPA-CONC>] < 1. Assigns the alloy-concentration corresponding to the atom-dependent read-in potential. Together with the variable <SITE>, <CPA-CONC> assigns the number and concentration of the atom-dependent potentials residing at each site form 1 to [NAEZ]. The sum of concentrations at each site should equal 1.'
]),
('<KAOEZL>', [
None, '%i', False,
'Chemistry, 2D mode: Controls the type of t-matrix at the lower (=left) half-crystal sites in case of embedding as these are given in the left-decimation file (i.e., changes the order compared to the one in the left-decimation file).'
]),
('<KAOEZR>', [
None, '%i', False,
'Chemistry, 2D mode: Controls the type of t-matrix at the upper (=right) half-crystal sites in case of embedding as these are given in the right-decimation file (i.e., changes the order compared to the one in the right-decimation file).'
]),
# external fields
('LINIPOL', [
None, '%l', False,
'External fields: If TRUE, triggers an external magn. field per atom in the first iteration.'
]),
('HFIELD', [
None, '%f', False,
'External fields: Value of an | |
return data
def serve_user_properties(self, group_locator, name, **kwargs): # noqa: E501
"""serve_user_properties # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.serve_user_properties(group_locator, name, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param str name: (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__serve_user_properties_with_http_info(group_locator, name, **kwargs) # noqa: E501
else:
(data) = self.__serve_user_properties_with_http_info(group_locator, name, **kwargs) # noqa: E501
return data
def set_parent_groups(self, group_locator, **kwargs): # noqa: E501
"""set_parent_groups # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.set_parent_groups(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param Groups body:
:param str fields:
:return: Groups
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__set_parent_groups_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__set_parent_groups_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def set_roles(self, group_locator, **kwargs): # noqa: E501
"""set_roles # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.set_roles(group_locator, async_req=True)
>>> result = thread.get()
:param async_req: bool
:param str group_locator: (required)
:param Roles body:
:return: Roles
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.__set_roles_with_http_info(group_locator, **kwargs) # noqa: E501
else:
(data) = self.__set_roles_with_http_info(group_locator, **kwargs) # noqa: E501
return data
def __add_group_with_http_info(self, **kwargs): # noqa: E501
"""add_group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__add_group_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param Group body:
:param str fields:
:return: Group
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'fields'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_group" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'fields' in params:
query_params.append(('fields', params['fields'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Group', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __add_role_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""add_role # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__add_role_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param Role body:
:return: Role
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_role" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `add_role`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/roles', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Role', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __add_role_simple_with_http_info(self, group_locator, role_id, scope, **kwargs): # noqa: E501
"""add_role_simple # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__add_role_simple_with_http_info(group_locator, role_id, scope, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str role_id: (required)
:param str scope: (required)
:return: Role
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'role_id', 'scope'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_role_simple" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `add_role_simple`") # noqa: E501
# verify the required parameter 'role_id' is set
if ('role_id' not in params or
params['role_id'] is None):
raise ValueError("Missing the required parameter `role_id` when calling `add_role_simple`") # noqa: E501
# verify the required parameter 'scope' is set
if ('scope' not in params or
params['scope'] is None):
raise ValueError("Missing the required parameter `scope` when calling `add_role_simple`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
if 'role_id' in params:
if isinstance(params['role_id'], TeamCityObject):
path_params['roleId'] = params['role_id'].locator_id
else:
path_params['roleId'] = params['role_id'] # noqa: E501
if 'scope' in params:
if isinstance(params['scope'], TeamCityObject):
path_params['scope'] = params['scope'].locator_id
else:
path_params['scope'] = params['scope'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}/roles/{roleId}/{scope}', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Role', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __delete_group_with_http_info(self, group_locator, **kwargs): # noqa: E501
"""delete_group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__delete_group_with_http_info(group_locator, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_group" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `delete_group`") # noqa: E501
collection_formats = {}
path_params = {}
if 'group_locator' in params:
if isinstance(params['group_locator'], TeamCityObject):
path_params['groupLocator'] = params['group_locator'].locator_id
else:
path_params['groupLocator'] = params['group_locator'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/app/rest/userGroups/{groupLocator}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def __delete_role_with_http_info(self, group_locator, role_id, scope, **kwargs): # noqa: E501
"""delete_role # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.__delete_role_with_http_info(group_locator, role_id, scope, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str group_locator: (required)
:param str role_id: (required)
:param str scope: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['group_locator', 'role_id', 'scope'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_role" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'group_locator' is set
if ('group_locator' not in params or
params['group_locator'] is None):
raise ValueError("Missing the required parameter `group_locator` when calling `delete_role`") # noqa: E501
| |
<gh_stars>10-100
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
from unittest import TestCase
import os
class TestStackAdvisorInitialization(TestCase):
def setUp(self):
import imp
self.test_directory = os.path.dirname(os.path.abspath(__file__))
stack_advisor_path = os.path.join(self.test_directory, '../../main/resources/scripts/stack_advisor.py')
with open(stack_advisor_path, 'rb') as fp:
self.stack_advisor = imp.load_module( 'stack_advisor', fp, stack_advisor_path, ('.py', 'rb', imp.PY_SOURCE) )
def test_stackAdvisorLoadedForNotHDPStack(self):
path_template = os.path.join(self.test_directory, '../resources/stacks/{0}/{1}/services/stack_advisor.py')
path_template_name = "STACK_ADVISOR_IMPL_PATH_TEMPLATE"
setattr(self.stack_advisor, path_template_name, path_template)
self.assertEquals(path_template, getattr(self.stack_advisor, path_template_name))
instantiate_stack_advisor_method_name = 'instantiateStackAdvisor'
instantiate_stack_advisor_method = getattr(self.stack_advisor, instantiate_stack_advisor_method_name)
stack_advisor = instantiate_stack_advisor_method("XYZ", "1.0.1", ["1.0.0"])
self.assertEquals("XYZ101StackAdvisor", stack_advisor.__class__.__name__)
services = {
"Versions":
{
"stack_name":"XYZ",
"stack_version":"1.0.1"
},
"services":[
{
"StackServices":{
"service_name":"YARN"
},
"components":[
{
"StackServiceComponents": {
"component_name": "RESOURCEMANAGER"
}
},
{
"StackServiceComponents": {
"component_name": "APP_TIMELINE_SERVER"
}
},
{
"StackServiceComponents": {
"component_name":"YARN_CLIENT"
}
},
{
"StackServiceComponents": {
"component_name": "NODEMANAGER"
}
}
]
}
]
}
hosts= {
"items": [
{"Hosts": {"host_name": "host1"}},
{"Hosts": {"host_name": "host2"}}
]
}
config_recommendations = stack_advisor.recommendConfigurations(services, hosts)
yarn_configs = config_recommendations["recommendations"]["blueprint"]["configurations"]["yarn-site"]["properties"]
'''Check that value is populated from child class, not parent'''
self.assertEquals("-Xmx101m", yarn_configs["yarn.nodemanager.resource.memory-mb"])
def test_stackAdvisorDefaultImpl(self):
instantiate_stack_advisor_method_name = 'instantiateStackAdvisor'
instantiate_stack_advisor_method = getattr(self.stack_advisor, instantiate_stack_advisor_method_name)
'''Not existent stack - to return default implementation'''
default_stack_advisor = instantiate_stack_advisor_method("HDP1", "2.0.6", [])
self.assertEquals("DefaultStackAdvisor", default_stack_advisor.__class__.__name__)
services = {
"Versions":
{
"stack_name":"HDP1",
"stack_version":"2.0.6"
},
"services" : [
{
"StackServices" : {
"service_name" : "GANGLIA",
"service_version" : "3.5.0",
},
"components" : [
{
"StackServiceComponents" : {
"cardinality" : "ALL",
"component_name" : "GANGLIA_MONITOR",
"is_master" : False,
"hostnames" : [ ]
}
},
{
"StackServiceComponents" : {
"cardinality" : "1",
"component_name" : "GANGLIA_SERVER",
"is_master" : True,
"hostnames" : [ ]
}
}
]
},
{
"StackServices" : {
"service_name" : "HBASE",
"service_version" : "0.9192.168.3.11"
},
"components" : [
{
"StackServiceComponents" : {
"cardinality" : "1+",
"component_name" : "HBASE_CLIENT",
"is_master" : False,
"hostnames" : [ ]
}
},
{
"StackServiceComponents" : {
"cardinality" : "1+",
"component_name" : "HBASE_MASTER",
"is_master" : True,
"hostnames" : [ ]
}
},
{
"StackServiceComponents" : {
"cardinality" : "1+",
"component_name" : "HBASE_REGIONSERVER",
"is_master" : False,
"hostnames" : [ ]
}
}
]
},
{
"StackServices" : {
"service_name" : "HDFS",
"service_version" : "2.4.0.2.1"
},
"components" : [
{
"StackServiceComponents" : {
"cardinality" : "1+",
"component_name" : "DATANODE",
"is_master" : False,
"hostnames" : [ ]
}
}, {
"StackServiceComponents" : {
"cardinality" : "1+",
"component_name" : "HDFS_CLIENT",
"is_master" : False,
"hostnames" : [ ]
}
}, {
"StackServiceComponents" : {
"cardinality" : "0+",
"component_name" : "JOURNALNODE",
"is_master" : False,
"hostnames" : [ ]
}
},
{
"StackServiceComponents" : {
"cardinality" : "1-2",
"component_name" : "NAMENODE",
"is_master" : True,
"hostnames" : [ ]
}
},
{
"StackServiceComponents" : {
"cardinality" : "1",
"component_name" : "SECONDARY_NAMENODE",
"is_master" : True,
"hostnames" : [ ]
}
},
{
"StackServiceComponents" : {
"cardinality" : "0+",
"component_name" : "ZKFC",
"is_master" : False,
"hostnames" : [ ]
}
}
]
},
{
"StackServices" : {
"service_name" : "PIG",
"service_version" : "0.192.168.127.12"
},
"components" : [
{
"StackServiceComponents" : {
"cardinality" : "0+",
"component_name" : "PIG",
"is_master" : False,
"hostnames" : [ ]
}
}
]
},
{
"StackServices" : {
"service_name" : "TEZ",
"service_version" : "0.4.0.2.1"
},
"components" : [
{
"StackServiceComponents" : {
"cardinality" : "0+",
"component_name" : "TEZ_CLIENT",
"is_master" : False,
"hostnames" : [ ]
}
}
]
},
{
"StackServices" : {
"service_name" : "ZOOKEEPER",
"service_version" : "3.4.5.2.1",
},
"components" : [
{
"StackServiceComponents" : {
"cardinality" : "1+",
"component_category" : "CLIENT",
"component_name" : "ZOOKEEPER_CLIENT",
"is_master" : False,
"hostnames" : [ ]
}
},
{
"StackServiceComponents" : {
"cardinality" : "1+",
"component_name" : "ZOOKEEPER_SERVER",
"is_master" : True,
"hostnames" : [ ]
}
}
]
}
],
"configurations" : {}
}
hosts= {
"items": [
{"Hosts": {"host_name": "host1",
"cpu_count": 1,
"total_mem": 2097152,
"disk_info": [{
"size": '80000000',
"mountpoint": "/"
}]
}
},
{"Hosts": {"host_name": "host2",
"cpu_count": 1,
"total_mem": 2097152,
"disk_info": [{
"size": '80000000',
"mountpoint": "/"
}]
}
}
]
}
actualValidateConfigResponse = default_stack_advisor.validateConfigurations(services, hosts)
actualValidateLayoutResponse = default_stack_advisor.validateComponentLayout(services, hosts)
expectedValidationResponse = {
"Versions": {"stack_name": "HDP1", "stack_version": "2.0.6"},
"items": []
}
self.assertEquals(actualValidateConfigResponse, expectedValidationResponse)
self.assertEquals(actualValidateLayoutResponse, expectedValidationResponse)
actualRecommendConfigResponse = default_stack_advisor.recommendConfigurations(services, hosts)
expectedRecommendConfigResponse = {
"Versions": {"stack_name": "HDP1", "stack_version": "2.0.6"},
"hosts": ["host1", "host2"],
"services": ['GANGLIA', 'HBASE', 'HDFS', 'PIG', 'TEZ', 'ZOOKEEPER'],
"recommendations": {
"blueprint": {
"configurations": {},
"host_groups": []
},
"blueprint_cluster_binding": {
"host_groups": []
}
}
}
self.assertEquals(actualRecommendConfigResponse, expectedRecommendConfigResponse)
actualRecommendLayoutResponse = default_stack_advisor.recommendComponentLayout(services, hosts)
expectedRecommendLayoutResponse = {
"Versions": {"stack_name": "HDP1", "stack_version": "2.0.6"},
"hosts": ["host1", "host2"],
"services": ['GANGLIA', 'HBASE', 'HDFS', 'PIG', 'TEZ', 'ZOOKEEPER'],
"recommendations": {
"blueprint": {
"host_groups": [
{
"name": "host-group-1",
"components": []
},
{
"name": "host-group-2",
"components": [
{"name": "GANGLIA_SERVER"},
{"name": "HBASE_MASTER"},
{"name": "NAMENODE"},
{"name": "SECONDARY_NAMENODE"},
{"name": "ZOOKEEPER_SERVER"},
{"name": "ZOOKEEPER_CLIENT"}
]
}
]
},
"blueprint_cluster_binding":
{
"host_groups": [
{
"name": "host-group-1",
"hosts": [{"fqdn": "host2"}]
},
{
"name": "host-group-2",
"hosts": [{"fqdn": "host1"}]
}
]
}
}
}
self.assertEquals(actualRecommendLayoutResponse, expectedRecommendLayoutResponse)
# Test with maintenance_state. One host is in maintenance mode.
hosts= {
"items": [
{"Hosts": {"host_name": "host1",
"maintenance_state":"OFF",
"cpu_count": 1}
},
{"Hosts": {"host_name": "host2",
"maintenance_state":"ON",
"cpu_count": 1}
}
]
}
actualRecommendLayoutResponse = default_stack_advisor.recommendComponentLayout(services, hosts)
expectedRecommendLayoutResponse = {
"services": ["GANGLIA", "HBASE", "HDFS", "PIG", "TEZ", "ZOOKEEPER"],
"recommendations": {
"blueprint": {
"host_groups": [
{
"name": "host-group-1",
"components": [
{
"name": "GANGLIA_SERVER"
},
{
"name": "HBASE_MASTER"
},
{
"name": "NAMENODE"
},
{
"name": "SECONDARY_NAMENODE"
},
{
"name": "ZOOKEEPER_SERVER"
},
{
"name": "ZOOKEEPER_CLIENT"
}
]
}
]
},
"blueprint_cluster_binding":
{
"host_groups": [
{
"hosts": [{"fqdn": "host1"}],
"name": "host-group-1"
}
]
}
},
"hosts": ["host1"],
"Versions": {"stack_name": "HDP1", "stack_version": "2.0.6"}
}
self.assertEquals(actualRecommendLayoutResponse, expectedRecommendLayoutResponse)
# Test with maintenance_state. Both hosts are in maintenance mode.
hosts= {
"items": [
{"Hosts": {"host_name": "host1",
"maintenance_state":"ON",
"cpu_count": 1,
"total_mem": 2097152,
"disk_info": [{
"size": '80000000',
"mountpoint": "/"
}]
}
},
{"Hosts": {"host_name": "host2",
"maintenance_state":"ON",
"cpu_count": 1,
"total_mem": 2097152,
"disk_info": [{
"size": '80000000',
"mountpoint": "/"
}]
}
}
]
}
actualRecommendLayoutResponse = default_stack_advisor.recommendComponentLayout(services, hosts)
expectedRecommendLayoutResponse = {
"Versions": {"stack_name": "HDP1", "stack_version": "2.0.6"},
"hosts": [],
"services": ['GANGLIA', 'HBASE', 'HDFS', 'PIG', 'TEZ', 'ZOOKEEPER'],
"recommendations": {
"blueprint": {
"host_groups": []
},
"blueprint_cluster_binding": {
"host_groups": []
}
}
}
self.assertEquals(actualRecommendLayoutResponse, expectedRecommendLayoutResponse)
# Config groups support by default
services["config-groups"] = [{
"configurations": {
},
"hosts": [
'host2'
]
}]
actualConfigGroupRecommendConfigResponse = \
default_stack_advisor.recommendConfigurations(services, hosts)
expectedConfigGroupRecommendConfigResponse = {
"Versions": {"stack_name": "HDP1", "stack_version": "2.0.6"},
"hosts": ["host1", "host2"],
"services": ['GANGLIA', 'HBASE', 'HDFS', 'PIG', 'TEZ', 'ZOOKEEPER'],
"recommendations": {
'config-groups': [
{
'configurations': {},
'dependent_configurations': {},
'hosts': [
'host2'
]
}
],
"blueprint": {
"configurations": {},
"host_groups": []
},
"blueprint_cluster_binding": {
"host_groups": []
}
}
}
self.assertEquals(actualConfigGroupRecommendConfigResponse, expectedConfigGroupRecommendConfigResponse)
services = {
"services": [
{
"StackServices" : {
"service_name" : "YARN",
"stack_name" : "HDP",
"stack_version" : "2.3"
},
"configurations" : [
{
"StackConfigurations" : {
"property_depended_by" : [
{
"type" : "yarn-site",
"name" : "yarn.scheduler.minimum-allocation-vcores"
},
{
"type" : "yarn-site",
"name" : "yarn.scheduler.maximum-allocation-vcores"
}
],
"property_name" : "yarn.nodemanager.resource.cpu-vcores",
"type" : "yarn-site.xml"
},
"dependencies": []
},
{
"StackConfigurations" : {
"property_name" : "yarn.nodemanager.resource.memory-mb",
"type" : "yarn-site.xml"
},
"dependencies": [
{
"StackConfigurationDependency" : {
"dependency_name": "yarn.scheduler.maximum-allocation-mb",
"dependency_type": "yarn-site"
}
},
{
"StackConfigurationDependency" : {
"dependency_name": "yarn.scheduler.minimum-allocation-mb",
"dependency_type": "yarn-site"
}
},
]
},
{
"StackConfigurations" : {
"property_depended_by" : [
{
"type" : "mapred-site",
"name" : "yarn.app.mapreduce.am.resource.mb"
},
{
"type" : "mapred-site",
"name" : "mapreduce.map.memory.mb"
},
{
"type" : "mapred-site",
"name" : "mapreduce.reduce.memory.mb"
}
],
"property_name" : "yarn.scheduler.maximum-allocation-mb",
"type" : "yarn-site.xml"
},
"dependencies": []
},
{
"StackConfigurations" : {
"property_depended_by" : [ ],
"property_name" : "yarn.scheduler.maximum-allocation-vcores",
"type" : "yarn-site.xml"
},
"dependencies": []
},
{
"StackConfigurations" : {
"property_name" : "yarn.scheduler.minimum-allocation-mb",
"type" : "yarn-site.xml"
},
"dependencies": [
{
"StackConfigurationDependency" : {
"dependency_name": "hive.tez.container.size",
"dependency_type": "hive-site"
}
},
| |
assert data_from_database == [(record[0], record[1]) for record in
[unified_record.split(',') for unified_record in csv_records[:-1]]]
error_msgs = wiretap.error_records
assert 1 == len(error_msgs)
error_record = error_msgs[0]
assert 'hellolargerword' == error_record.field['1']
assert 'JDBC_14' == error_record.header['errorCode']
assert 'SQLSTATE=22001' in error_record.header['errorMessage']
finally:
logger.info('Dropping table %s in %s database ...', table_name, database.type)
database.engine.execute(f'DROP TABLE {table_name}')
# SDC-13624: JDBC Multitable Consumer ingests duplicates when initial offset is set for a column in partitioned mode
@database
@sdc_min_version('3.0.0.0')
def test_jdbc_multitable_consumer_duplicates_read_when_initial_offset_configured(sdc_builder, sdc_executor, database):
"""
SDC-13625 Integration test for SDC-13624 - MT Consumer ingests duplicates when initial offset is specified
Setup origin as follows:
partitioning enabled + num_threads and num partitions > 1 + override offset column set
+ initial value specified for offset
Verify that origin does not ingest the records more than once (duplicates) when initial value for offset is set
Pipeline:
JDBC MT Consumer >> Wiretap
>= Pipeline Finisher (no-more-data)
"""
if database.type == 'Oracle':
pytest.skip("This test depends on proper case for column names that Oracle auto-uppers.")
src_table_prefix = get_random_string(string.ascii_lowercase, 6)
table_name = '{}_{}'.format(src_table_prefix, get_random_string(string.ascii_lowercase, 20))
pipeline_builder = sdc_builder.get_pipeline_builder()
jdbc_multitable_consumer = pipeline_builder.add_stage('JDBC Multitable Consumer')
jdbc_multitable_consumer.set_attributes(table_configs=[{
"tablePattern": f'{table_name}',
"enableNonIncremental": False,
"partitioningMode": "REQUIRED",
"partitionSize": "100000",
"maxNumActivePartitions": 5,
'overrideDefaultOffsetColumns': True,
'offsetColumns': ['created'],
'offsetColumnToInitialOffsetValue': [{
'key': 'created',
'value': '0'
}]
}])
jdbc_multitable_consumer.number_of_threads = 2
jdbc_multitable_consumer.maximum_pool_size = 2
wiretap = pipeline_builder.add_wiretap()
jdbc_multitable_consumer >> wiretap.destination
finisher = pipeline_builder.add_stage("Pipeline Finisher Executor")
finisher.stage_record_preconditions = ['${record:eventType() == "no-more-data"}']
jdbc_multitable_consumer >= finisher
pipeline = pipeline_builder.build().configure_for_environment(database)
ONE_MILLION = 1000000
rows_in_table = [{'id': i, 'name': get_random_string(string.ascii_lowercase, 5), 'created': i + ONE_MILLION}
for i in range(1, 21)]
metadata = sqlalchemy.MetaData()
table = sqlalchemy.Table(
table_name,
metadata,
sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column('name', sqlalchemy.String(5)),
sqlalchemy.Column('created', sqlalchemy.Integer)
)
try:
logger.info('Creating table %s in %s database ...', table_name, database.type)
table.create(database.engine)
logger.info('Adding 20 rows into %s table', table_name)
connection = database.engine.connect()
connection.execute(table.insert(), rows_in_table)
connection.close()
sdc_executor.add_pipeline(pipeline)
sdc_executor.start_pipeline(pipeline).wait_for_finished()
rows_from_wiretap = [(record.get_field_data('/name').value,
record.get_field_data('/id').value,
record.get_field_data('/created').value)
for record in wiretap.output_records]
expected_data = [(row['name'], row['id'], row['created']) for row in rows_in_table]
assert rows_from_wiretap == expected_data
finally:
logger.info('Dropping table %s in %s database...', table_name, database.type)
table.drop(database.engine)
# SDC-14489: JDBC Multitable origin must escape string columns
@database
@pytest.mark.parametrize('input_string', [
"::problematical::value::",
"=another=problematical=value=",
""
])
def test_multitable_string_offset_column(sdc_builder, sdc_executor, database, input_string):
"""Ensure that problematical values in String-typed offset column are covered, e.g. our special separator '::'."""
if database.type == 'Oracle' and not input_string:
pytest.skip("Oracle doesn't support concept of empty string - it always converts it to NULL which is invalid for primary key.")
builder = sdc_builder.get_pipeline_builder()
table_name = get_random_string(string.ascii_letters, 10)
origin = builder.add_stage('JDBC Multitable Consumer')
origin.table_configs = [{"tablePattern": f'{table_name}'}]
origin.max_batch_size_in_records = 10
wiretap = builder.add_wiretap()
origin >> wiretap.destination
pipeline = builder.build().configure_for_environment(database)
# Work-arounding STF behavior of upper-casing table name configuration
origin.table_configs[0]["tablePattern"] = f'{table_name}'
# Creating table with primary key that is String
metadata = sqlalchemy.MetaData()
table = sqlalchemy.Table(
table_name,
metadata,
sqlalchemy.Column('id', sqlalchemy.String(60), primary_key=True, quote=True),
quote=True
)
try:
logger.info('Creating table %s in %s database ...', table_name, database.type)
table.create(database.engine)
connection = database.engine.connect()
connection.execute(table.insert(), [{'id': input_string}])
sdc_executor.add_pipeline(pipeline)
sdc_executor.start_pipeline(pipeline).wait_for_pipeline_output_records_count(2)
sdc_executor.stop_pipeline(pipeline)
# There should be no errors reported
history = sdc_executor.get_pipeline_history(pipeline)
assert history.latest.metrics.counter('stage.JDBCMultitableConsumer_01.errorRecords.counter').count == 0
assert history.latest.metrics.counter('stage.JDBCMultitableConsumer_01.stageErrors.counter').count == 0
# And verify that we properly read that one record
assert len(wiretap.output_records) == 1
assert wiretap.output_records[0].get_field_data('/id') == input_string
finally:
logger.info('Dropping table %s in %s database...', table_name, database.type)
table.drop(database.engine)
@database
@pytest.mark.parametrize('batch_strategy', ['SWITCH_TABLES', 'PROCESS_ALL_AVAILABLE_ROWS_FROM_TABLE'])
@pytest.mark.parametrize('no_of_threads', [1, 2, 3])
def test_jdbc_multitable_consumer_batch_strategy(sdc_builder, sdc_executor, database, batch_strategy, no_of_threads):
"""
Check if Jdbc Multi-table Origin can load a couple of tables without duplicates using both batch_strategy options.
Also it includes different thread combinations to ensure that with less, same and more threads works fine.
jdbc_multitable_consumer >> wiretap.destination
jdbc_multitable_consumer >= pipeline_finished_executor
"""
if database.type == 'Oracle':
pytest.skip("This test depends on proper case for column names that Oracle auto-uppers.")
no_of_records_per_table = random.randint(5001, 10000)
src_table_prefix = get_random_string(string.ascii_lowercase, 6)
table_name1 = f'{src_table_prefix}_{get_random_string(string.ascii_lowercase, 20)}'
table_name2 = f'{src_table_prefix}_{get_random_string(string.ascii_lowercase, 20)}'
pipeline_builder = sdc_builder.get_pipeline_builder()
jdbc_multitable_consumer = pipeline_builder.add_stage('JDBC Multitable Consumer')
jdbc_multitable_consumer.set_attributes(table_configs=[{"tablePattern": f'{src_table_prefix}%'}],
per_batch_strategy=batch_strategy,
number_of_threads=no_of_threads,
maximum_pool_size=no_of_threads)
pipeline_finished_executor = pipeline_builder.add_stage('Pipeline Finisher Executor')
pipeline_finished_executor.set_attributes(stage_record_preconditions=["${record:eventType() == 'no-more-data'}"])
wiretap = pipeline_builder.add_wiretap()
jdbc_multitable_consumer >> wiretap.destination
jdbc_multitable_consumer >= pipeline_finished_executor
pipeline = pipeline_builder.build().configure_for_environment(database)
sdc_executor.add_pipeline(pipeline)
def get_table_schema(table_name):
return sqlalchemy.Table(
table_name,
sqlalchemy.MetaData(),
sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column('field1', sqlalchemy.String(32)),
sqlalchemy.Column('field2', sqlalchemy.String(32)),
sqlalchemy.Column('field3', sqlalchemy.String(32)),
sqlalchemy.Column('field4', sqlalchemy.String(32)),
sqlalchemy.Column('field5', sqlalchemy.String(32)),
sqlalchemy.Column('field6', sqlalchemy.String(32)),
sqlalchemy.Column('field7', sqlalchemy.String(32)),
sqlalchemy.Column('field8', sqlalchemy.String(32)),
sqlalchemy.Column('field9', sqlalchemy.String(32))
)
def get_table_data(table):
return [{'id': i, 'field1': f'field1_{i}_{table}', 'field2': f'field2_{i}_{table}',
'field3': f'field3_{i}_{table}', 'field4': f'field4_{i}_{table}',
'field5': f'field5_{i}_{table}', 'field6': f'field6_{i}_{table}',
'field7': f'field7_{i}_{table}', 'field8': f'field8_{i}_{table}',
'field9': f'field9_{i}_{table}'} for i in range(1, no_of_records_per_table + 1)]
table1 = get_table_schema(table_name1)
table2 = get_table_schema(table_name2)
table_data1 = get_table_data(1)
table_data2 = get_table_data(2)
try:
logger.info('Creating table %s in %s database ...', table_name1, database.type)
logger.info('Creating table %s in %s database ...', table_name2, database.type)
table1.create(database.engine)
table2.create(database.engine)
logger.info('Adding three rows into %s database ...', database.type)
connection = database.engine.connect()
connection.execute(table1.insert(), table_data1)
connection.execute(table2.insert(), table_data2)
sdc_executor.start_pipeline(pipeline).wait_for_finished()
records = [{'id': record.field['id'], 'field1': record.field['field1'], 'field2': record.field['field2'],
'field3': record.field['field3'], 'field4': record.field['field4'],
'field5': record.field['field5'], 'field6': record.field['field6'],
'field7': record.field['field7'], 'field8': record.field['field8'],
'field9': record.field['field9']} for record in wiretap.output_records]
assert len(records) == len(table_data1) + len(table_data2) == no_of_records_per_table * 2
assert all(element in records for element in table_data1)
assert all(element in records for element in table_data2)
finally:
logger.info('Dropping table %s in %s database...', table_name1, database.type)
logger.info('Dropping table %s in %s database...', table_name2, database.type)
table1.drop(database.engine)
table2.drop(database.engine)
@database
@pytest.mark.parametrize('test_data', [
{'per_batch_strategy': 'SWITCH_TABLES', 'thread_count': 2, 'partition_size': 1000},
{'per_batch_strategy': 'SWITCH_TABLES', 'thread_count': 3, 'partition_size': 1000},
{'per_batch_strategy': 'SWITCH_TABLES', 'thread_count': 4, 'partition_size': 1000},
{'per_batch_strategy': 'PROCESS_ALL_AVAILABLE_ROWS_FROM_TABLE', 'thread_count': 2, 'partition_size': 1000},
{'per_batch_strategy': 'PROCESS_ALL_AVAILABLE_ROWS_FROM_TABLE', 'thread_count': 3, 'partition_size': 1000},
{'per_batch_strategy': 'PROCESS_ALL_AVAILABLE_ROWS_FROM_TABLE', 'thread_count': 4, 'partition_size': 1000},
{'per_batch_strategy': 'SWITCH_TABLES', 'thread_count': 2, 'partition_size': 0},
{'per_batch_strategy': 'SWITCH_TABLES', 'thread_count': 3, 'partition_size': 0},
{'per_batch_strategy': 'SWITCH_TABLES', 'thread_count': 4, 'partition_size': 0},
{'per_batch_strategy': 'PROCESS_ALL_AVAILABLE_ROWS_FROM_TABLE', 'thread_count': 2, 'partition_size': 0},
{'per_batch_strategy': 'PROCESS_ALL_AVAILABLE_ROWS_FROM_TABLE', 'thread_count': 3, 'partition_size': 0},
{'per_batch_strategy': 'PROCESS_ALL_AVAILABLE_ROWS_FROM_TABLE', 'thread_count': 4, 'partition_size': 0}
])
def test_no_data_losses_or_duplicates_in_multithreaded_mode(sdc_builder, sdc_executor, database, test_data):
"""
We want to make sure that there are no duplicates or data loses when the number of threads is less than
the number of tables; is equal to the number of tables or is greater than the number of tables.
And we want to run the same test for all batch strategies with partitioning enabled and disabled too.
To run the test we first create 3 tables and populate them with 12000, 36000 and 6000 random records respectively.
To prove the connector works as expected we will
1) test that the number of records written is as expected for every table, not more (to exclude data duplicates)
and not less (to exclude data loses).
2) test that at the end we get all expected events: 3 table-finished events (1 for each table), 1 schema-finished
event with 3 table names and 1 no-more-data event.
The pipeline is as follows:
JDBC Multitable Consumer >> Splitter >> Wiretap1 (12000 records)
Splitter >> Wiretap2 (36000 records)
Splitter >> Wiretap3 (6000 records)
Splitter >> Default Wiretap (0 records)
>= Event Wiretap
"""
rows_in_tables = [12000, 36000, 6000]
table_prefix = f'{get_random_string(string.ascii_lowercase, 6)}_'
table_names = [f'{table_prefix}{get_random_string(string.ascii_lowercase, 20)}'
for _ in range(0, len(rows_in_tables))]
tables = []
all_rows = []
pipeline = None
try:
all_row_count = 0
for i, rows_in_table in enumerate(rows_in_tables):
columns = [
sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True, quote=True),
sqlalchemy.Column('NAME', sqlalchemy.String(32), quote=True)
]
rows = [{'id': j + 1, 'NAME': get_random_string(string.ascii_lowercase, 32)} for j in range(rows_in_table)]
all_rows += [rows]
all_row_count += len(rows)
table = sqlalchemy.Table(table_names[i], sqlalchemy.MetaData(), *columns, quote=True)
table.create(database.engine)
tables += [table]
connection = database.engine.connect()
connection.execute(table.insert(), rows)
pipeline_builder = sdc_builder.get_pipeline_builder()
attributes = {
'table_configs': [{
"tablePattern": f'{table_prefix}%',
'partitioningMode': 'REQUIRED' if test_data['partition_size'] > 0 else 'DISABLED',
'partitionSize': str(test_data['partition_size'])
}],
'max_batch_size_in_records': 100,
'fetch_size': 10,
'number_of_threads': test_data['thread_count'],
'maximum_pool_size': test_data['thread_count'],
'per_batch_strategy': test_data['per_batch_strategy']
}
jdbc_multitable_consumer = pipeline_builder.add_stage('JDBC Multitable Consumer')
jdbc_multitable_consumer.set_attributes(**attributes)
stream_selector = pipeline_builder.add_stage('Stream Selector')
jdbc_multitable_consumer >> stream_selector
event_wiretap = pipeline_builder.add_wiretap()
jdbc_multitable_consumer >= event_wiretap.destination
wiretaps = []
for _ in range(0, len(table_names) + 1):
wiretap = pipeline_builder.add_wiretap()
stream_selector >> wiretap.destination
wiretaps += [wiretap]
conditions = [{
'outputLane': stream_selector.output_lanes[i],
'predicate': f"${{record:attribute('jdbc.tables')=='{table_name}'}}"
} for i, table_name in enumerate(table_names)]
conditions += [{'outputLane': stream_selector.output_lanes[len(table_names)], 'predicate': 'default'}]
stream_selector.condition = conditions
pipeline = pipeline_builder.build().configure_for_environment(database)
jdbc_multitable_consumer.table_configs[0]["tablePattern"] = f'{table_prefix}%'
sdc_executor.add_pipeline(pipeline)
status = sdc_executor.start_pipeline(pipeline)
status.wait_for_pipeline_output_records_count(all_row_count + all_row_count / 1000 + 9)
for i, rows in enumerate(all_rows):
assert len(rows) == len(wiretaps[i].output_records)
output_records = [{
'id': r.field['id'].value,
'NAME': r.field['NAME'].value
} for r in wiretaps[i].output_records]
output_records.sort(key=lambda r: r['id'])
assert rows == output_records
assert 0 == len(wiretaps[len(wiretaps) - 1].output_records)
finished_tables = set()
| |
<reponame>vincenttran-msft/azure-sdk-for-python<gh_stars>1-10
# pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
from msrest import Serializer
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, List, Optional, TypeVar
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
# fmt: off
def build_dequeue_request(
url, # type: str
**kwargs # type: Any
):
# type: (...) -> HttpRequest
version = kwargs.pop('version', "2018-03-28") # type: str
number_of_messages = kwargs.pop('number_of_messages', None) # type: Optional[int]
visibilitytimeout = kwargs.pop('visibilitytimeout', None) # type: Optional[int]
timeout = kwargs.pop('timeout', None) # type: Optional[int]
request_id_parameter = kwargs.pop('request_id_parameter', None) # type: Optional[str]
accept = "application/xml"
# Construct URL
_url = kwargs.pop("template_url", "{url}/{queueName}/messages")
path_format_arguments = {
"url": _SERIALIZER.url("url", url, 'str', skip_quote=True),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
if number_of_messages is not None:
_query_parameters['numofmessages'] = _SERIALIZER.query("number_of_messages", number_of_messages, 'int', minimum=1)
if visibilitytimeout is not None:
_query_parameters['visibilitytimeout'] = _SERIALIZER.query("visibilitytimeout", visibilitytimeout, 'int', maximum=604800, minimum=0)
if timeout is not None:
_query_parameters['timeout'] = _SERIALIZER.query("timeout", timeout, 'int', minimum=0)
# Construct headers
_header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
_header_parameters['x-ms-version'] = _SERIALIZER.header("version", version, 'str')
if request_id_parameter is not None:
_header_parameters['x-ms-client-request-id'] = _SERIALIZER.header("request_id_parameter", request_id_parameter, 'str')
_header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=_url,
params=_query_parameters,
headers=_header_parameters,
**kwargs
)
def build_clear_request(
url, # type: str
**kwargs # type: Any
):
# type: (...) -> HttpRequest
version = kwargs.pop('version', "2018-03-28") # type: str
timeout = kwargs.pop('timeout', None) # type: Optional[int]
request_id_parameter = kwargs.pop('request_id_parameter', None) # type: Optional[str]
accept = "application/xml"
# Construct URL
_url = kwargs.pop("template_url", "{url}/{queueName}/messages")
path_format_arguments = {
"url": _SERIALIZER.url("url", url, 'str', skip_quote=True),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
if timeout is not None:
_query_parameters['timeout'] = _SERIALIZER.query("timeout", timeout, 'int', minimum=0)
# Construct headers
_header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
_header_parameters['x-ms-version'] = _SERIALIZER.header("version", version, 'str')
if request_id_parameter is not None:
_header_parameters['x-ms-client-request-id'] = _SERIALIZER.header("request_id_parameter", request_id_parameter, 'str')
_header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="DELETE",
url=_url,
params=_query_parameters,
headers=_header_parameters,
**kwargs
)
def build_enqueue_request(
url, # type: str
**kwargs # type: Any
):
# type: (...) -> HttpRequest
version = kwargs.pop('version', "2018-03-28") # type: str
content_type = kwargs.pop('content_type', None) # type: Optional[str]
visibilitytimeout = kwargs.pop('visibilitytimeout', None) # type: Optional[int]
message_time_to_live = kwargs.pop('message_time_to_live', None) # type: Optional[int]
timeout = kwargs.pop('timeout', None) # type: Optional[int]
request_id_parameter = kwargs.pop('request_id_parameter', None) # type: Optional[str]
accept = "application/xml"
# Construct URL
_url = kwargs.pop("template_url", "{url}/{queueName}/messages")
path_format_arguments = {
"url": _SERIALIZER.url("url", url, 'str', skip_quote=True),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
if visibilitytimeout is not None:
_query_parameters['visibilitytimeout'] = _SERIALIZER.query("visibilitytimeout", visibilitytimeout, 'int', maximum=604800, minimum=0)
if message_time_to_live is not None:
_query_parameters['messagettl'] = _SERIALIZER.query("message_time_to_live", message_time_to_live, 'int', minimum=-1)
if timeout is not None:
_query_parameters['timeout'] = _SERIALIZER.query("timeout", timeout, 'int', minimum=0)
# Construct headers
_header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
_header_parameters['x-ms-version'] = _SERIALIZER.header("version", version, 'str')
if request_id_parameter is not None:
_header_parameters['x-ms-client-request-id'] = _SERIALIZER.header("request_id_parameter", request_id_parameter, 'str')
if content_type is not None:
_header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
_header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="POST",
url=_url,
params=_query_parameters,
headers=_header_parameters,
**kwargs
)
def build_peek_request(
url, # type: str
**kwargs # type: Any
):
# type: (...) -> HttpRequest
peekonly = kwargs.pop('peekonly', "true") # type: str
version = kwargs.pop('version', "2018-03-28") # type: str
number_of_messages = kwargs.pop('number_of_messages', None) # type: Optional[int]
timeout = kwargs.pop('timeout', None) # type: Optional[int]
request_id_parameter = kwargs.pop('request_id_parameter', None) # type: Optional[str]
accept = "application/xml"
# Construct URL
_url = kwargs.pop("template_url", "{url}/{queueName}/messages")
path_format_arguments = {
"url": _SERIALIZER.url("url", url, 'str', skip_quote=True),
}
_url = _format_url_section(_url, **path_format_arguments)
# Construct parameters
_query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
_query_parameters['peekonly'] = _SERIALIZER.query("peekonly", peekonly, 'str')
if number_of_messages is not None:
_query_parameters['numofmessages'] = _SERIALIZER.query("number_of_messages", number_of_messages, 'int', minimum=1)
if timeout is not None:
_query_parameters['timeout'] = _SERIALIZER.query("timeout", timeout, 'int', minimum=0)
# Construct headers
_header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
_header_parameters['x-ms-version'] = _SERIALIZER.header("version", version, 'str')
if request_id_parameter is not None:
_header_parameters['x-ms-client-request-id'] = _SERIALIZER.header("request_id_parameter", request_id_parameter, 'str')
_header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRequest(
method="GET",
url=_url,
params=_query_parameters,
headers=_header_parameters,
**kwargs
)
# fmt: on
class MessagesOperations(object):
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.storage.queue.AzureQueueStorage`'s
:attr:`messages` attribute.
"""
models = _models
def __init__(self, *args, **kwargs):
args = list(args)
self._client = args.pop(0) if args else kwargs.pop("client")
self._config = args.pop(0) if args else kwargs.pop("config")
self._serialize = args.pop(0) if args else kwargs.pop("serializer")
self._deserialize = args.pop(0) if args else kwargs.pop("deserializer")
@distributed_trace
def dequeue(
self,
number_of_messages=None, # type: Optional[int]
visibilitytimeout=None, # type: Optional[int]
timeout=None, # type: Optional[int]
request_id_parameter=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> List["_models.DequeuedMessageItem"]
"""The Dequeue operation retrieves one or more messages from the front of the queue.
:param number_of_messages: Optional. A nonzero integer value that specifies the number of
messages to retrieve from the queue, up to a maximum of 32. If fewer are visible, the visible
messages are returned. By default, a single message is retrieved from the queue with this
operation. Default value is None.
:type number_of_messages: int
:param visibilitytimeout: Optional. Specifies the new visibility timeout value, in seconds,
relative to server time. The default value is 30 seconds. A specified value must be larger than
or equal to 1 second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol
versions prior to version 2011-08-18. The visibility timeout of a message can be set to a value
later than the expiry time.
:type visibilitytimeout: int
:param timeout: The The timeout parameter is expressed in seconds. For more information, see <a
href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting
Timeouts for Queue Service Operations.</a>. Default value is None.
:type timeout: int
:param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character
limit that is recorded in the analytics logs when storage analytics logging is enabled. Default
value is None.
:type request_id_parameter: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: list of DequeuedMessageItem, or the result of cls(response)
:rtype: list[~azure.storage.queue.models.DequeuedMessageItem]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[List["_models.DequeuedMessageItem"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_dequeue_request(
url=self._config.url,
version=self._config.version,
number_of_messages=number_of_messages,
visibilitytimeout=visibilitytimeout,
timeout=timeout,
request_id_parameter=request_id_parameter,
template_url=self.dequeue.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run( # pylint: disable=protected-access
request,
stream=False,
**kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.StorageError, pipeline_response)
raise HttpResponseError(response=response, model=error)
response_headers = {}
response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id'))
response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version'))
response_headers['Date']=self._deserialize('rfc-1123', response.headers.get('Date'))
deserialized = self._deserialize('[DequeuedMessageItem]', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
dequeue.metadata = {'url': "{url}/{queueName}/messages"} # type: ignore
@distributed_trace
def clear( # pylint: disable=inconsistent-return-statements
self,
timeout=None, # type: Optional[int]
request_id_parameter=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> None
"""The Clear operation deletes all messages from the specified queue.
:param timeout: The The timeout parameter is expressed in seconds. For more information, see <a
href="https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations>Setting
Timeouts for Queue Service Operations.</a>. Default value is None.
:type timeout: int
:param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character
limit that is recorded in the analytics logs when storage analytics logging is enabled. Default
value is None.
:type request_id_parameter: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
request = build_clear_request(
url=self._config.url,
version=self._config.version,
timeout=timeout,
request_id_parameter=request_id_parameter,
template_url=self.clear.metadata['url'],
)
request = _convert_request(request)
| |
from __future__ import division
import numpy, pandas
from scipy.signal import butter
from scipy import interpolate
import scipy
import csv
import click
import sys, os, re, pprint
from scipy.optimize import curve_fit
from scipy.fftpack import fft
from scipy.signal import butter, lfilter, find_peaks_cwt, detrend, periodogram, remez, iirfilter
from scipy.interpolate import CubicSpline, interp1d, UnivariateSpline
from src.utils import metadataExtractor, cxpPrinter
import collections
def gcamp_interpolate(gcamp, number_of_additional_timepoints):
gcamp_len = len(gcamp)
timelabels = range(0, gcamp_len)
cs = scipy.interpolate.CubicSpline(timelabels, gcamp)
timelabels_spline = numpy.arange(0, gcamp_len-1, 1/number_of_additional_timepoints)
gcamp_spline = cs(timelabels_spline)
return gcamp_spline
def gcamp_normalize(gcamp, gcamp_min, gcamp_max):
# signal min already remove during extraction
return numpy.asarray(gcamp) / (gcamp_max - gcamp_min)
def gcamp_fwhm(gcamp, window_length, peak_ind, original_gcamp_length):
win_rise = peak_ind - window_length if peak_ind >= window_length else 0
win_fall = peak_ind + window_length + 1 if peak_ind < len(gcamp) - window_length else len(gcamp)
gcamp_windowed = gcamp[win_rise:win_fall] # look for a minimum within the window
# argrelextrema requires an *order* less than or equal to half the length of the input array
if window_length > len(gcamp_windowed) / 2:
min_ind = scipy.signal.argrelextrema(gcamp_windowed, numpy.less,
order=numpy.floor(len(gcamp_windowed) / 2).astype(int))
else:
min_ind = scipy.signal.argrelextrema(gcamp_windowed, numpy.less, order=window_length)
if len(min_ind[0]) == 0:
min_ind = numpy.where(gcamp_windowed == numpy.min(gcamp_windowed))
fwhm_cutoff = (gcamp[peak_ind] - numpy.min(gcamp_windowed[min_ind])) / 2 + numpy.min(gcamp_windowed[min_ind])
window_length_expanded = window_length * 2 # after determining a cutoff expand the search in case of assymettry between rise and fall
# a fold change of 2 implies the decay of a signal could take twice as long as the activation of length *window_length*
# alternatively, the entire time-series could be searched. This might be better since processing costs for this length of signal are neglgible
win_rise_expanded = peak_ind - window_length_expanded if peak_ind >= window_length_expanded else 0
win_fall_expanded = peak_ind + window_length_expanded + 1 if peak_ind < len(
gcamp) - window_length_expanded else len(gcamp)
gcamp_windowed_expanded = gcamp[win_rise_expanded:win_fall_expanded]
peak_ind_expanded = peak_ind - win_rise_expanded
# There are special cases when the signal in the window does not reach the *fwhm_cutoff*.
# When this happens the fwhm will just use the ends of the window.
# The first point past the cutoff is chosen by numpy.min() and numpy.max().
# To choose the closest index, the first point just before the closet index must also be considered.
fwhm_rise_ind = numpy.where(gcamp_windowed_expanded[:peak_ind_expanded] < fwhm_cutoff)
if len(fwhm_rise_ind[0]) == 0:
fwhm_rise = peak_ind - win_rise_expanded
else:
fwhm_riseA = numpy.asscalar(peak_ind_expanded - numpy.max(fwhm_rise_ind))
fwhm_rise_testA = abs(gcamp_windowed_expanded[peak_ind_expanded - fwhm_riseA] - fwhm_cutoff)
fwhm_rise_testB = abs(gcamp_windowed_expanded[peak_ind_expanded - fwhm_riseA + 1] - fwhm_cutoff)
fwhm_rise = fwhm_riseA if fwhm_rise_testA <= fwhm_rise_testB else fwhm_riseA - 1
fwhm_fall_ind = numpy.where(gcamp_windowed_expanded[peak_ind_expanded:] < fwhm_cutoff)
if len(fwhm_fall_ind[0]) == 0:
fwhm_fall = win_fall_expanded - peak_ind - 1 # the *-1* is to correct for an offset
else:
fwhm_fallA = numpy.asscalar(numpy.min(fwhm_fall_ind))
fwhm_fall_testA = abs(gcamp_windowed_expanded[fwhm_fallA + peak_ind_expanded] - fwhm_cutoff)
fwhm_fall_testB = abs(gcamp_windowed_expanded[fwhm_fallA + peak_ind_expanded - 1] - fwhm_cutoff)
fwhm_fall = fwhm_fallA if fwhm_fall_testA <= fwhm_fall_testB else fwhm_fallA - 1
# fwhm_rise and fwhm_fall should be greater than zero
fwhm_rise = 1 if fwhm_rise == 0 else fwhm_rise
fwhm_fall = 1 if fwhm_fall == 0 else fwhm_fall
# peak width
peak_start_ind = (peak_ind - fwhm_rise) if (peak_ind - fwhm_rise) > 0 else 0
peak_end_ind = (peak_ind + fwhm_fall) if (peak_ind + fwhm_fall) < len(gcamp) else len(gcamp)-1
peak_width = peak_end_ind - peak_start_ind # same as fwhm_rise + fwhm_fall
# area under the curve (area under the peak only)
area_under_curve = numpy.trapz(gcamp[peak_start_ind:peak_end_ind+1], dx=original_gcamp_length/len(gcamp))
return fwhm_rise, fwhm_fall, fwhm_cutoff, peak_width, area_under_curve
# To find in array the element closest to value
def find_nearest(array,value,startIdx,endIdx):
if endIdx < len(array)-1:
endIdx = endIdx+1
idx = (numpy.abs(array[startIdx:endIdx]-value)).argmin() + startIdx
return idx
# - To obtain half maximum points, peak start/end, height
# - Half max data not used currently, this method also returns other important
# metrics such as peak height, etc.
def getPeakDefiningPoints(signal, peaks, valleys, wellmin):
half_maximums, peak_halfmax_starts, peak_halfmax_ends = [],[],[] # halfmax values (halfmax,halfmax start, halfmax end)
peak_rise_starts, peak_fall_ends= [],[]
peak_heights_localmin, peak_heights_signalmin, peak_heights_wellmin = [],[],[]
for idx,peak in enumerate(peaks):
# Step 1: Get valleys between previous and current peak
if len(peaks) > 1 and idx > 0:
valleys_considered = valleys[(valleys > peaks[idx - 1]) & (valleys < peak)]
else:
valleys_considered = valleys[(valleys < peak)]
# Step 2: Determine peak start index
if len(valleys_considered) > 0:
peak_start = valleys_considered[-1] # 1st valley to the left of current peak
else:
peak_start = 0
peak_rise_starts.append(peak_start)
# Step 3: Determine peak end idx
if idx <= len(peaks) - 2: # if there is at least 1 more peak in peaks
# valleys between current and next peak
nextValleys = valleys[(valleys > peak) & (valleys < peaks[idx + 1])]
else:
# valleys between current peak and end of signal
nextValleys = valleys[(valleys > peak) & (valleys < (len(signal)-1))]
# take 1st valley to the right of current peak
if len(nextValleys) > 0:
peak_end = nextValleys[0]
else:
peak_end = len(signal) - 1
peak_fall_ends.append(peak_end)
# Step 4: Compute halfmax and approximate corresponding halfmax start/end index
halfmax = (max(signal[peak] - signal[peak_start], signal[peak] - signal[peak_end]))/2.0 + signal[peak_start]
half_maximums.append(halfmax)
halfmax_start = find_nearest(signal, halfmax, peak_start, peak)
peak_halfmax_starts.append(halfmax_start)
peak_halfmax_ends.append(find_nearest(signal, signal[halfmax_start], peak, peak_end))
# Step 5: Compute peak height
# Method 1: Difference between gcamp signal and minimum value of that same gcamp signal.
peakheight_signalmin = signal[peak] - min(signal)
peak_heights_signalmin.append(peakheight_signalmin)
# Method 2: Difference between gcamp signal and local minimum of the peak under analysis.
peakheight_localmin = max(signal[peak] - signal[peak_start], signal[peak] - signal[peak_end])
peak_heights_localmin.append(peakheight_localmin)
# Method 3: Difference between gcamp signal and minimum gcamp value (avg background intensity of well)
# This difference correspond to the height of the signal itself as it is corrected for background intensity already.
peakheight_wellmin = signal[peak]
peak_heights_wellmin.append(peakheight_wellmin)
return half_maximums, peak_halfmax_starts, peak_halfmax_ends, peak_rise_starts, peak_fall_ends, peak_heights_signalmin, peak_heights_localmin, peak_heights_wellmin
def wavelet_peak(gcamp, max_scale, min_length_0, min_snr_0, noise_perc_0):
widths = numpy.arange(1,max_scale,1)
peakind = find_peaks_cwt(detrend(gcamp), widths, max_distances=widths/2, gap_thresh=3, min_length=min_length_0, min_snr=min_snr_0, noise_perc=noise_perc_0)
if len(peakind) == 0:
peakind = [0]
return peakind
"""
x: signal
min_peak_height: anything smaller than that will be rejected
edge: {'rising','falling','both'} --> determine which indices to keep for irregular peaks, plateaus, etc.
valley: if true, will returns indices of valleys instead of peaks
min_rel_height_neighbor: specifies a minimum relative height difference between peaks and their immediate neighbors
min_peak_distance: minimum distance that must separate each peak for them to be valid
keep_peaks_same_height: keep peaks of same height even if closer than min_peak_distance
Returns indices of identified peaks
"""
def find_peaks(x, min_peak_height=None, edge='rising', valley=False, min_rel_height_neighbor=0, min_peak_distance=1,
keep_peaks_same_height=False):
# need at least 3 points to identify valid peaks
if x.size < 3:
return numpy.array([], dtype=int)
# if looking for valleys, invert the signal and look for peaks
if valley:
x = -x
# identify the different types of peaks
dx = numpy.diff(x)
singlePointPeaks, risingEdgePeaks, fallingEdgePeaks = numpy.array([[], [], []], dtype=int)
if not edge:
singlePointPeaks = numpy.where((numpy.hstack((dx, 0)) < 0) & (numpy.hstack((0, dx)) > 0))[0]
else:
if edge.lower() in ['rising', 'both']:
risingEdgePeaks = numpy.where((numpy.hstack((dx, 0)) <= 0) & (numpy.hstack((0, dx)) > 0))[0]
if edge.lower() in ['falling', 'both']:
fallingEdgePeaks = numpy.where((numpy.hstack((dx, 0)) < 0) & (numpy.hstack((0, dx)) >= 0))[0]
ind = numpy.unique(numpy.hstack((singlePointPeaks, risingEdgePeaks, fallingEdgePeaks)))
# first and last values of x cannot be peaks
if ind.size and ind[0] == 0:
ind = ind[1:]
if ind.size and ind[-1] == x.size - 1:
ind = ind[:-1]
# keep only peaks > minimum peak height
if ind.size and min_peak_height is not None:
ind = ind[x[ind] >= min_peak_height]
# remove peaks that are less than "neighbor_threshold" higher than their neighbors
if ind.size and min_rel_height_neighbor > 0:
dx_neighbors = numpy.min(numpy.vstack([x[ind] - x[ind - 1], x[ind] - x[ind + 1]]), axis=0)
ind = numpy.delete(ind, numpy.where(dx_neighbors < min_rel_height_neighbor)[0])
# identify peaks closer to one another than min_peak_distance
if ind.size and min_peak_distance > 1:
ind = ind[numpy.argsort(x[ind])][::-1] # sort ind by peak height
idel = numpy.zeros(ind.size, dtype=bool)
for i in range(ind.size):
if not idel[i]:
# keep peaks with the same height if kpsh is True
idel = idel | (ind >= ind[i] - min_peak_distance) & (ind <= ind[i] + min_peak_distance) \
& (x[ind[i]] > x[ind] if keep_peaks_same_height else True)
idel[i] = 0 # Keep current peak
# remove the small peaks and sort back the indexes by their occurrence
ind = numpy.sort(ind[~idel])
return ind
# Returns wavelet analysis | |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
from collections import OrderedDict
from functools import partial
import numpy as np
from numpy.testing import assert_allclose
import pytest
from jax import random
import jax.numpy as jnp
from funsor import Tensor, bint, reals
import numpyro
from numpyro.contrib.control_flow import scan
from numpyro.contrib.funsor import config_enumerate, enum, markov, to_data, to_funsor
from numpyro.contrib.funsor.enum_messenger import NamedMessenger
from numpyro.contrib.funsor.enum_messenger import plate as enum_plate
from numpyro.contrib.funsor.infer_util import log_density
from numpyro.contrib.indexing import Vindex
import numpyro.distributions as dist
from numpyro.infer import MCMC, NUTS
from numpyro.primitives import _PYRO_STACK
def test_gaussian_mixture_model():
K, N = 3, 1000
def gmm(data):
mix_proportions = numpyro.sample("phi", dist.Dirichlet(jnp.ones(K)))
with numpyro.plate("num_clusters", K, dim=-1):
cluster_means = numpyro.sample("cluster_means", dist.Normal(jnp.arange(K), 1.))
with numpyro.plate("data", data.shape[0], dim=-1):
assignments = numpyro.sample("assignments", dist.Categorical(mix_proportions))
numpyro.sample("obs", dist.Normal(cluster_means[assignments], 1.), obs=data)
true_cluster_means = jnp.array([1., 5., 10.])
true_mix_proportions = jnp.array([0.1, 0.3, 0.6])
cluster_assignments = dist.Categorical(true_mix_proportions).sample(random.PRNGKey(0), (N,))
data = dist.Normal(true_cluster_means[cluster_assignments], 1.0).sample(random.PRNGKey(1))
nuts_kernel = NUTS(gmm)
mcmc = MCMC(nuts_kernel, num_warmup=500, num_samples=500)
mcmc.run(random.PRNGKey(2), data)
samples = mcmc.get_samples()
assert_allclose(samples["phi"].mean(0).sort(), true_mix_proportions, atol=0.05)
assert_allclose(samples["cluster_means"].mean(0).sort(), true_cluster_means, atol=0.2)
def test_bernoulli_latent_model():
def model(data):
y_prob = numpyro.sample("y_prob", dist.Beta(1., 1.))
with numpyro.plate("data", data.shape[0]):
y = numpyro.sample("y", dist.Bernoulli(y_prob))
z = numpyro.sample("z", dist.Bernoulli(0.65 * y + 0.1))
numpyro.sample("obs", dist.Normal(2. * z, 1.), obs=data)
N = 2000
y_prob = 0.3
y = dist.Bernoulli(y_prob).sample(random.PRNGKey(0), (N,))
z = dist.Bernoulli(0.65 * y + 0.1).sample(random.PRNGKey(1))
data = dist.Normal(2. * z, 1.0).sample(random.PRNGKey(2))
nuts_kernel = NUTS(model)
mcmc = MCMC(nuts_kernel, num_warmup=500, num_samples=500)
mcmc.run(random.PRNGKey(3), data)
samples = mcmc.get_samples()
assert_allclose(samples["y_prob"].mean(0), y_prob, atol=0.05)
def test_change_point():
def model(count_data):
n_count_data = count_data.shape[0]
alpha = 1 / jnp.mean(count_data.astype(np.float32))
lambda_1 = numpyro.sample('lambda_1', dist.Exponential(alpha))
lambda_2 = numpyro.sample('lambda_2', dist.Exponential(alpha))
# this is the same as DiscreteUniform(0, 69)
tau = numpyro.sample('tau', dist.Categorical(logits=jnp.zeros(70)))
idx = jnp.arange(n_count_data)
lambda_ = jnp.where(tau > idx, lambda_1, lambda_2)
with numpyro.plate("data", n_count_data):
numpyro.sample('obs', dist.Poisson(lambda_), obs=count_data)
count_data = jnp.array([
13, 24, 8, 24, 7, 35, 14, 11, 15, 11, 22, 22, 11, 57, 11,
19, 29, 6, 19, 12, 22, 12, 18, 72, 32, 9, 7, 13, 19, 23,
27, 20, 6, 17, 13, 10, 14, 6, 16, 15, 7, 2, 15, 15, 19,
70, 49, 7, 53, 22, 21, 31, 19, 11, 1, 20, 12, 35, 17, 23,
17, 4, 2, 31, 30, 13, 27, 0, 39, 37, 5, 14, 13, 22,
])
kernel = NUTS(model)
mcmc = MCMC(kernel, num_warmup=500, num_samples=500)
mcmc.run(random.PRNGKey(0), count_data)
samples = mcmc.get_samples()
assert_allclose(samples["lambda_1"].mean(0), 18., atol=1.)
assert_allclose(samples["lambda_2"].mean(0), 22.5, atol=1.5)
def test_gaussian_hmm():
dim = 4
num_steps = 10
def model(data):
with numpyro.plate("states", dim):
transition = numpyro.sample("transition", dist.Dirichlet(jnp.ones(dim)))
emission_loc = numpyro.sample("emission_loc", dist.Normal(0, 1))
emission_scale = numpyro.sample("emission_scale", dist.LogNormal(0, 1))
trans_prob = numpyro.sample("initialize", dist.Dirichlet(jnp.ones(dim)))
for t, y in markov(enumerate(data)):
x = numpyro.sample("x_{}".format(t), dist.Categorical(trans_prob))
numpyro.sample("y_{}".format(t), dist.Normal(emission_loc[x], emission_scale[x]), obs=y)
trans_prob = transition[x]
def _generate_data():
transition_probs = np.random.rand(dim, dim)
transition_probs = transition_probs / transition_probs.sum(-1, keepdims=True)
emissions_loc = np.arange(dim)
emissions_scale = 1.
state = np.random.choice(3)
obs = [np.random.normal(emissions_loc[state], emissions_scale)]
for _ in range(num_steps - 1):
state = np.random.choice(dim, p=transition_probs[state])
obs.append(np.random.normal(emissions_loc[state], emissions_scale))
return np.stack(obs)
data = _generate_data()
nuts_kernel = NUTS(model)
mcmc = MCMC(nuts_kernel, num_warmup=500, num_samples=500)
mcmc.run(random.PRNGKey(0), data)
def test_iteration():
def testing():
for i in markov(range(5)):
v1 = to_data(Tensor(jnp.ones(2), OrderedDict([(str(i), bint(2))]), 'real'))
v2 = to_data(Tensor(jnp.zeros(2), OrderedDict([('a', bint(2))]), 'real'))
fv1 = to_funsor(v1, reals())
fv2 = to_funsor(v2, reals())
print(i, v1.shape) # shapes should alternate
if i % 2 == 0:
assert v1.shape == (2,)
else:
assert v1.shape == (2, 1, 1)
assert v2.shape == (2, 1)
print(i, fv1.inputs)
print('a', v2.shape) # shapes should stay the same
print('a', fv2.inputs)
with NamedMessenger():
testing()
def test_nesting():
def testing():
with markov():
v1 = to_data(Tensor(jnp.ones(2), OrderedDict([("1", bint(2))]), 'real'))
print(1, v1.shape) # shapes should alternate
assert v1.shape == (2,)
with markov():
v2 = to_data(Tensor(jnp.ones(2), OrderedDict([("2", bint(2))]), 'real'))
print(2, v2.shape) # shapes should alternate
assert v2.shape == (2, 1)
with markov():
v3 = to_data(Tensor(jnp.ones(2), OrderedDict([("3", bint(2))]), 'real'))
print(3, v3.shape) # shapes should alternate
assert v3.shape == (2,)
with markov():
v4 = to_data(Tensor(jnp.ones(2), OrderedDict([("4", bint(2))]), 'real'))
print(4, v4.shape) # shapes should alternate
assert v4.shape == (2, 1)
with NamedMessenger():
testing()
def test_staggered():
def testing():
for i in markov(range(12)):
if i % 4 == 0:
v2 = to_data(Tensor(jnp.zeros(2), OrderedDict([('a', bint(2))]), 'real'))
fv2 = to_funsor(v2, reals())
assert v2.shape == (2,)
print('a', v2.shape)
print('a', fv2.inputs)
with NamedMessenger():
testing()
def test_nested_plate():
with enum(first_available_dim=-3):
with enum_plate("a", 5):
with enum_plate("b", 2):
x = numpyro.sample("x", dist.Normal(0, 1), rng_key=random.PRNGKey(0))
assert x.shape == (2, 5)
@pytest.mark.parametrize('num_steps', [1, 10, 11])
def test_scan_enum_one_latent(num_steps):
data = random.normal(random.PRNGKey(0), (num_steps,))
init_probs = jnp.array([0.6, 0.4])
transition_probs = jnp.array([[0.8, 0.2], [0.1, 0.9]])
locs = jnp.array([-1.0, 1.0])
def model(data):
x = None
for i, y in markov(enumerate(data)):
probs = init_probs if x is None else transition_probs[x]
x = numpyro.sample(f"x_{i}", dist.Categorical(probs))
numpyro.sample(f"y_{i}", dist.Normal(locs[x], 1), obs=y)
return x
def fun_model(data):
def transition_fn(x, y):
probs = init_probs if x is None else transition_probs[x]
x = numpyro.sample("x", dist.Categorical(probs))
numpyro.sample("y", dist.Normal(locs[x], 1), obs=y)
return x, None
x, collections = scan(transition_fn, None, data)
assert collections is None
return x
actual_log_joint = log_density(enum(config_enumerate(fun_model)), (data,), {}, {})[0]
expected_log_joint = log_density(enum(config_enumerate(model)), (data,), {}, {})[0]
assert_allclose(actual_log_joint, expected_log_joint)
actual_last_x = enum(config_enumerate(fun_model))(data)
expected_last_x = enum(config_enumerate(model))(data)
assert_allclose(actual_last_x, expected_last_x)
def test_scan_enum_plate():
N, D = 10, 3
data = random.normal(random.PRNGKey(0), (N, D))
init_probs = jnp.array([0.6, 0.4])
transition_probs = jnp.array([[0.8, 0.2], [0.1, 0.9]])
locs = jnp.array([-1.0, 1.0])
def model(data):
x = None
D_plate = numpyro.plate("D", D, dim=-1)
for i, y in markov(enumerate(data)):
with D_plate:
probs = init_probs if x is None else transition_probs[x]
x = numpyro.sample(f"x_{i}", dist.Categorical(probs))
numpyro.sample(f"y_{i}", dist.Normal(locs[x], 1), obs=y)
def fun_model(data):
def transition_fn(x, y):
probs = init_probs if x is None else transition_probs[x]
with numpyro.plate("D", D, dim=-1):
x = numpyro.sample("x", dist.Categorical(probs))
numpyro.sample("y", dist.Normal(locs[x], 1), obs=y)
return x, None
scan(transition_fn, None, data)
actual_log_joint = log_density(enum(config_enumerate(fun_model), -2), (data,), {}, {})[0]
expected_log_joint = log_density(enum(config_enumerate(model), -2), (data,), {}, {})[0]
assert_allclose(actual_log_joint, expected_log_joint)
def test_scan_enum_separated_plates_same_dim():
N, D1, D2 = 10, 3, 4
data = random.normal(random.PRNGKey(0), (N, D1 + D2))
data1, data2 = data[:, :D1], data[:, D1:]
init_probs = jnp.array([0.6, 0.4])
transition_probs = jnp.array([[0.8, 0.2], [0.1, 0.9]])
locs = jnp.array([-1.0, 1.0])
def model(data1, data2):
x = None
D1_plate = numpyro.plate("D1", D1, dim=-1)
D2_plate = numpyro.plate("D2", D2, dim=-1)
for i, (y1, y2) in markov(enumerate(zip(data1, data2))):
probs = init_probs if x is None else transition_probs[x]
x = numpyro.sample(f"x_{i}", dist.Categorical(probs))
with D1_plate:
numpyro.sample(f"y1_{i}", dist.Normal(locs[x], 1), obs=y1)
with D2_plate:
numpyro.sample(f"y2_{i}", dist.Normal(locs[x], 1), obs=y2)
def fun_model(data1, data2):
def transition_fn(x, y):
y1, y2 = y
probs = init_probs if x is None else transition_probs[x]
x = numpyro.sample("x", dist.Categorical(probs))
with numpyro.plate("D1", D1, dim=-1):
numpyro.sample("y1", dist.Normal(locs[x], 1), obs=y1)
with numpyro.plate("D2", D2, dim=-1):
numpyro.sample("y2", dist.Normal(locs[x], 1), obs=y2)
return x, None
scan(transition_fn, None, (data1, data2))
actual_log_joint = log_density(enum(config_enumerate(fun_model), -2), (data1, data2), {}, {})[0]
expected_log_joint = log_density(enum(config_enumerate(model), -2), (data1, data2), {}, {})[0]
assert_allclose(actual_log_joint, expected_log_joint)
def test_scan_enum_separated_plate_discrete():
N, D = 10, 3
data = random.normal(random.PRNGKey(0), (N, D))
transition_probs = jnp.array([[0.8, 0.2], [0.1, 0.9]])
locs = jnp.array([[-1.0, 1.0], [2.0, 3.0]])
def model(data):
x = 0
D_plate = numpyro.plate("D", D, dim=-1)
for i, y in markov(enumerate(data)):
probs = transition_probs[x]
x = numpyro.sample(f"x_{i}", dist.Categorical(probs))
with D_plate:
w = numpyro.sample(f"w_{i}", dist.Bernoulli(0.6))
numpyro.sample(f"y_{i}", dist.Normal(Vindex(locs)[x, w], 1), obs=y)
def fun_model(data):
def transition_fn(x, y):
probs = transition_probs[x]
x = numpyro.sample("x", dist.Categorical(probs))
with numpyro.plate("D", D, dim=-1):
w = numpyro.sample("w", dist.Bernoulli(0.6))
numpyro.sample("y", dist.Normal(Vindex(locs)[x, w], 1), obs=y)
return x, None
scan(transition_fn, 0, data)
actual_log_joint = log_density(enum(config_enumerate(fun_model), -2), (data,), {}, {})[0]
expected_log_joint = log_density(enum(config_enumerate(model), -2), (data,), {}, {})[0]
assert_allclose(actual_log_joint, expected_log_joint)
def test_scan_enum_discrete_outside():
data = random.normal(random.PRNGKey(0), (10,))
probs = jnp.array([[[0.8, 0.2], [0.1, 0.9]],
[[0.7, 0.3], [0.6, 0.4]]])
locs = jnp.array([-1.0, 1.0])
def model(data):
w = numpyro.sample("w", dist.Bernoulli(0.6))
x = 0
for i, y in markov(enumerate(data)):
x = numpyro.sample(f"x_{i}", dist.Categorical(probs[w, x]))
numpyro.sample(f"y_{i}", dist.Normal(locs[x], 1), obs=y)
def fun_model(data):
w = numpyro.sample("w", dist.Bernoulli(0.6))
def transition_fn(x, y):
x = numpyro.sample("x", dist.Categorical(probs[w, x]))
numpyro.sample("y", dist.Normal(locs[x], 1), obs=y)
return x, None
scan(transition_fn, 0, data)
actual_log_joint = log_density(enum(config_enumerate(fun_model)), (data,), {}, {})[0]
expected_log_joint = log_density(enum(config_enumerate(model)), (data,), {}, {})[0]
assert_allclose(actual_log_joint, expected_log_joint)
def test_scan_enum_two_latents():
num_steps = 11
data = random.normal(random.PRNGKey(0), (num_steps,))
probs_x = jnp.array([[0.8, 0.2], [0.1, 0.9]])
probs_w = jnp.array([[0.7, 0.3], [0.6, 0.4]])
locs = jnp.array([[-1.0, 1.0], [2.0, 3.0]])
def model(data):
x = w = 0
for i, y in markov(enumerate(data)):
x = numpyro.sample(f"x_{i}", dist.Categorical(probs_x[x]))
w = numpyro.sample(f"w_{i}", dist.Categorical(probs_w[w]))
numpyro.sample(f"y_{i}", dist.Normal(locs[w, x], 1), obs=y)
def fun_model(data):
def transition_fn(carry, y):
x, w = carry
x = numpyro.sample("x", dist.Categorical(probs_x[x]))
w = numpyro.sample("w", dist.Categorical(probs_w[w]))
numpyro.sample("y", dist.Normal(locs[w, x], 1), obs=y)
# also test if scan's `ys` are | |
a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + b +
let a = b in a + | |
= (-0.1,0.1))
return fig
def correlation_plots(self, df=None, dfuw=None):
"""correlation plots
We assume that the UW sources correponding to 3FHL sources must have detected photons above 10 GeV.
We use the TS for the energy bands above
10 GeV, called TS10 below, as a measure. Out the ~11K sources with TS>10, %(numuw)d satisfy this.
<br>Left: histogram of closested distance
<br>Right: Venn diagram, showing number in common, selected from the 3FHL closest
"""
from matplotlib_venn import venn2
if df is None: df=self.gdf;
if dfuw is None: dfuw=self.df
fig, axx =plt.subplots(1,2, figsize=(12,6))
ax=axx[0]
hist_kw=dict(bins=np.linspace(0,0.5, 26), histtype='step', log=True,lw=2)
ax.hist(self.cl_fhl[:,1].clip(0,1800)/3600.,
label='{} [{}]'.format('3FHL',len(self.cl_fhl)), **hist_kw);
ax.hist(self.cl_uw[:,1].clip(0,1800)/3600.,
label='{} [{}]'.format('uw7000',len(self.cl_uw)), color='orange',**hist_kw);
ax.axvline(self.angle_cut, color='red', ls='--', label='angle cut')
plt.setp(ax, ylim=(0.8,None), xlabel='distance (deg)', title='minimum distance')
ax.legend(loc='upper left');
ax.grid(alpha=0.5)
# make a Venn diagram
self.common=common = sum(df.uwok)
self.numuw=len(dfuw)
v=venn2(ax=axx[1], subsets=(len(dfuw)-common, len(df.uwok)-common,common)
,set_labels=('uw7000 with TS10>{}'.format(self.uwts10_min),'3FHL'))
for text in v.set_labels:
text.set_fontsize(14)
fig.set_facecolor('white')
return fig
def all_plots(self):
self.runfigures([
self.seed_selection,
self.seed_plots,
self.acceptance_plots,
self.rejected_source_info,
self.lost_source_info,
self.comparison_plots,
self.quality_check_plots,
]
)
#======================================================
# seed stuff
def get_seeds(pattern='605'):
seeded = np.array([name.startswith(pattern) for name in df.index]);
sdf = df[seeded].copy(); sdf.head()['ts']
print ('Pattern {}: {} seeds, {} with TS>25, {} kept in 4FGL'.format(
pattern, sum(seeded), sum(sdf.ts>25), sum(sdf.fl8y)))
sdf['key'] = [name[3] for name in sdf.index]
return sdf
def plot_seeds(sdf, tsmax=100, title=None):
groups = sdf.groupby('key');
fig, axx = plt.subplots(2,3, figsize=(15,10))
hatch_type=dict(H='//', F=r'\\', S='||', P='//', N=r'\\')
for name, group in groups:
hkw = dict( histtype='stepfilled', lw=2,
alpha=0.25,edgecolor='black', hatch=hatch_type[name])
label = dict(H='hard',F='flat',S='soft', P='peaked', N='psr')[name]
curved = dict(H=0, F=0, S=0, P=1, N=1)[name]
pi = np.array(group.pindex, float)
ts = np.array(group.ts, float).clip(0,tsmax)
axi = axx[curved,0] # photon index
axi.hist(pi, np.linspace(1, 3.5, 16), label=label, **hkw)
if curved==0:
x = dict(hard=1.8, flat=2.2, soft=2.7)[label]
axi.axvline(x, ls='--')
axi.set(xlabel='Photon index')
axt = axx[curved,1] # TS
axt.hist(ts, np.linspace(10, tsmax, 21), label=label, **hkw)
axt.set(xlabel='TS')
e0 = np.array(group.e0, float).clip(100,1e5)
axe = axx[curved, 2] # Pivot Energy
axe.hist(e0, np.logspace(2,5,16), label=label, **hkw)
axe.set(xlabel='Pivot Energy [MeV]', xscale='log', xlim=(1e2,1e5))
for ax in axx.flatten():
ax.legend();
fig.tight_layout()
fig.subplots_adjust(top=0.92)
if title is not None: fig.suptitle(title, fontsize=24)
class GtlikeComparison(sourcecomparison.SourceComparison):
"""Results of comparison with glike
Gtlike version: %(catname)s <br>Compare the two lists of sources and spectral parameters, assuming that the skymodel names
correspond to the "NickName" field in the gtlike-generated FITS file.
Assume that a special run has been made to evaluate the likelihoods for the gtlike models.
"""
def setup(self, catpat=None, **kw):
if catpat is None:
catpat = self.config['gllcat']
pat = os.path.expandvars(os.path.join('$FERMI','catalog', catpat))
gllcats = sorted(glob.glob(pat))
assert len(gllcats)>0, 'No gtlike catalogs found using {}'.format(pat)
cat = gllcats[-1]
catname= os.path.split(cat)[-1]
super(GtlikeComparison, self).setup(cat=cat, catname=catname ) #cat.split('_')[-1].split('.')[0], **kw)
cat_version = (catname.split('_')[2]).lower()
assert cat_version[0]=='v', 'expected version in 3rd token of %s' %catname
self.plotfolder = 'comparison_%s' % cat_version
# make copy of the df index with no blanks in names, for comparison, combination
cname = [n.replace(' ','') for n in self.df.index]
gtname_dict= dict(zip(cname,self.df.index)) # look up original name, w/ blanks
self.dfx = self.df.copy()
self.dfx.index=cname
#make a data frame from the analysis
ff, tt = self.load_pickles('gtlike/models')
gtcat = dict()
for t in tt:
for s in t:
gtcat[s['name']] = s
#gtcat[s[0]]=s[1]
self.gdf = pd.DataFrame(gtcat).T
self.gdf.index = [n.replace(' ','') for n in self.gdf.name]
print ('loaded analysis of gtlike fit models, found %d sources' % len(self.gdf))
# copy info from gtlike to columns of corresponding skymodel entries
for col in self.gdf.columns:
self.dfx[col] = self.gdf[col]
df = self.dfx
self.delta = df.ts-df.other_ts
df['name3'] = self.cat.name3
df['plane']= np.abs(df.glat)<5
df['ts_gtlike']= self.cat.ts ## should be the TS from the catalog
df['ts_delta'] = self.delta
df['ts_gt'] = df.other_ts
df['index_gt'] = [m['Index'] if isinstance(m, Models.Model) else np.nan for m in self.dfx.othermodel]
df['ts_pt'] = df.ts
df['no_gtlike'] = pd.isnull(df.ts_gtlike) * (~np.isinf(df.ts_gtlike))
df['pivot_gt'] = self.cat['pivot']
df['flux_gt'] = self.cat.flux
df['modflux'] =[m(e) for (m, e ) in zip(df.model, df.pivot_gt)]
df['flux_ratio']= df.modflux/df.flux_gt
# finally, restore the blanks in the index for self.dfx
df.index = [gtname_dict[n] for n in df.index]
def pulsar_candidates(self, mints=16):
"""Pulsar candidate selection
Only choose those that are NOT in the gtlike list
%(pulsar_pivot_info)s
"""
df = self.dfx
cut = cut = (df.no_gtlike) & (np.abs(df.glat)>5) & (df.ts>mints)
sedrec = self.dfx['sedrec']
tflow = []
tfmed = []
for sr in sedrec:
ts = sum(sr.ts)
low, middle, high = [sum(sr.ts[i:i+4]/ts).round(2) for i in (0,4,8)]
tflow.append(low)
tfmed.append(middle)
self.dfx['tflow']=tflow
self.dfx['tfmed']=tfmed
pcand = df[cut & (df.tfmed>0.6) & (df.locqual<5)]['ra dec glat glon ts tflow tfmed a locqual'.split()]; print (len(pcand))
pcand.index.name='name'
pcand.to_csv('weak_pulsar_candidate.csv')
try:
pc=makepivot.MakeCollection('weak pulsar candidates', 'sedfig', 'weak_pulsar_candidate.csv', refresh=True)
self.pulsar_pivot_info="""<p> These can be examined with a
<a href="http://deeptalk.phys.washington.edu/PivotWeb/SLViewer.html?cID=%d">Pivot browser</a>,
which requires Silverlight. """% pc.cId
except Exception as msg:
self.pulsar_pivot_info = '<p>No pivot output; job failed %s' %msg
fig, axx = plt.subplots(1,2, figsize=(10,4))
def scat_low_med(ax):
ax.plot(df[cut]['tflow'], df[cut]['tfmed'], '.')
plt.setp(ax, xlabel='low TS fraction', ylabel='medium TS fraction',
xlim=(-0.02,1), ylim=(-0.02, 1))
def hist_med(ax):
ax.hist(df[cut]['tfmed'], np.linspace(0,1,26))
plt.setp(ax, xlabel='medium TS fraction')
hist_med(axx[0]); scat_low_med(axx[1])
return fig
def check_contents(self):
"""Contents of the two lists
%(content_differences)s
"""
df = self.dfx
gtnames = set(self.cat.index.values)
ptnames = set(map(lambda s:s.replace(' ',''), df.index.values))
added, lost = list(gtnames.difference(ptnames)), sorted(list(ptnames.difference(gtnames)))
s = html_table(self.cat.ix[added]['ra dec ts'.split()],
dict(ts='TS, gtlike TS', ra='RA,', dec='Dec,'),
heading = '\n<h4>Sources in gtlike not in pointlike</h4>',
float_format=FloatFormat(2), maxlines=50)
cut50 = (df.no_gtlike)*((df.ts>50)+df.psr*(df.ts>10))
missing50 = df.ix[np.array(cut50,bool)]['ra dec ts fitqual locqual roiname'.split()]
s += html_table(missing50,
dict(ts='TS, pointlike TS', ra='RA,', dec='Dec,', fitqual=',Fit quality,',
locqual=',Localization quality; this is NaN for extended sources'),
heading='\n<h4>Sources with pointlike TS>50 or LAT pulsars and TS>10, not in gtlike</h4>',
float_format=FloatFormat(2), maxlines=50)
s += html_table(df.ix[np.isinf(df.ts_gtlike.values)] ['ra dec ts fitqual locqual roiname'.split()],
dict(ts='TS, pointlike TS', ra='RA,', dec='Dec,', fitqual=',Fit quality,',
locqual=',Localization quality; this is NaN for extended sources'),
heading = '\n<h4>Sources present, but not fit by gtlike</h4>',
float_format=FloatFormat(2), maxlines=50)
self.content_differences = s
def compare_fits(self):
""" Compare spectral quantities for sources common to both models
<br><b>Top Left: </b> Gtlike TS distribution.
<br><b>Top center:</b> Gtlike TS vs. pointlike TS, showing the high latitude subset.
<br><b>Top right: </b> Comparison of the pivot energies.
<br><b>Bottom: </b>Ratio of pointlike differential flux at gtlike pivot energy, vs ptlike flux.
"""
df = self.dfx
cat = self.cat
lowlat = np.abs(df.glat)<5
psr = df.modelname=='PLSuperExpCutoff'
def plot1(ax):
ax.hist(self.cat.ts.clip(0,1000), np.logspace(1,3,41))
plt.setp(ax, xscale='log', ylim=(0,200), xlabel='gtlike TS')
ax.grid()
ax.axvline(25, color='g')
def plot2(ax, lim=(10,1e4)):
df['ts_gtlike'] = self.cat.ts
ax.loglog(df.ts_gtlike, df.ts, '.')
ax.plot(df.ts_gtlike[lowlat], df.ts[lowlat], '.r', label='|b|<5')
ax.plot(lim, lim, '--g')
plt.setp(ax, xlabel='gtlike TS', ylabel='pointlike TS', xlim=lim,ylim=lim)
ax.grid()
ax.legend(loc='upper left', prop=dict(size=10))
ax.axvline(25, color='g')
def plot_pivot(ax, xylim = (100,3e4)):
self.dfx['pivot_gt'] = self.cat['pivot']
ax.loglog(self.dfx.pivot_gt, self.dfx.e0, '.')
plt.setp(ax, xlim=xylim, ylim=xylim, xlabel='gtlike pivot', ylabel='pointlike pivot')
ax.plot(xylim, xylim, '--g')
ax.grid();
def plot_flux_ratio(ax):
df['pivot_gt'] = cat['pivot']
df['flux_gt'] = cat.flux
df['modflux'] =[m(e) for (m, e ) in zip(df.model, df.pivot_gt)]
ax.loglog(df.modflux, df.modflux/df.flux_gt, '.')
ax.loglog(df.modflux[lowlat], (df.modflux/df.flux_gt)[lowlat], '.r', label='|b|<5')
plt.setp(ax, ylim=(0.5,2.0), xlim=(1e-15, 2e-9), xlabel='ptlike flux at gtlike pivot', ylabel='pt/gt flux ratio')
ax.axhline(1, color='gray')
for u in (0.95,1.05):
ax.axhline(u, ls='--', color='orange')
ax.set_yticks((0.5, 0.8, 1.0, 1.25, 2.0))
ax.set_yticklabels('0.5 0.8 1.0 1.25 2.0'.split())
ax.legend()
ax.grid()
gs = gridspec.GridSpec(2,3)
gs.update(wspace=0.3, hspace=0.3)
fig = plt.figure(figsize=(12,8))
axx = [plt.subplot(gs[0,col]) for col in range(3)]
axx.append(plt.subplot(gs[1,:]) )
toplot = [plot1, plot2, plot_pivot, plot_flux_ratio]
for f, ax in zip(toplot, axx):
f(ax)
return fig
def galactic_distortion(self):
"""Galactic plane distortion
Check for distortion of the spectral fits to moderate strength sources near the galactic plane.
Sources were selected with flux to the range $10^{-13}$ to $10^{-11}$.
</br>
<b>Top row:</b> Histograms of the ratio of fluxes, spectral indeces, and the correlation.
<br>
<b>Bottom row:</b> Histogram of the TS difference, and that compared with the flux ratio for galactic sources.
"""
df = self.dfx
cut1 = (df.modflux>1e-13) & (df.modflux<1e-11)
cut2 = cut1 & (np.abs(df.glat)<10)
cut2_label='|b|<10'
def plot1(ax):
ax.hist((df.modflux/df.flux_gt)[cut1], np.linspace(0,2))
ax.hist((df.modflux/df.flux_gt)[cut2], np.linspace(0,2), color='orange',label=cut2_label)
plt.setp(ax, xlabel='pt/gt flux ratio')
ax.legend(prop=dict(size=10)); ax.grid()
def plot2(ax, space=np.linspace(0.75, 1.25)):
ax.hist((df.pindex/df.index_gt)[cut1], space)
ax.hist((df.pindex/df.index_gt)[cut2], space, color='orange', label=cut2_label)
plt.setp(ax, xlabel='pt/gt index ratio')
ax.legend(prop=dict(size=10)); ax.grid()
def plot3(ax):
ax.plot((df.modflux/df.flux_gt)[cut2], (df.pindex/df.index_gt)[cut2], '.', color='blue')
plt.setp(ax, xlim=(0,2), xlabel='flux ratio', ylim=(0.75, 1.25), ylabel='index ratio')
ax.grid()
tdlim=(-50,50); tsdiff_label='TS_pt-TS_gtlike'
tsdiff =(df.ts_pt-df.ts_gtlike).clip(*tdlim)
tdspace=np.linspace(*tdlim)
def plot4(ax):
ax.hist(tsdiff[cut1], tdspace)
ax.hist(tsdiff[cut2], tdspace, color='orange', label=cut2_label)
ax.grid(); ax.legend(prop=dict(size=10))
plt.setp(ax, xlabel=tsdiff_label, xlim=tdlim)
def plot5(ax):
ax.plot( (df.modflux/df.flux_gt)[cut2], tsdiff[cut2], '.')
plt.setp(ax, xlim=(0.,2.0), | |
value):
self._storage[self._wrap_key(key)] = value
def __delitem__(self, key):
del self._storage[self._wrap_key(key)]
def __len__(self):
return len(self._storage)
def __iter__(self):
for key in self._storage:
yield key.unwrapped
class _ObjectIdentityWeakKeyDictionary(_ObjectIdentityDictionary):
"""Like weakref.WeakKeyDictionary, but compares objects with "is"."""
def _wrap_key(self, key):
return _WeakObjectIdentityWrapper(key)
def __len__(self):
# Iterate, discarding old weak refs
return len(list(self._storage))
def __iter__(self):
keys = self._storage.keys()
for key in keys:
unwrapped = key.unwrapped
if unwrapped is None:
del self[key]
else:
yield unwrapped
class _ObjectIdentityWeakSet(collections.MutableSet):
"""Like weakref.WeakSet, but compares objects with "is"."""
def __init__(self):
self._storage = set()
def __contains__(self, key):
return _WeakObjectIdentityWrapper(key) in self._storage
def discard(self, key):
self._storage.discard(_WeakObjectIdentityWrapper(key))
def add(self, key):
self._storage.add(_WeakObjectIdentityWrapper(key))
def __len__(self):
# Iterate, discarding old weak refs
return len(list(self))
def __iter__(self):
keys = list(self._storage)
for key in keys:
unwrapped = key.unwrapped
if unwrapped is None:
self.discard(key)
else:
yield unwrapped
def _breadth_first_checkpointable_traversal(root_checkpointable):
"""Find shortest paths to all variables owned by dependencies of root."""
bfs_sorted = []
to_visit = collections.deque([root_checkpointable])
path_to_root = _ObjectIdentityDictionary()
path_to_root[root_checkpointable] = ()
while to_visit:
current_checkpointable = to_visit.popleft()
if isinstance(current_checkpointable, tracking.NotCheckpointable):
raise NotImplementedError(
("The object %s does not support object-based saving. File a feature "
"request if this limitation bothers you. In the meantime, you can "
"remove the dependency on this object and save everything else.")
% (current_checkpointable,))
current_checkpointable._maybe_initialize_checkpointable() # pylint: disable=protected-access
bfs_sorted.append(current_checkpointable)
for child_checkpointable in (
current_checkpointable._checkpoint_dependencies): # pylint: disable=protected-access
if child_checkpointable.ref not in path_to_root:
path_to_root[child_checkpointable.ref] = (
path_to_root[current_checkpointable] + (child_checkpointable,))
to_visit.append(child_checkpointable.ref)
return bfs_sorted, path_to_root
def _escape_local_name(name):
# We need to support slashes in local names for compatibility, since this
# naming scheme is being patched in to things like Layer.add_variable where
# slashes were previously accepted. We also want to use slashes to indicate
# edges traversed to reach the variable, so we escape forward slashes in
# names.
return (name.replace(_ESCAPE_CHAR, _ESCAPE_CHAR + _ESCAPE_CHAR)
.replace(r"/", _ESCAPE_CHAR + "S"))
def _object_prefix_from_path(path_to_root):
return "/".join(
(_escape_local_name(checkpointable.name)
for checkpointable in path_to_root))
def _slot_variable_naming_for_optimizer(optimizer_path):
"""Make a function for naming slot variables in an optimizer."""
# Name slot variables:
#
# <variable name>/<_OPTIMIZER_SLOTS_NAME>/<optimizer path>/<slot name>
#
# where <variable name> is exactly the checkpoint name used for the original
# variable, including the path from the checkpoint root and the local name in
# the object which owns it. Note that we only save slot variables if the
# variable it's slotting for is also being saved.
optimizer_identifier = "/%s/%s/" % (_OPTIMIZER_SLOTS_NAME, optimizer_path)
def _name_slot_variable(variable_path, slot_name):
"""With an optimizer specified, name a slot variable."""
return (variable_path
+ optimizer_identifier
+ _escape_local_name(slot_name))
return _name_slot_variable
def _serialize_slot_variables(checkpointable_objects, node_ids, object_names):
"""Gather and name slot variables."""
non_slot_objects = list(checkpointable_objects)
slot_variables = _ObjectIdentityDictionary()
for checkpointable in non_slot_objects:
if isinstance(checkpointable, optimizer_lib.Optimizer):
naming_scheme = _slot_variable_naming_for_optimizer(
optimizer_path=object_names[checkpointable])
slot_names = checkpointable.get_slot_names()
for slot_name in slot_names:
for original_variable_node_id, original_variable in enumerate(
non_slot_objects):
try:
slot_variable = checkpointable.get_slot(
original_variable, slot_name)
except AttributeError:
slot_variable = None
if slot_variable is None:
continue
slot_variable._maybe_initialize_checkpointable() # pylint: disable=protected-access
if slot_variable._checkpoint_dependencies: # pylint: disable=protected-access
# TODO(allenl): Gather dependencies of slot variables.
raise NotImplementedError(
"Currently only variables with no dependencies can be saved as "
"slot variables. File a feature request if this limitation "
"bothers you.")
if slot_variable in node_ids:
raise NotImplementedError(
"A slot variable was re-used as a dependency of a "
"Checkpointable object. This is not currently allowed. File a "
"feature request if this limitation bothers you.")
checkpoint_name = naming_scheme(
variable_path=object_names[original_variable],
slot_name=slot_name)
object_names[slot_variable] = checkpoint_name
slot_variable_node_id = len(checkpointable_objects)
node_ids[slot_variable] = slot_variable_node_id
checkpointable_objects.append(slot_variable)
slot_variable_proto = (
checkpointable_object_graph_pb2.CheckpointableObjectGraph
.CheckpointableObject.SlotVariableReference(
slot_name=slot_name,
original_variable_node_id=original_variable_node_id,
slot_variable_node_id=slot_variable_node_id))
slot_variables.setdefault(checkpointable, []).append(
slot_variable_proto)
return slot_variables
def _serialize_checkpointables(
checkpointable_objects, node_ids, object_names, slot_variables,
saveables_cache):
"""Name non-slot `Checkpointable`s and add them to `object_graph_proto`."""
object_graph_proto = (
checkpointable_object_graph_pb2.CheckpointableObjectGraph())
named_saveables = []
feed_additions = {}
for checkpoint_id, checkpointable in enumerate(checkpointable_objects):
assert node_ids[checkpointable] == checkpoint_id
object_proto = object_graph_proto.nodes.add()
object_proto.slot_variables.extend(slot_variables.get(checkpointable, ()))
object_name = object_names[checkpointable]
if saveables_cache is not None:
cached_attributes = saveables_cache.setdefault(checkpointable, {})
else:
cached_attributes = None
for name, saveable_factory in (
checkpointable._gather_saveables_for_checkpoint().items()): # pylint: disable=protected-access
attribute = object_proto.attributes.add()
attribute.name = name
attribute.checkpoint_key = "%s/%s/%s" % (
object_name, _OBJECT_ATTRIBUTES_NAME, _escape_local_name(name))
if cached_attributes is None:
saveables = None
else:
saveables = cached_attributes.get(name, None)
if saveables is not None:
for saveable in saveables:
if attribute.checkpoint_key not in saveable.name:
# The checkpoint key for this SaveableObject is different. We need
# to re-create it.
saveables = None
del cached_attributes[name]
break
if saveables is None:
if callable(saveable_factory):
maybe_saveable = saveable_factory(name=attribute.checkpoint_key)
else:
maybe_saveable = saveable_factory
if isinstance(maybe_saveable, saveable_object_lib.SaveableObject):
saveables = (maybe_saveable,)
else:
# Figure out the name-based Saver's name for this variable. If it's
# already a SaveableObject we'd just get the checkpoint key back, so
# we leave full_name blank.
saver_dict = saver_lib.BaseSaverBuilder.OpListToDict(
[maybe_saveable], convert_variable_to_tensor=False)
full_name, = saver_dict.keys()
saveables = tuple(saver_lib.BaseSaverBuilder.SaveableObjectsForOp(
op=maybe_saveable, name=attribute.checkpoint_key))
for saveable in saveables:
saveable.full_name = full_name
for saveable in saveables:
if attribute.checkpoint_key not in saveable.name:
raise AssertionError(
("The object %s produced a SaveableObject with name '%s' for "
"attribute '%s'. Expected a name containing '%s'.")
% (checkpointable, name, saveable.name,
attribute.checkpoint_key))
if cached_attributes is not None:
cached_attributes[name] = saveables
for saveable in saveables:
if hasattr(saveable, "full_name"):
attribute.full_name = saveable.full_name
saveable_feed_dict_fn = getattr(saveable, "feed_dict_additions", None)
if saveable_feed_dict_fn is not None:
saveable_feed_dict = saveable_feed_dict_fn() # pylint: disable=not-callable
for new_feed_key in saveable_feed_dict.keys():
if new_feed_key in feed_additions:
raise AssertionError(
("The object %s tried to feed a value for the Tensor %s "
"when saving, but another object is already feeding a "
"value.")
% (checkpointable, new_feed_key))
feed_additions.update(saveable_feed_dict)
named_saveables.extend(saveables)
for child in checkpointable._checkpoint_dependencies: # pylint: disable=protected-access
child_proto = object_proto.children.add()
child_proto.node_id = node_ids[child.ref]
child_proto.local_name = child.name
return named_saveables, object_graph_proto, feed_additions
def _serialize_object_graph(root_checkpointable, saveables_cache):
"""Determine checkpoint keys for variables and build a serialized graph.
Non-slot variables are keyed based on a shortest path from the root saveable
to the object which owns the variable (i.e. the one which called
`Checkpointable._add_variable` to create it).
Slot variables are keyed based on a shortest path to the variable being
slotted for, a shortest path to their optimizer, and the slot name.
Args:
root_checkpointable: A `Checkpointable` object whose variables (including
the variables of dependencies, recursively) should be saved.
saveables_cache: A dictionary mapping `Checkpointable` objects -> attribute
names -> SaveableObjects, used to avoid re-creating SaveableObjects when
graph building.
Returns:
A tuple of (named_variables, object_graph_proto, feed_additions):
named_variables: A dictionary mapping names to variable objects.
object_graph_proto: A CheckpointableObjectGraph protocol buffer containing
the serialized object graph and variable references.
feed_additions: A dictionary mapping from Tensors to values which should
be fed when saving.
Raises:
ValueError: If there are invalid characters in an optimizer's slot names.
"""
checkpointable_objects, path_to_root = (
_breadth_first_checkpointable_traversal(root_checkpointable))
object_names = _ObjectIdentityDictionary()
for obj, path in path_to_root.items():
object_names[obj] = _object_prefix_from_path(path)
node_ids = _ObjectIdentityDictionary()
for node_id, node in enumerate(checkpointable_objects):
node_ids[node] = node_id
slot_variables = _serialize_slot_variables(
checkpointable_objects=checkpointable_objects,
node_ids=node_ids,
object_names=object_names)
return _serialize_checkpointables(
checkpointable_objects=checkpointable_objects,
node_ids=node_ids,
object_names=object_names,
slot_variables=slot_variables,
saveables_cache=saveables_cache)
def list_objects(root_checkpointable):
"""Traverse the object graph and list all accessible objects.
Looks for `Checkpointable` objects which are dependencies of
`root_checkpointable`. Includes slot variables only if the variable they are
slotting for and the optimizer are dependencies of `root_checkpointable`
(i.e. if they would be saved with a checkpoint).
Args:
root_checkpointable: A `Checkpointable` object whose dependencies should be
flattened.
Returns:
A flat list of objects.
"""
# TODO(allenl): Extract out gathering logic so the naming logic doesn't have
# to run.
checkpointable_objects, path_to_root = (
_breadth_first_checkpointable_traversal(root_checkpointable))
object_names = _ObjectIdentityDictionary()
for obj, path in path_to_root.items():
object_names[obj] = _object_prefix_from_path(path)
node_ids = _ObjectIdentityDictionary()
for node_id, node in enumerate(checkpointable_objects):
node_ids[node] = node_id
_serialize_slot_variables(
checkpointable_objects=checkpointable_objects,
node_ids=node_ids,
object_names=object_names)
return checkpointable_objects
def gather_initializers(root_checkpointable):
"""Traverse the object graph and find initialization ops.
Looks for `Checkpointable` objects which are dependencies of
`root_checkpointable` and which have an `initializer` property. Includes
initializers for slot variables only if the variable they are slotting for and
the optimizer are dependencies of `root_checkpointable` (i.e. if they would be
saved with a checkpoint).
Args:
root_checkpointable: A `Checkpointable` object to gather initializers for.
Returns:
A list of initialization ops.
"""
checkpointable_objects = list_objects(root_checkpointable)
return [c.initializer for c in checkpointable_objects
if hasattr(c, "initializer") and c.initializer is not None]
@tf_contextlib.contextmanager
def capture_dependencies(template):
"""Capture variables created within this scope as `Template` dependencies.
Requires that `template.variable_scope` is active.
This scope is intended as | |
#################################################################################
def getThreePointCombinations(self, unique=False):
"""
-------------------------------------------------------------------------
Return all or only unique 3-point combinations of baselines
Input:
unique [boolean] If set to True, only unique 3-point combinations of
baseline triads are returned. If set to False (default), all
3-point combinations are returned.
Output:
Tuple containing two lists. The first list is a list of triplet tuples of
antenna labels in the form [(a1,a2,a3), (a1,a4,a6), ...], the second list
is a list of triplet tuples of baselines encoded as strings
-------------------------------------------------------------------------
"""
if not isinstance(unique, bool):
raise TypeError('Input unique must be boolean')
bl = self.baselines + 0.0 # to avoid any weird negative sign before 0.0
blstr = NP.unique(['{0[0]:.2f}_{0[1]:.2f}_{0[2]:.2f}'.format(lo) for lo in bl])
bltriplets = []
blvecttriplets = []
anttriplets = []
for aind1,albl1 in enumerate(self.layout['labels']):
for aind2,albl2 in enumerate(self.layout['labels']):
bl12 = self.layout['positions'][aind2] - self.layout['positions'][aind1]
bl12 += 0.0 # to avoid any weird negative sign before 0.0
bl12[NP.abs(bl12) < 1e-10] = 0.0
bl12_len = NP.sqrt(NP.sum(bl12**2))
if bl12_len > 0.0:
bl12str = '{0[0]:.2f}_{0[1]:.2f}_{0[2]:.2f}'.format(bl12)
if bl12str not in blstr:
bl12 *= -1
bl12 += 0.0 # to avoid any weird negative sign before 0.0
bl12str = '{0[0]:.2f}_{0[1]:.2f}_{0[2]:.2f}'.format(bl12)
if bl12str not in blstr:
warnings.warn('A baseline not found in the simulated reference baselines. Proceeding with the rest')
# raise IndexError('A baseline not found in reference baselines')
else:
for aind3,albl3 in enumerate(self.layout['labels']):
bl23 = self.layout['positions'][aind3] - self.layout['positions'][aind2]
bl31 = self.layout['positions'][aind1] - self.layout['positions'][aind3]
bl23 += 0.0 # to avoid any weird negative sign before 0.0
bl31 += 0.0 # to avoid any weird negative sign before 0.0
bl23[NP.abs(bl23) < 1e-10] = 0.0
bl31[NP.abs(bl31) < 1e-10] = 0.0
bl23_len = NP.sqrt(NP.sum(bl23**2))
bl31_len = NP.sqrt(NP.sum(bl31**2))
if (bl23_len > 0.0) and (bl31_len > 0.0):
bl23str = '{0[0]:.2f}_{0[1]:.2f}_{0[2]:.2f}'.format(bl23)
if bl23str not in blstr:
bl23 *= -1
bl23 += 0.0 # to avoid any weird negative sign before 0.0
bl23str = '{0[0]:.2f}_{0[1]:.2f}_{0[2]:.2f}'.format(bl23)
if bl23str not in blstr:
warnings.warn('A baseline not found in the simulated reference baselines. Proceeding with the rest')
# raise IndexError('A baseline not found in reference baselines')
else:
bl31str = '{0[0]:.2f}_{0[1]:.2f}_{0[2]:.2f}'.format(bl31)
if bl31str not in blstr:
bl31 *= -1
bl31 += 0.0 # to avoid any weird negative sign before 0.0
bl31str = '{0[0]:.2f}_{0[1]:.2f}_{0[2]:.2f}'.format(bl31)
if bl31str not in blstr:
warnings.warn('A baseline not found in the simulated reference baselines. Proceeding with the rest')
# raise IndexError('A baseline not found in reference baselines')
else:
list123_str = [bl12str, bl23str, bl31str]
if len(list123_str) == 3:
if len(bltriplets) == 0:
bltriplets += [list123_str]
blvecttriplets += [[bl12, bl23, bl31]]
anttriplets += [(albl1, albl2, albl3)]
else:
found = False
if unique:
ind = 0
while (not found) and (ind < len(bltriplets)):
bltriplet = bltriplets[ind]
if NP.setdiff1d(list123_str, bltriplet).size == 0:
found = True
else:
ind += 1
if not found:
bltriplets += [list123_str]
blvecttriplets += [[bl12, bl23, bl31]]
anttriplets += [(albl1, albl2, albl3)]
# return (anttriplets, bltriplets)
return (anttriplets, blvecttriplets)
#############################################################################
def getClosurePhase(self, antenna_triplets=None, delay_filter_info=None,
specsmooth_info=None, spectral_window_info=None,
unique=False):
"""
-------------------------------------------------------------------------
Get closure phases of visibilities from triplets of antennas.
Inputs:
antenna_triplets
[list of tuples] List of antenna ID triplets where each
triplet is given as a tuple. If set to None (default), all
the unique triplets based on the antenna layout attribute
in class InterferometerArray
unique [boolean] If set to True, only unique 3-point combinations
of baseline triads are returned. If set to False (default),
all 3-point combinations are returned. Applies only if
antenna_triplets is set to None, otherwise the 3-point
combinations of the specified antenna_triplets is returned.
delay_filter_info
[NoneType or dictionary] Info containing delay filter
parameters. If set to None (default), no delay filtering is
performed. Otherwise, delay filter is applied on each of the
visibilities in the triplet before computing the closure
phases. The delay filter parameters are specified in a
dictionary as follows:
'type' [string] 'horizon' (default) or 'regular'. If
set to 'horizon', the horizon delay limits are
estimated from the respective baseline lengths
in the triplet. If set to 'regular', the extent
of the filter is determined by the 'min' and
'width' keys (see below).
'min' [scalar] Non-negative number (in seconds) that
specifies the minimum delay in the filter span.
If not specified, it is assumed to be 0. If
'type' is set to 'horizon', the 'min' is ignored
and set to 0.
'width' [scalar] Non-negative number (in numbers of
inverse bandwidths). If 'type' is set to
'horizon', the width represents the delay
buffer beyond the horizon. If 'type' is set to
'regular', this number has to be positive and
determines the span of the filter starting from
the minimum delay in key 'min'.
'mode' [string] 'discard' (default) or 'retain'. If set
to 'discard', the span defining the filter is
discarded and the rest retained. If set to
'retain', the span defining the filter is
retained and the rest discarded. For example,
if 'type' is set to 'horizon' and 'mode' is set
to 'discard', the horizon-to-horizon is
filtered out (discarded).
specsmooth_info
[NoneType or dictionary] Spectral smoothing window to be
applied prior to the delay transform. If set to None, no
smoothing is done. This is usually set if spectral
smoothing is to be done such as in the case of RFI. The
smoothing window parameters are specified using the
following keys and values:
'op_type' [string] Smoothing operation type.
Default='median' (currently accepts only
'median' or 'interp').
'window_size' [integer] Size of smoothing window (in
pixels) along frequency axis. Applies only
if op_type is set to 'median'
'maskchans' [NoneType or numpy array] Numpy boolean array
of size nchan. False entries imply those
channels are not masked and will be used in
in interpolation while True implies they are
masked and will not be used in determining the
interpolation function. If set to None, all
channels are assumed to be unmasked (False).
'evalchans' [NoneType or numpy array] Channel numbers at
which visibilities are to be evaluated. Will
be useful for filling in RFI flagged channels.
If set to None, channels masked in 'maskchans'
will be evaluated
'noiseRMS' [NoneType or scalar or numpy array] If set to
None (default), the rest of the parameters are
used in determining the RMS of thermal noise.
If specified as scalar, all other parameters
will be ignored in estimating noiseRMS and
this value will be used instead. If specified
as a numpy array, it must be of shape
broadcastable to (nbl,nchan,ntimes). So
accpeted shapes can be (1,1,1), (1,1,ntimes),
(1,nchan,1), (nbl,1,1), (1,nchan,ntimes),
(nbl,nchan,1), (nbl,1,ntimes), or
(nbl,nchan,ntimes).
spectral_window_info
[NoneType or dictionary] Spectral window parameters to
determine the spectral weights and apply to the visibilities
in the frequency domain before filtering in the delay domain.
THESE PARAMETERS ARE APPLIED ON THE INDIVIDUAL VISIBILITIES
THAT GO INTO THE CLOSURE PHASE. THESE ARE NOT TO BE CONFUSED
WITH THE PARAMETERS THAT WILL BE USED IN THE ACTUAL DELAY
TRANSFORM OF CLOSURE PHASE SPECTRA WHICH ARE SPECIFIED
SEPARATELY FURTHER BELOW.
If set to None (default), unity spectral weights are applied.
If spectral weights are to be applied, it must be a provided
as a dictionary with the following keys and values:
bw_eff [scalar] effective bandwidths (in Hz) for the
spectral window
freq_center [scalar] frequency center (in Hz) for the
spectral window
shape [string] frequency window shape for the
spectral window. Accepted values are 'rect' or
'RECT' (for rectangular), 'bnw' and 'BNW' (for
Blackman-Nuttall), and 'bhw' or 'BHW' (for
Blackman-Harris). Default=None sets it to 'rect'
fftpow [scalar] power to which the FFT of the window
will be raised. The value must | |
#!/usr/bin/env python3
"""Logging index verification tool
This script is meant to help verify ElasticSearch indices after generating logs with logtest clusterloader.
It also has a lot of general helper functions for working with ElasticSearch.
To use this script, you should set up a route to ElasticSearch as described here:
https://docs.openshift.com/container-platform/4.1/logging/config/efk-logging-elasticsearch.html#efk-logging-elasticsearch-exposing_efk-logging-elasticsearch
This script uses python 3 and has Requests as an external dependency.
I recommend setting up a venv like so:
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
"""
import argparse
import json
import math
import os
import sys
import time
import requests
import urllib3
# https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
urllib3.disable_warnings()
class ElsHelper:
def __init__(self, route, token, verbose=False):
self.headers = {"Authorization": "Bearer {}".format(token)}
if 'http' in route:
# Assume we were passed route properly formatted already
self.base_url = route
else:
self.base_url = "https://{}".format(route)
self.verbose = verbose
def custom_query(self, custom_endpoint: str, put=False, data=None):
url = self.base_url + custom_endpoint
if put is True:
r = requests.put(url, headers=self.headers, verify=False, json=data)
else:
r = requests.get(url, headers=self.headers, verify=False)
r.raise_for_status()
if 'json' in r.headers['content-type']:
print(json.dumps(r.json(), indent=2))
else:
print(r.text)
def print_health(self):
endpoint = "/_cluster/health"
url = self.base_url + endpoint
r = requests.get(url, headers=self.headers, verify=False)
r.raise_for_status()
print(json.dumps(r.json(), indent=2))
return
def print_indices(self):
"""
Print ElasticSearch indices and exit.
"""
# Putting the param in the endpoint here because why not
endpoint = "/_cat/indices?v"
url = self.base_url + endpoint
r = requests.get(url, headers=self.headers, verify=False)
r.raise_for_status()
print(r.text)
return
def print_info(self):
r = requests.get(self.base_url, headers=self.headers, verify=False)
r.raise_for_status()
print(r.text)
return
def print_nodes(self):
endpoint = "/_cat/nodes?v&h=ip,m,disk.used_percent,disk.total,heap.percent,ram.percent,cpu,load_1m,load_5m"
url = self.base_url + endpoint
r = requests.get(url, headers=self.headers, verify=False)
r.raise_for_status()
print(r.text)
return
def get_index_doc_count(self, index, query=None):
count_endpoint = "/{}/_count".format(index)
data = None
headers = self.headers
if query:
data = {"query": query}
print(data)
headers['Content-Type'] = "application/json"
count_request = requests.get(self.base_url + count_endpoint, headers=headers, verify=False, data=json.dumps(data))
else:
count_request = requests.get(self.base_url + count_endpoint, headers=headers, verify=False)
count_request.raise_for_status()
index_count = count_request.json()["count"]
return index_count
def dump_index(self, index, output=None):
"""
Uses ELS scroll search to dump an entire logtest index.
If there are more than 10k results, then further API calls are made and those results are lumped into the ["hits"]["hits"] value of the first call.
:type output: str
:param index:
"""
endpoint = "/{}/_search".format(index)
url = self.base_url + endpoint
params = {"scroll": "1m"}
result_size = 10000
data = {"sort": ["_doc"], "size": result_size}
scroll_headers = {"Content-Type": "application/json"}
scroll_headers.update(self.headers)
# Initial request to _search endpoint
r1 = requests.get(url, headers=scroll_headers, params=params, data=json.dumps(data), verify=False)
r1.raise_for_status()
r1_dict = r1.json()
r1_ml: list = r1_dict["hits"]["hits"]
total_hits = r1_dict['hits']['total']
# To find the number of time we have to scroll.
# Divide total results by result_size
# Round up to nearest integer
# Subtract 1 because we already pulled the first ${result_size} results in the first request
# Provide result or 0 if it is negative
num_of_scrolls = max(int(math.ceil((total_hits / result_size))) - 1, 0)
if self.verbose:
print("num of scrolls: {}".format(num_of_scrolls))
# Get _scroll_id
# Scroll requests hit generic _search/scroll endpoint
scroll_id = r1_dict["_scroll_id"]
scroll_endpoint = "/_search/scroll"
scroll_url = self.base_url + scroll_endpoint
data = {"scroll": "1m", "scroll_id": scroll_id}
# Call scroll API til we have all results pushed into r1_dict
for i in range(num_of_scrolls):
if self.verbose:
print("Current length of message list: {}".format(len(r1_ml)))
print("Calling scroll endpoint: {}/{}".format(i + 1, num_of_scrolls))
start = time.time()
r_scroll = requests.get(scroll_url, headers=scroll_headers, data=json.dumps(data), verify=False)
if self.verbose:
end = time.time()
print("Time taken for scroll request: {}".format(end - start))
r_scroll.raise_for_status()
r_scroll_dict = r_scroll.json()
if self.verbose:
print("Extending r1_ml with new messages")
r1_ml.extend(r_scroll_dict["hits"]["hits"])
# print("Dict obj size: {}".format(sys.getsizeof(json.dumps(r1_dict))))
# If output is specified then output to file
if output is not None:
with open(output, 'w') as f:
json.dump(r1_dict, f, indent=2)
return r1_dict
def index_generator(self, index, query=None):
endpoint = "/{}/_search".format(index)
url = self.base_url + endpoint
params = {"scroll": "1m"}
result_size = 10000
data = {"sort": ["_doc"], "size": result_size}
if query is not None:
data["query"] = query
scroll_headers = {"Content-Type": "application/json"}
scroll_headers.update(self.headers)
scroll_endpoint = "/_search/scroll"
scroll_url = self.base_url + scroll_endpoint
scroll_id = None
scroll_data = {"scroll": "1m", "scroll_id": scroll_id}
# Get number of documents in the index
index_count = self.get_index_doc_count(index, query=query)
print("Index document count: {}".format(index_count))
num_of_scrolls = max(int(math.ceil((index_count / result_size))), 1)
if self.verbose:
print("num scrolls: {}".format(num_of_scrolls))
for i in range(num_of_scrolls):
if i == 0:
if self.verbose:
print("Making initial request to search endpoint")
r = requests.get(url, headers=scroll_headers, params=params, data=json.dumps(data), verify=False)
scroll_id = r.json()["_scroll_id"]
scroll_data["scroll_id"] = scroll_id
yield r.json()
else:
if self.verbose:
print("Requesting scroll enpoint")
scroll_start = time.time()
r = requests.get(scroll_url, headers=scroll_headers, data=json.dumps(scroll_data), verify=False)
print("Time taken: {}".format(time.time() - scroll_start))
else:
r = requests.get(scroll_url, headers=scroll_headers, data=json.dumps(scroll_data), verify=False)
yield r.json()
def extract_message_list(self, r_json: dict):
message_list = []
for i in r_json["hits"]["hits"]:
message_list.append(i["_source"]["message"])
return message_list
def verify_els_message_stream(index_iter, max_expected):
num_tracker = {i: 0 for i in range(1, max_expected + 1)}
for i in index_iter:
# Extract message list from JSON
message_list = [message["_source"]["message"] for message in i["hits"]["hits"]]
# Extract message numbers from message list lines
for m in message_list:
try:
num = int(m.split()[9])
# print(type(num))
num_tracker[num] += 1
except ValueError:
print("ERROR: Couldn't parse number from log line. Got '{}'".format(m.split()[9]))
print(m)
# Output duplicates
duplicates_found = 0
for k, v in num_tracker.items():
if v > 1:
print("Duplicate: {} - Count: {}".format(k, v))
duplicates_found += 1
# Output missing
missing_nums = [i for i in num_tracker if num_tracker[i] == 0]
missing_found = len(missing_nums)
missing_ranges = compute_ranges(missing_nums)
for j in missing_ranges:
print("Missing log line(s): {}".format(j))
# Output summary
if duplicates_found > 0:
print("Duplicate numbers found: {}".format(duplicates_found))
else:
print("No duplicates found!")
if missing_found > 0:
print("Number of missing logs: {}".format(missing_found))
print("{:.4f}% message loss rate".format(missing_found / max_expected * 100))
else:
print("No missing messages!")
def verify_els_messages(els_json: dict, max_expected):
els_hits_total = els_json["hits"]["total"]
print("ElasticSearch hits matching search query: {}".format(els_hits_total))
hit_list = els_json["hits"]["hits"]
print("Number of hits in this JSON body: {}".format(len(hit_list)))
# Extract just message value from dict
# Example log message:
# 2019-06-19 18:56:25,359 - SVTLogger - INFO - centos-logtest-2cvbs : 1 : cviv9Fexf iJXjmkt5q 9OEE6ym79 gUFpysfap sseH7CIk4 DVbdIk4Bx YDNVPfhhk BVW5GRR6u O4zTsDm7x etc....
message_list = [i["_source"]["message"] for i in hit_list]
# Extract message number from message and sort resulting list
# TODO: change this as splitting the message can be unreliable
message_num_list = []
for m in message_list:
try:
num = int(m.split()[9])
message_num_list.append(num)
except ValueError:
print("ERROR: Couldn't parse number from log line. Got '{}'".format(m.split()[9]))
print(m)
message_num_list.sort()
min_num = message_num_list[0]
max_num = message_num_list[-1]
print("Lowest number found: {}".format(min_num))
print("Highest number found: {}".format(max_num))
if max_expected is None:
max_expected = max_num
print(
"WARNING: No max specified in command line, assuming expected maximum is the highest number found in the message list. "
"This will throw off metrics if the expected max is higher than the max found in the message list")
print("Expected max number: {}".format(max_expected))
# Find number of occurrences for each number from min_num to max_num
num_tracker = {i: 0 for i in range(1, max_expected + 1)}
for i in message_num_list:
num_tracker[i] += 1
missing_nums = [i for i in num_tracker if num_tracker[i] == 0]
missing_found = len(missing_nums)
# Output duplicates
duplicates_found = 0
for k, v in num_tracker.items():
if v > 1:
print("Duplicate: {} - Count: {}".format(k, v))
duplicates_found += 1
# Output missing number ranges
missing_ranges = compute_ranges(missing_nums)
for i in missing_ranges:
print("Missing log line(s): {}".format(i))
# Output Summary
if duplicates_found > 0:
print("Duplicate numbers found: {}".format(duplicates_found))
if missing_found > 0:
print("Number of missing logs: {}".format(missing_found))
print("{:.4f}% message loss rate".format(missing_found / max_expected * 100))
def compute_ranges(num_list):
if len(num_list) == 0:
return []
if len(num_list) == 1:
return [str(num_list[0])]
result = []
current_range = [num_list[0]]
for i in num_list[1:]:
if i == current_range[-1] + 1:
current_range.append(i)
else:
if len(current_range) > 1:
num_range = current_range[-1] - current_range[0] + 1
result.append("{}-{} ({})".format(current_range[0], current_range[-1], num_range))
elif len(current_range) == 1:
result.append(str(current_range[0]))
else:
result.append(str(i))
current_range = [i]
if len(current_range) == 1:
# Handle last number in num list being by itself
result.append(str(current_range[0]))
elif len(current_range) > 1:
# handle case where all numbers in num_list are sequential
num_range = current_range[-1] - current_range[0] + 1
result.append("{}-{} ({})".format(current_range[0], current_range[-1], num_range))
return result
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--custom', help="Print output from given custom endpoint")
parser.add_argument('--put', action='store_true', help='Use HTTP PUT method when sending --custom request')
parser.add_argument('--data', help='Pass JSON data when using --custom and --put. Accepts | |
gk not in igKeys]
return keys1, keys2
def vis_divided_grid(self, gBins, bBins):
'''
gBins: grid bins
bBins: chosen bins
'''
nX, nY = len(self.binList), len(self.binList[0])
plt.ion()
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
im = np.zeros((nY, nX, 3))
imBoth = np.zeros((nY, nX, 3))
for i, g in enumerate(gBins):
x, y = g
im[y,x,:] = cmap.jet(int(255*float(i)/len(gBins)))[0:3]
imBoth[y,x,:] = cmap.jet(int(255*float(i)/len(gBins)))[0:3]
ax1.imshow(im, interpolation="nearest")
im2 = np.zeros((nY, nX, 3))
for i, g in enumerate(bBins):
x, y = g
im2[y,x,:] = 1.0, 1.0, 1.0
imBoth[y,x,:] = 1.0, 1.0, 1.0
ax2.imshow(im2, interpolation="nearest")
ax3.imshow(imBoth, interpolation="nearest")
plt.show()
plt.draw()
def _debug_group_list_div(grps, grpList, mxCount=5000):
sgList = StreetGroupList.from_dict(grps, grpList)
sgList.grid_xy()
div, bdiv = sgList.divide_group_counts(mxCount)
sgList.vis_divided_grid(div, bdiv)
class StreetFolder(object):
'''
prefix: prefix.jpg, prefix.txt define the corresponding image and lbl file
target_group: group of images looking at the same target point.
'''
def __init__(self, name, splitPrms=None, isAlign=False, forceHost=None):
'''
name: relative path where the raw data in the folder is present
splitPrms: parameters that decide train/val splits
isAlign : use the groups for which alignment information is avail.
forceHost: use the host with name forceHost for getting the paths
'''
#folder id
fStore = FolderStore('streetview')
self.id_ = fStore.get_id(name)
self.name_ = name
self.isAlign_ = isAlign
self.forceHost_ = forceHost
if splitPrms is None:
self.splitPrms_ = sev2.get_trainval_split_prms()
#folder paths
self._paths()
#Prefixes
self.prefixList_ = []
self._read_prefixes_from_file()
#
def _paths(self):
pths = sev2.get_folder_paths(self.id_, self.splitPrms_,
self.isAlign_, hostName=self.forceHost_)
cPaths = get_config_paths(self.forceHost_)
#raw data
self.dirName_ = osp.join(cPaths.mainDataDr, self.name_)
self.paths_ = pths
#Save all prefixes in the folder
def _save_prefixes(self):
if not osp.exists(self.dirName_):
print ('PREFIX CANNOT BE SAVED AS RAW DATA NOT PRESENT')
return False
allNames = os.listdir(self.dirName_)
imNames = sorted([f for f in allNames if '.jpg' in f], reverse=True)
lbNames = sorted([f for f in allNames if '.txt' in f], reverse=True)
prefixStr = []
for (i,imn) in enumerate(imNames):
imn = imn[0:-4]
if i>= len(lbNames):
continue
if imn in lbNames[i]:
#Determine that the labelfile is not empty
lbDat = StreetLabel.from_file(osp.join(self.dirName_, lbNames[i]))
if lbDat is None:
print ('%s has no label info' % lbNames[i])
continue
prefixStr = prefixStr + [imn]
pickle.dump({'prefixStr': prefixStr}, open(self.paths_.prefix, 'w'))
return True
#Read the prefixes from saved file
def _read_prefixes_from_file(self, forceCompute=False):
''' Read all the prefixes
forceCompute: True - recompute the prefixes
'''
if not forceCompute and osp.exists(self.paths_.prefix):
dat = pickle.load(open(self.paths_.prefix,'r'))
self.prefixList_ = dat['prefixStr']
return
print ('Computing prefixes for folderid %s' % self.id_)
isSave = self._save_prefixes()
if not isSave:
print ('PREFIX CANNOT BE READ')
return False
self._read_prefixes_from_file(forceCompute=False)
#Get the prefixes
def get_prefixes(self):
return copy.deepcopy(self.prefixList_)
#
def get_im_label_files(self):
imFiles = [osp.join(self.dirName_, '%s.jpg') % p for p in self.prefixList_]
lbFiles = [osp.join(self.dirName_, '%s.txt') % p for p in self.prefixList_]
return imFiles, lbFiles
#Save group of images that look at the same target point.
def _save_target_group_counts(self):
if self.isAlign_:
self._save_target_group_counts_aligned()
return
grps = {}
prev = None
count = 0
tgtList = []
for (i,p) in enumerate(self.prefixList_):
_,_,_,grp = p.split('_')
if i == 0:
prev = grp
if not(grp == prev):
tgtList.append(prev)
grps[prev]= count
prev = grp
count = 0
count += 1
pickle.dump(grps, open(self.paths_.prePerGrp, 'w'))
pickle.dump({'grpList': tgtList}, open(self.paths_.targetGrpList, 'w'))
#get all the target group counts
def get_num_prefix_per_target_group(self, forceCompute=False):
if not forceCompute and osp.exists(self.paths_.prePerGrp):
prePerGrp = pickle.load(open(self.paths_.prePerGrp, 'r'))
return prePerGrp
self._save_target_group_counts()
return self.get_num_prefix_per_target_group()
#ordered list of groups
def get_target_group_list(self):
if self.isAlign_:
data = pickle.load(open(self.paths_.targetGrpListAlign, 'r'))
else:
data = pickle.load(open(self.paths_.targetGrpList, 'r'))
return data['grpList']
#save the target group data
def _save_target_groups(self, forceWrite=False):
if self.isAlign_:
self._save_target_groups_aligned(forceWrite=forceWrite)
return
if osp.exists(self.paths_.targetGrps) and not forceWrite:
print ('Group file %s exists, NOT recomputing' % self.paths_.targetGrps)
return
print ('Computing group file %s' % self.paths_.targetGrps)
imNames, lbNames = self.get_im_label_files()
preCountPerGrp = self.get_num_prefix_per_target_group()
grps = edict()
grpKeys = self.get_target_group_list()
prevCount = 0
for gk in grpKeys:
numPrefix = preCountPerGrp[gk]
st, en = prevCount, prevCount + numPrefix
cropImNames = [self._idx2cropname(idx) for idx in range(st, en)]
try:
grps[gk] = StreetGroup.from_raw(self.id_, gk,
self.prefixList_[st:en], lbNames[st:en], cropImNames)
except:
print ('#### ERROR Encountered #####')
print (self.id_, gk, st, en)
print (self.prefixList_[st:en])
pdb.set_trace()
prevCount += numPrefix
print ('SAVING to %s' % self.paths_.targetGrps)
pickle.dump({'groups': grps}, open(self.paths_.targetGrps, 'w'))
#Save the counts of aligned groups
def _save_target_groups_aligned(self, forceWrite=False):
assert self.isAlign_, 'Align_ is set to False'
self.isAlign_ = False
#Check is the original groups have been saved
if not osp.exists(self.paths_.targetGrpList):
self._save_target_group_counts()
#Check if the aligned groups have already been saved
if osp.exists(self.paths_.targetGrpsAlign) and not forceWrite:
print ('Group file %s exists, NOT recomputing' % self.paths_.targetGrpsAlign)
return
print ('%s loading all groups' % self.id_)
allGrpList = self.get_target_group_list()
allGrps = self.get_target_groups()
alignGrpList = []
alignGrps = edict()
alignPrefixList = []
print ('%s filtering aligned groups' % self.id_)
for gk in allGrpList:
alGrp = allGrps[gk].subset_aligned()
if alGrp is not None:
alignGrpList.append(gk)
alignGrps[gk] = alGrp
for p in alGrp.grp.prefix:
alignPrefixList.append(p)
print ('Folder: %s, number of groups: %d, number of align: %d' %
(self.id_, len(allGrpList), len(alignGrpList)))
pickle.dump({'grpList': alignGrpList}, open(self.paths_.targetGrpListAlign, 'w'))
pickle.dump({'groups': alignGrps}, open(self.paths_.targetGrpsAlign, 'w'))
pickle.dump({'prefixStr': alignPrefixList}, open(self.paths_.prefixAlign, 'w'))
self.isAlign_ = True
#get groups
def get_target_groups(self):
if self.isAlign_:
dat = pickle.load(open(self.paths_.targetGrpsAlign, 'r'))
else:
dat = pickle.load(open(self.paths_.targetGrps, 'r'))
return dat['groups']
#crop and save images - that makes it faster to read for training nets
def save_cropped_images(self, imSz=256, isForceWrite=False):
if self.isAlign_:
self.save_cropped_images_aligned(imSz=imSz, isForceWrite=isForceWrite)
return
cropDirName = self.paths_.crpImPath % imSz
ou.mkdir(cropDirName)
for i, p in enumerate(self.prefixList_):
if np.mod(i,1000)==1:
print(i)
inName = osp.join(self.dirName_, p + '.jpg')
outName = osp.join(self.paths_.crpImPath % imSz,
self._idx2cropname(i))
#Save the image
save_cropped_image_unaligned([inName], [outName],
imSz, isForceWrite)
def save_cropped_images_aligned(self, imSz=256, isForceWrite=False):
assert self.isAlign_, 'self.Align_ must be True'
print('%s, loading groups' % self.id_)
grpList = self.get_target_group_list()
grps = self.get_target_groups()
for gk in grpList:
g = grps[gk]
for n in range(g.grp.num):
prf = g.grp.prefix[n]
loc = g.grp.data[n].label.align.loc
inName = osp.join(self.dirName_, prf + '.jpg')
outName = osp.join(self.paths_.crpImPathAlign % imSz,
g.grp.crpImNames[n])
#Save the image
save_cropped_image_aligned([inName], [outName], loc,
imSz, isForceWrite)
def _idx2cropname(self, idx):
lNum = int(idx/1000)
imNum = np.mod(idx, 1000)
name = 'l-%d/im%04d.jpg' % (lNum, imNum)
return name
def get_cropped_imname(self, prefix):
idx = self.prefixList_.index(prefix)
return self._idx2cropname(idx)
#Split into train/test/val
def split_trainval_sets(self, grps=None):
sPrms = self.splitPrms_
assert sPrms.minDist == 100, 'Modify StreetGroupList gridding to\
work for other distance values'
if grps is None:
print ('Reading Groups')
grps = self.get_target_groups()
gKeys = self.get_target_group_list()
N = len(gKeys)
nTrn = int(np.floor((sPrms.trnPct/100.0 * (N))))
nVal = int(np.floor((sPrms.valPct/100.0 * (N))))
nTe = int(np.floor((sPrms.tePct/100.0 * (N))))
#Make a list of groups
gList = StreetGroupList.from_dict(grps, gKeys)
trnKeys, oKeys = gList.get_split_groups(nTrn)
oL = len(oKeys)
tL = len(trnKeys)
assert N >= tL + oL
print ('FolderId: %s, Num-Train: %d, Num-Others: %d, NumLost: %d' %
(self.id_, tL, oL, N - (tL + oL)))
valIdx = int(oL * (float(sPrms.valPct)/(sPrms.valPct + sPrms.tePct)))
setKeys = edict()
setKeys['train'] = [k for k in trnKeys if grps[k].grp.num > 1]
setKeys['val'] = [k for k in oKeys[0:valIdx] if grps[k].grp.num > 1]
setKeys['test'] = [k for k in oKeys[valIdx:] if grps[k].grp.num > 1]
print ('Num-Train: %d, Num-Val: %d, Num-Test: %d' %
(len(setKeys['train']), len(setKeys['val']), len(setKeys['test'])))
#Sanity checks
assert len(set(setKeys['train']).intersection(set(setKeys['val']))) == 0
assert len(set(setKeys['train']).intersection(set(setKeys['test']))) == 0
#Save the split keys
dirName = osp.dirname(self.paths_.trainvalSplitGrpKeys)
ou.mkdir(dirName)
pickle.dump({'setKeys': setKeys, 'splitPrms': self.splitPrms_},
open(self.paths_.trainvalSplitGrpKeys, 'w'))
for s in ['train', 'val', 'test']:
sGroups = [grps[gk].as_dict_small_memory() for gk in setKeys[s]]
pickle.dump({'groups': sGroups}, open(self.paths_.grpSplits[s], 'w'))
#Verify that all the image files in the split exist
def verify_trainval_split_files(self, imSz=256):
import cv2
for s in ['train', 'val', 'test']:
print(s)
dat = pickle.load(open(self.paths_.grpSplits[s], 'r'))
dat = dat['groups']
for i, g in enumerate(dat):
for n in range(g.num):
if self.isAlign_:
imName = osp.join(self.paths_.crpImPathAlign % imSz,
g.crpImNames[n])
else:
imName = osp.join(self.paths_.crpImPath % imSz,
g.crpImNames[n])
im = cv2.imread(imName)
h, w, ch = im.shape
assert h==imSz and w==imSz and ch==3, im.shape
if not(osp.exists(imName)):
print ('%s DOESNOT EXISTS ...WTF' % imName)
def tar_trainval_splits(self, forceWrite=False):
drName = self.paths_.deriv.grps
trFile = self.paths_.deriv.grpsTar
if not osp.exists(trFile) or forceWrite:
print ('Making %s' % trFile)
subprocess.check_call(['tar -cf %s -C %s .' % (trFile, drName)],shell=True)
else:
print ('TAR file already exists')
#untar the files in the correct directory
def untar_trainval_splits(self, hostName=None):
if hostName is None:
drName = self.paths_.deriv.grps
else:
fPaths = sev2.get_folder_paths(self.id_, self.splitPrms_,
self.isAlign_, hostName)
drName = fPaths.deriv.grps + '/'
ou.mkdir(drName)
ou.mkdir(drName)
trFile = self.paths_.deriv.grpsTar
cmd = 'tar -xf %s -C %s' % (trFile, drName)
print (cmd)
subprocess.check_call([cmd] ,shell=True)
def tar_cropped_images(self, imSz=256, forceWrite=False):
if self.isAlign_:
drName = self.paths_.crpImPathAlign % imSz
trFile = self.paths_.crpImPathAlignTar % imSz
else:
drName = self.paths_.crpImPath % imSz
trFile = self.paths_.crpImPathTar % imSz
dirName = osp.dirname(trFile)
ou.mkdir(dirName)
if not osp.exists(trFile) or forceWrite:
print ('Making %s' % trFile)
subprocess.check_call(['tar -cf %s -C %s .' % (trFile, drName)],shell=True)
else:
print ('TAR file already exists')
#Transfer the trainval splits to a host
def scp_trainval_splits(self, hostName):
fPaths = sev2.get_folder_paths(self.id_, self.splitPrms_,
self.isAlign_, hostName)
srcPath = self.paths_.deriv.grpsTar
tgHost = scput.get_hostaddr(hostName)
tgPath = tgHost + fPaths.deriv.grpsTar
print (tgPath)
subprocess.check_call(['rsync -ravz %s %s' % (srcPath, tgPath)],shell=True)
#Fetch trainval splits from a host
def fetch_scp_trainval_splits(self, hostName):
fPaths = sev2.get_folder_paths(self.id_, self.splitPrms_,
self.isAlign_, hostName)
tgPath = self.paths_.deriv.grpsTar
srcHost = scput.get_hostaddr(hostName)
srcPath = srcHost + fPaths.deriv.grpsTar
print (srcPath)
dirName = osp.dirname(tgPath)
ou.mkdir(dirName)
#subprocess.check_call(['rsync -ravz --progress %s %s' % (srcPath, tgPath)],shell=True)
subprocess.check_call(['scp %s %s' % (srcPath, tgPath)],shell=True)
#Transfer the cropped images to a host
def fetch_scp_cropped_images(self, hostName, imSz=256):
print ('I AM HERE')
fPaths = sev2.get_folder_paths(self.id_, self.splitPrms_,
self.isAlign_, hostName)
srcHost = scput.get_hostaddr(hostName)
if self.isAlign_:
tgPath = self.paths_.crpImPathAlignTar % imSz
srcPath = srcHost + fPaths.crpImPathAlignTar % imSz
else:
tgPath = self.paths_.crpImPathTar % imSz
srcPath = srcHost + fPaths.crpImPathTar % imSz
dirName = osp.dirname(tgPath)
print (dirName)
if not osp.exists(dirName):
ou.mkdir(dirName)
print (srcPath)
#subprocess.check_call(['rsync -ravz %s %s' % (srcPath, tgPath)],shell=True)
subprocess.check_call(['scp %s %s' % (srcPath, tgPath)],shell=True)
#Transfer the cropped images to a host
def scp_cropped_images(self, hostName, imSz=256):
print ('I AM HERE')
fPaths = sev2.get_folder_paths(self.id_, self.splitPrms_,
self.isAlign_, hostName)
tgHost = scput.get_hostaddr(hostName)
if self.isAlign_:
srcPath = self.paths_.crpImPathAlignTar % imSz
tgPath = tgHost + fPaths.crpImPathAlignTar % imSz
else:
srcPath = self.paths_.crpImPathTar % imSz
tgPath = tgHost + fPaths.crpImPathTar % imSz
print (tgPath)
subprocess.check_call(['rsync -ravz --progress %s %s' % (srcPath, tgPath)],shell=True)
def untar_cropped_images(self, imSz=256, hostName=None):
if hostName is not None:
pth = sev2.get_folder_paths(self.id_, self.splitPrms_,
self.isAlign_, hostName)
else:
pth = self.paths_
if self.isAlign_:
trFile = self.paths_.crpImPathAlignTar % imSz
drName = pth.crpImPathAlign % imSz
else:
trFile = self.paths_.crpImPathTar % imSz
drName = pth.crpImPath % imSz
ou.mkdir(drName)
subprocess.check_call(['tar -xf %s -C %s' % (trFile, drName)],shell=True)
def del_cropped_images(self, imSz=256):
if self.isAlign_:
drName = self.paths_.crpImPathAlign % imSz
else:
drName = self.paths_.crpImPath % imSz
if osp.exists(drName):
print ('Deleting: %s' % drName)
subprocess.check_call(['rm -r %s' % drName],shell=True)
#Delete the tar file
if self.isAlign_:
trFile = self.paths_.crpImPathAlignTar % imSz
else:
trFile = self.paths_.crpImPathTar % imSz
if osp.exists(trFile):
print ('Deleting: %s' % trFile)
subprocess.check_call(['rm %s' % trFile],shell=True)
def del_trainval_splits(self):
trFile = self.paths_.deriv.grpsTar
drName = self.paths_.deriv.grps
if osp.exists(drName):
print ('Deleting: %s' % drName)
subprocess.check_call(['rm -r %s' % | |
# -*- coding: utf-8 -*-
#Plotting is on python since this will make it much easier to debug and adjsut
#no need to recompile everytime i change graph color....
#needs a serious refactor
from matplotlib import pyplot as plt
import numpy as np
from .nputil import mid, minmax, vector_apply
from util import parse_arg, describe
from math import sqrt, ceil, floor
from warnings import warn
def draw_simultaneous(self, minuit=None, args=None, errors=None, **kwds):
numf = len(self.allf)
ret = []
numraw = sqrt(numf)
numcol = ceil(numraw)
numrow = floor(numraw) if floor(numraw)*numcol>=numf else ceil(numraw)
for i in range(numf):
plt.subplot(numrow, numcol, i+1)
part_args, part_errors = self.args_and_error_for(i, minuit, args, errors)
ret.append(self.allf[i].draw(args=part_args, errors=part_errors, **kwds))
return ret
def _get_args_and_errors(self, minuit=None, args=None, errors=None):
"""
consistent algorithm to get argument and errors
1) get it from minuit if minuit is available
2) if not get it from args and errors
2.1) if args is dict parse it.
3) if all else fail get it from self.last_arg
"""
ret_arg = None
ret_error = None
if minuit is not None: # case 1
ret_arg = minuit.args
ret_error = minuit.errors
return ret_arg, ret_error
#no minuit specified use args and errors
if args is not None:
if isinstance(args, dict):
ret_arg = parse_arg(self, args)
else:
ret_arg = args
else: # case 3
ret_arg = self.last_arg
if errors is not None:
ret_error = errors
return ret_arg, ret_error
def _param_text(parameters, arg, error):
txt = u''
for i, (k, v) in enumerate(zip(parameters, arg)):
txt += u'%s = %5.4g'%(k, v)
if error is not None:
txt += u'±%5.4g'%error[k]
txt += u'\n'
return txt
#from UML
def draw_ulh(self, minuit=None, bins=100, ax=None, bound=None,
parmloc=(0.05, 0.95), nfbins=200, print_par=True, grid=True,
args=None, errors=None, parts=False, show_errbars='normal'):
data_ret = None
error_ret = None
total_ret = None
part_ret = []
ax = plt.gca() if ax is None else ax
arg, error = _get_args_and_errors(self, minuit, args, errors)
n,e= np.histogram(self.data, bins=bins, range=bound, weights=self.weights)
dataint= (n*np.diff(e)).sum()
data_ret = (e, n)
if not show_errbars:
pp= ax.hist(mid(e), bins=e, weights=n, histtype='step')
error_ret = (np.sqrt(n), np.sqrt(n))
else:
w2= None
if show_errbars=='normal':
w2=n
error_ret = (np.sqrt(n), np.sqrt(n))
elif show_errbars=='sumw2':
weights= None
if self.weights!= None:
weights= self.weights**2
w2,e= np.histogram(self.data, bins=e, weights=weights)
error_ret = (np.sqrt(w2), np.sqrt(w2))
else:
raise ValueError('show_errbars must be \'normal\' or \'sumw2\'')
pp= ax.errorbar(mid(e), n, np.sqrt(w2) , fmt='b+', capsize=0)
#bound = (e[0], e[-1])
draw_arg = [('lw', 2)]
if not parts:
draw_arg.append(('color', 'r'))
# Draw pdf with finer bins
ef= np.linspace(e[0],e[-1], nfbins+1)
scale= dataint if not self.extended else nfbins/float(bins)
total_ret = draw_pdf_with_edges(self.f, arg, ef, ax=ax, density=not self.extended, scale=scale,
**dict(draw_arg))
if parts:
f_parts = getattr(self.f, 'parts', None)
if f_parts is not None:
for p in f_parts():
ret = draw_pdf_with_edges(p, arg, ef, ax=ax, scale=scale, density=not self.extended)
part_ret.append(ret)
ax.grid(grid)
txt = _param_text(describe(self), arg, error)
if print_par:
ax.text(parmloc[0], parmloc[1], txt, ha='left', va='top',
transform=ax.transAxes)
return (data_ret, error_ret, total_ret, part_ret)
def draw_residual_ulh(self, minuit=None, bins=100, ax=None, bound=None,
parmloc=(0.05, 0.95), print_par=False, grid=True,
args=None, errors=None, show_errbars=True,
errbar_algo='normal', norm=False):
ax = plt.gca() if ax is None else ax
arg, error = _get_args_and_errors(self, minuit, args, errors)
n,e= np.histogram(self.data, bins=bins, range=bound, weights=self.weights)
dataint= (n*np.diff(e)).sum()
scale= dataint if not self.extended else 1.0
w2= None
if errbar_algo=='normal':
w2=n
elif errbar_algo=='sumw2':
weights= None
if self.weights!= None:
weights= self.weights**2
w2,e= np.histogram(self.data, bins=e, weights=weights)
else:
raise ValueError('errbar_algo must be \'normal\' or \'sumw2\'')
yerr= np.sqrt(w2)
arg = parse_arg(self.f, arg, 1) if isinstance(arg, dict) else arg
yf = vector_apply(self.f, mid(e), *arg)
yf*= (scale*np.diff(e) if self.extended else scale)
n = n- yf
if norm:
sel= yerr>0
n[sel]/= yerr[sel]
yerr= np.ones(len(yerr))
if show_errbars:
pp= ax.errorbar(mid(e), n, yerr , fmt='b+', capsize=0)
else: # No errorbars
pp= ax.bar(e[:-1], n, width=np.diff(e))
#bound = (e[0], e[-1])
#draw_arg = [('lw', 2), ('color', 'r')]
ax.plot([e[0],e[-1]],[0.,0.], 'r-')
ax.grid(grid)
txt = _param_text(describe(self), arg, error)
if print_par:
ax.text(parmloc[0], parmloc[1], txt, ha='left', va='top',
transform=ax.transAxes)
return mid(e), n, yerr
#from chi2 regression
def draw_x2(self, minuit=None, ax=None, parmloc=(0.05, 0.95), print_par=True,
args=None, errors=None, grid=True, parts=False, nbins=None):
data_ret = None
error_ret = None
total_ret = None
part_ret = []
ax = plt.gca() if ax is None else ax
arg, error = _get_args_and_errors(self, minuit, args, errors)
x=self.x
y=self.y
data_err = self.error
# Draw data points
data_ret = x,y
if data_err is None:
ax.plot(x, y, '+')
err_ret = (np.ones(len(self.x)), np.ones(len(self.x)))
else:
ax.errorbar(x, y, data_err, fmt='+', capsize=0)
err_ret = (data_err, data_err)
draw_arg = [('lw', 2)]
draw_arg.append(('color', 'r'))
# Draw PDF curve(s)
if nbins is not None:
x = np.linspace(x[0],x[-1], nbins)
total_ret = draw_pdf_with_midpoints(self.f, arg, x, ax=ax, **dict(draw_arg))
if parts:
f_parts = getattr(self.f, 'parts', None)
if f_parts is not None:
for p in f_parts():
tmp = draw_pdf_with_midpoints(p, arg, x, ax=ax, **dict(draw_arg))
part_ret.append(tmp)
# Print text
txt = _param_text(describe(self), arg, error)
chi2 = self(*arg)
if self.ndof > 0:
txt+=u'chi2/ndof = %5.4g(%5.4g/%d)'%(chi2/self.ndof, chi2, self.ndof)
else:
txt+=u'chi2/ndof = (%5.4g/%d)'%(chi2, self.ndof)
if print_par:
ax.text(parmloc[0], parmloc[1], txt, ha='left', va='top',
transform=ax.transAxes)
ax.grid(grid)
return (data_ret, error_ret, total_ret , part_ret)
def draw_x2_residual(self, minuit=None, ax=None, args=None, errors=None, grid=True,
norm=False):
ax = plt.gca() if ax is None else ax
arg, error = _get_args_and_errors(self, minuit, args, errors)
x=self.x
y=self.y
data_err = self.error
f=self.f
arg = parse_arg(f, arg, 1) if isinstance(arg, dict) else arg
yf = vector_apply(f, x, *arg)
yplot= y-yf
eplot= data_err if data_err is not None else np.zeros(len(x))
if norm:
if data_err is None:
warn(RuntimeWarning('No error on data points; cannot normalize to error'))
else:
yplot= yplot/data_err
eplot= data_err/data_err
ax.errorbar(x, yplot, eplot, fmt='b+', capsize=0)
ax.grid(grid)
return x, yplot, eplot
#from binned chi2
def draw_bx2(self, minuit=None, parmloc=(0.05, 0.95), nfbins=500, ax=None,
print_par=True, args=None, errors=None, parts=False, grid=True):
data_ret = None
error_ret = None
total_ret = None
part_ret = []
ax = plt.gca() if ax is None else ax
arg, error = _get_args_and_errors(self, minuit, args, errors)
m = mid(self.edges)
ax.errorbar(m, self.h, self.err, fmt='+', capsize=0)
data_ret = (self.edges, self.h)
error_ret = (self.err, self.err)
bound = (self.edges[0], self.edges[-1])
scale = nfbins/float(self.bins) #scale back to bins
draw_arg = [('lw', 2)]
if not parts:
draw_arg.append(('color', 'r'))
total_ret = draw_pdf(self.f, arg, bins=nfbins, bound=bound, ax=ax, density=False,
scale=scale, **dict(draw_arg))
if parts:
f_parts = getattr(self.f, 'parts', None)
if f_parts is not None:
for p in f_parts():
tmp = draw_pdf(p, arg, bound=bound, bins=nfbins, ax=ax, density=False,
scale=scale)
part_ret.append(tmp)
ax.grid(grid)
txt = _param_text(describe(self), arg, error)
chi2 = self(*arg)
if self.ndof > 0:
txt+=u'chi2/ndof = %5.4g(%5.4g/%d)'%(chi2/self.ndof, chi2, self.ndof)
else:
txt+=u'chi2/ndof = (%5.4g/%d)'%(chi2, self.ndof)
if print_par:
ax.text(parmloc[0], parmloc[1], txt, ha='left', va='top',
transform=ax.transAxes)
return (data_ret, error_ret, total_ret, part_ret)
#from binnedLH
def draw_blh(self, minuit=None, parmloc=(0.05, 0.95),
nfbins=1000, ax=None, print_par=True, grid=True,
args=None, errors=None, parts=False):
data_ret = None
error_ret = None
total_ret = None
part_ret = []
ax = plt.gca() if ax is None else ax
arg, error = _get_args_and_errors(self, minuit, args, errors)
m = mid(self.edges)
if self.use_w2:
err = np.sqrt(self.w2)
else:
err = np.sqrt(self.h)
n= np.copy(self.h)
dataint= (n*np.diff(self.edges)).sum()
scale= dataint if not self.extended else 1.0
ax.errorbar(m, n, err, fmt='+', capsize=0)
data_ret = (self.edges, n)
error_ret = (err, err)
draw_arg = [('lw', 2)]
if not parts:
draw_arg.append(('color', 'r'))
bound = (self.edges[0], self.edges[-1])
#scale back to bins
if self.extended:
scale= nfbins/float(self.bins)
total_ret = draw_pdf(self.f, arg, bins=nfbins, bound=bound, ax=ax, density=not self.extended,
scale=scale, **dict(draw_arg))
if parts:
f_parts = getattr(self.f, 'parts', None)
if f_parts is not None:
for p in f_parts():
tmp = draw_pdf(p, arg, bins=nfbins, bound=bound, ax=ax,
density=not self.extended, scale=scale)
part_ret.append(tmp)
ax.grid(grid)
txt = _param_text(describe(self), arg, error)
if print_par:
ax.text(parmloc[0], parmloc[1], txt, ha='left', va='top',
transform=ax.transAxes)
return (data_ret, error_ret, total_ret, part_ret)
def draw_residual_blh(self, minuit=None, parmloc=(0.05, 0.95),
ax=None, print_par=False, args=None, errors=None,
norm=False, grid=True):
ax = plt.gca() if ax is None else ax
arg, error = _get_args_and_errors(self, minuit, args, errors)
m = mid(self.edges)
if self.use_w2:
err = np.sqrt(self.w2)
else:
err = np.sqrt(self.h)
n= np.copy(self.h)
dataint= (n*np.diff(self.edges)).sum()
scale= dataint if not self.extended else 1.0
arg = parse_arg(self.f, arg, 1) if isinstance(arg, dict) else arg
yf = vector_apply(self.f, m, *arg)
yf*= (scale*np.diff(self.edges) if self.extended else scale)
n = n- yf
if norm:
sel= err>0
n[sel]/= err[sel]
err= np.ones(len(err))
ax.errorbar(m, n, err, fmt='+', capsize=0)
ax.plot([self.edges[0],self.edges[-1]],[0.,0.], 'r-')
ax.grid(grid)
txt = _param_text(describe(self), arg, error)
if print_par:
ax.text(parmloc[0], parmloc[1], txt, ha='left', va='top',
transform=ax.transAxes)
return m, n, err
def draw_compare(f, arg, edges, data, errors=None, ax=None, grid=True, normed=False, parts=False):
"""
TODO: this needs to be rewritten
"""
#arg is either map or tuple
ax = plt.gca() if ax | |
th, phi) +
s**5 * (-20 * Rho(r, th, phi)**4 * QL(r, th)**5 + 10 * 1j * Rho(r, th, phi)**6 * QL(r, th)**6 + Rho(r, th, phi)**8 * QL(r, th)**7) * Eta(r, th, phi)))
# right
# Take left fiber fields and make coordinate changes (x,y,z,d) ->
# (x,-y,-z,d) and amplitude changes (Ex,Ey,Ez) -> (Ex,-Ey,-Ez).
def ZetaR(r, th): return -(r * np.cos(th) - d) / (beta * w0**2)
def QR(r, th): return 1. / (1j + 2 * ZetaR(r, th))
def Psi0R(r, th, phi): return 1j * QR(r, th) * \
np.exp(-1j * (Rho(r, th, phi))**2 * QR(r, th))
def eExiR(r, th, phi): return np.conj(ER * Psi0R(r, th, phi) * np.exp(-1j * ZetaR(r, th) / s**2) *
(1 + s**2 * (-Rho(r, th, phi)**2 * QR(r, th)**2 + 1j * Rho(r, th, phi)**4 * QR(r, th)**3 - 2 * QR(r, th)**2 * Xi(r, th, phi)**2) +
s**4 * (2 * Rho(r, th, phi)**4 * QR(r, th)**4 - 3 * 1j * Rho(r, th, phi)**6 * QR(r, th)**5 - 0.5 * Rho(r, th, phi)**8 * QR(r, th)**6 +
(8 * Rho(r, th, phi)**2 * QR(r, th)**4 - 2 * 1j * Rho(r, th, phi)**4 * QR(r, th)**5) * Xi(r, th, phi)**2)))
def eEyiR(r, th, phi): return np.conj(ER * Psi0R(r, th, phi) * np.exp(-1j * ZetaR(r, th) / s**2) *
(s**2 * (-2 * QR(r, th)**2 * Xi(r, th, phi) * Eta(r, th, phi)) +
s**4 * ((8 * Rho(r, th, phi)**2 * QR(r, th)**4 - 2 * 1j * Rho(r, th, phi)**4 * QR(r, th)**5) * Xi(r, th, phi) * Eta(r, th, phi))))
def eEziR(r, th, phi): return - np.conj(ER * Psi0R(r, th, phi) * np.exp(-1j * ZetaR(r, th) / s**2) *
(s * (-2 * QR(r, th) * Xi(r, th, phi)) + s**3 * (6 * Rho(r, th, phi)**2 * QR(r, th)**3 - 2 * 1j * Rho(r, th, phi)**4 * QR(r, th)**4) * Xi(r, th, phi) +
s**5 * (-20 * Rho(r, th, phi)**4 * QR(r, th)**5 + 10 * 1j * Rho(r, th, phi)**6 * QR(r, th)**6 + Rho(r, th, phi)**8 * QR(r, th)**7) * Xi(r, th, phi)))
def eHxiR(r, th, phi): return - np.conj(+np.sqrt(EpsilonI) * ER * Psi0R(r, th, phi) * np.exp(-1j * ZetaR(r, th) / s**2) *
(s**2 * (-2 * QR(r, th)**2 * Xi(r, th, phi) * Eta(r, th, phi)) +
s**4 * ((8 * Rho(r, th, phi)**2 * QR(r, th)**4 - 2 * 1j * Rho(r, th, phi)**4 * QR(r, th)**5) * Xi(r, th, phi) * Eta(r, th, phi))))
def eHyiR(r, th, phi): return - np.conj(+np.sqrt(EpsilonI) * ER * Psi0R(r, th, phi) * np.exp(-1j * ZetaR(r, th) / s**2) *
(1 + s**2 * (-Rho(r, th, phi)**2 * QR(r, th)**2 + 1j * Rho(r, th, phi)**4 * QR(r, th)**3 - 2 * QR(r, th)**2 * Eta(r, th, phi)**2) +
s**4 * (2 * Rho(r, th, phi)**4 * QR(r, th)**4 - 3 * 1j * Rho(r, th, phi)**6 * QR(r, th)**5 - 0.5 * Rho(r, th, phi)**8 * QR(r, th)**6 +
(8 * Rho(r, th, phi)**2 * QR(r, th)**4 - 2 * 1j * Rho(r, th, phi)**4 * QR(r, th)**5) * Eta(r, th, phi)**2)))
def eHziR(r, th, phi): return np.conj(np.sqrt(EpsilonI) * ER * Psi0R(r, th, phi) * np.exp(-1j * ZetaR(r, th) / s**2) *
(s * (-2 * QR(r, th) * Eta(r, th, phi)) + s**3 * (6 * Rho(r, th, phi)**2 * QR(r, th)**3 - 2 * 1j * Rho(r, th, phi)**4 * QR(r, th)**4) * Eta(r, th, phi) +
s**5 * (-20 * Rho(r, th, phi)**4 * QR(r, th)**5 + 10 * 1j * Rho(r, th, phi)**6 * QR(r, th)**6 + Rho(r, th, phi)**8 * QR(r, th)**7) * Eta(r, th, phi)))
# Gaussian beam (incident fields) - in spherical polar coordinates basis
# left
def eEriL(r, th, phi): return np.sin(th) * np.cos(phi) * eExiL(r, th, phi) + \
np.sin(th) * np.sin(phi) * eEyiL(r, th, phi) + \
np.cos(th) * eEziL(r, th, phi)
def eEthiL(r, th, phi): return np.cos(th) * np.cos(phi) * eExiL(r, th, phi) + \
np.cos(th) * np.sin(phi) * eEyiL(r, th, phi) - \
np.sin(th) * eEziL(r, th, phi)
def eEphiiL(r, th, phi): return - np.sin(phi) * \
eExiL(r, th, phi) + np.cos(phi) * eEyiL(r, th, phi)
def eHriL(r, th, phi): return np.sin(th) * np.cos(phi) * eHxiL(r, th, phi) + \
np.sin(th) * np.sin(phi) * eHyiL(r, th, phi) + \
np.cos(th) * eHziL(r, th, phi)
def eHthiL(r, th, phi): return np.cos(th) * np.cos(phi) * eHxiL(r, th, phi) + \
np.cos(th) * np.sin(phi) * eHyiL(r, th, phi) - \
np.sin(th) * eHziL(r, th, phi)
def eHphiiL(r, th, phi): return - np.sin(phi) * \
eHxiL(r, th, phi) + np.cos(phi) * eHyiL(r, th, phi)
# right
def eEriR(r, th, phi): return np.sin(th) * np.cos(phi) * eExiR(r, th, phi) + \
np.sin(th) * np.sin(phi) * eEyiR(r, th, phi) + \
np.cos(th) * eEziR(r, th, phi)
def eEthiR(r, th, phi): return np.cos(th) * np.cos(phi) * eExiR(r, th, phi) + \
np.cos(th) * np.sin(phi) * eEyiR(r, th, phi) - \
np.sin(th) * eEziR(r, th, phi)
def eEphiiR(r, th, phi): return - np.sin(phi) * \
eExiR(r, th, phi) + np.cos(phi) * eEyiR(r, th, phi)
def eHriR(r, th, phi): return np.sin(th) * np.cos(phi) * eHxiR(r, th, phi) + \
np.sin(th) * np.sin(phi) * eHyiR(r, th, phi) + \
np.cos(th) * eHziR(r, th, phi)
def eHthiR(r, th, phi): return np.cos(th) * np.cos(phi) * eHxiR(r, th, phi) + \
np.cos(th) * np.sin(phi) * eHyiR(r, th, phi) - \
np.sin(th) * eHziR(r, th, phi)
def eHphiiR(r, th, phi): return - np.sin(phi) * \
eHxiR(r, th, phi) + np.cos(phi) * eHyiR(r, th, phi)
eBL = np.zeros(lmax, dtype=complex)
mBL = np.zeros(lmax, dtype=complex)
eBR = np.zeros(lmax, dtype=complex)
# eBR_test = np.zeros(lmax, dtype=complex)
mBR = np.zeros(lmax, dtype=complex)
if field_approx == "davis": # Davis
tau = np.zeros(lmax, dtype=complex)
for ii in range(lmax):
l = ii + 1
tau[ii] = 0 # sum over m and n
niimax = int(np.floor((l - 1) / 3))
for n in range(niimax + 1):
miimax = int(np.floor((l - 1) / 2 - 3 / 2 * n))
for m in range(miimax + 1):
if l < (2 * m + 3 * n + 2):
Delta = 0
else:
Delta = 1
tau[ii] = tau[ii] + np.exp(gammaln(l / 2 - m - n) + gammaln(m + n + 2) - gammaln(l - 2 * m - 3 * n) - gammaln(l / 2 + 2) - gammaln(m + 1) - gammaln(n + 1)) * hypergeomcoeff[l - 1, m + n] \
* (-1)**(m + 1) / (S**m * (beta * zR)**n) * (S / (1j * beta * w0))**(2 * m + 2 * n) * (1 - Delta * 2 * S / (beta * zR) * (l - 1 - 2 * m - 3 * n))
# print(tau)
# calculate expansion coefficients of order l for electric and magnetic
# Debye potentials
def emB(l): return S * np.exp(1j * beta * d) * (1j * beta / (2 * kI))**(l - 1) * \
(l + 1 / 2)**2 / (l + 1) * \
np.exp(gammaln(2 * l) - gammaln(l + 1)) * tau[l - 1]
for ii in range(lmax):
l = ii + 1
# left
eBL[ii] = EL * emB(l)
mBL[ii] = HL * emB(l)
# right
# should include factor of (-1)**(l-1) for symmetry reasons, this
# is taken into account only after least square fitting (see below)
eBR[ii] = ER * emB(l)
# should include factor of (-1)**l for symmetry reasons, this is
# taken into account only after least square fitting (see
mBR[ii] = HR * emB(l)
else: # Barton
for ii in range(lmax):
l = ii + 1
eBL[ii] = np.sqrt(2) * quadl(lambda th: eEriL(a, th, np.pi / 4) * legendrePl(l, np.cos(
th)) * np.sin(th), | |
<reponame>hanxucn/mongo-upgrade
#!/usr/bin/python2
# -*- coding: utf-8 -*-
# Copyright (c) 2013-2022, SMARTX
# All rights reserved.
import ConfigParser
import logging
import os
import platform
import subprocess
import sys
import textwrap
from time import sleep
X86_VERSION_MAP = {
"2.6": "2.6",
"3.0": "2.6",
"3.2": "3.0",
"3.4": "3.2",
"3.6": "3.4",
"4.0": "3.6",
"4.2": "4.0",
"4.4": "4.2",
"5.0": "4.4",
}
AARCH64_VERSION_MAP = {
"3.2": "3.2",
"3.4": "3.2",
"3.6": "3.4",
"4.0": "3.6",
"4.2": "4.0",
"4.4": "4.2",
"5.0": "4.4",
}
STATE_PRIMARY = "PRIMARY"
STATE_SECONDARY = "SECONDARY"
STATE_NOLIVE = "(not reachable/healthy)"
INVENTORY_IP_ATTACHMENT = "ansible_ssh_user=smartx ansible_ssh_private_key_file=/home/smartx/.ssh/smartx_id_rsa"
action_dict = {}
def register_action(func):
action_dict[func.__name__] = func
return func
def get_current_data_ip():
parser = ConfigParser.SafeConfigParser()
parser.read("/etc/zbs/zbs.conf")
return parser.get("network", "data_ip")
def get_mongo_image_name():
cmd = "podman images localhost/mongodb-base --format '{{.Repository}}:{{.Tag}}'"
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if process.returncode != 0:
msg = "podman query mongo images failed, rc: {} stdout: {} stderr: {}"
logging.error(msg.format(process.returncode, stdout, stderr))
return []
res = []
for line in stdout.split("\n"):
if line.strip():
res.append(line.strip())
return res
def get_container_id():
cmd = "podman ps | grep localhost/mongodb-base | awk '{print $1}'"
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if process.returncode != 0:
msg = "podman query mongo container failed, rc: {} stdout: {} stderr: {}"
logging.error(msg.format(process.returncode, stdout, stderr))
return []
container_id = stdout.strip()
return container_id
def get_mongo_db_version(mongo_ip):
cmd = 'mongo --host {} --quiet --norc --eval "db.version()"'.format(mongo_ip)
container_id = get_container_id()
if container_id:
cmd = "podman exec -it {} ".format(container_id) + cmd
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if process.returncode != 0:
msg = "get mongo {} db.version failed, stdout: {} stderr: {} rc: {}"
logging.info(msg.format(mongo_ip, stdout, stderr, process.returncode))
return ""
return stdout.strip()
def get_expected_mongo_nodes(down_ips):
parser = ConfigParser.SafeConfigParser()
parser.read("/etc/zbs/zbs.conf")
cluster_storage = parser.get("cluster", "mongo")
expected_mongo_nodes = cluster_storage.split(",")
return expected_mongo_nodes
def get_mongo_rs_status(with_db_version=True, down_node=""):
# cluster_live_storage_ips = get_live_node_data_ip()
# cmd_str = """\
# mongo --host %s --quiet --norc --eval "rs.status().members.forEach(function(i){ print(i.name + '@' + i.stateStr) })"
# """ % cluster_live_storage_ips[0]
# cmd = textwrap.dedent(cmd_str).strip()
down_ips = []
if down_node:
down_ips = down_node.split(",")
cmd = textwrap.dedent(
"""
mongo --quiet --norc --eval "rs.status().members.forEach(function(i){ print(i.name + '@' + i.stateStr) })"
"""
).strip()
container_id = get_container_id()
if container_id:
cmd = "podman exec -it {} ".format(container_id) + cmd
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if process.returncode != 0:
msg = "get mongo rs.status failed, stdout: {} stderr: {} rc: {}"
logging.info(msg.format(stdout, stderr, process.returncode))
return []
res = []
for line in stdout.strip().split("\n"):
mongo_ip_port, state_str = line.strip().split("@")
mongo_ip, _ = mongo_ip_port.split(":")
if mongo_ip in down_ips:
continue
if with_db_version and state_str in [STATE_PRIMARY, STATE_SECONDARY]:
db_version = get_mongo_db_version(mongo_ip)
else:
db_version = ""
res.append(
{
"mongo_ip": mongo_ip,
"state": state_str,
"db_version": db_version,
}
)
return res
def step_down_mongo_primary(mongo_ip):
"""
see https://docs.mongodb.com/manual/reference/method/rs.stepDown/#client-connections
Because the disconnect includes the connection used to run the method,
you cannot retrieve the return status of the method if the method completes successfully.
You can only retrieve the return status of the method if it errors.
"""
cmd = "mongo --host {} --norc --eval 'rs.stepDown()'".format(mongo_ip)
container_id = get_container_id()
if container_id:
cmd = "podman exec -it {} ".format(container_id) + cmd
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if process.returncode != 0: # expected result before mongo v4.2
return False
return True
def set_compatibility_version(data_ip, version):
cmd = "mongo --host {} --quiet --norc --eval ".format(data_ip)
container_id = get_container_id()
if container_id:
cmd = "podman exec -it {} ".format(container_id) + cmd
exec_cmd = cmd + '"db.adminCommand( { setFeatureCompatibilityVersion:' + "'{}'".format(version) + '} )"'
process = subprocess.Popen(exec_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if process.returncode != 0:
msg = "setFeatureCompatibilityVersion failed on mongo {}, stdout: {} stderr: {} rc: {}"
logging.info(msg.format(data_ip, stdout, stderr, process.returncode))
return False
_eval = '"db.adminCommand({ getParameter: 1, featureCompatibilityVersion: 1 }).featureCompatibilityVersion"'
exec_cmd = cmd + _eval
process = subprocess.Popen(exec_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if process.returncode != 0:
msg = "query featureCompatibilityVersion failed on mongo {}, stdout: {} stderr: {} rc: {}"
logging.info(msg.format(data_ip, stderr, process.returncode))
return False
if version not in stdout:
logging.error("Expected featureCompatibilityVersion {}, actually get {}".format(version, stdout.strip()))
return False
return True
@register_action
def cmd_get_mongo_list(*args):
mongo_list = get_mongo_rs_status(with_db_version=False)
if not mongo_list:
logging.error("Failed to get mongo rs.status()")
return False
print(" ".join([item["mongo_ip"] for item in mongo_list]))
return True
@register_action
def cmd_get_pre_down_mongo(*args):
mongo_list = get_mongo_rs_status()
current_ip = get_current_data_ip()
# expect_mongo_nodes = get_expected_mongo_nodes()
down_mongo = []
if len(mongo_list) > 3:
down_num = len(mongo_list) - 3
for item in mongo_list:
if len(down_mongo) == down_num:
break
if item["state"] == STATE_SECONDARY and item["mongo_ip"] != current_ip:
down_mongo.append(item["mongo_ip"])
print(",".join(down_mongo))
else:
print("")
@register_action
def gen_mongo_cluster_inventory(down_node, *args):
mongo_list = get_mongo_rs_status(with_db_version=False)
if not mongo_list:
logging.error("Failed to get mongo rs.status()")
return False
witness = []
if os.path.exists("/etc/zbs/witness"):
with open("/etc/zbs/witness", "rt") as f:
witness_ip_port = f.read().strip().split(":")[0]
if witness_ip_port and witness_ip_port[0]:
witness.append(witness_ip_port[0])
conf_str = "[mongo_cluster]\n"
for item in mongo_list:
conf_str += "{} {}\n".format(item["mongo_ip"], INVENTORY_IP_ATTACHMENT)
conf_str += "[witness]\n"
for item in witness:
conf_str += "{} {}\n".format(item, INVENTORY_IP_ATTACHMENT)
conf_str += "[current_node]\n"
conf_str += "{} {}\n".format(get_current_data_ip(), INVENTORY_IP_ATTACHMENT)
if down_node:
secondary_to_down = down_node.split(",")
conf_str += "[secondary_to_down]\n"
for down_ip in secondary_to_down:
conf_str += "{} {}\n".format(down_ip, INVENTORY_IP_ATTACHMENT)
with open(os.path.join(os.getcwd(), "mongo_cluster_inventory"), "w") as f:
f.write(conf_str)
return True
@register_action
def cmd_get_upgrade_road_map(down_node="", *args):
version_map = {
"x86_64": X86_VERSION_MAP,
"aarch64": AARCH64_VERSION_MAP,
}.get(platform.machine())
full_version_list = sorted(version_map.keys())
mongo_list = get_mongo_rs_status(down_node=down_node)
if not mongo_list:
logging.error("Failed to get mongo rs.status() and db.version()")
return False
cluster_versions = []
for item in mongo_list:
if item.get("db_version"):
cluster_versions.append(item["db_version"][:3])
else:
logging.error("Failed to get db.version() from {}".format(item["mongo_ip"]))
return False
start_version = min(cluster_versions)
print(" ".join(sorted(item for item in full_version_list if item > start_version)))
return True
@register_action
def gen_new_mongo_conf(*args):
conf_str = textwrap.dedent(
"""
systemLog:
path: /var/log/mongodb/mongod.log
destination: file
logAppend: true
logRotate: reopen
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
processManagement:
fork: false
net:
bindIp: 127.0.0.1,{}
port: 27017
maxIncomingConnections: 64000
replication:
oplogSizeMB: 4096
replSetName: zbs
"""
)
with open("/etc/mongod.conf", "w") as f:
f.write(conf_str.format(get_current_data_ip()).strip() + "\n")
return True
def _check_cluster_version(next_v, mongo_list):
version_map = {
"x86_64": X86_VERSION_MAP,
"aarch64": AARCH64_VERSION_MAP,
}.get(platform.machine())
if next_v not in version_map:
logging.error("not support upgrade for target version: {}".format(next_v))
return False
if len(mongo_list) not in [3, 5]:
logging.error("The number of cluster nodes needs to be 3 or 5.")
return False
v = version_map.get(next_v)
pre_v = version_map.get(v)
mongodb_versions = sorted(item["db_version"][:3] for item in mongo_list)
if len(set(mongodb_versions)) not in [1, 2]:
logging.error("Please upgrade all {} to {} before upgrade to {}".format(mongodb_versions, v, next_v))
return False
if pre_v != v and pre_v in mongodb_versions:
if mongodb_versions in [[pre_v, v, v], [pre_v, v, v, v, v]]:
return True
else:
logging.error("Please upgrade all {} to {} before upgrade to {}".format(mongodb_versions, v, next_v))
return False
abnormal_versions = [item for item in mongodb_versions if item not in {v, next_v}]
if abnormal_versions:
logging.error("Please upgrade all {} to {} before upgrade to {}".format(abnormal_versions, v, next_v))
return False
return True
@register_action
def loop_check_for(target_version, down_node="", *args):
for r in range(120):
logging.info("check mongo rs.status(), round {}".format(r))
mongo_list = get_mongo_rs_status(down_node=down_node)
if not mongo_list:
sleep(10)
continue
full_info = True
for item in mongo_list:
logging.info("{} {} {}".format(item["mongo_ip"], item["db_version"], item["state"]))
if not (item["mongo_ip"] and item["db_version"] and item["state"]):
full_info = False
if not full_info:
logging.info("Incomplete access to rs.status() and db.version(), wait ...")
sleep(10)
continue
if not _check_cluster_version(target_version, mongo_list):
logging.info("Current cluster version does not support upgrading to {}".format(target_version))
return False
primary = [item for item in mongo_list if item["state"] == STATE_PRIMARY]
if not primary:
logging.info("Mongo PRIMARY not FOUND, wait for PRIMARY ...")
sleep(10)
continue
abnormal = [item["state"] for item in mongo_list if item["state"] not in [STATE_PRIMARY, STATE_SECONDARY]]
if abnormal:
logging.info("wait for abnormal states: {} ...".format(abnormal))
sleep(10)
continue
return True
logging.info("check mongo rs.status() timeout, please check mongo cluster status.")
return False
@register_action
def check_mongo_cluster_states(down_node="", *args):
mongo_list = get_mongo_rs_status(down_node=down_node)
if not mongo_list:
logging.error("Failed to get mongo rs.status()")
return False
for item in mongo_list:
logging.info("{} {} {}".format(item["mongo_ip"], item["db_version"], item["state"]))
primary = [item for item in mongo_list if item["state"] == STATE_PRIMARY]
if not primary:
logging.info("Mongo PRIMARY not FOUND, wait for PRIMARY ...")
return False
abnormal = [item["state"] for item in mongo_list if item["state"] not in [STATE_PRIMARY, STATE_SECONDARY]]
if abnormal:
logging.info("Wait for abnormal states: {} ...".format(abnormal))
return False
return True
@register_action
def gen_plan_inventory(next_v, down_mongo="", *args):
version_map = {
"x86_64": X86_VERSION_MAP,
"aarch64": AARCH64_VERSION_MAP,
}.get(platform.machine())
if next_v not in version_map:
logging.error("not support upgrade for target version: {}".format(next_v))
return False
v = version_map.get(next_v)
mongo_list = get_mongo_rs_status(down_node=down_mongo)
if not mongo_list:
logging.error("Failed to get mongo rs.status() and db.version()")
| |
*args)
def getElementName(self):
"""getElementName(SedListOfDataGenerators self) -> string"""
return _libsedml.SedListOfDataGenerators_getElementName(self)
def getTypeCode(self):
"""getTypeCode(SedListOfDataGenerators self) -> int"""
return _libsedml.SedListOfDataGenerators_getTypeCode(self)
def getItemTypeCode(self):
"""getItemTypeCode(SedListOfDataGenerators self) -> int"""
return _libsedml.SedListOfDataGenerators_getItemTypeCode(self)
__swig_destroy__ = _libsedml.delete_SedListOfDataGenerators
__del__ = lambda self : None;
SedListOfDataGenerators_swigregister = _libsedml.SedListOfDataGenerators_swigregister
SedListOfDataGenerators_swigregister(SedListOfDataGenerators)
class SedRange(SedBase):
"""Proxy of C++ SedRange class"""
__swig_setmethods__ = {}
for _s in [SedBase]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{}))
__setattr__ = lambda self, name, value: _swig_setattr(self, SedRange, name, value)
__swig_getmethods__ = {}
for _s in [SedBase]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{}))
__getattr__ = lambda self, name: _swig_getattr(self, SedRange, name)
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(SedRange self, unsigned int level=SEDML_DEFAULT_LEVEL, unsigned int version=SEDML_DEFAULT_VERSION) -> SedRange
__init__(SedRange self, unsigned int level=SEDML_DEFAULT_LEVEL) -> SedRange
__init__(SedRange self) -> SedRange
__init__(SedRange self, SedNamespaces sedns) -> SedRange
__init__(SedRange self, SedRange orig) -> SedRange
"""
this = _libsedml.new_SedRange(*args)
try: self.this.append(this)
except: self.this = this
def clone(self):
"""clone(SedRange self) -> SedRange"""
return _libsedml.SedRange_clone(self)
__swig_destroy__ = _libsedml.delete_SedRange
__del__ = lambda self : None;
def getId(self):
"""getId(SedRange self) -> string"""
return _libsedml.SedRange_getId(self)
def isSetId(self):
"""isSetId(SedRange self) -> bool"""
return _libsedml.SedRange_isSetId(self)
def setId(self, *args):
"""setId(SedRange self, string id) -> int"""
return _libsedml.SedRange_setId(self, *args)
def unsetId(self):
"""unsetId(SedRange self) -> int"""
return _libsedml.SedRange_unsetId(self)
def getElementName(self):
"""getElementName(SedRange self) -> string"""
return _libsedml.SedRange_getElementName(self)
def getTypeCode(self):
"""getTypeCode(SedRange self) -> int"""
return _libsedml.SedRange_getTypeCode(self)
def hasRequiredAttributes(self):
"""hasRequiredAttributes(SedRange self) -> bool"""
return _libsedml.SedRange_hasRequiredAttributes(self)
def setSedDocument(self, *args):
"""setSedDocument(SedRange self, SedDocument d)"""
return _libsedml.SedRange_setSedDocument(self, *args)
SedRange_swigregister = _libsedml.SedRange_swigregister
SedRange_swigregister(SedRange)
class SedListOfRanges(SedListOf):
"""Proxy of C++ SedListOfRanges class"""
__swig_setmethods__ = {}
for _s in [SedListOf]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{}))
__setattr__ = lambda self, name, value: _swig_setattr(self, SedListOfRanges, name, value)
__swig_getmethods__ = {}
for _s in [SedListOf]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{}))
__getattr__ = lambda self, name: _swig_getattr(self, SedListOfRanges, name)
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(SedListOfRanges self, unsigned int level=SEDML_DEFAULT_LEVEL, unsigned int version=SEDML_DEFAULT_VERSION) -> SedListOfRanges
__init__(SedListOfRanges self, unsigned int level=SEDML_DEFAULT_LEVEL) -> SedListOfRanges
__init__(SedListOfRanges self) -> SedListOfRanges
__init__(SedListOfRanges self, SedNamespaces sedns) -> SedListOfRanges
"""
this = _libsedml.new_SedListOfRanges(*args)
try: self.this.append(this)
except: self.this = this
def clone(self):
"""clone(SedListOfRanges self) -> SedListOfRanges"""
return _libsedml.SedListOfRanges_clone(self)
def get(self, *args):
"""
get(SedListOfRanges self, unsigned int n) -> SedRange
get(SedListOfRanges self, unsigned int n) -> SedRange
get(SedListOfRanges self, string sid) -> SedRange
get(SedListOfRanges self, string sid) -> SedRange
"""
return _libsedml.SedListOfRanges_get(self, *args)
def addRange(self, *args):
"""addRange(SedListOfRanges self, SedRange r) -> int"""
return _libsedml.SedListOfRanges_addRange(self, *args)
def getNumRanges(self):
"""getNumRanges(SedListOfRanges self) -> unsigned int"""
return _libsedml.SedListOfRanges_getNumRanges(self)
def createUniformRange(self):
"""createUniformRange(SedListOfRanges self) -> SedUniformRange"""
return _libsedml.SedListOfRanges_createUniformRange(self)
def createVectorRange(self):
"""createVectorRange(SedListOfRanges self) -> SedVectorRange"""
return _libsedml.SedListOfRanges_createVectorRange(self)
def createFunctionalRange(self):
"""createFunctionalRange(SedListOfRanges self) -> SedFunctionalRange"""
return _libsedml.SedListOfRanges_createFunctionalRange(self)
def remove(self, *args):
"""
remove(SedListOfRanges self, unsigned int n) -> SedRange
remove(SedListOfRanges self, string sid) -> SedRange
"""
return _libsedml.SedListOfRanges_remove(self, *args)
def getElementName(self):
"""getElementName(SedListOfRanges self) -> string"""
return _libsedml.SedListOfRanges_getElementName(self)
def getTypeCode(self):
"""getTypeCode(SedListOfRanges self) -> int"""
return _libsedml.SedListOfRanges_getTypeCode(self)
def getItemTypeCode(self):
"""getItemTypeCode(SedListOfRanges self) -> int"""
return _libsedml.SedListOfRanges_getItemTypeCode(self)
__swig_destroy__ = _libsedml.delete_SedListOfRanges
__del__ = lambda self : None;
SedListOfRanges_swigregister = _libsedml.SedListOfRanges_swigregister
SedListOfRanges_swigregister(SedListOfRanges)
class SedVectorRange(SedRange):
"""Proxy of C++ SedVectorRange class"""
__swig_setmethods__ = {}
for _s in [SedRange]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{}))
__setattr__ = lambda self, name, value: _swig_setattr(self, SedVectorRange, name, value)
__swig_getmethods__ = {}
for _s in [SedRange]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{}))
__getattr__ = lambda self, name: _swig_getattr(self, SedVectorRange, name)
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(SedVectorRange self, unsigned int level=SEDML_DEFAULT_LEVEL, unsigned int version=SEDML_DEFAULT_VERSION) -> SedVectorRange
__init__(SedVectorRange self, unsigned int level=SEDML_DEFAULT_LEVEL) -> SedVectorRange
__init__(SedVectorRange self) -> SedVectorRange
__init__(SedVectorRange self, SedNamespaces sedns) -> SedVectorRange
__init__(SedVectorRange self, SedVectorRange orig) -> SedVectorRange
"""
this = _libsedml.new_SedVectorRange(*args)
try: self.this.append(this)
except: self.this = this
def clone(self):
"""clone(SedVectorRange self) -> SedVectorRange"""
return _libsedml.SedVectorRange_clone(self)
__swig_destroy__ = _libsedml.delete_SedVectorRange
__del__ = lambda self : None;
def getValues(self, *args):
"""
getValues(SedVectorRange self) -> DoubleStdVector
getValues(SedVectorRange self) -> DoubleStdVector
"""
return _libsedml.SedVectorRange_getValues(self, *args)
def hasValues(self):
"""hasValues(SedVectorRange self) -> bool"""
return _libsedml.SedVectorRange_hasValues(self)
def getNumValues(self):
"""getNumValues(SedVectorRange self) -> unsigned int"""
return _libsedml.SedVectorRange_getNumValues(self)
def setValues(self, *args):
"""setValues(SedVectorRange self, DoubleStdVector value) -> int"""
return _libsedml.SedVectorRange_setValues(self, *args)
def addValue(self, *args):
"""addValue(SedVectorRange self, double value) -> int"""
return _libsedml.SedVectorRange_addValue(self, *args)
def clearValues(self):
"""clearValues(SedVectorRange self) -> int"""
return _libsedml.SedVectorRange_clearValues(self)
def getElementName(self):
"""getElementName(SedVectorRange self) -> string"""
return _libsedml.SedVectorRange_getElementName(self)
def getTypeCode(self):
"""getTypeCode(SedVectorRange self) -> int"""
return _libsedml.SedVectorRange_getTypeCode(self)
def hasRequiredAttributes(self):
"""hasRequiredAttributes(SedVectorRange self) -> bool"""
return _libsedml.SedVectorRange_hasRequiredAttributes(self)
def setSedDocument(self, *args):
"""setSedDocument(SedVectorRange self, SedDocument d)"""
return _libsedml.SedVectorRange_setSedDocument(self, *args)
SedVectorRange_swigregister = _libsedml.SedVectorRange_swigregister
SedVectorRange_swigregister(SedVectorRange)
class SedUniformRange(SedRange):
"""Proxy of C++ SedUniformRange class"""
__swig_setmethods__ = {}
for _s in [SedRange]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{}))
__setattr__ = lambda self, name, value: _swig_setattr(self, SedUniformRange, name, value)
__swig_getmethods__ = {}
for _s in [SedRange]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{}))
__getattr__ = lambda self, name: _swig_getattr(self, SedUniformRange, name)
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(SedUniformRange self, unsigned int level=SEDML_DEFAULT_LEVEL, unsigned int version=SEDML_DEFAULT_VERSION) -> SedUniformRange
__init__(SedUniformRange self, unsigned int level=SEDML_DEFAULT_LEVEL) -> SedUniformRange
__init__(SedUniformRange self) -> SedUniformRange
__init__(SedUniformRange self, SedNamespaces sedns) -> SedUniformRange
__init__(SedUniformRange self, SedUniformRange orig) -> SedUniformRange
"""
this = _libsedml.new_SedUniformRange(*args)
try: self.this.append(this)
except: self.this = this
def clone(self):
"""clone(SedUniformRange self) -> SedUniformRange"""
return _libsedml.SedUniformRange_clone(self)
__swig_destroy__ = _libsedml.delete_SedUniformRange
__del__ = lambda self : None;
def getStart(self):
"""getStart(SedUniformRange self) -> double const"""
return _libsedml.SedUniformRange_getStart(self)
def isSetStart(self):
"""isSetStart(SedUniformRange self) -> bool"""
return _libsedml.SedUniformRange_isSetStart(self)
def setStart(self, *args):
"""setStart(SedUniformRange self, double start) -> int"""
return _libsedml.SedUniformRange_setStart(self, *args)
def unsetStart(self):
"""unsetStart(SedUniformRange self) -> int"""
return _libsedml.SedUniformRange_unsetStart(self)
def getEnd(self):
"""getEnd(SedUniformRange self) -> double const"""
return _libsedml.SedUniformRange_getEnd(self)
def isSetEnd(self):
"""isSetEnd(SedUniformRange self) -> bool"""
return _libsedml.SedUniformRange_isSetEnd(self)
def setEnd(self, *args):
"""setEnd(SedUniformRange self, double end) -> int"""
return _libsedml.SedUniformRange_setEnd(self, *args)
def unsetEnd(self):
"""unsetEnd(SedUniformRange self) -> int"""
return _libsedml.SedUniformRange_unsetEnd(self)
def getNumberOfPoints(self):
"""getNumberOfPoints(SedUniformRange self) -> int const"""
return _libsedml.SedUniformRange_getNumberOfPoints(self)
def isSetNumberOfPoints(self):
"""isSetNumberOfPoints(SedUniformRange self) -> bool"""
return _libsedml.SedUniformRange_isSetNumberOfPoints(self)
def setNumberOfPoints(self, *args):
"""setNumberOfPoints(SedUniformRange self, int numberOfPoints) -> int"""
return _libsedml.SedUniformRange_setNumberOfPoints(self, *args)
def unsetNumberOfPoints(self):
"""unsetNumberOfPoints(SedUniformRange self) -> int"""
return _libsedml.SedUniformRange_unsetNumberOfPoints(self)
def getType(self):
"""getType(SedUniformRange self) -> string"""
return _libsedml.SedUniformRange_getType(self)
def isSetType(self):
"""isSetType(SedUniformRange self) -> bool"""
return _libsedml.SedUniformRange_isSetType(self)
def setType(self, *args):
"""setType(SedUniformRange self, string type) -> int"""
return _libsedml.SedUniformRange_setType(self, *args)
def unsetType(self):
"""unsetType(SedUniformRange self) -> int"""
return _libsedml.SedUniformRange_unsetType(self)
def getElementName(self):
"""getElementName(SedUniformRange self) -> string"""
return _libsedml.SedUniformRange_getElementName(self)
def getTypeCode(self):
"""getTypeCode(SedUniformRange self) -> int"""
return _libsedml.SedUniformRange_getTypeCode(self)
def hasRequiredAttributes(self):
"""hasRequiredAttributes(SedUniformRange self) -> bool"""
return _libsedml.SedUniformRange_hasRequiredAttributes(self)
def setSedDocument(self, *args):
"""setSedDocument(SedUniformRange self, SedDocument d)"""
return _libsedml.SedUniformRange_setSedDocument(self, *args)
SedUniformRange_swigregister = _libsedml.SedUniformRange_swigregister
SedUniformRange_swigregister(SedUniformRange)
class SedFunctionalRange(SedRange):
"""Proxy of C++ SedFunctionalRange class"""
__swig_setmethods__ = {}
for _s in [SedRange]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{}))
__setattr__ = lambda self, name, value: _swig_setattr(self, SedFunctionalRange, name, value)
__swig_getmethods__ = {}
for _s in [SedRange]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{}))
__getattr__ = lambda self, name: _swig_getattr(self, SedFunctionalRange, name)
__repr__ = _swig_repr
def __init__(self, *args):
"""
__init__(SedFunctionalRange self, unsigned int level=SEDML_DEFAULT_LEVEL, unsigned int version=SEDML_DEFAULT_VERSION) -> SedFunctionalRange
__init__(SedFunctionalRange self, unsigned int level=SEDML_DEFAULT_LEVEL) -> SedFunctionalRange
__init__(SedFunctionalRange self) -> SedFunctionalRange
__init__(SedFunctionalRange self, SedNamespaces sedns) -> SedFunctionalRange
__init__(SedFunctionalRange self, SedFunctionalRange orig) -> SedFunctionalRange
"""
this = _libsedml.new_SedFunctionalRange(*args)
try: self.this.append(this)
except: self.this = this
def clone(self):
"""clone(SedFunctionalRange self) -> SedFunctionalRange"""
return _libsedml.SedFunctionalRange_clone(self)
__swig_destroy__ = _libsedml.delete_SedFunctionalRange
__del__ = lambda self : None;
def getRange(self):
"""getRange(SedFunctionalRange self) -> string"""
return _libsedml.SedFunctionalRange_getRange(self)
def isSetRange(self):
"""isSetRange(SedFunctionalRange self) -> bool"""
return _libsedml.SedFunctionalRange_isSetRange(self)
def setRange(self, *args):
"""setRange(SedFunctionalRange self, string range) -> int"""
return _libsedml.SedFunctionalRange_setRange(self, *args)
def unsetRange(self):
"""unsetRange(SedFunctionalRange self) -> int"""
return _libsedml.SedFunctionalRange_unsetRange(self)
def getMath(self):
"""getMath(SedFunctionalRange self) -> ASTNode"""
return _libsedml.SedFunctionalRange_getMath(self)
def isSetMath(self):
"""isSetMath(SedFunctionalRange self) -> bool"""
return _libsedml.SedFunctionalRange_isSetMath(self)
def setMath(self, *args):
"""setMath(SedFunctionalRange self, ASTNode math) -> int"""
return _libsedml.SedFunctionalRange_setMath(self, *args)
def unsetMath(self):
"""unsetMath(SedFunctionalRange self) -> int"""
return _libsedml.SedFunctionalRange_unsetMath(self)
def getListOfVariables(self):
"""getListOfVariables(SedFunctionalRange self) -> SedListOfVariables"""
return _libsedml.SedFunctionalRange_getListOfVariables(self)
def getVariable(self, *args):
"""
getVariable(SedFunctionalRange self, unsigned int n) -> SedVariable
getVariable(SedFunctionalRange self, unsigned int n) -> SedVariable
getVariable(SedFunctionalRange self, string sid) -> SedVariable
getVariable(SedFunctionalRange self, string sid) -> SedVariable
"""
return _libsedml.SedFunctionalRange_getVariable(self, *args)
def addVariable(self, *args):
"""addVariable(SedFunctionalRange self, SedVariable sv) -> int"""
return _libsedml.SedFunctionalRange_addVariable(self, *args)
def getNumVariables(self):
"""getNumVariables(SedFunctionalRange self) -> unsigned int"""
return _libsedml.SedFunctionalRange_getNumVariables(self)
def createVariable(self):
"""createVariable(SedFunctionalRange self) -> SedVariable"""
return _libsedml.SedFunctionalRange_createVariable(self)
def removeVariable(self, *args):
"""
removeVariable(SedFunctionalRange self, unsigned int n) -> SedVariable
removeVariable(SedFunctionalRange self, string sid) -> SedVariable
"""
return _libsedml.SedFunctionalRange_removeVariable(self, *args)
def getListOfParameters(self):
"""getListOfParameters(SedFunctionalRange self) -> SedListOfParameters"""
return _libsedml.SedFunctionalRange_getListOfParameters(self)
def getParameter(self, *args):
"""
getParameter(SedFunctionalRange self, unsigned int n) -> SedParameter
getParameter(SedFunctionalRange self, unsigned int n) -> SedParameter
getParameter(SedFunctionalRange self, string sid) -> SedParameter
getParameter(SedFunctionalRange self, string sid) -> SedParameter
"""
return _libsedml.SedFunctionalRange_getParameter(self, *args)
def addParameter(self, *args):
"""addParameter(SedFunctionalRange self, SedParameter sp) -> int"""
return _libsedml.SedFunctionalRange_addParameter(self, *args)
def getNumParameters(self):
"""getNumParameters(SedFunctionalRange self) -> unsigned int"""
return _libsedml.SedFunctionalRange_getNumParameters(self)
def | |
<gh_stars>0
# Built-in
import os
import sys
import logging
import subprocess
import traceback
from collections import OrderedDict
import webbrowser
from functools import partial
import time
# External
from Qt import QtWidgets
from Qt import QtGui
from Qt import QtCore
# Internal
import nxt_editor
from nxt_editor import user_dir
from nxt.session import Session
from nxt_editor.constants import EDITOR_VERSION
from nxt_editor.stage_view import StageView
from nxt_editor.stage_model import StageModel
from nxt_editor.dockwidgets import (DockWidgetBase, CodeEditor, PropertyEditor,
HotkeyEditor, LayerManager, OutputLog,
HistoryView, WidgetBuilder, BuildView,
FindRepDockWidget)
from nxt_editor.dockwidgets.output_log import (FileTailingThread,
QtLogStreamHandler)
from nxt_editor.dockwidgets.code_editor import NxtCodeEditor
from nxt import nxt_log, nxt_io, nxt_layer
from nxt_editor.dialogs import (NxtFileDialog, NxtWarningDialog,
UnsavedLayersDialogue, UnsavedChangesMessage)
from nxt_editor import actions, LoggingSignaler
from nxt.constants import (API_VERSION, GRAPH_VERSION, USER_PLUGIN_DIR,
NXT_DCC_ENV_VAR, is_standalone)
from nxt.remote.client import NxtClient
import nxt.remote.contexts
from nxt_editor import qresources
logger = logging.getLogger(nxt_editor.LOGGER_NAME)
class MainWindow(QtWidgets.QMainWindow):
"""The main window of the nxt UI. Includes the menu bar, tool bar, and dock widgets."""
tab_changed = QtCore.Signal()
close_signal = QtCore.Signal()
new_log_signal = QtCore.Signal(logging.LogRecord)
def __init__(self, filepath=None, parent=None, start_rpc=True):
"""Create NXT window.
:param parent: parent to attach this UI to.
:type parent: QtWidgets.QtWidgets.QWidget
"""
self.in_startup = True
pixmap = QtGui.QPixmap(':icons/icons/nxt.svg')
self.splash_screen = QtWidgets.QSplashScreen(pixmap)
self.splash_screen.show()
self.splash_screen.showMessage('Starting nxt...',
QtCore.Qt.AlignCenter, QtCore.Qt.white)
QtWidgets.QApplication.processEvents()
super(MainWindow, self).__init__(parent=parent)
self.new_log_signal.connect(self.handle_remote_log)
old_cwd = os.getcwd()
ui_dir = os.path.dirname(__file__)
os.chdir(ui_dir)
# Test to see if we're launching from a git branch, if so the title
# bar will be updated for easy reference.
# Used to hide the stderr from the user as it doesn't matter
f = open(nxt_io.generate_temp_file('NxtGitErr'))
try:
git_out = subprocess.check_output(["git", "branch"],
stderr=f).decode("utf8")
cur = next(line for line in git_out.split("\n")
if line.startswith("*"))
current_branch = cur.strip("*").strip()
except: # Broad because Maya
# Failed to run git branch, attempting fallback method
try:
with open('../../.git/HEAD') as f:
head = f.read()
_, __, current_branch = head.rpartition('/')
except:
# Could not determine git branch, must be pip package.
current_branch = ''
finally:
f.close()
os.chdir(old_cwd)
if is_standalone():
context = 'standalone'
else:
context = os.environ.get(NXT_DCC_ENV_VAR) or ''
self.host_app = context
self.setWindowTitle("nxt {} - Editor v{} | Graph v{} | API v{} "
"(Python {}) {}".format(self.host_app,
EDITOR_VERSION.VERSION_STR,
GRAPH_VERSION.VERSION_STR,
API_VERSION.VERSION_STR,
'.'.join([str(n) for n in sys.version_info[:3]]),
current_branch))
self.setObjectName('Main Window')
self.zoom_keys = QtGui.QKeySequence(QtCore.Qt.Key_Alt)
self.zoom_keys_down = False
self._held_keys = []
self._closing = False
self.last_focused_start = 0 # Start point focus tracker
# FIXME: Fix with MV signal
self.last_focused_tab = -1 # Tab tracker for upating the comp layer
# set app icon
self.app_icon = QtGui.QIcon(pixmap)
self.setWindowIcon(self.app_icon)
# set style sheet
style_file = QtCore.QFile(':styles/styles/dark/dark.qss')
style_file.open(QtCore.QFile.ReadOnly)
self.stylesheet = str(style_file.readAll())
self.setStyleSheet(self.stylesheet)
# fonts
font_db = QtGui.QFontDatabase()
font_db.addApplicationFont(":fonts/fonts/RobotoMono/RobotoMono-Regular.ttf")
font_db.addApplicationFont(":fonts/fonts/Roboto/Roboto-Regular.ttf")
# nxt object in charge of loaded graphs
self.nxt = Session()
# APPLICATION WIDE ACTIONS
# TODO: All the actions should be connected to functions in nxt not
# view
self.splash_screen.showMessage('Setting up hotkeys...',
QtCore.Qt.AlignCenter, QtCore.Qt.white)
self.app_actions = actions.AppActions(self)
self.addActions(self.app_actions.actions())
# NODE ACTIONS
self.node_actions = actions.NodeActions(self)
# PROPERTY ACTIONS
self.property_manager_actions = actions.PropertyEditorActions(self)
# NODE COMMENT ACTIONS
self.node_comment_actions = actions.NodeCommentActions(self)
# LAYER ACTIONS
self.layer_actions = actions.LayerActions(self)
# ALIGNMENT ACTIONS
self.alignment_actions = actions.AlignmentActions(self)
# DISPLAY ACTIONS
self.display_actions = actions.DisplayActions(self)
# VIEW ACTIONS
self.view_actions = actions.StageViewActions(self)
# EXEC ACTIONS
self.execute_actions = actions.ExecuteActions(self)
self.addAction(self.execute_actions.stop_exec_action)
# CODE EDITOR ACTIONS
self.code_editor_actions = actions.CodeEditorActions(self)
# TOOL BARS
self.authoring_toolbar = NodeAuthoringToolBar(self)
self.addToolBar(self.authoring_toolbar)
self.execute_toolbar = ExecuteToolBar(self)
self.addToolBar(self.execute_toolbar)
self.display_toolbar = DisplayToolBar(self)
self.addToolBar(self.display_toolbar)
self.align_distribute_toolbar = AlignDistributeToolBar(self)
self.addToolBar(self.align_distribute_toolbar)
# TABS WIDGET
self.open_files_tab_widget = OpenFilesTabWidget(parent=self)
self.open_files = {} # TODO: Doesn't this duplicate what Nxt does?
self.previous_view = None
# graph tabs
self.open_files_tab_widget.currentChanged.connect(self.on_tab_change)
self.setCentralWidget(self.open_files_tab_widget)
self.splash_screen.showMessage('Setting up dockwidgets...',
QtCore.Qt.AlignCenter, QtCore.Qt.white)
# Dock Widgets
# hotkey editor
self.hotkey_editor = HotkeyEditor(parent=self)
self.hotkey_editor.hide()
# property editor
self.property_editor = PropertyEditor(parent=self)
self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.property_editor)
# code editor
self.code_editor = CodeEditor(parent=self)
self.code_editor.editor.viewport().installEventFilter(self)
self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.code_editor)
# Find and Replace
self.find_rep = FindRepDockWidget(parent=self)
self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.find_rep)
self.find_rep.hide()
# layer manager
self.layer_manager = LayerManager(parent=self)
self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.layer_manager)
# history view
self.history_view = HistoryView(parent=self)
self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.history_view)
# build View
self.build_view = BuildView(parent=self)
self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.build_view)
# output log
self.output_log = OutputLog(parent=self)
self.output_log.hide()
self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.output_log)
# workflow tools
self.workflow_tools = WidgetBuilder(parent=self)
self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.workflow_tools)
self.setCorner(QtCore.Qt.BottomRightCorner,
QtCore.Qt.RightDockWidgetArea)
self.setCorner(QtCore.Qt.BottomLeftCorner,
QtCore.Qt.LeftDockWidgetArea)
self.setTabPosition(QtCore.Qt.AllDockWidgetAreas,
QtWidgets.QTabWidget.North)
# status bar
self.status_bar = QtWidgets.QStatusBar()
self.status_bar.setSizeGripEnabled(False)
self.status_bar.setContentsMargins(4, 4, 4, 4)
self.status_bar.setStyleSheet('color: lightGrey; background-color: #232323; border: 4px solid #3E3E3E')
self.setStatusBar(self.status_bar)
self.log_button = QtWidgets.QPushButton("Show Log")
self.log_button.setMinimumWidth(75)
self.log_button.setStyleSheet(self.stylesheet)
self.output_log.visibilityChanged.connect(self.refresh_log_button)
self.log_button.clicked.connect(self.log_button_clicked)
self.status_bar.addPermanentWidget(self.log_button)
self.refresh_log_button()
self.logger = logging.getLogger('nxt')
self.logger.addHandler(StatusBarHandler(self.status_bar))
self.state_last_hidden = None
# TODO set and load default geometry
# TODO determine and create sensible default position and size for the window, perhaps 80% of available screen?
# print QDesktopWidget.availableGeometry(self)
self.resize(1600, 800)
self.resizeDocks([self.property_editor, self.code_editor], [400, 300], QtCore.Qt.Vertical)
if filepath:
self.load_file(filepath=filepath)
else:
self.new_tab()
# menu bar
# TODO: Depends on dock widgets this should change
self.menu_bar = MenuBar(self)
self.setMenuBar(self.menu_bar)
self.menuBar().setNativeMenuBar(False)
self.display_actions.resolve_action.setChecked(True)
# Rpc startup
self.rpc_log_tail = None
if start_rpc:
self.startup_rpc_server(join=False)
# Should this be a signal? Like Startup done, now you can refresh?
self.splash_screen.finish(self)
self.in_startup = False
t = QtCore.QTimer()
t.setInterval(256)
def failure_check():
if self.view:
self.view.failure_check()
t.stop()
t.timeout.connect(failure_check)
t.start()
app = QtWidgets.QApplication.instance()
app.aboutToQuit.connect(self.shutdown_rpc_server)
# RPC
def startup_rpc_server(self, join=True):
t = StartRPCThread(self)
t.start()
if join:
t.wait()
else:
txt = 'Waiting on rpc server...'
txt_len = len(txt)
self.count = 0
def tick():
self.splash_screen.showMessage(txt[:self.count % -txt_len],
QtCore.Qt.AlignCenter,
QtCore.Qt.white)
self.count += 1
timer = QtCore.QTimer()
timer.setInterval(100)
timer.timeout.connect(tick)
t.finished.connect(timer.stop)
timer.start()
while not t.isFinished():
QtWidgets.QApplication.processEvents()
@staticmethod
def handle_remote_log(record):
logger.handle(record)
def shutdown_rpc_server(self):
if self.model:
self.model.processing.emit(True)
self.safe_stop_rpc_tailing()
self.nxt.shutdown_rpc_server()
if self.model:
self.model.processing.emit(False)
if not self.rpc_log_tail:
return
wait_started = time.time()
while not self.rpc_log_tail.isFinished():
QtWidgets.QApplication.processEvents()
if time.time() - wait_started > 5:
logger.error('Failed to stop rpc log tail!')
return
self.rpc_log_tail = None
def safe_stop_rpc_tailing(self):
if not self.rpc_log_tail:
return
self.handle_rpc_tailing_signals(False)
self.rpc_log_tail.requestInterruption()
def handle_rpc_tailing_signals(self, state):
if not self.rpc_log_tail:
return
raw_write_func = self.output_log._write_raw_output
rich_write_func = self.output_log.write_rich_output
if state:
self.rpc_log_tail.new_text.connect(raw_write_func)
self.rpc_log_tail.new_text.connect(rich_write_func)
else:
self.rpc_log_tail.new_text.disconnect(raw_write_func)
self.rpc_log_tail.new_text.disconnect(rich_write_func)
def event(self, event):
if event.type() == QtCore.QEvent.WindowDeactivate:
self._held_keys = []
self.zoom_keys_down = False
return super(MainWindow, self).event(event)
@staticmethod
def set_waiting_cursor(state=True):
if state:
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
else:
QtWidgets.QApplication.restoreOverrideCursor()
@staticmethod
def create_remote_context(place_holder_text='',
interpreter_exe=sys.executable,
context_graph=None, exe_script_args=()):
cur_context = nxt.remote.contexts.get_current_context_exe_name()
pop_up = QtWidgets.QDialog()
pop_up.setWindowTitle('Create context for "{}"'.format(cur_context))
v_layout = QtWidgets.QVBoxLayout()
pop_up.setLayout(v_layout)
label = QtWidgets.QPlainTextEdit()
info = ('Create remote context for your host '
'Python interpreter/DCC\n'
'Type your desired name in the box below '
'and click create.'.format(cur_context))
label.setPlainText(info)
label.setReadOnly(True)
font_metric = QtGui.QFontMetrics(label.document().defaultFont())
text_size = font_metric.size(QtCore.Qt.TextExpandTabs, info)
label.setFixedSize(text_size.width() + 50, text_size.height() + 30)
v_layout.addWidget(label)
h_layout = QtWidgets.QHBoxLayout()
v_layout.addLayout(h_layout)
name = QtWidgets.QLineEdit()
name.setPlaceholderText(str(place_holder_text))
name.setText(str(place_holder_text))
create_button = QtWidgets.QPushButton('Create!')
h_layout.addWidget(name)
h_layout.addWidget(create_button)
def do_create():
try:
nxt.create_context(name.text(),
interpreter_exe=interpreter_exe,
context_graph=context_graph,
exe_script_args=exe_script_args)
pop_up.close()
except (IOError, NameError) as e:
info = str(e)
msg = 'Failed to create context!'
logger.error(info)
nxt_editor.dialogs.NxtWarningDialog.show_message(msg,
info=info)
create_button.pressed.connect(do_create)
pop_up.exec_()
def get_global_actions(self):
"""Get a list of NxtActions with the WindowShortcut context
:return: List of NxtActions
"""
global_actions = []
for action in self.get_all_nxt_actions():
if action.shortcutContext() == QtCore.Qt.WindowShortcut:
global_actions += [action]
return global_actions
def get_all_nxt_actions(self):
"""Get a list of all NxtActions via the NxtActionContainer objects
:return: List of NxtActions
"""
all_actions = []
all_containers = self.findChildren(actions.NxtActionContainer)
for container in all_containers:
all_actions += container.actions()
return all_actions
def get_hotkey_map(self):
"""Get a map of NxtAction containers and their actions in an
ordered dict where each key is a row row for a QAbstractTableModel.
:return: OrderedDict
"""
hotkeys = OrderedDict()
# Action container objects in the order we wish to display them
action_containers = [self.app_actions, self.alignment_actions,
self.display_actions, self.view_actions,
self.layer_actions, self.node_actions,
self.property_manager_actions,
self.node_comment_actions,
self.execute_actions, self.code_editor_actions]
for container in action_containers:
hotkeys[container.objectName()] = container.get_action_data()
return hotkeys
@property
def view(self):
return self.get_current_view()
@property
def model(self):
if self.view:
return self.view.model
def new_tab(self, initial_stage=None, update=True):
"""Open a new graph view, optionally on a specific initial graph.
Create necessary model, pass to nxt to connect graph to model,
create tab for new file.
:param initial_stage: Graph object to make new view of.
:type initial_stage: nxt.core.Graph.Graph
:param update: If true the different views will update
:type update: bool
"""
self.set_waiting_cursor(True)
# get new graph
if initial_stage:
stage = initial_stage
else:
stage = self.nxt.new_file()
# create model
model = StageModel(stage=stage)
model.processing.connect(self.set_waiting_cursor)
model.request_ding.connect(self.ding)
model.layer_alias_changed.connect(partial(self.update_tab_title, model))
# create view
view = StageView(model=model, parent=self)
# setup tab
tab_index = self.open_files_tab_widget.count()
self.open_files[model.uid] = {'stage': stage, 'model': model,
'view': view}
self.open_files_tab_widget.addTab(view, stage._name)
if update:
self.open_files_tab_widget.setCurrentIndex(tab_index)
self.layer_manager.set_stage_model(model)
model.layer_color_changed.connect(self.update_target_color)
model.target_layer_changed.connect(self.update_target_color)
model.comp_layer_changed.connect(self.update_target_color)
self.update_target_color()
self.update_grid_action()
self.update() # TODO: Make this better
self.set_waiting_cursor(False)
@staticmethod
def ding():
if user_dir.user_prefs.get(user_dir.USER_PREF.DING, True):
QtWidgets.QApplication.instance().beep()
def center_view(self):
target_graph_view = self.get_current_view()
if target_graph_view:
target_graph_view.centerOn(0, 0)
def load_file(self, filepath=None):
"""Open an NxtFileDialog to allow user to select .nxt file to open.
Attempt to open resulting choice. If an attempt is made to open a
file | |
import os
import time
import datetime
import random
import pygame
import io
import sys
import builtins
import traceback
import subprocess
import configparser
from subprocess import check_output, call
from kivy.app import App
from kivy.clock import Clock
from kivy.properties import NumericProperty, StringProperty, ObjectProperty
from kivy.uix.floatlayout import FloatLayout
from kivy.config import Config
from lib import constants
from lib import utils
os.putenv('SDL_AUDIODRIVER', 'alsa')
os.putenv('SDL_AUDIODEV', '/dev/audio')
class DigitalClock(FloatLayout):
secs_to_next_minute = int(0)
display_time = StringProperty("00 : 00")
clock_view = NumericProperty(1) # Variable to enable view of the Clock Time
settings_view = NumericProperty(0) # Variable to enable view of the Settings & Alarm Time
settings_pic = StringProperty("./Images/Buttons/Settings_Normal.png")
am_pm_alarm = NumericProperty(0) # Variable to view AM/PM button in settings when 12hr clock is selected
is_alarming = NumericProperty(0) # Track when Alarm is Active
is_snoozing = NumericProperty(0) # Track when in Snooze mode
alarm_time_hour = NumericProperty(0)
alarm_time_minute = NumericProperty(0)
alarm_time = StringProperty('0')
set_sunday = StringProperty('0')
set_monday = StringProperty('0')
set_tuesday = StringProperty('0')
set_wednesday = StringProperty('0')
set_thursday = StringProperty('0')
set_friday = StringProperty('0')
set_saturday = StringProperty('0')
alarm_switch = NumericProperty(0)
switch_text = StringProperty('OFF')
hr_setting = NumericProperty(0)
hr_text = StringProperty('24HR')
am_pm_clock = NumericProperty(0)
am_pm_clock_text = StringProperty('AM')
am_pm_setting = NumericProperty('0')
am_pm_text = StringProperty('AM')
nfc_cap = str('3e')
nfc_cap2 = str('4>')
nfc_hulk = str('48')
nfc_hulk2 = str('4H')
nfc_locked = False
colour = NumericProperty(0)
curr_time = int
curr_day_name = StringProperty('')
button_state = StringProperty('normal')
alarm_event = ()
nfc_checking = int(0)
section = int(0) # Section of audio files to use 1=1-7, 2=8-14, 3=15-21
audio_path = str('')
audio = int(0)
curr_vol = NumericProperty(50)
label_vol = StringProperty('0%')
pygame.init()
def startup(self):
config_mod = False
if not os.path.exists(os.path.join(constants.FILES, 'config.ini')):
utils.create_default_config_file()
config = configparser.ConfigParser()
self.load_config_file(config)
os.system("amixer sset 'Speaker' " + str(self.curr_vol) + "%")
# subprocess.Popen(['gmediarender', '--gstout-audiosink=alsasink'])
self.update()
def load_config_file(self, config):
config.read(os.path.join(constants.FILES, 'config.ini'))
self.alarm_time_hour = int(config['Alarm Time']['alarm_time_hour'])
self.alarm_time_minute = int(config['Alarm Time']['alarm_time_minute'])
now = datetime.datetime.now()
self.alarm_time = now.replace(hour=self.alarm_time_hour, minute=self.alarm_time_minute).strftime('%H : %M')
# self.alarm_time = (str(self.alarm_time_hour).zfill(2) + " : " + str(self.alarm_time_minute).zfill(2))
print('sunday')
print(self.set_sunday)
self.set_sunday = config['Alarm Days']['set_sunday']
print(type(self.set_sunday))
self.set_monday = config['Alarm Days']['set_monday']
print(self.set_monday)
self.set_tuesday = config['Alarm Days']['set_tuesday']
print(self.set_tuesday)
self.set_wednesday = config['Alarm Days']['set_wednesday']
print(self.set_wednesday)
self.set_thursday = config['Alarm Days']['set_thursday']
print(self.set_thursday)
self.set_friday = config['Alarm Days']['set_friday']
print(self.set_friday)
self.set_saturday = config['Alarm Days']['set_saturday']
print(self.set_saturday)
self.alarm_switch = config['Miscellaneous']['alarm_switch']
self.switch_text = config['Miscellaneous']['switch_text']
self.hr_setting = config['Miscellaneous']['hr_setting']
self.hr_text = config['Miscellaneous']['hr_text']
self.am_pm_clock = config['Miscellaneous']['am_pm_clock']
self.am_pm_clock_text = config['Miscellaneous']['am_pm_clock_text']
self.am_pm_setting = config['Miscellaneous']['am_pm_setting']
self.am_pm_text = config['Miscellaneous']['am_pm_text']
self.nfc_cap = config['Character IDs']['nfc_cap']
self.nfc_cap2 = config['Character IDs']['nfc_cap2']
self.nfc_hulk = config['Character IDs']['nfc_hulk']
self.nfc_hulk2 = config['Character IDs']['nfc_hulk2']
def update(self, dt=0):
Clock.unschedule(self.update) # attempt to fix memory leak - Attempt Successful :)
if self.hr_setting == 0:
self.display_time = time.strftime("%H : %M")
else:
if self.hr_setting == 12:
self.display_time = time.strftime("%I : %M")
self.schedule_update()
def schedule_update(self, dt=0):
self.am_pm_clock_text = time.strftime("%p")
current_time = time.localtime()
seconds = current_time[5]
self.curr_time = datetime.datetime.now()
# self.curr_day_name = self.curr_time.strftime("%A") + " - " + self.curr_time.strftime("%B") + " " + self.curr_time.strftime("%-d")
self.curr_day_name = self.curr_time.strftime("%A")
if ((self.display_time == self.alarm_time) # If alarm time is equal to current time
and (self.alarm_switch == 1) # and alarm switch is ON
and (self.is_alarming == 0)): # and system is currently not in alarm
if (str(
datetime.datetime.today().isoweekday()) == "1" and self.set_monday == '1' # checking current day of week against if it's enabled below
or str(datetime.datetime.today().isoweekday()) == "2" and self.set_tuesday == '1'
or str(datetime.datetime.today().isoweekday()) == "3" and self.set_wednesday == '1'
or str(datetime.datetime.today().isoweekday()) == "4" and self.set_thursday == '1'
or str(datetime.datetime.today().isoweekday()) == "5" and self.set_friday == '1'
or str(datetime.datetime.today().isoweekday()) == "6" and self.set_saturday == '1'
or str(datetime.datetime.today().isoweekday()) == "7" and self.set_sunday == '1'):
if ((self.hr_setting == 12)
and (self.am_pm_text == self.am_pm_clock_text)):
self.alarm_start()
else:
if (self.hr_setting == 0):
self.alarm_start()
else:
self.secs_to_next_minute = (60 - seconds)
Clock.schedule_once(self.update, self.secs_to_next_minute) # Update again in 1 minute
def alarm_start(self, *args):
self.is_alarming = 1 # put system in alarm mode, this is probably reduntant by this point with as many unschedules and kills I have in the script
self.settings_pic = "./Images/Buttons/Settings_Normal.png"
self.settings_view = 0
self.clock_view = 1
self.button_state = "normal"
print("setting volume")
os.system("amixer sset 'Speaker' 100%")
print("volume set")
Clock.schedule_once(self.update, self.secs_to_next_minute) # update again in 1 minute
self.alarm_loop()
def alarm_loop(self, *args):
Clock.unschedule(self.alarm_event) # unschedule the 1 second loop that runs self.alarm_loop
self.alarm_event = Clock.schedule_interval(self.alarm_loop,
1) # Reschedule for one second. Doing Clock.schduled_once in 1 second intervals had bad results.
play_num = int(0)
file_type = str('')
nfc_read = str()
self.settings_view = 0
self.is_snoozing = 0
self.am_pm_alarm = 0
if self.nfc_locked == False:
if (self.nfc_checking == 0): # Allows only one instance of running the NFC check.
self.nfc_checking = 1
self.nfc_read = ''
"""Grab the entire output of the NFC mobule from the I2C channel."""
try: # Run the nfc-poll command and get its output
self.nfc_read = check_output('nfc-poll',
universal_newlines=True) # universal_newlines just makes it easier to read if you decide to Print
except:
pass # If there's an error, just move along and try again.
self.nfc_checking = 0
if (self.nfc_cap in str(self.nfc_read) # Determine audio file path based on NFC read
or self.nfc_cap2 in str(self.nfc_read)):
self.audio_path = "/home/pi/Desktop/PyClock/Sounds/01-CaptainAmerica/"
self.nfc_locked = True
else:
if (self.nfc_hulk in str(self.nfc_read) # Determine audio file path based on NFC read
or self.nfc_hulk2 in str(self.nfc_read)):
self.audio_path = "/home/pi/Desktop/PyClock/Sounds/02-Hulk/"
self.nfc_locked = True
else:
self.audio_path = "/home/pi/Desktop/PyClock/Sounds/" # Default alarm sounds if no NFC tag is found that matches above
self.nfc_locked = True
if self.is_alarming == 1 and (self.alarm_switch == 1):
if self.colour == 0:
self.colour = 1
else:
self.colour = 0
if pygame.mixer.get_busy() == False: # Check that audio currently isn't running
rando = NumericProperty(0)
if self.audio_path == "/home/pi/Desktop/PyClock/Sounds/":
self.rando = random.randint(1, 2)
file_type = '.wav'
self.section = 0
else:
self.rando = random.randint(1, 7) # Random number between 1 and 7, inclusive
file_type = '.ogg'
if self.section == 0: # Increment to next section every round
self.section = 7
else:
if self.section == 7:
self.section = 14
else:
self.section = 0
play_num = (self.rando) + (
self.section) # My files are split into 3 sections, 1-7, 8-14, 15-21 based on natural progression of intensity
sound_file = pygame.mixer.Sound(
str(self.audio_path + str(play_num) + file_type)) # Load sound file into Pygame
alarm = pygame.mixer.Sound(sound_file) # Play sound file
alarm.set_volume(1.0)
# volume = alarm.get_volume()
alarm.play()
else:
self.is_alarming = 0 # Shouldn't need this, but doesn't hurt. Some redundant stuff from def switch_state
Clock.unschedule(self.alarm_event)
def snooze_func(self, *args):
if ((self.is_alarming == 1)
and (self.is_snoozing == 0)):
self.is_snoozing = 1
Clock.unschedule(self.alarm_event) # unschedule the 1 second loop that runs self.alarm_loop
self.section = 0
self.alarm_event = Clock.schedule_once(self.alarm_loop, 300) # schedule new 5-minute Snooze timer
self.colour = 0 # Set background color to Black
self.nfc_locked = False # Reset NFC to try again for tag
if pygame.mixer.get_busy() == True: # If sounds is currently playing
pygame.mixer.stop() # Stop currently playing sound
def cancel_func(self, *args):
if self.is_alarming == 1:
self.is_snoozing = 0
self.is_alarming = 0
Clock.unschedule(self.alarm_event) # unschedule the 1 second loop that runs self.alarm_loop
self.section = 0
self.colour = 0 # Set background color to Black
self.nfc_locked = False # Reset NFC to try again for tag
os.system("amixer sset 'Speaker' " + str(self.curr_vol) + "%")
if pygame.mixer.get_busy() == True: # If sounds is currently playing
pygame.mixer.stop() # Stop currently playing sound
def switch_state(self, *args): # Arm/disarm alarm
if self.settings_view == 1:
if self.alarm_switch == 0:
self.alarm_switch = 1
self.switch_text = "ALARM ON"
else:
self.alarm_switch = 0 # Toggle switch mode to "Off"
self.switch_text = "ALARM OFF"
if self.is_alarming == 1:
self.cancel_func() # Call function to stop alarming
self.save_config()
def click_settings(self, *args):
if self.settings_view == 0:
self.settings_pic = "./Images/Buttons/Settings_Pushed.png"
self.settings_view = 1 # See digitalclock.kv for buttons using this variable
self.clock_view = 0 # See digitalclock.kv for buttons using this variable
self.am_pm_clock = 0
if self.hr_setting == 12:
self.am_pm_alarm = 1
else:
self.am_pm_alarm = 0
else:
self.settings_pic = "./Images/Buttons/Settings_Normal.png"
self.settings_view = 0
self.clock_view = 1
self.am_pm_alarm = 0
if self.hr_setting == 12:
self.am_pm_clock = 1
else:
self.am_pm_clock = 0
self.save_config()
def click_12hr(self, *args):
if self.settings_view == 1:
if self.hr_setting == 0:
self.hr_setting = 12
self.display_time = time.strftime("%I : %M")
self.am_pm_clock_text = time.strftime("%p")
self.hr_text = "12HR"
self.am_pm_alarm = 1
if self.alarm_time_hour > 12:
self.alarm_time_hour = self.alarm_time_hour - 12
self.am_pm_setting = 1
self.am_pm_text = "PM"
if self.alarm_time_hour == 0:
self.alarm_time_hour = self.alarm_time_hour + 12
self.am_pm_setting = 0
self.am_pm_text = "AM"
self.alarm_time = str(self.alarm_time_hour).zfill(2) + " : " + str(self.alarm_time_minute).zfill(
2) # zfill used for padding single digits numbers with a zero
self.save_config()
else:
self.hr_setting = 0
self.display_time = time.strftime("%H : %M")
self.hr_text = "24HR"
self.am_pm_alarm = 0
self.save_config()
def alarm_am_pm(self, *args):
if self.am_pm_setting == 0:
self.am_pm_setting = 1
self.am_pm_text = "PM"
else:
self.am_pm_setting = 0
self.am_pm_text = "AM"
def save_config(self):
config_file = configparser.ConfigParser()
config_file['Alarm Time'] = {'alarm_time_hour': str(self.alarm_time_hour),
'alarm_time_minute': str(self.alarm_time_minute),
}
config_file['Alarm Days'] = {'set_sunday': str(self.set_sunday),
'set_monday': str(self.set_monday),
'set_tuesday': str(self.set_tuesday),
'set_wednesday': str(self.set_wednesday),
'set_thursday': str(self.set_thursday),
'set_friday': str(self.set_friday),
'set_saturday': str(self.set_saturday),
}
config_file['Miscellaneous'] = {'alarm_switch': str(self.alarm_switch),
'switch_text': str(self.switch_text),
'hr_setting': str(self.hr_setting),
'hr_text': str(self.hr_text),
'am_pm_clock': str(self.am_pm_clock),
'am_pm_clock_text': str(self.am_pm_clock_text),
'am_pm_setting': str(self.am_pm_setting),
'am_pm_text': str(self.am_pm_text),
}
config_file['Character IDs'] = {'nfc_cap': str(self.nfc_cap),
'nfc_cap2': str(self.nfc_cap2),
'nfc_hulk': str(self.nfc_hulk),
'nfc_hulk2': str(self.nfc_hulk2)}
with open('config.ini', 'w') as configfile:
config_file.write(configfile)
def hour10_up(self):
if self.settings_view == 1:
# # Might not be the best way to do this, with the "now()".
# # Seems like overkill to get a filled out datetime object
# datetime.datetime.now().replace(hour=, minute=)
if self.hr_setting == 0:
if self.alarm_time_hour <= 14:
self.alarm_time_hour = self.alarm_time_hour + 10
self.alarm_time = str(self.alarm_time_hour).zfill(2) + " : " + str(self.alarm_time_minute).zfill(
2) # zfill used for padding single digits numbers with a zero
else:
if self.alarm_time_hour <= 2:
self.alarm_time_hour = self.alarm_time_hour + 10
self.alarm_time = str(self.alarm_time_hour).zfill(2) + " : " + str(self.alarm_time_minute).zfill(
2) # zfill used for padding single digits numbers with a zero
def hour1_up(self):
if self.settings_view == 1:
# Convert string time into datetime object
alarm_time = datetime.datetime.strptime(self.alarm_time, '%H : %M')
# Add one hour to the datetime object
hour = (alarm_time + datetime.timedelta(hours=1)).hour
# Return the datetime object as a "HH : MM" formatted string
self.alarm_time = alarm_time.replace(hour=hour).strftime('%H : %M')
def min10_up(self):
if self.settings_view == 1:
if self.alarm_time_minute <= (49):
self.alarm_time_minute = self.alarm_time_minute + 10
self.alarm_time = str(self.alarm_time_hour).zfill(2) + " : " + str(self.alarm_time_minute).zfill(2)
else:
self.alarm_time_minute = self.alarm_time_minute - 50
self.alarm_time = str(self.alarm_time_hour).zfill(2) + " : | |
as combined NO and NO2
try:
df['NOx'] = df['no_mr'].values + df['no2_mr'].values
except:
print('WARNING: failed to add NOx to flight {}'.format(flight_ID))
# Add a values for H2O
try:
ds = set_flagged_data2NaNs(ds, VarName='NV_LWC1_C',
FlagName='NV_LWC1_C_FLAG')
ds = set_flagged_data2NaNs(ds, VarName='NV_LWC2_C',
FlagName='NV_LWC2_C_FLAG')
ds['H2O'] = ds['NV_LWC1_C'].copy()
ds['H2O'] += ds['NV_LWC2_C']
ds['H2O_U'] = ds['NV_LWC1_C'].copy()
ds['H2O_U'] += ds['NV_LWC2_C']
# Air density ( ρ = P / RT )
# ds = set_flagged_data2NaNs(ds, VarName='TAT_DI_R',
# FlagName='TAT_DI_R_FLAG')
# ds = set_flagged_data2NaNs(ds, VarName='PS_RVSM',
# FlagName='PS_RVSM_FLAG')
# GasConst = 8.314 4621 # m3 Pa K−1 mol−1
# GasConst *= 0.01 # m3 hPa K−1 mol−1
# GasConst /= AC.constants('AVG') # m3 hPa K−1
GasConst = 0.167226 # J/ kg K
ds['AIR_DEN'] = ds["PS_RVSM"]*10 / (GasConst * ds['TAT_DI_R'])
# (kg/m3) => g/m3
ds['AIR_DEN'] = ds['AIR_DEN']*1E3
# convert g/M3 to ppbv
ds['H2O'] = ds['H2O'] / ds['AIR_DEN']
except:
print('WARNING: failed to add H2O to flight {}'.format(flight_ID))
# Include flight_ID
df['flight_ID'] = flight_ID
# Resample the data?
if resample_data:
df = df.resample('1T').mean()
# Add derived variables
df = add_derived_variables2FAAM_data(df)
return df
def explore_FAAM_aerosol_data():
"""
Explore the FAAM aerosol data (CDP, PCASP) from ARNA-2 campaign
"""
# -- PCASP
dsPCASP = get_FAAM_mineral_dust_calibration(instrument='PCASP',
rtn_values=False)
# -- CDP
dsCDP = get_FAAM_mineral_dust_calibration(instrument='CDP',
rtn_values=False)
# only consider "potential dust" above a certain size?
# Use 100 um for now
def get_FAAM_mineral_dust_calibration(instrument='PCASP', rtn_values=True):
"""
Retrieve FAAM mineral dust calibration
"""
# Location and name of calibration files?
folder = '{}/FAAM/'.format(get_local_folder('ARNA_data'))
if instrument == 'PCASP':
# NOTE: range ~0.1-4 microns
filename = 'PCASP1_faam_20200128_v001_r000_cal.nc'
# NOTE: dust values are a nc subgroup!
# group = 'bin_cal'
group = 'bin_cal/mineral_dust'
# group = 'flow_cal'
# The real part of the refractive index was taken as 1.53 which is a common value and is in the OPAC database. It is quite a bit smaller than the 1.547 that was reported by Weinzierl et al. [2011] but has been shown to have a relatively weak effect on the instrument response. The values of the imaginary part were based on references in Ryder et al. [2019] along with the frequency distribution of k(550nm) presented in fig 9 of Ryder et al. [2013]. So the minimum value was extended from 0.0015i to 0.001i. Calculating the bin boundaries with these multiple Mie curves was done with Gaussian centre-weighted averaging with 0.001i and 0.0024i being +/-2 sigma extreme values.
elif instrument == 'CDP':
# NOTE: range ~4-120 microns
filename = 'CDP1_faam_20200208_v001_r000_cal.nc'
# NOTE: dust values are a nc subgroup!
group = 'master_cal/mineral_dust'
# Open and return the widths and
ds = xr.open_dataset(folder+filename, group=group)
# Get values for bin centres and widths in microns (1E-6 metres)
BinWidths = ds['dia_width'].values.flatten()
BinCentres = ds['dia_centre'].values.flatten()
d = {'BinWidths': BinWidths, 'BinCentres': BinCentres}
if rtn_values:
return d
else:
return ds
def get_surface_area4flight(flight_ID='C225', instrument='PCASP',
plt_up_values=False, ds=None):
"""
Assuming spherical shape, calculate surface area
"""
# - Consider the surface area Exclude the first channel
# Retrieve calibration for mineral dust
d = get_FAAM_mineral_dust_calibration(instrument=instrument)
# Get the bin widths and centres (and convert to in metres)
BinWidths = d['BinWidths'] * 1E-6
BinCentres = d['BinCentres'] * 1E-6
# What is the (max) radius of something in a given bin
# R = BinCentres + BinWidths/2 # Assume all max radius of bin?
R = BinCentres # assume all have same radius as middle of bin
# Surface area (units microns^2 / binned particule)
S = 4*np.pi*R**2
# Get the FAAM dataset for specific flight if not provided
if isinstance(ds, type(None)):
folder = '{}/CEDA/{}/'.format(get_local_folder('ARNA_data'), version)
files2use = glob.glob(folder + '*_{}*'.format(flight_ID.lower()))
cloud_phy_fnames = [i for i in files2use if 'cloud-phy' in i]
# Just include the main file that ends "<flight_ID>.nc"
suffix = '{}.nc'.format(flight_ID.lower())
cloud_phy_fname = [i for i in cloud_phy_fnames if i.endswith(suffix)]
if len(cloud_phy_fname) >= 1:
ass_str = 'More than one main cloud phys file found for flight!'
assert len(cloud_phy_filename) == 1, ass_str
try:
ds = xr.open_dataset(cloud_phy_filename[0])
except KeyError:
pstr = 'WARNING: no {} data found for {}'
print(pstr.format(instrument, flight_ID))
# Now extract PCASP/CDP data
# Variable prefix?
if instrument == 'PCASP':
# ‘corrected’ for aspiration efficiency of particles entering the inlet based on some broad assumptions
VarStr = 'PCAS2_{:0>2}'
# not corrected for aspiration efficiency
# VarStr = 'PCAS_{}_u'
FlagName = 'PCAS2_FLAG'
TimeVar = 'PCAS2TSPM'
elif instrument == 'CDP':
VarStr = 'CDP_{:0>2}'
TimeVar = 'CDP_TSPM'
FlagName = 'CDP_FLAG'
# "It is traditional to skip bin 1 as the lower boundary is ‘undefined’, it is also where all the electronic noise ends up."
# Values to use?
range2use = np.arange(2, 31)
vars2use = [VarStr.format(i) for i in range2use]
# Remove flagged values for PCASP
for var in vars2use:
ds = set_flagged_data2NaNs(ds, VarName=var, FlagName=FlagName)
# Now apply to get surface area by bin
suffix = 'surface'
for n_channel, channel in enumerate(range2use):
Python_idx = channel-1
ChannelName = vars2use[n_channel]
VarName = '{}_{}'.format(vars2use[n_channel], suffix)
surface = S[Python_idx]
ds[VarName] = ds[ChannelName]*surface
attrs = {
'units': 'm3/cm-3',
'long_name': 'Surface area of {}'.format(ChannelName),
}
ds[VarName].attrs = attrs
# Plot this up to sanity check
if plt_up_values:
vars2plt = ['{}_{}'.format(i, suffix) for i in vars2use]
vals2plt = ds[vars2plt].copy().mean(dim=TimeVar).to_array().values
plt.bar(BinCentres[1:], vals2plt, width=BinWidths[1:])
ax = plt.gca()
plt.yscale('log')
units = 'm${^3}$/cm$^{-3}$'
plt.ylabel('Binned surface area ({})'.format(units))
plt.title('Surface Area during ARNA-2')
AC.save_plot('ARNA_aerosol_area_{}'.format(instrument))
plt.close()
# Then give a total and bin this value by <2.5um and >2.5um
VarName = '{}-total-surface'.format(instrument)
vars2use = ['{}_{}'.format(i, suffix) for i in vars2use]
ds[VarName] = ds[vars2use[0]].copy()
for var2use in vars2use[1:]:
ds[VarName].values = ds[VarName].values + ds[var2use].values
#
# vars2rtn = ['{}-total-surface'.format(instrument)]
return ds
def mk_file_of_flags(flights_nums=[]):
"""
Make csv files of flagging (e.g. SLR, dust) for ARNA flights
"""
# Which flights to plot?
# Just use non-transit ARNA flights
if len(flights_nums) == 0:
flights_nums = [
217, 218, 219, 220, 221, 222, 223, 224, 225,
]
flight_IDs = ['C{}'.format(i) for i in flight_nums]
# Loop by flight and retrieve flights
dfs_obs = {}
for flight_ID in flight_IDs:
df = get_FAAM_core4flightnum(flight_ID=flight_ID)
df['flight_ID'] = flight_ID
dfs_obs[flight_ID] = df
# Only include a few variables for spaces
vars2use = [
'IS_DUST', 'IS_SLR', 'PS_RVSM', 'PS_RVSM_FLAG',
'LAT_GIN', 'LAT_GIN_FLAG',
'LON_GIN', 'LON_GIN_FLAG',
'ALT_GIN', 'ALT_GIN_FLAG', 'flight_ID',
]
version = 'v1_0'
filename = 'ARNA_FAAM_flightpath_flagging_{}_{}.csv'
for flight_ID in flight_IDs:
df = dfs_obs[flight_ID]
df[vars2use].to_csv(filename.format(flight_ID, version))
# Save all the values together
df = pd.concat([dfs_obs[i] for i in dfs_obs.keys()], axis=1)
df[vars2use].to_csv(filename.format('ALL', version))
def get_FAAM_flights_df():
"""
Retrieve DataFrame of FAAM BAe146 flights
"""
# Flights to use...
DataRoot = get_local_folder('DataRoot')
folder = '/{}/FAAM/core_faam_NetCDFs/'.format(DataRoot)
filename = 'FAAM_BAe146_Biomass_burning_and_ACISIS_flights_tabulated.csv'
df = pd.read_csv(folder+filename)
# Only consider the dates after Jan 2018
DateVar = 'Date'
df[DateVar] = pd.to_datetime(df[DateVar])
return df
def get_flighttracks4campaign(campaign='ARNA-2', PressVar="PS_RVSM",
LonVar='LON_GIN', TimeVar='Time',
LatVar='LAT_GIN', resample_data=True):
"""
Flight tracks for campaign
"""
# Get dataframe of all flights and select those for a given campaign
DataRoot = get_local_folder('DataRoot')
folder = '/{}/FAAM/core_faam_NetCDFs/'.format(DataRoot)
df = get_FAAM_flights_df()
flight_IDs = df.loc[df['Campaign'] == campaign, :]['Flight ID']
# For flight in campaign flights
dfs = []
for flight_ID in flight_IDs:
try:
# Retrieve FAAM BAe146 Core NetCDF files
filename = 'core_faam_*_{}_1hz.nc'.format(flight_ID.lower())
file2use = glob.glob(folder+filename)
pstr = 'WARNING: more that one file found! (so using latest file)'
if len(file2use) > 1:
print(pstr)
print(file2use)
ds = xr.open_dataset(file2use[0])
# Only select the variable of intereest and drop where these are NaNs
df = ds[[PressVar, LatVar, LonVar, TimeVar]].to_dataframe()
df = df.dropna()
# Remove the index name and add index values to a column
df.index.name = None
dfs += [df.copy()]
del ds, df
except IndexError:
pstr = 'WARNING: failed to extract flight data for {} ({})'
print(pstr.format(flight_ID, campaign))
# Return
df = pd.concat(dfs, axis=0)
if resample_data:
df = df.resample('1T').mean()
return df
def mk_planeflight_files4sites(testing_mode=False):
"""
Make plane-flight input files for various ground sites
"""
# Location of flight data
locs = ['CVO{}'.format(i) for i in range(1, 8)]
#
sdate = datetime.datetime(2015, 1, 1,)
edate = datetime.datetime(2015, 1, 15,)
dates = pd.date_range(sdate, edate, freq='T')
#
LOCS_df = pd.read_csv(filename)
vars_ = ['LAT', 'LON', 'PRESS', 'TYPE']
LAT, LON, PRESS, TYPE = [LOCS_df[i].values for i in vars_]
# for each location make a DataFrame, then conbime
dfs = []
for n, type_ in enumerate(TYPE):
# dictionary of data
nvar = len(dates)
d | |
<filename>kernels.py
import numpy as np
import sys
def symmetrize(X): return X + X.T - np.diag(X.diagonal())
def raiseK(K, d):
if (d<1): raise Exception('non-positive power requested!')
if (d==1): return K
Kpower = K**2
for i in range(d-2): Kpower*=K #this is faster than direct power
return Kpower
def sq_dist(a, b=None):
#mean-center for numerical stability
D, n = a.shape[0], a.shape[1]
if (b is None):
mu = a.mean(axis=1)
a -= mu[:, np.newaxis]
b = a
m = n
aSq = np.sum(a**2, axis=0)
bSq = aSq
else:
d, m = b.shape[0], b.shape[1]
if (d != D): raise Exception('column lengths must agree')
mu = (float(m)/float(m+n))*b.mean(axis=1) + (float(n)/float(m+n))*a.mean(axis=1)
a -= mu[:, np.newaxis]
b -= mu[:, np.newaxis]
aSq = np.sum(a**2, axis=0)
bSq = np.sum(b**2, axis=0)
C = np.tile(np.column_stack(aSq).T, (1, m)) + np.tile(bSq, (n, 1)) - 2*a.T.dot(b)
C = np.maximum(C, 0) #remove numerical noise
return C
#evaluate 'power sums' of the individual terms in Z
def elsympol(Z,R):
sz = Z.shape
E = np.zeros((sz[0], sz[1], R+1)) #E(:,:,r+1) yields polynomial r
E[:,:,0] = np.ones(sz[:2])
if (R==0): return E #init recursion
P = np.zeros((sz[0], sz[1], R))
for r in range(1,R+1): P[:,:,r-1] = np.sum(Z**r, axis=2)
E[:,:,1] = P[:,:,0]
if (R==1): return E #init recursion
for r in range(2,R+1):
for i in range(1,r+1):
E[:,:,r] += P[:,:,i-1]*E[:,:,r-i] * (-1)**(i-1)/float(r)
return E
class Kernel:
def __init__(self):
self.epsilon = 1e-80
self.prevParams = None
self.cache = dict([])
def checkParams(self, params):
if (len(params.shape) != 1 or params.shape[0] != self.getNumParams()): raise Exception('Incorrect number of parameters')
def checkParamsI(self, params, i):
self.checkParams(params)
if (i<0 or i>=params.shape[0]): raise Exception('Invalid parameter number')
def sameParams(self, params, i=None):
if (self.prevParams is None): return False
if (i is None): return (np.max(np.abs(params-self.prevParams)) < self.epsilon)
return ((np.abs(params[i]-self.prevParams[i])) < self.epsilon)
def saveParams(self, params): self.prevParams = params.copy()
def getNumParams(self): raise Exception('getNumParams() called from base Kernel class')
def getTrainKernel(self, params): raise Exception('getTrainKernel() called from base Kernel class')
def getTrainTestKernel(self, params, Xtest): raise Exception('getTrainTestKernel() called from base Kernel class')
def getTestKernelDiag(self, params, Xtest): raise Exception('getTestKernelDiag() called from base Kernel class')
def deriveKernel(self, params, i): raise Exception('deriveKernel() called from base Kernel class')
class IdentityKernel(Kernel):
def __init__(self, n):
Kernel.__init__(self)
self.n = n
def getNumParams(self): return 0
def getTrainKernel(self, params):
self.checkParams(params)
return np.eye(self.n)
def deriveKernel(self, params, i): raise Exception('Identity Kernel cannot be derived')
def getTrainTestKernel(self, params, Xtest):
self.checkParams(params)
return np.zeros((self.n, Xtest.shape[0]))
def getTestKernelDiag(self, params, Xtest):
self.checkParams(params)
return np.ones(Xtest.shape[0])
class linearKernel(Kernel):
def __init__(self, X):
Kernel.__init__(self)
self.X_scaled = X / X.shape[1]
assert np.all(~np.isnan(X))
if (X.shape[1] >= X.shape[0]):
self.XXT = X.dot(X.T) / X.shape[1]
else:
self.XXT = None
self.X = X
def getNumParams(self): return 0
def getTrainKernel(self, params):
self.checkParams(params)
if (self.XXT is not None): return self.XXT
else: return self.X_scaled.dot(self.X.T)
def deriveKernel(self, params, i): raise Exception('Linear Kernel cannot be derived')
def getTrainTestKernel(self, params, Xtest):
self.checkParams(params)
return self.X_scaled.dot(Xtest.T)
def getTestKernelDiag(self, params, Xtest):
self.checkParams(params)
return np.sum(Xtest**2, axis=1) / Xtest.shape[1]
class ScaledKernel(Kernel):
def __init__(self, kernel):
Kernel.__init__(self)
self.kernel = kernel
def getNumParams(self): return 1+self.kernel.getNumParams()
def getTrainKernel(self, params):
self.checkParams(params)
if (self.sameParams(params)): return self.cache['getTrainKernel']
coeff = np.exp(2*params[-1])
K = coeff * self.kernel.getTrainKernel(params[:-1])
self.cache['getTrainKernel'] = K
self.saveParams(params)
return K
def deriveKernel(self, params, i):
self.checkParamsI(params, i)
coeff = np.exp(2*params[-1])
if (i==params.shape[0]-1): K = 2*self.getTrainKernel(params)
else: K = coeff * self.kernel.deriveKernel(params[:-1], i)
return K
def getTrainTestKernel(self, params, Xtest):
self.checkParams(params)
coeff = np.exp(2*params[-1])
return coeff * self.kernel.getTrainTestKernel(params[:-1], Xtest)
def getTestKernelDiag(self, params, Xtest):
self.checkParams(params)
coeff = np.exp(2*params[-1])
return coeff * self.kernel.getTestKernelDiag(params[:-1], Xtest)
class SumKernel(Kernel):
def __init__(self, kernels):
Kernel.__init__(self)
self.kernels = kernels
def getNumParams(self): return np.sum([k.getNumParams() for k in self.kernels])
def getTrainKernel(self, params, i=None):
self.checkParams(params)
K = 0
params_ind = 0
for k_i, k in enumerate(self.kernels):
numHyp = k.getNumParams()
currK = k.getTrainKernel(params[params_ind:params_ind+numHyp])
if (i is None): K += currK
elif (i==k_i): return currK
params_ind += numHyp
return K
def deriveKernel(self, params, i):
self.checkParamsI(params, i)
params_ind = 0
for k in self.kernels:
numHyp = k.getNumParams()
if (i not in range(params_ind, params_ind+numHyp)):
params_ind += numHyp
continue
return k.deriveKernel(params[params_ind:params_ind+numHyp], i-params_ind)
raise Exception('invalid parameter index')
def getTrainTestKernel(self, params, Xtest):
self.checkParams(params)
if (len(Xtest) != len(self.kernels)): raise Exception('Xtest should be a list with length equal to #kernels!')
K = 0
params_ind = 0
for k_i, k in enumerate(self.kernels):
numHyp = k.getNumParams()
K += k.getTrainTestKernel(params[params_ind:params_ind+numHyp], Xtest[k_i])
params_ind += numHyp
return K
def getTestKernelDiag(self, params, Xtest):
self.checkParams(params)
if (len(Xtest) != len(self.kernels)): raise Exception('Xtest should be a list with length equal to #kernels!')
diag = 0
params_ind = 0
for k_i, k in enumerate(self.kernels):
numHyp = k.getNumParams()
diag += k.getTestKernelDiag(params[params_ind:params_ind+numHyp], Xtest[k_i])
params_ind += numHyp
return diag
#the only parameter here is the bias term c...
class PolyKernel(Kernel):
def __init__(self, kernel):
Kernel.__init__(self)
self.kernel = kernel
def getNumParams(self): return 1+self.kernel.getNumParams()
def getTrainKernel(self, params):
self.checkParams(params)
c = np.exp(params[-1])
K = self.kernel.getTrainKernel(params[:-1]) + c
Kpower = K**2 #this is very fast, so we do it manually
for i in range(self.polyDegree-2): Kpower*=K #this is faster than direct power
return Kpower
def deriveKernel(self, params, i):
self.checkParamsI(params, i)
c = np.exp(params[-1])
#K = self.kernel.getTrainKernel(params[:-1])
#deriv1 = self.polyDegree * (c+K)**(self.polyDegree-1)
K = self.kernel.getTrainKernel(params[:-1]) + c
if (self.polyDegree==2): Kpower=K
else:
Kpower=K**2
for i in range(self.polyDegree-3): Kpower*=K #this is faster than direct power
deriv1 = self.polyDegree * Kpower
if (i==params.shape[0]-1): K_deriv = deriv1*c
else: K_deriv = deriv1 * self.kernel.deriveKernel(params[:-1], i)
return K_deriv
def getTrainTestKernel(self, params, Xtest):
self.checkParams(params)
c = np.exp(params[-1])
return (self.kernel.getTrainTestKernel(params[:-1], Xtest) + c)**self.polyDegree
def getTestKernelDiag(self, params, Xtest):
self.checkParams(params)
c = np.exp(params[-1])
return (self.kernel.getTestKernelDiag(params[:-1], Xtest) + c)**self.polyDegree
class Poly2Kernel(PolyKernel):
def __init__(self, kernel):
PolyKernel.__init__(self, kernel)
self.polyDegree = 2
class Poly3Kernel(PolyKernel):
def __init__(self, kernel):
PolyKernel.__init__(self, kernel)
self.polyDegree = 3
class PolyKernelHomo(Kernel):
def __init__(self, kernel):
Kernel.__init__(self)
self.kernel = kernel
def getNumParams(self): return self.kernel.getNumParams()
def getTrainKernel(self, params):
self.checkParams(params)
K = self.kernel.getTrainKernel(params)
return raiseK(K, self.polyDegree)
def deriveKernel(self, params, i):
self.checkParamsI(params, i)
K = self.kernel.getTrainKernel(params)
Kpower = raiseK(K, self.polyDegree-1)
deriv1 = self.polyDegree * Kpower
return deriv1 * self.kernel.deriveKernel(params, i)
def getTrainTestKernel(self, params, Xtest):
self.checkParams(params)
return raiseK(self.kernel.getTrainTestKernel(params, Xtest), self.polyDegree)
def getTestKernelDiag(self, params, Xtest):
self.checkParams(params)
return raiseK(self.kernel.getTestKernelDiag(params, Xtest), self.polyDegree)
class Poly2KernelHomo(PolyKernelHomo):
def __init__(self, kernel):
PolyKernelHomo.__init__(self, kernel)
self.polyDegree = 2
class Poly3KernelHomo(PolyKernelHomo):
def __init__(self, kernel):
PolyKernelHomo.__init__(self, kernel)
self.polyDegree = 3
class RBFKernel(Kernel):
def __init__(self, X):
Kernel.__init__(self)
self.X_scaled = X/np.sqrt(X.shape[1])
if (X.shape[1] >= X.shape[0] or True): self.K_sq = sq_dist(self.X_scaled.T)
else: self.K_sq = None
def getNumParams(self): return 1
def getTrainKernel(self, params):
self.checkParams(params)
if (self.sameParams(params)): return self.cache['getTrainKernel']
ell = np.exp(params[0])
if (self.K_sq is None): K = sq_dist(self.X_scaled.T / ell) #precompute squared distances
else: K = self.K_sq / ell**2
self.cache['K_sq_scaled'] = K
# # # #manual computation (just for sanity checks)
# # # K1 = np.exp(-K / 2.0)
# # # K2 = np.zeros((self.X_scaled.shape[0], self.X_scaled.shape[0]))
# # # for i1 in xrange(self.X_scaled.shape[0]):
# # # for i2 in xrange(i1, self.X_scaled.shape[0]):
# # # diff = self.X_scaled[i1,:] - self.X_scaled[i2,:]
# # # K2[i1, i2] = np.exp(-np.sum(diff**2) / (2*ell))
# # # K2[i2, i1] = K2[i1, i2]
# # # print np.max((K1-K2)**2)
# # # sys.exit(0)
K_exp = np.exp(-K / 2.0)
self.cache['getTrainKernel'] = K_exp
self.saveParams(params)
return K_exp
def deriveKernel(self, params, i):
self.checkParamsI(params, i)
return self.getTrainKernel(params) * self.cache['K_sq_scaled']
#ell = np.exp(params[0])
#if (self.K_sq is None): K = sq_dist(self.X_scaled.T / ell) #precompute squared distances
#else: K = self.K_sq / ell**2
#return np.exp(-K / 2.0)*K
def getTrainTestKernel(self, params, Xtest):
self.checkParams(params)
ell = np.exp(params[0])
K = sq_dist(self.X_scaled.T/ell, (Xtest/np.sqrt(Xtest.shape[1])).T/ell) #precompute squared distances
return np.exp(-K / 2.0)
def getTestKernelDiag(self, params, Xtest):
self.checkParams(params)
return np.ones(Xtest.shape[0])
class GaborKernel(Kernel):
def __init__(self, X):
Kernel.__init__(self)
self.X_scaled = X/np.sqrt(X.shape[1])
if (X.shape[1] >= X.shape[0] or True): self.K_sq = sq_dist(self.X_scaled.T)
else: self.K_sq = None
#compute dp
self.dp = np.zeros((X.shape[0], X.shape[0]))
for d in range(self.X_scaled.shape[1]):
self.dp += (np.outer(self.X_scaled[:,d], np.ones((1, self.X_scaled.shape[0]))) | |
network_tools.edge_aware_smoothness_order2(img=s_im1, pred=s_flow_f)
smooth_loss += self.smooth_order_2_weight * network_tools.edge_aware_smoothness_order2(img=s_im2, pred=s_flow_b)
elif self.smooth_type == 'delta':
smooth_loss += self.smooth_order_2_weight * network_tools.flow_smooth_delta(flow=s_flow_f, if_second_order=True)
smooth_loss += self.smooth_order_2_weight * network_tools.flow_smooth_delta(flow=s_flow_b, if_second_order=True)
else:
raise ValueError('wrong smooth_type: %s' % self.smooth_type)
output_dict['smooth_loss'] = smooth_loss
# ?? photo loss
if self.if_use_boundary_warp:
# im1_warp = tools.nianjin_warp.warp_im(im2, flow_fw, start) # warped im1 by forward flow and im2
# im2_warp = tools.nianjin_warp.warp_im(im1, flow_bw, start)
im1_s, im2_s, start_s = input_dict['im1_raw'], input_dict['im2_raw'], input_dict['start']
im1_warp = tools.nianjin_warp.warp_im(im2_s, flow_f_out, start_s) # warped im1 by forward flow and im2
im2_warp = tools.nianjin_warp.warp_im(im1_s, flow_b_out, start_s)
else:
im1_warp = tools.torch_warp(im2_ori, flow_f_out) # warped im1 by forward flow and im2
im2_warp = tools.torch_warp(im1_ori, flow_b_out)
# im_diff_fw = im1 - im1_warp
# im_diff_bw = im2 - im2_warp
# photo loss
if self.stop_occ_gradient:
occ_fw, occ_bw = occ_fw.clone().detach(), occ_bw.clone().detach()
photo_loss = network_tools.photo_loss_multi_type(im1_ori, im1_warp, occ_fw, photo_loss_type=self.photo_loss_type,
photo_loss_delta=self.photo_loss_delta, photo_loss_use_occ=self.photo_loss_use_occ)
photo_loss += network_tools.photo_loss_multi_type(im2_ori, im2_warp, occ_bw, photo_loss_type=self.photo_loss_type,
photo_loss_delta=self.photo_loss_delta, photo_loss_use_occ=self.photo_loss_use_occ)
output_dict['photo_loss'] = photo_loss
output_dict['im1_warp'] = im1_warp
output_dict['im2_warp'] = im2_warp
# ?? census loss
if self.photo_loss_census_weight > 0:
census_loss = loss_functions.census_loss_torch(img1=im1_ori, img1_warp=im1_warp, mask=occ_fw, q=self.photo_loss_delta,
charbonnier_or_abs_robust=False, if_use_occ=self.photo_loss_use_occ, averge=True) + \
loss_functions.census_loss_torch(img1=im2_ori, img1_warp=im2_warp, mask=occ_bw, q=self.photo_loss_delta,
charbonnier_or_abs_robust=False, if_use_occ=self.photo_loss_use_occ, averge=True)
census_loss *= self.photo_loss_census_weight
else:
census_loss = None
output_dict['census_loss'] = census_loss
# ???????msd loss
if self.multi_scale_distillation_weight > 0:
flow_fw_label = flow_f_out.clone().detach()
flow_bw_label = flow_b_out.clone().detach()
msd_loss_ls = []
for i, (scale_fw, scale_bw) in enumerate(flows):
if self.multi_scale_distillation_style == 'down':
flow_fw_label_sacle = upsample_flow(flow_fw_label, target_flow=scale_fw)
occ_scale_fw = F.interpolate(occ_fw, [scale_fw.size(2), scale_fw.size(3)], mode='nearest')
flow_bw_label_sacle = upsample_flow(flow_bw_label, target_flow=scale_bw)
occ_scale_bw = F.interpolate(occ_bw, [scale_bw.size(2), scale_bw.size(3)], mode='nearest')
elif self.multi_scale_distillation_style == 'upup':
flow_fw_label_sacle = flow_fw_label
scale_fw = upsample_flow(scale_fw, target_flow=flow_fw_label_sacle)
occ_scale_fw = occ_fw
flow_bw_label_sacle = flow_bw_label
scale_bw = upsample_flow(scale_bw, target_flow=flow_bw_label_sacle)
occ_scale_bw = occ_bw
elif self.multi_scale_distillation_style == 'updown':
scale_fw = upsample_flow(scale_fw, target_size=(scale_fw.size(2) * 4, scale_fw.size(3) * 4)) #
flow_fw_label_sacle = upsample_flow(flow_fw_label, target_flow=scale_fw) #
occ_scale_fw = F.interpolate(occ_fw, [scale_fw.size(2), scale_fw.size(3)], mode='nearest') # occ
scale_bw = upsample_flow(scale_bw, target_size=(scale_bw.size(2) * 4, scale_bw.size(3) * 4))
flow_bw_label_sacle = upsample_flow(flow_bw_label, target_flow=scale_bw)
occ_scale_bw = F.interpolate(occ_bw, [scale_bw.size(2), scale_bw.size(3)], mode='nearest')
else:
raise ValueError('wrong multi_scale_distillation_style: %s' % self.multi_scale_distillation_style)
msd_loss_scale_fw = network_tools.photo_loss_multi_type(x=scale_fw, y=flow_fw_label_sacle, occ_mask=occ_scale_fw, photo_loss_type='abs_robust',
photo_loss_use_occ=self.multi_scale_distillation_occ)
msd_loss_ls.append(msd_loss_scale_fw)
msd_loss_scale_bw = network_tools.photo_loss_multi_type(x=scale_bw, y=flow_bw_label_sacle, occ_mask=occ_scale_bw, photo_loss_type='abs_robust',
photo_loss_use_occ=self.multi_scale_distillation_occ)
msd_loss_ls.append(msd_loss_scale_bw)
msd_loss = sum(msd_loss_ls)
msd_loss = self.multi_scale_distillation_weight * msd_loss
else:
# ???????photo loss? multi_scale_photo_weight
if self.multi_scale_photo_weight > 0:
_, _, h_raw, w_raw = im1_s.size()
_, _, h_temp_crop, h_temp_crop = im1_ori.size()
msd_loss_ls = []
for i, (scale_fw, scale_bw) in enumerate(flows):
if self.multi_scale_distillation_style == 'down': # ??resize???photo loss
_, _, h_temp, w_temp = scale_fw.size()
rate = h_temp_crop / h_temp
occ_f_resize, occ_b_resize = self.occ_check_model(flow_f=scale_fw, flow_b=scale_bw)
im1_crop_resize = F.interpolate(im1_ori, [h_temp, w_temp], mode="bilinear", align_corners=True)
im2_crop_resize = F.interpolate(im2_ori, [h_temp, w_temp], mode="bilinear", align_corners=True)
im1_raw_resize = F.interpolate(im1_s, [int(h_raw / rate), int(w_raw / rate)], mode="bilinear", align_corners=True)
im2_raw_resize = F.interpolate(im2_s, [int(h_raw / rate), int(w_raw / rate)], mode="bilinear", align_corners=True)
im1_resize_warp = tools.nianjin_warp.warp_im(im2_raw_resize, scale_fw, start_s / rate) # use forward flow to warp im2
im2_resize_warp = tools.nianjin_warp.warp_im(im1_raw_resize, scale_bw, start_s / rate)
elif self.multi_scale_distillation_style == 'upup': # ???flow resize???????photo loss
occ_f_resize = occ_fw
occ_b_resize = occ_bw
scale_fw = upsample_flow(scale_fw, target_flow=im1_ori)
scale_bw = upsample_flow(scale_bw, target_flow=im2_ori)
im1_crop_resize = im1
im2_crop_resize = im2
im1_resize_warp = tools.nianjin_warp.warp_im(im2_s, scale_fw, start_s) # use forward flow to warp im2
im2_resize_warp = tools.nianjin_warp.warp_im(im1_s, scale_bw, start_s)
elif self.multi_scale_distillation_style == 'updown':
scale_fw = upsample_flow(scale_fw, target_size=(scale_fw.size(2) * 4, scale_fw.size(3) * 4)) #
scale_bw = upsample_flow(scale_bw, target_size=(scale_bw.size(2) * 4, scale_bw.size(3) * 4))
_, _, h_temp, w_temp = scale_fw.size()
rate = h_temp_crop / h_temp
occ_f_resize, occ_b_resize = self.occ_check_model(flow_f=scale_fw, flow_b=scale_bw)
im1_crop_resize = F.interpolate(im1_ori, [h_temp, w_temp], mode="bilinear", align_corners=True)
im2_crop_resize = F.interpolate(im2_ori, [h_temp, w_temp], mode="bilinear", align_corners=True)
im1_raw_resize = F.interpolate(im1_s, [int(h_raw / rate), int(w_raw / rate)], mode="bilinear", align_corners=True)
im2_raw_resize = F.interpolate(im2_s, [int(h_raw / rate), int(w_raw / rate)], mode="bilinear", align_corners=True)
im1_resize_warp = tools.nianjin_warp.warp_im(im2_raw_resize, scale_fw, start_s / rate) # use forward flow to warp im2
im2_resize_warp = tools.nianjin_warp.warp_im(im1_raw_resize, scale_bw, start_s / rate)
else:
raise ValueError('wrong multi_scale_distillation_style: %s' % self.multi_scale_distillation_style)
temp_mds_fw = network_tools.photo_loss_multi_type(im1_crop_resize, im1_resize_warp, occ_f_resize, photo_loss_type=self.photo_loss_type,
photo_loss_delta=self.photo_loss_delta, photo_loss_use_occ=self.photo_loss_use_occ)
msd_loss_ls.append(temp_mds_fw)
temp_mds_bw = network_tools.photo_loss_multi_type(im2_crop_resize, im2_resize_warp, occ_b_resize, photo_loss_type=self.photo_loss_type,
photo_loss_delta=self.photo_loss_delta, photo_loss_use_occ=self.photo_loss_use_occ)
msd_loss_ls.append(temp_mds_bw)
msd_loss = sum(msd_loss_ls)
msd_loss = self.multi_scale_photo_weight * msd_loss
else:
msd_loss = None
output_dict['msd_loss'] = msd_loss
return output_dict
@classmethod
def demo(cls):
net = PWCNet_unsup_irr_bi_v5_2(occ_type='for_back_check', occ_alpha_1=0.1, occ_alpha_2=0.5, occ_check_sum_abs_or_squar=True,
occ_check_obj_out_all='obj', stop_occ_gradient=False,
smooth_level='final', smooth_type='edge', smooth_order_1_weight=1, smooth_order_2_weight=0,
photo_loss_type='abs_robust', photo_loss_use_occ=False, photo_loss_census_weight=0,
if_norm_before_cost_volume=True, norm_moments_across_channels=False, norm_moments_across_images=False,
multi_scale_distillation_weight=1,
multi_scale_distillation_style='upup',
multi_scale_distillation_occ=True,
# appearance flow params
if_froze_pwc=False,
app_occ_stop_gradient=True,
app_loss_weight=1,
app_distilation_weight=1,
if_upsample_flow=False,
if_upsample_flow_mask=False,
if_upsample_flow_output=False,
).cuda()
net.eval()
im = np.random.random((1, 3, 320, 320))
start = np.zeros((1, 2, 1, 1))
start = torch.from_numpy(start).float().cuda()
im_torch = torch.from_numpy(im).float().cuda()
input_dict = {'im1': im_torch, 'im2': im_torch,
'im1_raw': im_torch, 'im2_raw': im_torch, 'start': start, 'if_loss': True}
output_dict = net(input_dict)
print('smooth_loss', output_dict['smooth_loss'], 'photo_loss', output_dict['photo_loss'], 'census_loss', output_dict['census_loss'], output_dict['app_loss'], output_dict['appd_loss'])
@classmethod
def demo_model_size(cls):
from thop import profile
net = PWCNet_unsup_irr_bi_v5_2(occ_type='for_back_check', occ_alpha_1=0.1, occ_alpha_2=0.5, occ_check_sum_abs_or_squar=True,
occ_check_obj_out_all='obj', stop_occ_gradient=False,
smooth_level='final', smooth_type='edge', smooth_order_1_weight=1, smooth_order_2_weight=0,
photo_loss_type='abs_robust', photo_loss_use_occ=False, photo_loss_census_weight=0,
if_norm_before_cost_volume=True, norm_moments_across_channels=False, norm_moments_across_images=False,
multi_scale_distillation_weight=1,
multi_scale_distillation_style='upup',
multi_scale_distillation_occ=True,
# appearance flow params
if_froze_pwc=False,
app_occ_stop_gradient=True,
app_loss_weight=0,
app_distilation_weight=0,
if_upsample_flow=False,
if_upsample_flow_mask=False,
if_upsample_flow_output=False,
if_upsample_small=False,
if_upsample_cost_volume=False,
if_upsample_mask_inpainting=False,
if_dense_decode=True,
if_decoder_small=True,
).cuda()
# without upsample: flops: 39.893 G, params: 3.354 M
'''
model size when using the upsample module
| meta flow | meta mask | meta out | small |cost volume| mask inp |
| True | False | False | False | False | False |flops: 50.525 G, params: 3.996 M
| True | False | False | False | True | False |flops: 51.321 G, params: 4.043 M
| True | False | True | False | True | False |flops: 60.498 G, params: 4.043 M
| True | False | True | False | False | False |flops: 59.103 G, params: 3.996 M
| True | False | True | True | True | False |flops: 47.208 G, params: 3.597 M
| True | False | True | True | False | False |flops: 46.506 G, params: 3.573 M
| True | False | False | True | False | False |flops: 43.339 G, params: 3.573 M
| True | True | True | True | True | False |flops: 47.273 G, params: 3.599 M
'''
# dense decode=True without upsample:flops: 144.675 G, params: 3.354 M
'''
model size when using the upsample module
| meta flow | meta mask | meta out | small |cost volume| mask inp |
| True | False | False | False | False | False |flops: 183.825 G, params: 3.996 M
'''
net.eval()
im = np.random.random((1, 3, 320, 320))
start = np.zeros((1, 2, 1, 1))
start = torch.from_numpy(start).float().cuda()
im_torch = torch.from_numpy(im).float().cuda()
input_dict = {'im1': im_torch, 'im2': im_torch,
'im1_raw': im_torch, 'im2_raw': im_torch, 'start': start, 'if_loss': False}
flops, params = profile(net, inputs=(input_dict,), verbose=False)
print('temp(%s): flops: %.3f G, params: %.3f M' % (' ', flops / 1000 / 1000 / 1000, params / 1000 / 1000))
# output_dict = net(input_dict)
# print('smooth_loss', output_dict['smooth_loss'], 'photo_loss', output_dict['photo_loss'], 'census_loss', output_dict['census_loss'], output_dict['app_loss'], output_dict['appd_loss'])
# add appearance flow v2
class PWCNet_unsup_irr_bi_v5_3(tools.abstract_model):
def __init__(self,
# smooth loss choose
occ_type='for_back_check', occ_alpha_1=0.1, occ_alpha_2=0.5, occ_check_sum_abs_or_squar=True, occ_check_obj_out_all='obj', stop_occ_gradient=False,
smooth_level='final', # final or 1/4
smooth_type='edge', # edge or delta
smooth_order_1_weight=1,
# smooth loss
smooth_order_2_weight=0,
# photo loss type add SSIM
photo_loss_type='abs_robust', # abs_robust, charbonnier,L1, SSIM
photo_loss_delta=0.4,
photo_loss_use_occ=False,
photo_loss_census_weight=0,
# use cost volume norm
if_norm_before_cost_volume=False,
norm_moments_across_channels=True,
norm_moments_across_images=True,
if_test=False,
multi_scale_distillation_weight=0,
multi_scale_distillation_style='upup',
multi_scale_photo_weight=0,
# 'down', 'upup', 'updown'
multi_scale_distillation_occ=True, # if consider occlusion mask in multiscale distilation
# appearance flow params
if_froze_pwc=False,
app_occ_stop_gradient=True,
app_loss_weight=0,
app_distilation_weight=0,
app_v2_if_app=False, # if use app flow in each scale
app_v2_if_app_level=(0, 0, 0, 0, 0, 0), # if use app flow in each level,(1/64,1/32,1/16,1/8,1/4,output)
app_v2_if_app_level_alpha=((0.1, 0.5), (0.1, 0.5), (0.1, 0.5), (0.1, 0.5), (0.1, 0.5), (0.1, 0.5)),
app_v2_app_loss_weight=0, # app loss weight
app_v2_app_loss_type='abs_robust', # abs_robust, charbonnier,L1, SSIM
app_v2_if_app_small_level=0,
app_v2_iter_num=1, # 默认只迭代一次,但可迭代多次
if_upsample_flow=False,
if_upsample_flow_mask=False,
if_upsample_flow_output=False,
if_upsample_small=False,
if_upsample_cost_volume=False,
if_upsample_mask_inpainting=False,
if_concat_multi_scale_feature=False,
input_or_sp_input=1,
if_dense_decode=False, # dense decoder
if_decoder_small=False, # small decoder for dense connection
if_use_boundary_warp=True,
featureExtractor_if_end_relu=True,
featureExtractor_if_end_norm=False,
):
super(PWCNet_unsup_irr_bi_v5_3, self).__init__()
self.input_or_sp_input = input_or_sp_input # ???sp crop?forward????????photo loss
self.if_save_running_process = False
self.save_running_process_dir = ''
self.if_test = if_test
self.if_use_boundary_warp = if_use_boundary_warp
self.multi_scale_distillation_weight = multi_scale_distillation_weight
self.multi_scale_photo_weight = multi_scale_photo_weight
self.multi_scale_distillation_style = multi_scale_distillation_style
self.multi_scale_distillation_occ = multi_scale_distillation_occ
# smooth
self.occ_check_model = tools.occ_check_model(occ_type=occ_type, occ_alpha_1=occ_alpha_1, occ_alpha_2=occ_alpha_2,
sum_abs_or_squar=occ_check_sum_abs_or_squar, obj_out_all=occ_check_obj_out_all)
self.smooth_level = smooth_level
self.smooth_type = smooth_type
self.smooth_order_1_weight = smooth_order_1_weight
self.smooth_order_2_weight = smooth_order_2_weight
# photo loss
self.photo_loss_type = photo_loss_type
self.photo_loss_census_weight = photo_loss_census_weight
self.photo_loss_use_occ = photo_loss_use_occ # if use occ mask in | |
= matches[1].pk
matching_forms[1]["value"] = 800.01
matching_data = create_formset_data(match_form_prefix, matching_forms)
matching_data["match-INITIAL_FORMS"] = 2
data.update(matching_data)
response = self.client.post(url, data)
self.assertEqual(response.status_code, 200)
self.assertContains(
response,
"Value must be between 0 and 800"
)
# VALID
def test_decreasing_a_match_value_so_matched_to_is_matched_only_to_other_tran_23(self):
self.client.force_login(self.user)
create_invoice_with_nom_entries(
{
"type": "si",
"customer": self.customer,
"period": self.period,
"ref": self.ref,
"date": self.model_date,
"due_date": self.model_due_date,
"total": 2400,
"paid": 0,
"due": 2400,
"goods": 2000,
"vat": 400
},
[
{
'description': self.description,
'goods': 100,
'nominal': self.nominal,
'vat_code': self.vat_code,
'vat': 20
}
] * 20,
self.vat_nominal,
self.sale_control
)
invoice = SaleHeader.objects.first()
receipt1, receipt2 = create_receipts(
self.customer, "receipt", 2, self.period, 1200)
receipt2.paid = -400
receipt2.due = -800
receipt2.save()
match(invoice, [(receipt1, -1200), (receipt2, -600)])
invoice.refresh_from_db()
receipt1.refresh_from_db()
receipt2.refresh_from_db()
self.assertEqual(
invoice.due,
600
)
self.assertEqual(
invoice.paid,
1800
)
self.assertEqual(
invoice.total,
2400
)
self.assertEqual(
receipt1.due,
0
)
self.assertEqual(
receipt1.paid,
-1200
)
self.assertEqual(
receipt1.total,
-1200
)
self.assertEqual(
receipt2.due,
-200
)
self.assertEqual(
receipt2.paid,
-1000
)
self.assertEqual(
receipt2.total,
-1200
)
matches = SaleMatching.objects.all().order_by("pk")
self.assertEqual(
len(matches),
2
)
self.assertEqual(
matches[0].matched_by,
invoice
)
self.assertEqual(
matches[0].matched_to,
receipt1
)
self.assertEqual(
matches[0].value,
-1200
)
self.assertEqual(
matches[0].period,
self.period
)
self.assertEqual(
matches[1].matched_by,
invoice
)
self.assertEqual(
matches[1].matched_to,
receipt2
)
self.assertEqual(
matches[1].value,
-600
)
self.assertEqual(
matches[1].period,
self.period
)
url = reverse("sales:edit", kwargs={"pk": invoice.pk})
data = {}
header_data = create_header(
HEADER_FORM_PREFIX,
{
"type": invoice.type,
"customer": invoice.customer.pk,
"period": invoice.period.pk,
"ref": invoice.ref,
"date": invoice.date.strftime(DATE_INPUT_FORMAT),
"total": invoice.total
}
)
data.update(header_data)
lines = SaleLine.objects.all().order_by("pk")
lines_as_dicts = [to_dict(line) for line in lines]
line_trans = [get_fields(line, ['id', 'description', 'goods',
'nominal', 'vat_code', 'vat']) for line in lines_as_dicts]
line_forms = line_trans
line_data = create_formset_data(LINE_FORM_PREFIX, line_forms)
line_data["line-INITIAL_FORMS"] = 20
data.update(line_data)
matching_trans = [receipt1, receipt2]
matching_trans_as_dicts = [to_dict(m) for m in matching_trans]
matching_trans = [get_fields(
m, ['type', 'ref', 'total', 'paid', 'due', 'id']) for m in matching_trans_as_dicts]
matching_forms = []
matching_forms += add_and_replace_objects(
matching_trans, {"id": "matched_to"}, {"value": 1200})
matches = SaleMatching.objects.all().order_by("pk")
matching_forms[0]["id"] = matches[0].pk
matching_forms[1]["id"] = matches[1].pk
matching_forms[1]["value"] = 0
matching_data = create_formset_data(match_form_prefix, matching_forms)
matching_data["match-INITIAL_FORMS"] = 2
data.update(matching_data)
response = self.client.post(url, data)
self.assertEqual(response.status_code, 302)
invoice.refresh_from_db()
receipt1.refresh_from_db()
receipt2.refresh_from_db()
self.assertEqual(
invoice.due,
1200
)
self.assertEqual(
invoice.paid,
1200
)
self.assertEqual(
invoice.total,
2400
)
self.assertEqual(
receipt1.due,
0
)
self.assertEqual(
receipt1.paid,
-1200
)
self.assertEqual(
receipt1.total,
-1200
)
self.assertEqual(
receipt2.due,
-800
)
self.assertEqual(
receipt2.paid,
-400
)
self.assertEqual(
receipt2.total,
-1200
)
matches = SaleMatching.objects.all().order_by("pk")
self.assertEqual(
len(matches),
1
)
self.assertEqual(
matches[0].matched_by,
invoice
)
self.assertEqual(
matches[0].matched_to,
receipt1
)
self.assertEqual(
matches[0].value,
-1200
)
self.assertEqual(
matches[0].period,
self.period
)
# INVALID
# I.E. doing this would lower match value of match between matched_to and the other tran
def test_decreasing_a_match_value_so_matched_to_is_now_underallocated_24(self):
self.client.force_login(self.user)
create_invoice_with_nom_entries(
{
"type": "si",
"customer": self.customer,
"period": self.period,
"ref": self.ref,
"date": self.model_date,
"due_date": self.model_due_date,
"total": 2400,
"paid": 0,
"due": 2400,
"goods": 2000,
"vat": 400
},
[
{
'description': self.description,
'goods': 100,
'nominal': self.nominal,
'vat_code': self.vat_code,
'vat': 20
}
] * 20,
self.vat_nominal,
self.sale_control
)
invoice = SaleHeader.objects.first()
receipt1, receipt2 = create_receipts(
self.customer, "receipt", 2, self.period, 1200)
receipt2.paid = -400
receipt2.due = -800
receipt2.save()
match(invoice, [(receipt1, -1200), (receipt2, -600)])
invoice.refresh_from_db()
receipt1.refresh_from_db()
receipt2.refresh_from_db()
self.assertEqual(
invoice.due,
600
)
self.assertEqual(
invoice.paid,
1800
)
self.assertEqual(
invoice.total,
2400
)
self.assertEqual(
receipt1.due,
0
)
self.assertEqual(
receipt1.paid,
-1200
)
self.assertEqual(
receipt1.total,
-1200
)
self.assertEqual(
receipt2.due,
-200
)
self.assertEqual(
receipt2.paid,
-1000
)
self.assertEqual(
receipt2.total,
-1200
)
matches = SaleMatching.objects.all().order_by("pk")
self.assertEqual(
len(matches),
2
)
self.assertEqual(
matches[0].matched_by,
invoice
)
self.assertEqual(
matches[0].matched_to,
receipt1
)
self.assertEqual(
matches[0].value,
-1200
)
self.assertEqual(
matches[0].period,
self.period
)
self.assertEqual(
matches[1].matched_by,
invoice
)
self.assertEqual(
matches[1].matched_to,
receipt2
)
self.assertEqual(
matches[1].value,
-600
)
self.assertEqual(
matches[1].period,
self.period
)
url = reverse("sales:edit", kwargs={"pk": invoice.pk})
data = {}
header_data = create_header(
HEADER_FORM_PREFIX,
{
"type": invoice.type,
"customer": invoice.customer.pk,
"period": invoice.period.pk,
"ref": invoice.ref,
"date": invoice.date.strftime(DATE_INPUT_FORMAT),
"total": invoice.total
}
)
data.update(header_data)
lines = SaleLine.objects.all().order_by("pk")
lines_as_dicts = [to_dict(line) for line in lines]
line_trans = [get_fields(line, ['id', 'description', 'goods',
'nominal', 'vat_code', 'vat']) for line in lines_as_dicts]
line_forms = line_trans
line_data = create_formset_data(LINE_FORM_PREFIX, line_forms)
line_data["line-INITIAL_FORMS"] = 20
data.update(line_data)
matching_trans = [receipt1, receipt2]
matching_trans_as_dicts = [to_dict(m) for m in matching_trans]
matching_trans = [get_fields(
m, ['type', 'ref', 'total', 'paid', 'due', 'id']) for m in matching_trans_as_dicts]
matching_forms = []
matching_forms += add_and_replace_objects(
matching_trans, {"id": "matched_to"}, {"value": 1200})
matches = SaleMatching.objects.all().order_by("pk")
matching_forms[0]["id"] = matches[0].pk
matching_forms[1]["id"] = matches[1].pk
matching_forms[1]["value"] = -10
matching_data = create_formset_data(match_form_prefix, matching_forms)
matching_data["match-INITIAL_FORMS"] = 2
data.update(matching_data)
response = self.client.post(url, data)
self.assertEqual(response.status_code, 200)
self.assertContains(
response,
"Value must be between 0 and 800"
)
"""
Now change the outstanding of the transaction being edited by ADDING a new match
"""
# VALID
def test_adding_match_to_increase_outstanding_25(self):
self.client.force_login(self.user)
create_invoice_with_nom_entries(
{
"type": "si",
"customer": self.customer,
"period": self.period,
"ref": self.ref,
"date": self.model_date,
"due_date": self.model_due_date,
"total": 2400,
"paid": 0,
"due": 2400,
"goods": 2000,
"vat": 400
},
[
{
'description': self.description,
'goods': 100,
'nominal': self.nominal,
'vat_code': self.vat_code,
'vat': 20
}
] * 20,
self.vat_nominal,
self.sale_control
)
invoice = SaleHeader.objects.first()
receipt1, receipt2 = create_receipts(
self.customer, "receipt", 2, self.period, 1200)
receipt2.save()
match(invoice, [(receipt1, -1200), (receipt2, -600)])
receipt3 = create_receipts(
self.customer, "receipt", 1, self.period, -1200)[0]
invoice.refresh_from_db()
receipt1.refresh_from_db()
receipt2.refresh_from_db()
self.assertEqual(
invoice.due,
600
)
self.assertEqual(
invoice.paid,
1800
)
self.assertEqual(
invoice.total,
2400
)
self.assertEqual(
receipt1.due,
0
)
self.assertEqual(
receipt1.paid,
-1200
)
self.assertEqual(
receipt1.total,
-1200
)
self.assertEqual(
receipt2.due,
-600
)
self.assertEqual(
receipt2.paid,
-600
)
self.assertEqual(
receipt2.total,
-1200
)
self.assertEqual(
receipt3.due,
1200
)
self.assertEqual(
receipt3.paid,
0
)
self.assertEqual(
receipt3.total,
1200
)
matches = SaleMatching.objects.all().order_by("pk")
self.assertEqual(
len(matches),
2
)
self.assertEqual(
matches[0].matched_by,
invoice
)
self.assertEqual(
matches[0].matched_to,
receipt1
)
self.assertEqual(
matches[0].value,
-1200
)
self.assertEqual(
matches[0].period,
self.period
)
self.assertEqual(
matches[1].matched_by,
invoice
)
self.assertEqual(
matches[1].matched_to,
receipt2
)
self.assertEqual(
matches[1].value,
-600
)
self.assertEqual(
matches[1].period,
self.period
)
url = reverse("sales:edit", kwargs={"pk": invoice.pk})
data = {}
header_data = create_header(
HEADER_FORM_PREFIX,
{
"type": invoice.type,
"customer": invoice.customer.pk,
"period": invoice.period.pk,
"ref": invoice.ref,
"date": invoice.date.strftime(DATE_INPUT_FORMAT),
"total": invoice.total
}
)
data.update(header_data)
lines = SaleLine.objects.all().order_by("pk")
lines_as_dicts = [to_dict(line) for line in lines]
line_trans = [get_fields(line, ['id', 'description', 'goods',
'nominal', 'vat_code', 'vat']) for line in lines_as_dicts]
line_forms = line_trans
line_data = create_formset_data(LINE_FORM_PREFIX, line_forms)
line_data["line-INITIAL_FORMS"] = 20
data.update(line_data)
matching_trans = [receipt1, receipt2, receipt3]
matching_trans_as_dicts = [to_dict(m) for m in matching_trans]
matching_trans = [get_fields(
m, ['type', 'ref', 'total', 'paid', 'due', 'id']) for m in matching_trans_as_dicts]
matching_forms = []
matching_forms += add_and_replace_objects(
matching_trans, {"id": "matched_to"}, {"value": 1200})
matches = SaleMatching.objects.all().order_by("pk")
matching_forms[0]["id"] = matches[0].pk
matching_forms[1]["id"] = matches[1].pk
matching_forms[1]["value"] = 600
matching_forms[2]["value"] = -600
matching_data = create_formset_data(match_form_prefix, matching_forms)
matching_data["match-INITIAL_FORMS"] = 2
data.update(matching_data)
response = self.client.post(url, data)
self.assertEqual(response.status_code, 302)
invoice.refresh_from_db()
receipt1.refresh_from_db()
receipt2.refresh_from_db()
receipt3.refresh_from_db()
self.assertEqual(
invoice.due,
1200
)
self.assertEqual(
invoice.paid,
1200
)
self.assertEqual(
invoice.total,
2400
)
self.assertEqual(
receipt1.due,
0
)
self.assertEqual(
receipt1.paid,
-1200
)
self.assertEqual(
receipt1.total,
-1200
)
self.assertEqual(
receipt2.due,
-600
)
self.assertEqual(
receipt2.paid,
-600
)
self.assertEqual(
receipt2.total,
-1200
)
self.assertEqual(
receipt3.due,
600
)
self.assertEqual(
receipt3.paid,
600
)
self.assertEqual(
receipt3.total,
1200
)
matches = SaleMatching.objects.all().order_by("pk")
self.assertEqual(
len(matches),
3
)
self.assertEqual(
matches[0].matched_by,
invoice
)
self.assertEqual(
matches[0].matched_to,
receipt1
)
self.assertEqual(
matches[0].value,
-1200
)
self.assertEqual(
matches[0].period,
self.period
)
self.assertEqual(
matches[1].matched_by,
invoice
)
self.assertEqual(
matches[1].matched_to,
receipt2
)
self.assertEqual(
matches[1].value,
-600
)
self.assertEqual(
matches[1].period,
self.period
)
self.assertEqual(
matches[2].matched_by,
invoice
)
self.assertEqual(
matches[2].matched_to,
receipt3
)
self.assertEqual(
matches[2].value,
600
)
self.assertEqual(
matches[2].period,
self.period
)
# VALID
def test_adding_match_to_make_tran_fully_outstanding_26(self):
self.client.force_login(self.user)
create_invoice_with_nom_entries(
{
"type": "si",
"customer": self.customer,
"period": self.period,
"ref": self.ref,
"date": self.model_date,
"due_date": self.model_due_date,
"total": 2400,
"paid": 0,
"due": 2400,
"goods": 2000,
"vat": 400
},
[
{
'description': self.description,
'goods': 100,
'nominal': self.nominal,
'vat_code': self.vat_code,
'vat': 20
}
] * 20,
self.vat_nominal,
self.sale_control
)
invoice = SaleHeader.objects.first()
receipt1, receipt2 = create_receipts(
self.customer, "receipt", 2, self.period, 1200)
receipt2.save()
match(invoice, [(receipt1, -1200), (receipt2, -600)])
receipt3 = create_receipts(
self.customer, "receipt", 1, self.period, -1800)[0]
invoice.refresh_from_db()
receipt1.refresh_from_db()
receipt2.refresh_from_db()
self.assertEqual(
invoice.due,
600
)
self.assertEqual(
invoice.paid,
1800
)
self.assertEqual(
invoice.total,
2400
)
self.assertEqual(
receipt1.due,
0
)
self.assertEqual(
receipt1.paid,
-1200
)
self.assertEqual(
receipt1.total,
-1200
)
self.assertEqual(
receipt2.due,
-600
)
self.assertEqual(
receipt2.paid,
-600
)
self.assertEqual(
receipt2.total,
-1200
)
self.assertEqual(
receipt3.due,
1800
)
self.assertEqual(
receipt3.paid,
0
)
self.assertEqual(
receipt3.total,
1800
)
matches = SaleMatching.objects.all().order_by("pk")
self.assertEqual(
len(matches),
2
)
self.assertEqual(
matches[0].matched_by,
invoice
)
self.assertEqual(
matches[0].matched_to,
receipt1
)
self.assertEqual(
matches[0].value,
-1200
)
self.assertEqual(
matches[0].period,
self.period
)
self.assertEqual(
matches[1].matched_by,
invoice
)
self.assertEqual(
matches[1].matched_to,
receipt2
)
self.assertEqual(
matches[1].value,
-600
)
self.assertEqual(
matches[1].period,
self.period
)
url = reverse("sales:edit", kwargs={"pk": invoice.pk})
data = {}
header_data = create_header(
HEADER_FORM_PREFIX,
{
"type": invoice.type,
"customer": invoice.customer.pk,
"period": invoice.period.pk,
"ref": invoice.ref,
"date": invoice.date.strftime(DATE_INPUT_FORMAT),
"total": invoice.total
}
)
data.update(header_data)
lines = SaleLine.objects.all().order_by("pk")
lines_as_dicts | |
<reponame>chiawei-liu/DeepAlignmentNetwork
from __future__ import division
import numpy as np
from functools import partial
import warnings
from menpo.feature import no_op
from menpo.base import name_of_callable
from menpofit.visualize import print_progress
from menpofit.base import batch
from menpofit.builder import (scale_images, rescale_images_to_reference_shape,
compute_reference_shape, MenpoFitBuilderWarning,
compute_features)
from menpofit.fitter import (MultiScaleNonParametricFitter,
noisy_shape_from_bounding_box,
align_shape_with_bounding_box,
generate_perturbations_from_gt)
import menpofit.checks as checks
from .algorithm import NonParametricNewton
class SupervisedDescentFitter(MultiScaleNonParametricFitter):
r"""
Class for training a multi-scale Supervised Descent model.
Parameters
----------
images : `list` of `menpo.image.Image`
The `list` of training images.
group : `str` or ``None``, optional
The landmark group that corresponds to the ground truth shape of each
image. If ``None`` and the images only have a single landmark group,
then that is the one that will be used. Note that all the training
images need to have the specified landmark group.
bounding_box_group_glob : `glob` or ``None``, optional
Glob that defines the bounding boxes to be used for training. If
``None``, then the bounding boxes of the ground truth shapes are used.
sd_algorithm_cls : `class`, optional
The Supervised Descent algorithm to be used. The possible algorithms
are are separated in the following four categories:
**Non-parametric:**
===================================== ==============================
Class Regression
===================================== ==============================
:map:`NonParametricNewton` :map:`IRLRegression`
:map:`NonParametricGaussNewton` :map:`IIRLRegression`
:map:`NonParametricPCRRegression` :map:`PCRRegression`
:map:`NonParametricOptimalRegression` :map:`OptimalLinearRegression`
:map:`NonParametricOPPRegression` :map:`OPPRegression`
===================================== ==============================
**Parametric shape:**
======================================= ===================================
Class Regression
======================================= ===================================
:map:`ParametricShapeNewton` :map:`IRLRegression`
:map:`ParametricShapeGaussNewton` :map:`IIRLRegression`
:map:`ParametricShapePCRRegression` :map:`PCRRegression`
:map:`ParametricShapeOptimalRegression` :map:`OptimalLinearRegression`
:map:`ParametricShapeOPPRegression` :map:`ParametricShapeOPPRegression`
======================================= ===================================
**Parametric appearance:**
================================================== =====================
Class Regression
================================================== =====================
:map:`ParametricAppearanceProjectOutNewton` :map:`IRLRegression`
:map:`ParametricAppearanceProjectOutGuassNewton` :map:`IIRLRegression`
:map:`ParametricAppearanceMeanTemplateNewton` :map:`IRLRegression`
:map:`ParametricAppearanceMeanTemplateGuassNewton` :map:`IIRLRegression`
:map:`ParametricAppearanceWeightsNewton` :map:`IRLRegression`
:map:`ParametricAppearanceWeightsGuassNewton` :map:`IIRLRegression`
================================================== =====================
**Parametric shape and appearance:**
=========================================== =====================
Class Regression
=========================================== =====================
:map:`FullyParametricProjectOutNewton` :map:`IRLRegression`
:map:`FullyParametricProjectOutGaussNewton` :map:`IIRLRegression`
:map:`FullyParametricMeanTemplateNewton` :map:`IRLRegression`
:map:`FullyParametricWeightsNewton` :map:`IRLRegression`
:map:`FullyParametricProjectOutOPP` :map:`OPPRegression`
=========================================== =====================
reference_shape : `menpo.shape.PointCloud` or ``None``, optional
The reference shape that will be used for normalising the size of the
training images. The normalization is performed by rescaling all the
training images so that the scale of their ground truth shapes
matches the scale of the reference shape. Note that the reference
shape is rescaled with respect to the `diagonal` before performing
the normalisation. If ``None``, then the mean shape will be used.
diagonal : `int` or ``None``, optional
This parameter is used to rescale the reference shape so that the
diagonal of its bounding box matches the provided value. In other
words, this parameter controls the size of the model at the highest
scale. If ``None``, then the reference shape does not get rescaled.
holistic_features : `closure` or `list` of `closure`, optional
The features that will be extracted from the training images. Note
that the features are extracted before warping the images to the
reference shape. If `list`, then it must define a feature function per
scale. Please refer to `menpo.feature` for a list of potential features.
patch_features : `closure` or `list` of `closure`, optional
The features that will be extracted from the patches of the training
images. Note that, as opposed to `holistic_features`, these features
are extracted after extracting the patches. If `list`, then it must
define a feature function per scale. Please refer to `menpo.feature`
and `menpofit.feature` for a list of potential features.
patch_shape : (`int`, `int`) or `list` of (`int`, `int`), optional
The shape of the patches to be extracted. If a `list` is provided,
then it defines a patch shape per scale.
scales : `float` or `tuple` of `float`, optional
The scale value of each scale. They must provided in ascending order,
i.e. from lowest to highest scale. If `float`, then a single scale is
assumed.
n_iterations : `int` or `list` of `int`, optional
The number of iterations (cascades) of each level. If `list`, it must
specify a value per scale. If `int`, then it defines the total number of
iterations (cascades) over all scales.
n_perturbations : `int`, optional
The number of perturbations to be generated from each of the bounding
boxes using `perturb_from_gt_bounding_box`.
perturb_from_gt_bounding_box : `callable`, optional
The function that will be used to generate the perturbations from each
of the bounding boxes.
batch_size : `int` or ``None``, optional
If an `int` is provided, then the training is performed in an
incremental fashion on image batches of size equal to the provided
value. If ``None``, then the training is performed directly on the
all the images.
verbose : `bool`, optional
If ``True``, then the progress of the training will be printed.
References
----------
.. [1] <NAME>, and <NAME>. "Supervised Descent Method and its
applications to face alignment", Proceedings of the IEEE Conference on
Computer Vision and Pattern Recognition (CVPR), 2013.
.. [2] <NAME>, <NAME>, <NAME>, and <NAME>.
"Localizing parts of faces using a consensus of exemplars", Proceedings
of the IEEE Conference on Computer Vision and Pattern Recognition
(CVPR), 2011.
"""
def __init__(self, images, group=None, bounding_box_group_glob=None,
sd_algorithm_cls=None, reference_shape=None, diagonal=None,
holistic_features=no_op, patch_features=no_op,
patch_shape=(17, 17), scales=(0.5, 1.0), n_iterations=3,
n_perturbations=30,
perturb_from_gt_bounding_box=noisy_shape_from_bounding_box,
batch_size=None, verbose=False):
if batch_size is not None:
raise NotImplementedError('Training an SDM with a batch size '
'(incrementally) is not implemented yet.')
# Check parameters
checks.check_diagonal(diagonal)
scales = checks.check_scales(scales)
n_scales = len(scales)
patch_features = checks.check_callable(patch_features, n_scales)
sd_algorithm_cls = checks.check_callable(sd_algorithm_cls, n_scales)
holistic_features = checks.check_callable(holistic_features, n_scales)
patch_shape = checks.check_patch_shape(patch_shape, n_scales)
# Call superclass
super(SupervisedDescentFitter, self).__init__(
scales=scales, reference_shape=reference_shape,
holistic_features=holistic_features, algorithms=[])
# Set parameters
self._sd_algorithm_cls = sd_algorithm_cls
self.patch_features = patch_features
self.patch_shape = patch_shape
self.diagonal = diagonal
self.n_perturbations = n_perturbations
self.n_iterations = checks.check_max_iters(n_iterations, n_scales)
self._perturb_from_gt_bounding_box = perturb_from_gt_bounding_box
# Set up algorithms
self._setup_algorithms()
# Now, train the model!
self._train(images, increment=False, group=group,
bounding_box_group_glob=bounding_box_group_glob,
verbose=verbose, batch_size=batch_size)
def _setup_algorithms(self):
self.algorithms = [self._sd_algorithm_cls[j](
patch_features=self.patch_features[j],
patch_shape=self.patch_shape[j], n_iterations=self.n_iterations[j])
for j in range(self.n_scales)]
def _train(self, images, increment=False, group=None,
bounding_box_group_glob=None, verbose=False, batch_size=None):
# If batch_size is not None, then we may have a generator, else we
# assume we have a list.
if batch_size is not None:
# Create a generator of fixed sized batches. Will still work even
# on an infinite list.
image_batches = batch(images, batch_size)
else:
image_batches = [list(images)]
for k, image_batch in enumerate(image_batches):
if k == 0:
if self.reference_shape is None:
# If no reference shape was given, use the mean of the first
# batch
if batch_size is not None:
warnings.warn('No reference shape was provided. The '
'mean of the first batch will be the '
'reference shape. If the batch mean is '
'not representative of the true mean, '
'this may cause issues.',
MenpoFitBuilderWarning)
self._reference_shape = compute_reference_shape(
[i.landmarks[group].lms for i in image_batch],
self.diagonal, verbose=verbose)
# We set landmarks on the images to archive the perturbations, so
# when the default 'None' is used, we need to grab the actual
# label to sort out the ambiguity
if group is None:
group = image_batch[0].landmarks.group_labels[0]
# After the first batch, we are incrementing the model
if k > 0:
increment = True
if verbose:
print('Computing batch {}'.format(k))
# Train each batch
self._train_batch(
image_batch, increment=increment, group=group,
bounding_box_group_glob=bounding_box_group_glob,
verbose=verbose)
def _train_batch(self, image_batch, increment=False, group=None,
bounding_box_group_glob=None, verbose=False):
# Rescale images wrt the scale factor between the existing
# reference_shape and their ground truth (group) shapes
image_batch = rescale_images_to_reference_shape(
image_batch, group, self.reference_shape,
verbose=verbose)
# Create a callable that generates perturbations of the bounding boxes
# of the provided images.
generated_bb_func = generate_perturbations_from_gt(
image_batch, self.n_perturbations,
self._perturb_from_gt_bounding_box, gt_group=group,
bb_group_glob=bounding_box_group_glob, verbose=verbose)
# For each scale (low --> high)
for j in range(self.n_scales):
# Print progress if asked
if verbose:
if len(self.scales) > 1:
scale_prefix = ' - Scale {}: '.format(j)
else:
scale_prefix = ' - '
else:
scale_prefix = None
# Extract features. Features are extracted only if we are at the
# first scale or if the features of the current scale are different
# than the ones extracted at the previous scale.
if j == 0 and self.holistic_features[j] == no_op:
# Saves a lot of memory
feature_images = image_batch
elif (j == 0 or
self.holistic_features[j] != self.holistic_features[j - 1]):
# Compute features only if this is the first pass through
# the loop or the features at this scale are different from
# the features at the previous scale
feature_images = compute_features(image_batch,
self.holistic_features[j],
prefix=scale_prefix,
verbose=verbose)
# Rescale images according to scales. Note | |
= self.tfms(img)
chunk = torch.stack(chunk, 0).permute(1, 0, 2, 3)
return chunk, label
def __len__(self): return len(self.data)
def rescale_landmarks(landmarks,row_scale,col_scale):
landmarks2 = copy.deepcopy(torch.Tensor(landmarks).reshape((-1,2)))
for lm in landmarks2:
c,r = lm
lm[0] = c*col_scale
lm[1] = r*row_scale
# lm[0] = c*row_scale
# lm[1] = r*col_scale
landmarks2 = landmarks2.reshape((1,-1))
return landmarks2
def listdir_fullpath(d):
return [os.path.join(d, f) for f in os.listdir(d)]
def get_minorities(df,thresh=0.8):
c = df.iloc[:,1].value_counts()
lc = list(c)
max_count = lc[0]
diffs = [1-(x/max_count) for x in lc]
diffs = dict((k,v) for k,v in zip(c.keys(),diffs))
minorities = [c.keys()[x] for x,y in enumerate(lc) if y < (thresh*max_count)]
return minorities,diffs
def csv_from_path(path):
path = Path(path)
labels_paths = list(path.iterdir())
tr_images = []
tr_labels = []
for l in labels_paths:
if l.is_dir():
for i in list(l.iterdir()):
if i.suffix in IMG_EXTENSIONS:
name = i.name
label = l.name
new_name = f'{path.name}/{label}/{name}'
tr_images.append(new_name)
tr_labels.append(label)
if len(tr_labels) == 0:
return None
tr_img_label = {'Img':tr_images, 'Label': tr_labels}
csv = pd.DataFrame(tr_img_label,columns=['Img','Label'])
csv = csv.sample(frac=1).reset_index(drop=True)
return csv
def add_extension(a,e):
a = [x+e for x in a]
return a
def one_hot(targets, multi=False):
if multi:
binerizer = MultiLabelBinarizer()
dai_1hot = binerizer.fit_transform(targets)
else:
binerizer = LabelBinarizer()
dai_1hot = binerizer.fit_transform(targets)
return dai_1hot,binerizer.classes_
def get_img_stats(dataset,channels):
print('Calculating mean and std of the data for standardization. Might take some time, depending on the training data size.')
imgs = []
for d in dataset:
img = d[0]
imgs.append(img)
imgs_ = torch.stack(imgs,dim=3)
imgs_ = imgs_.view(channels,-1)
imgs_mean = imgs_.mean(dim=1)
imgs_std = imgs_.std(dim=1)
del imgs
del imgs_
print('Done')
return imgs_mean,imgs_std
def split_df(train_df,test_size = 0.15):
try:
train_df,val_df = train_test_split(train_df,test_size = test_size,random_state = 2,stratify = train_df.iloc[:,1])
except:
train_df,val_df = train_test_split(train_df,test_size = test_size,random_state = 2)
train_df = train_df.reset_index(drop = True)
val_df = val_df.reset_index(drop = True)
return train_df,val_df
def save_obj(path,obj):
with open(path, 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(path):
with open(path, 'rb') as f:
return pickle.load(f)
class DataProcessor:
def __init__(self, data_path=None, train_csv=None, val_csv=None, test_csv=None,
tr_name='train', val_name='val', test_name='test',
class_names=[], extension=None, setup_data=True, **kwargs):
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
(self.data_path,self.train_csv,self.val_csv,self.test_csv,
self.tr_name,self.val_name,self.test_name,self.extension) = (data_path,train_csv,val_csv,test_csv,
tr_name,val_name,test_name,extension)
data_type = {'seg':False, 'obj':False, 'sr':False, 'enhance':False,
'multi_head':False, 'multi_label':False, 'single_label':False}
self.data_type = dict(data_type, **kwargs)
self.seg = self.data_type['seg']
self.obj = self.data_type['obj']
self.sr = self.data_type['sr']
self.enhance = self.data_type['enhance']
self.multi_head = self.data_type['multi_head']
self.multi_label = self.data_type['multi_label']
self.single_label = self.data_type['single_label']
self.img_mean = self.img_std = None
self.data_dir,self.num_classes,self.class_names = data_path,len(class_names),class_names
if setup_data:
self.set_up_data()
def set_up_data(self,split_size = 0.15):
(data_path,train_csv,val_csv,test_csv,tr_name,val_name,test_name) = (self.data_path,self.train_csv,self.val_csv,self.test_csv,
self.tr_name,self.val_name,self.test_name)
# check if paths given and also set paths
if not data_path:
data_path = os.getcwd() + '/'
self.data_dir = data_path
tr_path = os.path.join(data_path,tr_name)
val_path = os.path.join(data_path,val_name)
test_path = os.path.join(data_path,test_name)
os.makedirs('mlflow_saved_training_models',exist_ok=True)
if train_csv is None:
# if (os.path.exists(os.path.join(data_path,tr_name+'.csv'))):
# train_csv = tr_name+'.csv'
# if os.path.exists(os.path.join(data_path,val_name+'.csv')):
# val_csv = val_name+'.csv'
# if os.path.exists(os.path.join(data_path,test_name+'.csv')):
# test_csv = test_name+'.csv'
# else:
train_csv,val_csv,test_csv = self.data_from_paths_to_csv(data_path,tr_path,val_path,test_path)
# else:
# self.data_dir = tr_path
train_csv_path = os.path.join(data_path,train_csv)
train_df = pd.read_csv(train_csv_path)
if 'Unnamed: 0' in train_df.columns:
train_df = train_df.drop('Unnamed: 0', 1)
img_names = [str(x) for x in list(train_df.iloc[:,0])]
if self.extension:
img_names = add_extension(img_names,self.extension)
if val_csv is not None:
val_csv_path = os.path.join(data_path,val_csv)
val_df = pd.read_csv(val_csv_path)
val_targets = list(val_df.iloc[:,1].apply(lambda x: str(x)))
if test_csv is not None:
test_csv_path = os.path.join(data_path,test_csv)
test_df = pd.read_csv(test_csv_path)
test_targets = list(test_df.iloc[:,1].apply(lambda x: str(x)))
if self.seg:
print('\nSemantic Segmentation\n')
elif self.obj:
print('\nObject Detection\n')
elif self.sr:
print('\nSuper Resolution\n')
elif self.enhance:
print('\nImage Enhancement\n')
else:
if self.multi_head:
print('\nMulti-head Classification\n')
train_df.fillna('',inplace=True)
train_df_single = train_df[[train_df.columns[0],train_df.columns[1]]].copy()
train_df_multi = train_df[[train_df.columns[0],train_df.columns[2]]].copy()
targets = list(train_df_multi.iloc[:,1].apply(lambda x: str(x)))
lengths = [len(t) for t in [s.split() for s in targets]]
split_targets = [t.split() for t in targets]
try:
split_targets = [list(map(int,x)) for x in split_targets]
except:
pass
dai_onehot,onehot_classes = one_hot(split_targets,multi=True)
train_df_multi.iloc[:,1] = [torch.from_numpy(x).type(torch.FloatTensor) for x in dai_onehot]
self.num_multi_classes,self.multi_class_names = len(onehot_classes),onehot_classes
targets = list(train_df_single.iloc[:,1].apply(lambda x: str(x)))
lengths = [len(t) for t in [s.split() for s in targets]]
split_targets = [t.split() for t in targets]
unique_targets = list(np.unique(targets))
try:
unique_targets.sort(key=int)
except:
unique_targets.sort()
unique_targets_dict = {k:v for v,k in enumerate(unique_targets)}
train_df_single.iloc[:,1] = pd.Series(targets).apply(lambda x: unique_targets_dict[x])
self.num_classes,self.class_names = len(unique_targets),unique_targets
train_df = pd.merge(train_df_single,train_df_multi,on=train_df_single.columns[0])
elif self.multi_label:
print('\nMulti-label Classification\n')
train_df_concat = train_df.copy()
if val_csv:
train_df_concat = pd.concat([train_df_concat,val_df]).reset_index(drop=True,inplace=False)
if test_csv:
train_df_concat = pd.concat([train_df_concat,test_df]).reset_index(drop=True,inplace=False)
train_df_concat.fillna('',inplace=True)
targets = list(train_df_concat.iloc[:,1].apply(lambda x: str(x)))
lengths = [len(t) for t in [s.split() for s in targets]]
split_targets = [t.split() for t in targets]
try:
split_targets = [list(map(int,x)) for x in split_targets]
except:
pass
dai_onehot,onehot_classes = one_hot(split_targets,self.multi_label)
train_df_concat.iloc[:,1] = [torch.from_numpy(x).type(torch.FloatTensor) for x in dai_onehot]
train_df = train_df_concat.loc[:len(train_df)-1].copy()
if val_csv:
val_df = train_df_concat.loc[len(train_df):len(train_df)+len(val_df)-1].copy().reset_index(drop=True)
if test_csv:
test_df = train_df_concat.loc[len(val_df)+len(train_df):len(val_df)+len(train_df)+len(test_df)-1].copy().reset_index(drop=True)
self.num_classes,self.class_names = len(onehot_classes),onehot_classes
# train_df.fillna('',inplace=True)
# targets = list(train_df.iloc[:,1].apply(lambda x: str(x)))
# lengths = [len(t) for t in [s.split() for s in targets]]
# split_targets = [t.split() for t in targets]
# try:
# split_targets = [list(map(int,x)) for x in split_targets]
# except:
# pass
# dai_onehot,onehot_classes = one_hot(split_targets,self.multi_label)
# train_df.iloc[:,1] = [torch.from_numpy(x).type(torch.FloatTensor) for x in dai_onehot]
else:
print('\nSingle-label Classification\n')
targets = list(train_df.iloc[:,1].apply(lambda x: str(x)))
lengths = [len(t) for t in [s.split() for s in targets]]
split_targets = [t.split() for t in targets]
self.single_label = True
unique_targets = list(np.unique(targets))
try:
unique_targets.sort(key=int)
except:
unique_targets.sort()
unique_targets_dict = {k:v for v,k in enumerate(unique_targets)}
train_df.iloc[:,1] = pd.Series(targets).apply(lambda x: unique_targets_dict[x])
if val_csv:
val_df.iloc[:,1] = pd.Series(val_targets).apply(lambda x: unique_targets_dict[x])
if test_csv:
test_df.iloc[:,1] = pd.Series(test_targets).apply(lambda x: unique_targets_dict[x])
self.num_classes,self.class_names = len(unique_targets),unique_targets
if not val_csv:
train_df,val_df = split_df(train_df,split_size)
if not test_csv:
val_df,test_df = split_df(val_df,split_size)
tr_images = [str(x) for x in list(train_df.iloc[:,0])]
val_images = [str(x) for x in list(val_df.iloc[:,0])]
test_images = [str(x) for x in list(test_df.iloc[:,0])]
if self.extension:
tr_images = add_extension(tr_images,self.extension)
val_images = add_extension(val_images,self.extension)
test_images = add_extension(test_images,self.extension)
train_df.iloc[:,0] = tr_images
val_df.iloc[:,0] = val_images
test_df.iloc[:,0] = test_images
if self.single_label:
dai_df = pd.concat([train_df,val_df,test_df]).reset_index(drop=True,inplace=False)
dai_df.iloc[:,1] = [self.class_names[x] for x in dai_df.iloc[:,1]]
# train_df.iloc[:,1] = [self.class_names[x] for x in train_df.iloc[:,1]]
# val_df.iloc[:,1] = [self.class_names[x] for x in val_df.iloc[:,1]]
# test_df.iloc[:,1] = [self.class_names[x] for x in test_df.iloc[:,1]]
dai_df.to_csv(os.path.join(data_path,'dai_processed_df.csv'),index=False)
train_df.to_csv(os.path.join(data_path,'dai_{}.csv'.format(self.tr_name)),index=False)
val_df.to_csv(os.path.join(data_path,'dai_{}.csv'.format(self.val_name)),index=False)
test_df.to_csv(os.path.join(data_path,'dai_{}.csv'.format(self.test_name)),index=False)
self.minorities,self.class_diffs = None,None
if self.single_label:
self.minorities,self.class_diffs = get_minorities(train_df)
self.data_dfs = {self.tr_name:train_df, self.val_name:val_df, self.test_name:test_df}
data_dict = dict({'data_dfs':self.data_dfs, 'data_dir':self.data_dir,
'num_classes':self.num_classes, 'class_names':self.class_names},
**self.data_type)
self.data_dict = data_dict
return data_dict
def data_from_paths_to_csv(self,data_path,tr_path,val_path = None,test_path = None):
train_df = csv_from_path(tr_path)
train_df.to_csv(os.path.join(data_path,f'dai_{self.tr_name}.csv'),index=False)
ret = (f'dai_{self.tr_name}.csv',None,None)
if val_path is not None:
if os.path.exists(val_path):
val_df = csv_from_path(val_path)
if val_df is not None:
val_df.to_csv(os.path.join(data_path,f'dai_{self.val_name}.csv'),index=False)
ret = (f'dai_{self.tr_name}.csv',f'dai_{self.val_name}.csv',None)
if test_path is not None:
if os.path.exists(test_path):
test_df = csv_from_path(test_path)
if test_df is not None:
test_df.to_csv(os.path.join(data_path,f'dai_{self.test_name}.csv'),index=False)
ret = (f'dai_{self.tr_name}.csv',f'dai_{self.val_name}.csv',f'dai_{self.test_name}.csv')
return ret
def get_data(self, data_dict = None, s = (224,224), dataset = dai_image_csv_dataset, train_resize_transform = None, val_resize_transform = None,
bs = 32, balance = False, super_res_crop = 256, super_res_upscale_factor = 1, sr_input_tfms = [], n_frames = 7,
tfms = [],bal_tfms = None,num_workers = 8, stats_percentage = 0.6,channels = 3, normalise = True, img_mean = None, img_std = None):
self.image_size = s
if not data_dict:
data_dict = self.data_dict
data_dfs, data_dir, single_label, seg, obj, sr= (data_dict['data_dfs'], data_dict['data_dir'],
data_dict['single_label'], data_dict['seg'],
data_dict['obj'], data_dict['sr'])
if not single_label:
balance = False
if not bal_tfms:
bal_tfms = { self.tr_name: [albu.HorizontalFlip()],
self.val_name: None,
self.test_name: None
}
else:
bal_tfms = {self.tr_name: bal_tfms, self.val_name: None, self.test_name: None}
# resize_transform = transforms.Resize(s,interpolation=Image.NEAREST)
if train_resize_transform is None:
train_resize_transform = albu.Resize(s[0],s[1],interpolation=2)
if normalise:
if img_mean is None and self.img_mean is None: # and not sr:
# temp_tfms = [resize_transform, transforms.ToTensor()]
temp_tfms = [train_resize_transform, AT.ToTensor()]
frac_data = data_dfs[self.tr_name].sample(frac = stats_percentage).reset_index(drop=True).copy()
temp_dataset = dai_image_csv_dataset(data_dir = data_dir,data = frac_data,transforms_ = temp_tfms,channels = channels)
self.img_mean,self.img_std = get_img_stats(temp_dataset,channels)
elif self.img_mean is None:
self.img_mean,self.img_std = img_mean,img_std
normalise_transform = albu.Normalize(self.img_mean, self.img_std)
else:
normalise_transform = None
# if obj:
# obj_transform = obj_utils.transform(size = s, mean = self.img_mean, std = self.img_std)
# dataset = dai_obj_dataset
# tfms = obj_transform.train_transform
# val_test_tfms = obj_transform.val_test_transform
# data_transforms = {
# self.tr_name: tfms,
# self.val_name: val_test_tfms,
# self.test_name: val_test_tfms
# }
# has_difficult = (len(data_dfs[self.tr_name].columns) == 4)
# image_datasets = {x: dataset(data_dir = data_dir,data = data_dfs[x],tfms = data_transforms[x],
# has_difficult = has_difficult)
# for x in [self.tr_name, self.val_name, self.test_name]}
# dataloaders = {x: DataLoader(image_datasets[x], batch_size=bs,collate_fn=image_datasets[x].collate_fn,
# shuffle=True, num_workers=num_workers)
# for x in [self.tr_name, self.val_name, self.test_name]}
if sr:
super_res_crop = super_res_crop - (super_res_crop % super_res_upscale_factor)
super_res_transforms = {
'pre_transforms':[albu.CenterCrop(super_res_crop,super_res_crop)]+tfms,
'pre_input_transforms':sr_input_tfms,
'downscale':
# [albu.OneOf([
# albu.Resize((super_res_crop // super_res_upscale_factor),
# (super_res_crop // super_res_upscale_factor),
# interpolation | |
import re
from typing import List, Dict
import argparse
from pathlib import Path
from pycparser import CParser, c_ast
from autopxd import AutoPxd
# List the includes to the stdlib we are expecting. This is needed to hack
# around them given they are needed for pycparser, but should endup in the pxd
# as `from libc.stdint cimport uint8_t` instead of being inside the `cdef extern`
# describing the whole header stuff.
STDLIB_INCLUDES = {
"stdbool.h": ["bool"],
"stdint.h": [
"uint8_t",
"int8_t",
"uint16_t",
"int16_t",
"uint32_t",
"int32_t",
"uint64_t",
"int64_t",
],
"wchar.h": ["wchar_t", "size_t"],
}
STDLIB_TYPES = {t for m in STDLIB_INCLUDES.values() for t in m}
class CCCP:
"""
CCCP: the Cheap&Coarse C Preprocessor
PyCParser needs to get passed preprocessed C code, but we don't want to
use a real one:
- different OS have different preprocessors (msvc vs clang vs gcc)
- we can control which #include to follow given we don't care about stdlibs ones
- we can easily tweak the behavior of #ifdef parts to ignore platform specificities
In the end remember that we are not compiling a C program, but creating a
.pxd file that will (in conjuction with a .pyx) be used to generate a .c
file that will include the godot api headers. So there is no need to handle
platform specific (or even opaque structure size !) detail here: they will
be ignored by cython and leave to the final C compilation.
"""
def __init__(
self, include_dirs: List[str], forced_defined_vars: Dict[str, str], debug: bool = False
):
self.source = []
self.source_cursor = 0
self.forced_defined_vars = forced_defined_vars.keys()
self.defined_vars = {**forced_defined_vars}
self.include_dirs = [Path(p) for p in include_dirs]
self.ingnored_includes = set()
self.debug = debug
@staticmethod
def source_to_lines(src: str) -> List[str]:
# First remove all comments
src = re.sub(r"(//.*$)", "", src, flags=re.MULTILINE)
src = re.sub(r"/\*.*?\*/", "", src, flags=re.DOTALL)
# Split lines, taking care of backslashes
lines = []
multi_lines = ""
for line in src.splitlines():
line = line.rstrip()
if line.endswith("\\"):
multi_lines += line[:-1]
continue
lines.append(multi_lines + line)
multi_lines = ""
return lines
def debug_explain(self, msg):
if self.debug:
print(msg)
def error_occurred(self, msg):
extract = "\n".join(self.source[max(0, self.source_cursor - 5) : self.source_cursor + 5])
raise RuntimeError(f"{msg}\n\nOccurred around:\n{extract}")
def handle_include(self, line):
match_include = re.match(r"^\s*#\s*include\s+[<\"]([a-zA-Z0-9_./]+)[>\"]$", line)
if not match_include:
return None
include_name = match_include.group(1)
if include_name in STDLIB_INCLUDES.keys():
self.debug_explain(f"INCLUDE INGNORED {include_name}")
self.source.pop(self.source_cursor)
return 0
for include_dir in self.include_dirs:
include_path = include_dir / include_name
try:
included_source = include_path.read_text()
# Remove #include line and replace it by included source
self.source = (
self.source[: self.source_cursor]
+ self.source_to_lines(included_source)
+ self.source[self.source_cursor + 1 :]
)
self.debug_explain(f"INCLUDE {include_name}")
return 0
except FileNotFoundError:
pass
self.error_occurred(f"Cannot resolve import `{line}`")
def handle_define(self, line):
match_define = re.match(r"^\s*#\s*define\s+([a-zA-Z0-9_]+)(\s+|$)", line)
if not match_define:
return None
define_name = match_define.group(1)
define_value = line[len(match_define.group(0)) :]
if define_name not in self.forced_defined_vars:
self.defined_vars[define_name] = self.expand_macros(define_value)
self.debug_explain(f"DEF {define_name}={define_value}")
else:
self.debug_explain(f"DEF IGNORED {define_name}={define_value}")
self.source.pop(self.source_cursor)
return 0
def handle_define_macro(self, line):
match_define_macro = re.match(r"^\s*#\s*define\s+([a-zA-Z0-9_]+)\(", line)
if not match_define_macro:
return None
define_name = match_define_macro.group(1)
define_value = line[len(match_define_macro.group(0)) :]
# Macro are not supported, this is ok given they are not used
# (but some are defined) in the gdnative headers.
# As a sanity measure, we make sure the code generated if the macro
# is used will cause the C parser to crash.
self.defined_vars[define_name] = f"#error unsuported macro {define_name}"
self.debug_explain(f"DEF MACRO {define_name}=__UNSUPORTED__")
self.source.pop(self.source_cursor)
return 0
def handle_undef(self, line):
match_undefine = re.match(r"^\s*#\s*undef\s+([a-zA-Z0-9_]+)$", line)
if not match_undefine:
return None
define_name = match_undefine.group(1)
if define_name not in self.forced_defined_vars:
self.defined_vars.pop(define_name)
self.debug_explain(f"UNDEF {define_name}")
else:
self.debug_explain(f"UNDEF INGNORED {define_name}")
self.source.pop(self.source_cursor)
return 0
def handle_if(self, line):
# Replace ifdef/ifndef by generic if to simplify parsing
line = re.sub(r"^\s*#\s*ifdef\s+([a-zA-Z0-9_]+)$", r"#if defined(\1)", line)
line = re.sub(r"^\s*#\s*ifndef\s+([a-zA-Z0-9_]+)$", r"#if !defined(\1)", line)
match_if = re.match(r"^\s*#\s*if\s+", line)
if not match_if:
return None
def _eval_if_condition(condition):
# Turn condition into Python code and eval it \o/
expr = condition.replace("||", " or ")
expr = expr.replace("&&", " and ")
expr = expr.replace("!", " not ")
expr = re.sub(r"defined\(([a-zA-Z0-9_]+)\)", r"defined('\1')", expr)
try:
return eval(
expr, {"defined": lambda key: key in self.defined_vars}, self.defined_vars
)
except Exception as exc:
self.error_occurred(
f"Error {exc} while evaluating `{expr}` (generated from `{condition}`)"
)
def _keep_until_next_condition(offset):
nested_count = 0
kept_body = []
while True:
try:
line = self.source[self.source_cursor + offset]
except IndexError:
self.error_occurred("Reach end of file without #endif")
if re.match(r"^\s*#\s*(if|ifdef|ifndef)(\s+|$)", line):
# Nested #if
nested_count += 1
else_match = re.match(r"^\s*#\s*(else$|elif\s+)", line)
if else_match:
if nested_count == 0:
condition_type = else_match.group(1).strip()
condition = line[len(else_match.group(1)) :]
return kept_body, condition_type, condition, offset + 1
if re.match(r"^\s*#\s*endif$", line):
if nested_count == 0:
return kept_body, "endif", "", offset + 1
else:
nested_count -= 1
offset += 1
kept_body.append(line)
def _retreive_kept_body(condition, offset):
if _eval_if_condition(condition):
kept_body, condition_type, condition, offset = _keep_until_next_condition(offset)
# Skip other else/elif body parts until the matching endif
while condition_type != "endif":
_, condition_type, _, offset = _keep_until_next_condition(offset)
return kept_body, offset
else:
# Ignore the if body part
_, condition_type, condition, offset = _keep_until_next_condition(offset)
if condition_type == "elif":
return _retreive_kept_body(condition, offset)
elif condition_type == "else":
return _retreive_kept_body("True", offset)
else: # endif
return [], offset
if_condition = line[len(match_if.group()) :]
body, offset = _retreive_kept_body(if_condition, offset=1)
if_starts = self.source_cursor
if_ends = self.source_cursor + offset
self.source[if_starts:if_ends] = body
self.debug_explain(f"IF ({line}) ==> {if_starts} {if_ends}")
return 0 # 0 is not equivalent to None !
def handle_unknown(self, line):
match_unknown = re.match(r"^\s*#", line)
if not match_unknown:
return None
self.error_occurred(f"Unknown preprocessor command `{line}`")
def expand_macros(self, line):
# Simple optim to discard most of the lines given regex search is cpu heavy
if not line or all(key not in line for key in self.defined_vars.keys()):
return line
expanded_line = line
# Recursive expansion given a macro can reference another one
while True:
for key, value in self.defined_vars.items():
expanded_line = re.sub(
f"(^|[^a-zA-Z0-9_]){key}([^a-zA-Z0-9_]|$)",
f"\\g<1>{value}\\g<2>",
expanded_line,
)
if expanded_line == line:
break
line = expanded_line
return line
def parse(self, src: str) -> str:
self.source = self.source_to_lines(src)
cpp_handlers = (
self.handle_define,
self.handle_define_macro,
self.handle_if,
self.handle_include,
self.handle_undef,
self.handle_unknown,
)
while True:
try:
source_line = self.source[self.source_cursor]
except IndexError:
# Parsing is done
break
for cpp_handler in cpp_handlers:
eaten_lines = cpp_handler(source_line)
if eaten_lines is not None:
self.source_cursor += eaten_lines
break
else:
# Not a preprocessor line
self.source[self.source_cursor] = self.expand_macros(source_line)
self.source_cursor += 1
return "\n".join(self.source)
class PatchedAutoPxd(AutoPxd):
def visit_TypeDecl(self, node):
# Ignore types from stdlib (will be provided by the
# `from libc.stdint cimport uint8_t` syntax)
if node.declname in STDLIB_TYPES:
return
else:
return super().visit_TypeDecl(node)
def visit_ArrayDecl(self, node):
# autopxd doesn't support array with an expression as size, but in:
# typedef struct {uint8_t _dont_touch_that[GODOT_VECTOR3_SIZE];} godot_vector3;
# `GODOT_VECTOR3_SIZE` gets resolved as `sizeof(void*)` :(
if node.type.declname == "_dont_touch_that":
# Of course the 0 size is wrong, but it's not an issue given
# we don't touch this array in Cython code (hence the name ^^)
node.dim = c_ast.Constant(type="int", value="0")
return super().visit_ArrayDecl(node)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Convert gdnative_api_struct.gen.h into Cython .pxd"
)
parser.add_argument(
"--input",
"-i",
required=True,
metavar="GODOT_HEADERS_PATH",
help="Path to Godot GDNative headers",
)
parser.add_argument(
"--output",
"-o",
required=True,
type=argparse.FileType("w", encoding="utf8"),
metavar="GDNATIVE_API_STRUCT_PXD",
help="Path to store the generated gdnative_api_struct.pxd file",
)
args = parser.parse_args()
# Step 1: preprocessing
header_name = "gdnative_api_struct.gen.h"
with open(f"{args.input}/{header_name}", "r") as fd:
source = fd.read()
# салют товарищ !
cccp = CCCP(
include_dirs=[args.input],
forced_defined_vars={"GDAPI": "", "GDN_EXPORT": "", "GDCALLINGCONV": ""},
)
preprocessed = ""
# pycparser requires each symbol must be defined, hence provide a dummy
# definition of the needed stdlib types.
# Note those definitions will then be detected and ignored by PatchedAutoPxd.
for stdtype in STDLIB_TYPES:
preprocessed += f"typedef int {stdtype};\n"
preprocessed += cccp.parse(source)
with open("output.preprocessed.c", "w") as fd:
fd.write(preprocessed)
# Step 2: C parsing
parser = CParser()
ast = parser.parse(preprocessed)
# Step 3: .pxd generation
p = PatchedAutoPxd(header_name)
p.visit(ast)
pxd_cdef = p.lines()
# Remove the cdef part given we want to add the `nogil` option and
# we also want to add the `godot_method_flags` C inline code
assert pxd_cdef[0].startswith("cdef extern from")
pxd_cdef_body = "\n".join(pxd_cdef[1:])
pxd = f"""\
# /!\\ Autogenerated code, modifications will be lost /!\\
# see `generation/generate_gdnative_api_struct.py`
from libc.stddef cimport wchar_t, size_t
from libc.stdint cimport {', '.join(STDLIB_INCLUDES['stdint.h'])}
cdef extern from "{header_name}" nogil:
\"\"\"
typedef enum {{
GODOT_METHOD_FLAG_NORMAL = 1,
| |
from manim_imports_ext import *
class TrigRepresentationsScene(Scene):
CONFIG = {
"unit_length" : 1.5,
"arc_radius" : 0.5,
"axes_color" : WHITE,
"circle_color" : RED,
"theta_color" : YELLOW,
"theta_height" : 0.3,
"theta_value" : np.pi/5,
"x_line_colors" : MAROON_B,
"y_line_colors" : BLUE,
}
def setup(self):
self.init_axes()
self.init_circle()
self.init_theta_group()
def init_axes(self):
self.axes = Axes(
unit_size = self.unit_length,
)
self.axes.set_color(self.axes_color)
self.add(self.axes)
def init_circle(self):
self.circle = Circle(
radius = self.unit_length,
color = self.circle_color
)
self.add(self.circle)
def init_theta_group(self):
self.theta_group = self.get_theta_group()
self.add(self.theta_group)
def add_trig_lines(self, *funcs, **kwargs):
lines = VGroup(*[
self.get_trig_line(func, **kwargs)
for func in funcs
])
self.add(*lines)
def get_theta_group(self):
arc = Arc(
self.theta_value,
radius = self.arc_radius,
color = self.theta_color,
)
theta = Tex("\\theta")
theta.shift(1.5*arc.point_from_proportion(0.5))
theta.set_color(self.theta_color)
theta.set_height(self.theta_height)
line = Line(ORIGIN, self.get_circle_point())
dot = Dot(line.get_end(), radius = 0.05)
return VGroup(line, arc, theta, dot)
def get_circle_point(self):
return rotate_vector(self.unit_length*RIGHT, self.theta_value)
def get_trig_line(self, func_name = "sin", color = None):
assert(func_name in ["sin", "tan", "sec", "cos", "cot", "csc"])
is_co = func_name in ["cos", "cot", "csc"]
if color is None:
if is_co:
color = self.y_line_colors
else:
color = self.x_line_colors
#Establish start point
if func_name in ["sin", "cos", "tan", "cot"]:
start_point = self.get_circle_point()
else:
start_point = ORIGIN
#Establish end point
if func_name is "sin":
end_point = start_point[0]*RIGHT
elif func_name is "cos":
end_point = start_point[1]*UP
elif func_name in ["tan", "sec"]:
end_point = (1./np.cos(self.theta_value))*self.unit_length*RIGHT
elif func_name in ["cot", "csc"]:
end_point = (1./np.sin(self.theta_value))*self.unit_length*UP
return Line(start_point, end_point, color = color)
class Introduce(TeacherStudentsScene):
def construct(self):
self.teacher_says(
"Something different today!",
target_mode = "hooray",
run_time = 2
)
self.change_student_modes("thinking", "happy", "sassy")
self.random_blink(2)
class ReactionsToTattoo(PiCreatureScene):
def construct(self):
modes = [
"horrified",
"hesitant",
"pondering",
"thinking",
"sassy",
]
tattoo_on_math = TexText("Tattoo on \\\\ math")
tattoo_on_math.to_edge(UP)
self.wait(2)
for mode in modes:
self.play(
self.pi_creature.change_mode, mode,
self.pi_creature.look, UP+RIGHT
)
self.wait(2)
self.play(
Write(tattoo_on_math),
self.pi_creature.change_mode, "hooray",
self.pi_creature.look, UP
)
self.wait()
self.change_mode("happy")
self.wait(2)
def create_pi_creature(self):
randy = Randolph()
randy.next_to(ORIGIN, DOWN)
return randy
class IntroduceCSC(TrigRepresentationsScene):
def construct(self):
self.clear()
Cam_S_C = TexText("Cam", "S.", "C.")
CSC = TexText("C", "S", "C", arg_separator = "")
csc_of_theta = TexText("c", "s", "c", "(\\theta)", arg_separator = "")
csc, of_theta = VGroup(*csc_of_theta[:3]), csc_of_theta[-1]
of_theta[1].set_color(YELLOW)
CSC.move_to(csc, DOWN)
csc_line = self.get_trig_line("csc")
csc_line.set_stroke(width = 8)
cot_line = self.get_trig_line("cot")
cot_line.set_color(WHITE)
brace = Brace(csc_line, LEFT)
self.play(Write(Cam_S_C))
self.wait()
self.play(Transform(Cam_S_C, CSC))
self.wait()
self.play(Transform(Cam_S_C, csc))
self.remove(Cam_S_C)
self.add(csc)
self.play(Write(of_theta))
self.wait(2)
csc_of_theta.add_to_back(BackgroundRectangle(csc))
self.play(
ShowCreation(self.axes),
ShowCreation(self.circle),
GrowFromCenter(brace),
csc_of_theta.rotate, np.pi/2,
csc_of_theta.next_to, brace, LEFT,
path_arc = np.pi/2,
)
self.play(Write(self.theta_group, run_time = 1))
self.play(ShowCreation(cot_line))
self.play(
ShowCreation(csc_line),
csc.set_color, csc_line.get_color(),
)
self.wait(3)
class TeachObscureTrigFunctions(TeacherStudentsScene):
def construct(self):
self.teacher_says(
"$\\sec(\\theta)$, ",
"$\\csc(\\theta)$, ",
"$\\cot(\\theta)$",
)
content = self.teacher.bubble.content.copy()
self.change_student_modes(*["confused"]*3)
self.student_says(
"But why?",
target_mode = "pleading",
added_anims = [content.to_corner, UP+RIGHT]
)
self.wait()
self.play(self.get_teacher().change_mode, "pondering")
self.wait(3)
class CanYouExplainTheTattoo(TeacherStudentsScene):
def construct(self):
self.student_says("""
Wait, can you explain
the actual tattoo here?
""")
self.random_blink()
self.play(self.get_teacher().change_mode, "hooray")
self.wait()
class ExplainTrigFunctionDistances(TrigRepresentationsScene, PiCreatureScene):
CONFIG = {
"use_morty" : False,
"alt_theta_val" : 2*np.pi/5,
}
def setup(self):
PiCreatureScene.setup(self)
TrigRepresentationsScene.setup(self)
def construct(self):
self.introduce_angle()
self.show_sine_and_cosine()
self.show_tangent_and_cotangent()
self.show_secant_and_cosecant()
self.explain_cosecant()
self.summarize_full_group()
def introduce_angle(self):
self.remove(self.circle)
self.remove(self.theta_group)
line, arc, theta, dot = self.theta_group
line.rotate(-self.theta_value)
brace = Brace(line, UP, buff = SMALL_BUFF)
one = brace.get_text("1", buff = SMALL_BUFF)
VGroup(line, brace, one).rotate(self.theta_value)
one.rotate(-self.theta_value)
self.circle.rotate(self.theta_value)
words = TexText("Corresponding point")
words.next_to(dot, UP+RIGHT, buff = 1.5*LARGE_BUFF)
words.shift_onto_screen()
arrow = Arrow(words.get_bottom(), dot, buff = SMALL_BUFF)
self.play(
ShowCreation(line),
ShowCreation(arc),
)
self.play(Write(theta))
self.play(self.pi_creature.change_mode, "pondering")
self.play(
ShowCreation(self.circle),
Rotating(line, rate_func = smooth, in_place = False),
run_time = 2
)
self.play(
Write(words),
ShowCreation(arrow),
ShowCreation(dot)
)
self.wait()
self.play(
GrowFromCenter(brace),
Write(one)
)
self.wait(2)
self.play(*list(map(FadeOut, [
words, arrow, brace, one
])))
self.radial_line_label = VGroup(brace, one)
def show_sine_and_cosine(self):
sin_line, sin_brace, sin_text = sin_group = self.get_line_brace_text("sin")
cos_line, cos_brace, cos_text = cos_group = self.get_line_brace_text("cos")
self.play(ShowCreation(sin_line))
self.play(
GrowFromCenter(sin_brace),
Write(sin_text),
)
self.play(self.pi_creature.change_mode, "happy")
self.play(ShowCreation(cos_line))
self.play(
GrowFromCenter(cos_brace),
Write(cos_text),
)
self.wait()
self.change_mode("well")
mover = VGroup(
sin_group,
cos_group,
self.theta_group,
)
thetas = np.linspace(self.theta_value, self.alt_theta_val, 100)
targets = []
for theta in thetas:
self.theta_value = theta
targets.append(VGroup(
self.get_line_brace_text("sin"),
self.get_line_brace_text("cos"),
self.get_theta_group()
))
self.play(Succession(
*[
Transform(mover, target, rate_func=linear)
for target in targets
],
run_time = 5,
rate_func = there_and_back
))
self.theta_value = thetas[0]
self.change_mode("happy")
self.wait()
self.sin_group, self.cos_group = sin_group, cos_group
def show_tangent_and_cotangent(self):
tan_group = self.get_line_brace_text("tan")
cot_group = self.get_line_brace_text("cot")
tan_text = tan_group[-1]
cot_text = cot_group[-1]
line = Line(UP, DOWN).scale(FRAME_Y_RADIUS)
line.rotate(self.theta_value)
line.move_to(self.theta_group[-1])
line.set_stroke(width = 2)
sin_tex = "{\\sin(\\theta)}"
cos_tex = "{\\cos(\\theta)}"
tan_frac = Tex("= \\frac" + sin_tex + cos_tex)
cot_frac = Tex("= \\frac" + cos_tex + sin_tex)
tan_frac.to_corner(UP+LEFT)
tan_frac.shift(2*RIGHT)
cot_frac.next_to(tan_frac, DOWN)
self.change_mode("pondering")
for frac, text in (tan_frac, tan_text), (cot_frac, cot_text):
VGroup(frac[5], frac[-2]).set_color(YELLOW)
frac.scale(0.7)
text.save_state()
text.next_to(frac, LEFT)
self.play(Write(VGroup(text, frac)))
self.wait()
self.change_mode("confused")
self.wait()
self.play(*list(map(FadeOut, [
tan_frac, cot_frac, self.sin_group, self.cos_group
])))
self.wait()
self.play(
self.theta_group[-1].set_color, YELLOW,
ShowCreation(line),
self.pi_creature.change_mode, 'pondering'
)
small_lines = VGroup()
for group in tan_group, cot_group:
small_line, brace, text = group
self.play(
ShowCreation(small_line),
GrowFromCenter(brace),
text.restore,
)
self.wait()
small_lines.add(small_line)
self.play(FadeOut(line), Animation(small_lines))
mover = VGroup(
tan_group,
cot_group,
self.theta_group,
)
thetas = np.linspace(self.theta_value, self.alt_theta_val, 100)
targets = []
for theta in thetas:
self.theta_value = theta
targets.append(VGroup(
self.get_line_brace_text("tan"),
self.get_line_brace_text("cot"),
self.get_theta_group()
))
self.play(Succession(
*[
Transform(mover, target, rate_func=linear)
for target in targets
],
run_time = 5,
rate_func = there_and_back
))
self.theta_value = thetas[0]
self.change_mode("happy")
self.wait(2)
self.tangent_line = self.get_tangent_line()
self.add(self.tangent_line)
self.play(*it.chain(*[
list(map(FadeOut, [tan_group, cot_group])),
[Animation(self.theta_group[-1])]
]))
def show_secant_and_cosecant(self):
sec_group = self.get_line_brace_text("sec")
csc_group = self.get_line_brace_text("csc")
sec_line, sec_brace, sec_text = sec_group
csc_line, csc_brace, csc_text = csc_group
sec_frac = Tex("= \\frac{1}{\\cos(\\theta)}")
sec_frac.to_corner(UP+LEFT).shift(2*RIGHT)
csc_frac = Tex("= \\frac{1}{\\sin(\\theta)}")
csc_frac.next_to(sec_frac, DOWN)
sec_dot, csc_dot = [
Dot(line.get_end(), color = line.get_color())
for line in (sec_line, csc_line)
]
sec_group.add(sec_dot)
csc_group.add(csc_dot)
for text, frac in (sec_text, sec_frac), (csc_text, csc_frac):
frac[-2].set_color(YELLOW)
frac.scale(0.7)
text.save_state()
text.next_to(frac, LEFT)
frac.add_to_back(text.copy())
self.play(
Write(frac),
self.pi_creature.change_mode, "erm"
)
self.wait()
self.wait()
for group in sec_group, csc_group:
line, brace, text, dot = group
dot.save_state()
dot.move_to(text)
dot.set_fill(opacity = 0)
self.play(dot.restore)
self.wait()
self.play(
ShowCreation(line),
GrowFromCenter(brace),
text.restore,
self.pi_creature.change_mode, "pondering"
)
self.wait()
mover = VGroup(
sec_group,
csc_group,
self.theta_group,
self.tangent_line,
)
thetas = np.linspace(self.theta_value, self.alt_theta_val, 100)
targets = []
for theta in thetas:
self.theta_value = theta
new_sec_group = self.get_line_brace_text("sec")
new_csc_group = self.get_line_brace_text("csc")
for group in new_sec_group, new_csc_group:
line = group[0]
group.add(
Dot(line.get_end(), color = line.get_color())
)
targets.append(VGroup(
new_sec_group,
new_csc_group,
self.get_theta_group(),
self.get_tangent_line(),
))
self.play(Succession(
*[
Transform(mover, target, rate_func=linear)
for target in targets
],
run_time = 5,
rate_func = there_and_back
))
self.theta_value = thetas[0]
self.change_mode("confused")
self.wait(2)
self.play(*list(map(FadeOut, [
sec_group, sec_frac
])))
self.csc_group = csc_group
self.csc_frac =csc_frac
def explain_cosecant(self):
sin_group = self.get_line_brace_text("sin")
sin_line, sin_brace, sin_text = sin_group
csc_line, csc_brace, csc_text, csc_dot = self.csc_group
csc_subgroup = VGroup(csc_brace, csc_text)
arc_theta = VGroup(*self.theta_group[1:3]).copy()
arc_theta.rotate(-np.pi/2)
arc_theta.shift(csc_line.get_end())
arc_theta[1].rotate(np.pi/2)
radial_line = self.theta_group[0]
tri1 = Polygon(
ORIGIN, radial_line.get_end(), sin_line.get_end(),
color = GREEN,
stroke_width = 8,
)
tri2 = Polygon(
csc_line.get_end(), ORIGIN, radial_line.get_end(),
color = GREEN,
stroke_width = 8,
)
opp_over_hyp = Tex(
"\\frac{\\text{Opposite}}{\\text{Hypotenuse}} ="
)
frac1 = Tex("\\frac{\\sin(\\theta)}{1}")
frac1.next_to(opp_over_hyp)
frac1[-4].set_color(YELLOW)
frac2 = Tex("= \\frac{1}{\\csc(\\theta)}")
frac2.next_to(frac1)
frac2[-2].set_color(YELLOW)
frac_group = VGroup(opp_over_hyp, frac1, frac2)
frac_group.set_width(FRAME_X_RADIUS-1)
frac_group.next_to(ORIGIN, RIGHT).to_edge(UP)
question = TexText("Why is this $\\theta$?")
question.set_color(YELLOW)
question.to_corner(UP+RIGHT)
arrow = Arrow(question.get_bottom(), arc_theta)
one_brace, one = self.radial_line_label
one.move_to(one_brace.get_center_of_mass())
self.play(ShowCreation(tri1))
self.play(
ApplyMethod(tri1.rotate, np.pi/12, rate_func = wiggle),
self.pi_creature.change_mode, "thinking"
)
self.wait()
tri1.save_state()
self.play(Transform(tri1, tri2, path_arc = np.pi/2))
self.play(Write(arc_theta))
self.play(ApplyMethod(
tri1.rotate, np.pi/12,
rate_func = wiggle
))
self.wait(2)
self.play(
Write(question),
ShowCreation(arrow),
self.pi_creature.change_mode, "confused"
)
self.wait(2)
self.play(*list(map(FadeOut, [question, arrow])))
self.play(Write(opp_over_hyp))
self.wait()
csc_subgroup.save_state()
self.play(
tri1.restore,
csc_subgroup.fade, 0.7
)
self.play(
ShowCreation(sin_line),
GrowFromCenter(sin_brace),
Write(sin_text)
)
self.wait()
self.play(Write(one))
self.wait()
self.play(Write(frac1))
self.wait()
self.play(
Transform(tri1, tri2),
FadeOut(sin_group)
)
self.play(
radial_line.rotate, np.pi/12,
rate_func = wiggle
)
self.wait()
self.play(csc_subgroup.restore)
self.wait()
self.play(Write(frac2))
self.change_mode("happy")
self.play(FadeOut(opp_over_hyp))
self.reciprocate(frac1, frac2)
self.play(*list(map(FadeOut, [
one, self.csc_group, tri1,
frac1, frac2, self.csc_frac,
arc_theta
])))
def reciprocate(self, frac1, frac2):
# Not general, meant only for these definitions:
# frac1 = Tex("\\frac{\\sin(\\theta)}{1}")
# frac2 = Tex("= \\frac{1}{\\csc(\\theta)}")
num1 = VGroup(*frac1[:6])
dem1 = frac1[-1]
num2 = frac2[1]
dem2 = VGroup(*frac2[-6:])
group = VGroup(frac1, frac2)
self.play(
group.scale, 1/0.7,
group.to_corner, UP+RIGHT,
)
self.play(
num1.move_to, dem1,
dem1.move_to, num1,
num2.move_to, dem2,
dem2.move_to, num2,
path_arc = np.pi
)
self.wait()
self.play(
dem2.move_to, frac2[2],
VGroup(*frac2[1:3]).set_fill, BLACK, 0
)
self.wait()
def summarize_full_group(self):
scale_factor = 1.5
theta_subgroup = VGroup(self.theta_group[0], self.theta_group[-1])
self.play(*it.chain(*[
[mob.scale, scale_factor]
for mob in [
self.circle, self.axes,
theta_subgroup, self.tangent_line
]
]))
self.unit_length *= scale_factor
to_fade = VGroup()
for func_name in ["sin", "tan", "sec", "cos", "cot", "csc"]:
line, brace, text = self.get_line_brace_text(func_name)
if func_name in ["sin", "cos"]:
angle = line.get_angle()
if np.cos(angle) < 0:
angle += np.pi
if func_name is "sin":
target = line.get_center()+0.2*LEFT+0.1*DOWN
else:
target = VGroup(brace, line).get_center_of_mass()
text.scale(0.75)
text.rotate(angle)
text.move_to(target)
line.set_stroke(width = 6)
| |
Annotate
xave = np.median(list(cdf['phi']))
yave = np.median(list(cdf['psi']))
ss_label = str(ss)
weight = 'normal'
if ss in mark_important_secondary_structures:
weight = 'bold'
if ss_label in ss_name_to_label:
ss_label = ss_name_to_label[ss_label]
axes[column]['rama'].annotate(ss_label, xy=(xave, yave), xytext=(xave+30, yave-30), weight=weight, color=c,
xycoords='data', arrowprops=dict(arrowstyle="-",color=c, lw=linewidth), fontsize=textsize*0.9)
def get_ave(vals):
X,Y = get_his(vals,norm=0); X=list(X); Y=list(Y)
return X[Y.index(np.max(Y))]
# We study the ss distributions as a function of R, theta, d
if ss != "all":
bins = 150
if column == 1:
bins = 50
# r
vals = cdf['R']
X,Y = get_his(vals,bins=bins)
axes[column]['R'].fill_between(X,Y,0,facecolor=c,alpha=alpha)
axes[column]['R'].plot(X,Y,c='k',linewidth=linewidth)
axis_to_average_x['R'].append([ss,get_ave(vals),c])
'''
# theta
vals = do_theta(cdf['theta'])
#vals = abs(cdf['d'])+(cdf['phi']+cdf['psi'] + 360.)/(720.)
if 0: # rescale values wrt min and max vals
mind = min(vals)
#maxd = max(vals)
#for i in range(len(vals)):
# if vals[i] < 0:
# vals[i] = vals + mind
vals = vals - mind
X, Y = get_his(vals,bins=bins)
axes[column]['theta'].fill_between(X,Y,0,facecolor=c,alpha=alpha)
axes[column]['theta'].plot(X,Y,c='k',linewidth=linewidth)
axis_to_average_x['theta'].append([ss,get_ave(vals),c])
# d
tdf = cdf.copy()
vals = do_d(tdf['d'])
if 0: # rescale values wrt min and max vals
mind = min(vals)
maxd = max(vals)
tdf.ix[tdf.d<=0, 'd'] = maxd+(tdf.ix[tdf.d <= 0, 'd']-mind)
vals = tdf['d']*-1*np.sign(np.cos(np.radians(tdf['theta'])/2.0))
#vals = tdf['d']*-1.0*np.cos(np.radians(tdf['theta'])/2.0)
#vals = np.sign(tdf['d'])*np.sin(np.radians(tdf['theta'])) # this is the h number from Mannige, PeerJ, 2017
X,Y = get_his(vals,bins=bins)
axes[column]['d'].fill_between(X,Y,0,facecolor=c,alpha=alpha)
axes[column]['d'].plot(X,Y,c='k',linewidth=linewidth)
axis_to_average_x['d'].append([ss,get_ave(vals),c])
# Example of how to plot vertically
#axes[column]['d'].fill_betweenx(X,Y,0,facecolor=c,alpha=alpha)
#axes[column]['d'].plot(Y,X,c='k',linewidth=linewidth)
'''
# setting the ramachandran plot aspect ratio
if 1:#for name in ['d','theta','R']: #axes.items():
axes[column]['rama'].set_aspect(1)
# Making some tweaks to all but the
for name in ['R']: #['d','theta','R']: #axes.items():
ax = axes[column][name]
xmin,xmax = ax.get_xlim(); ymin,ymax = ax.get_ylim() # getting axes min max values
ax.set_yticks([0,1.5])
ax.set_xlabel(type_to_label[name])
# Only show ticks on the left and bottom spines
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('none')
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
xpad = (xmax-xmin)*0.0; ypad = (ymax-ymin)*0.0; # setting padding
extent = [xmin, xmax+xpad, ymin, ymax+ypad+0.6] # storing (padded) axis min max values
xscaling = .094 # setting how much larger must the x axis be compared to the y axis
ax.axis(extent) # setting (padded) axis min max values
#ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/xscaling)
# Dissapearing the axis
plt.setp(ax.get_yticklabels(), visible=False)
# (Re)setting labels and titles
for name in ['rama','R']:#['rama','R','theta','d']:
ax = axes[column][name]
for spine in ax.spines.keys():
ax.spines[spine].set_linewidth(linewidth*1.2)
addto_title = r'('+next(panel_letters)+r')'+"\n"
t = ax.set_title(addto_title, size=textsize*1.4, loc='left',horizontalalignment='right')
#t.set_y(1.03) # Shifting the title up a little
# axis tick labels
plt.setp(ax.get_yticklabels(), size=textsize*1)#, rotation="vertical")
plt.setp(ax.get_xticklabels(), size=textsize*1)
# axis label (name of the axis)
ax.set_xlabel(ax.get_xlabel(), fontsize=textsize*2)
ax.set_ylabel(ax.get_ylabel(), fontsize=textsize*2, rotation="horizontal", ha='center', va='center',labelpad=20)
# Annotating distributions
for name in ['R']:#axis_to_average_x.keys():
ax = axes[column][name]
#
ss_to_avex = {}
ss_to_color = {}
for ss,avex,color in axis_to_average_x[name]:
ss_label = str(ss)
if ss_label in ss_name_to_label:
ss_label = ss_name_to_label[ss_label]
#avex = round(avex,1)
ss_to_avex[ss] = avex
ss_to_color[ss] = color
#
ss_names = ss_to_avex.keys()
ss_avex = ss_to_avex.values()
#
# sort names by avex:
ss_names_sorted = [x for (y,x) in sorted(zip(ss_avex,ss_names))]
#
min_avex = np.min(ss_avex)
max_avex = np.max(ss_avex)
unique_avexes = sorted(set(ss_avex))
#
paddings = itertools.cycle([0.0,0.0]) # If you want to cycle through some of vertical heights of the labels
for ss in ss_names_sorted:
# 0 for first sorted ss, 1 for last
ss_frac = float(ss_names_sorted.index(ss))/float(len(ss_names_sorted)-1)
#
text_x = min_avex + ss_frac*(max_avex-min_avex)
text_y = 1.9+next(paddings)
#
point_x = ss_to_avex[ss]
point_y = 1.05
#
total_height = 15
# length of vertical leg emanating from the label
armA = 14
# length of vertical leg emanating from the pointed region
label_frac = float(unique_avexes.index(point_x))/(len(unique_avexes)-1)
armB = total_height*label_frac
#
current_arrow_color = ss_to_color[ss]
current_text_color = ss_to_color[ss]
angleB = 90
if 0: # Also offset the angle
arange = 45
offset_weight = -1*(1-abs(2.0*(label_frac-0.5)))*np.sign(label_frac-0.5)
'''
offset_weight 0 .2 .4 .6 .8 1 -.8 -.6 -.4 -.2 0
| | | | | | | | | | |
label_frac 0 .1 .2 .3 .4 .5 .6 .7 .8 .9 1
'''
angleB_offset = offset_weight*arange # when label_frac == 0 or 1 armB_offset is +arange or -arange.
angleB = 90 + angleB_offset
#
connection_style = "arc,angleA=-90,angleB=%f,armA=%f,armB=%f,rad=0"%(angleB,armA,armB)
weight = 'normal'
if ss in mark_important_secondary_structures:
weight = 'bold'
ax.annotate(str(ss), xy=(point_x, point_y), xytext=(text_x, text_y),
xycoords='data', weight=weight,
arrowprops=dict(arrowstyle="-",color=current_arrow_color,
connectionstyle=connection_style, lw=linewidth),
horizontalalignment='center', verticalalignment='bottom',
fontsize=textsize*0.9, color=ss_to_color[ss])
# Add some artificial limits:
#axes[column]['theta'].set_xticks(range(-360,361,90))
#axes[column]['theta'].set_xlim(50,275)
plt.tight_layout(pad=0.0, w_pad=0.0, h_pad=0.0)
#gs.update(wspace=1, hspace=1)
#plt.subplots_adjust(wspace=.201)
#plt.subplots_adjust(hspace=0.001)
plt.savefig(figname, dpi=180, bbox_inches='tight',transparent=True) #facecolor='w', edgecolor='w',
if show_graphs:
os.system(pdf_viewer+" "+figname)
#
if 0: # FIGURE_START, shouldbeone
figname = output_fig_dir+"/fig_various_ss_formats.pdf"
sns.reset_orig()
#sns.set_context("notebook")#, font_scale=1)
sns.set_style("ticks")
set_grays()
textsize = 12.0
linewidth = 1.0
alpha = 0.5
annotation_color = 'teal'
# VERY IMPORTANT FOR GETTING THE SHAPE OF EACH PANEL CORRECT
plt.figure(figsize=(13,12))
# Plot distributions of secondary structures in various formats
sstype = 'segno' # check <ss_codes>
# ----------------
# nrows ncols
# | |
gs = mpl.gridspec.GridSpec(4, 2,
height_ratios = [5,1,1,1],
width_ratios = [1,1])
axes = {}
# Column
# |
axes[0] = {'rama': plt.subplot(gs[0,0]),
'R': plt.subplot(gs[1,0]),
'theta': plt.subplot(gs[2,0]),
'd': plt.subplot(gs[3,0])
}
axes[1] = {'rama': plt.subplot(gs[0,1]),
'R': plt.subplot(gs[1,1]),
'theta': plt.subplot(gs[2,1]),
'd': plt.subplot(gs[3,1])
}
draw_d_contours = 1
if draw_d_contours:
# we will draw a d=0 contour line in each plot that has the name 'rama'
d0df = pd.read_csv(length_dependent_csv_file)
d0df = d0df[(d0df['L']==8.0) & (d0df['omega']==180.0)]
mark_important_secondary_structures = [4,8,6,11]
panel_letters = itertools.cycle(list(string.ascii_lowercase))
for column in [0,1]:
# -----------------
# Loading up the SS database
if column == 0:
normal_levels = [0.3333,0.6666] # For ramachandran plots, given most ss keys
levels_for_all = [0.92] # Same, but in case the 'all' key is used for ss
# Loading:
if not os.path.isfile(master_ss_file):
prepare_master_ss_file()
df = pd.read_csv(master_ss_file)
# Cleaning:
df = df[(df['d'] != 999)]
ss_to_study = ['all','G','E','P','H']
if column == 1:
normal_levels = [0.6666,0.9] # For ramachandran plots, given most ss keys
if not os.path.isfile(fake_ss_file):
write_fake_secondary_structure_database(sstype = 'segno',omega=180.0,sample_points=50000, sigma=5)
df = pd.read_csv(fake_ss_file)
# Lets study ALL fake secondary structures
ss_to_study = sorted(set(list(df[sstype])))
'''
ds_ = np.abs(df[(df[sstype] == ss_codes[sstype]['E'])]['d'])
thetas_ = df['theta']
Rs_ = df['R']
mind ,maxd = ds_.min() , ds_.max()
minR ,maxR = Rs_.min() , Rs_.max()
minTheta,maxTheta = thetas_.min() , thetas_.max()
yextents_dict = {'d':[1,maxd],'R':[0.3,0.67],'R2':[0.3,0.67],'R2':[0.3,0.67],'theta':[minTheta,maxTheta]}
'''
# Creating a palette through which we cycle for various secondary structures
#palette_colors = sns.dark_palette("red", len(ss_to_study))
palette_colors = sns.color_palette("cubehelix", len(ss_to_study))
#palette_colors = sns.color_palette("RdBu", len(ss_to_study))
#if column == 0:
#palette_colors = sns.color_palette("colorblind",len(ss_to_study))
palette_colors = sns.hls_palette(len(ss_to_study), l=.4, s=.7)
palette = itertools.cycle(palette_colors)
if draw_d_contours:
# draw d=0 contour lines
X = d0df['phi']
Y = d0df['psi']
Z = d0df['d']
X,Y,Z = locallib.xyz_to_ndarrays(X,Y,Z)
Z = scipy.ndimage.filters.gaussian_filter(Z, 2)#, order=0)
CS = axes[column]['rama'].contour(X, Y, Z, [0], colors='gray', linewidths=linewidth, linestyles='dashdot')
if 0: # Draw contour labels
# Recast levels
fmt = {}
for l in CS.levels:
s = "%1.3f" %(l)
if float(l) == float(int(l)):
s = "d=%d" %(l)
fmt[l] = s
#
axes[column]['rama'].clabel(CS, fontsize=textsize*0.9, inline=1, fmt=fmt) #fmt = contour_label_format)
#
#
axis_to_average_x = {}; axis_to_average_x['theta']=[]; axis_to_average_x['d']=[]; axis_to_average_x['R']=[];
for ss in ss_to_study:
levels = normal_levels
if ss == 'all':
levels = levels_for_all
xtype = 'phi'; ytype = 'psi';
cdf = df.copy()
fill_contour_lines = 1
draw_contour_lines = 0
smooth = 2
cmap = "#D3D3D3" # This is the default color for an 'all' map
c = cmap # Uses only a color if cmap is a string
if ss != "all":
# ----------------
# NEW COLOR SCHEME:
c1 = [1,1,1]; c2 = next(palette);
cdict = {# c1 c2
'red': ((0.00, c1[0], c1[0]), (1.0, c2[0], c2[0])),
'green': ((0.00, c1[1], c1[1]), (1.0, c2[1], c2[1])),
'blue': ((0.00, c1[2], c1[2]), (1.0, c2[2], c2[2])) }
current_cmap = LinearSegmentedColormap('tmpcmap', cdict)
c = current_cmap(0.99999)
# ----------------
draw_contour_lines = 1
smooth = 2
cmap=current_cmap
# Here, if so inclined, you could put a check to transform the phi psi values
if ss in ss_codes[sstype]:
cdf = cdf[(cdf[sstype] == ss_codes[sstype][ss])]
else:
# Then this may be a 'fake' secondary structure. No translation needed, just use the ss code.
cdf = cdf[(cdf[sstype] == ss)]
all_size = len(df)
current_size = len(cdf)
print ss,'\t',current_size,'\t',100.0*float(current_size)/all_size
# Plotting contours on the ramachandran plot
# Fill
locallib.plot_ramachandran_histogram(cdf['phi'],cdf['psi'],levels=levels,cmap=cmap,
fill=1,lines=0, ax=axes[column]['rama'],
smooth=smooth, linestyles=['solid', 'dotted'],linewidths=0)
if ss != 'all':
# Lines
line_width_modifier = 1.3
if ss in mark_important_secondary_structures:
line_width_modifier = 2.3
#
locallib.plot_ramachandran_histogram(cdf['phi'],cdf['psi'],levels=[sorted(levels)[-1]],cmap='k',#cmap,
fill=0,lines=1, ax=axes[column]['rama'],
smooth=smooth, linestyles=['solid'], linewidths=linewidth*line_width_modifier)
#
# Annotate
xave = np.median(list(cdf['phi']))
yave = np.median(list(cdf['psi']))
ss_label = str(ss)
weight = 'normal'
if ss in mark_important_secondary_structures:
weight = 'bold'
if ss_label in ss_name_to_label:
ss_label = ss_name_to_label[ss_label]
axes[column]['rama'].annotate(ss_label, xy=(xave, yave), xytext=(xave+30, yave-30), weight=weight, color=c,
xycoords='data', arrowprops=dict(arrowstyle="-",color=c, lw=linewidth), fontsize=textsize*0.9)
def get_ave(vals):
X,Y = get_his(vals,norm=0); X=list(X); Y=list(Y)
return X[Y.index(np.max(Y))]
# We study the ss distributions as a function of R, theta, d
if ss != "all":
bins = 150
if column == 1:
bins = 50
# r
vals = cdf['R']
X,Y = get_his(vals,bins=bins)
axes[column]['R'].fill_between(X,Y,0,facecolor=c,alpha=alpha)
axes[column]['R'].plot(X,Y,c='k',linewidth=linewidth)
axis_to_average_x['R'].append([ss,get_ave(vals),c])
# theta
vals = do_theta(cdf['theta'])
#vals = abs(cdf['d'])+(cdf['phi']+cdf['psi'] + 360.)/(720.)
if 0: # rescale values wrt min and max vals
mind = min(vals)
#maxd = max(vals)
#for i in range(len(vals)):
# if vals[i] < 0:
# vals[i] = vals + mind
vals = vals - mind
X, Y = get_his(vals,bins=bins)
axes[column]['theta'].fill_between(X,Y,0,facecolor=c,alpha=alpha)
axes[column]['theta'].plot(X,Y,c='k',linewidth=linewidth)
axis_to_average_x['theta'].append([ss,get_ave(vals),c])
# d
tdf = cdf.copy()
vals = do_d(tdf['d'])
if 0: # rescale values wrt min and max vals
mind = min(vals)
maxd = max(vals)
tdf.ix[tdf.d<=0, 'd'] = maxd+(tdf.ix[tdf.d <= 0, 'd']-mind)
vals = tdf['d']*-1*np.sign(np.cos(np.radians(tdf['theta'])/2.0))
#vals = tdf['d']*-1.0*np.cos(np.radians(tdf['theta'])/2.0)
#vals = np.sign(tdf['d'])*np.sin(np.radians(tdf['theta'])) # this is the h number from Mannige, PeerJ, 2017
X,Y = get_his(vals,bins=bins)
axes[column]['d'].fill_between(X,Y,0,facecolor=c,alpha=alpha)
axes[column]['d'].plot(X,Y,c='k',linewidth=linewidth)
axis_to_average_x['d'].append([ss,get_ave(vals),c])
# Example of how to plot vertically
#axes[column]['d'].fill_betweenx(X,Y,0,facecolor=c,alpha=alpha)
#axes[column]['d'].plot(Y,X,c='k',linewidth=linewidth)
# setting the ramachandran plot aspect ratio
if 1:#for name in ['d','theta','R']: #axes.items():
axes[column]['rama'].set_aspect(1)
# Making some tweaks to all but the
for name in ['d','theta','R']: #axes.items():
ax = axes[column][name]
xmin,xmax = ax.get_xlim(); ymin,ymax = ax.get_ylim() # getting axes min max values
ax.set_yticks([0,1.5])
ax.set_xlabel(type_to_label[name])
# Only show ticks on the left and bottom spines
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('none')
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
xpad = (xmax-xmin)*0.0; ypad = (ymax-ymin)*0.0; # setting padding
extent = [xmin, xmax+xpad, ymin, ymax+ypad+0.6] # storing (padded) axis min max values
xscaling = .094 # setting how much larger must the x axis be compared to the y axis
ax.axis(extent) # setting (padded) axis min max values
#ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/xscaling)
# Dissapearing the axis
plt.setp(ax.get_yticklabels(), visible=False)
# (Re)setting labels and titles
for name in ['rama','R','theta','d']:
ax = axes[column][name]
for spine in ax.spines.keys():
ax.spines[spine].set_linewidth(linewidth*1.2)
addto_title = r'('+next(panel_letters)+r')'+"\n"
t = ax.set_title(addto_title, size=textsize*1.4, loc='left',horizontalalignment='right')
#t.set_y(1.03) # Shifting the title up a little
# axis tick labels
plt.setp(ax.get_yticklabels(), size=textsize*1)#, rotation="vertical")
plt.setp(ax.get_xticklabels(), size=textsize*1)
# axis label (name of the axis)
ax.set_xlabel(ax.get_xlabel(), fontsize=textsize*2)
ax.set_ylabel(ax.get_ylabel(), fontsize=textsize*2, rotation="horizontal", ha='center', va='center',labelpad=20)
# Annotating distributions
for name in axis_to_average_x.keys():
ax = axes[column][name]
#
ss_to_avex = {}
ss_to_color = {}
for | |
from the configuration.
Returns:
ApplyResult[(LinkedPATemplateSummaryRoot, int, typing.Dict)]
"""
self.apply_kwargs_defaults(kwargs=kwargs, return_http_data_only=False, async_req=True)
return self.get_linked_pa_templates_endpoint.call_with_http_info(**kwargs)
def get_linked_pa_templates_by_id(
self,
id="01234567890123456789012345678901",
**kwargs
) -> LinkedPATemplateRoot:
"""Get linked PA template by id # noqa: E501
This endpoint fetches the linked PA template settings. # noqa: E501
This method makes a synchronous HTTP request. Returns the http data only
Args:
id (str): Unique identifier for a linked PA template. defaults to "01234567890123456789012345678901", must be one of ["01234567890123456789012345678901"]
Keyword Args:
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): timeout setting for this request. If
one number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
Returns:
LinkedPATemplateRoot
Response Object
"""
self.apply_kwargs_defaults(kwargs=kwargs, return_http_data_only=True, async_req=False)
kwargs['id'] = \
id
return self.get_linked_pa_templates_by_id_endpoint.call_with_http_info(**kwargs)
def get_linked_pa_templates_by_id_with_http_info(
self,
id="01234567890123456789012345678901",
**kwargs
) -> typing.Tuple[LinkedPATemplateRoot, int, typing.MutableMapping]:
"""Get linked PA template by id # noqa: E501
This endpoint fetches the linked PA template settings. # noqa: E501
This method makes a synchronous HTTP request. Returns http data, http status and headers
Args:
id (str): Unique identifier for a linked PA template. defaults to "01234567890123456789012345678901", must be one of ["01234567890123456789012345678901"]
Keyword Args:
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): timeout setting for this request. If
one number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
Returns:
LinkedPATemplateRoot
Response Object
int
Http Status Code
dict
Dictionary of the response headers
"""
self.apply_kwargs_defaults(kwargs=kwargs, return_http_data_only=False, async_req=False)
kwargs['id'] = \
id
return self.get_linked_pa_templates_by_id_endpoint.call_with_http_info(**kwargs)
def get_linked_pa_templates_by_id_async(
self,
id="01234567890123456789012345678901",
**kwargs
) -> "ApplyResult[LinkedPATemplateRoot]":
"""Get linked PA template by id # noqa: E501
This endpoint fetches the linked PA template settings. # noqa: E501
This method makes a asynchronous HTTP request. Returns the http data, wrapped in ApplyResult
Args:
id (str): Unique identifier for a linked PA template. defaults to "01234567890123456789012345678901", must be one of ["01234567890123456789012345678901"]
Keyword Args:
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): timeout setting for this request. If
one number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
Returns:
ApplyResult[LinkedPATemplateRoot]
"""
self.apply_kwargs_defaults(kwargs=kwargs, return_http_data_only=True, async_req=True)
kwargs['id'] = \
id
return self.get_linked_pa_templates_by_id_endpoint.call_with_http_info(**kwargs)
def get_linked_pa_templates_by_id_with_http_info_async(
self,
id="01234567890123456789012345678901",
**kwargs
) -> "ApplyResult[typing.Tuple[LinkedPATemplateRoot, int, typing.MutableMapping]]":
"""Get linked PA template by id # noqa: E501
This endpoint fetches the linked PA template settings. # noqa: E501
This method makes a asynchronous HTTP request. Returns http data, http status and headers, wrapped in ApplyResult
Args:
id (str): Unique identifier for a linked PA template. defaults to "01234567890123456789012345678901", must be one of ["01234567890123456789012345678901"]
Keyword Args:
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): timeout setting for this request. If
one number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
Returns:
ApplyResult[(LinkedPATemplateRoot, int, typing.Dict)]
"""
self.apply_kwargs_defaults(kwargs=kwargs, return_http_data_only=False, async_req=True)
kwargs['id'] = \
id
return self.get_linked_pa_templates_by_id_endpoint.call_with_http_info(**kwargs)
def update_linked_pa_templates(
self,
linked_pa_template_update_parameters_root,
id="01234567890123456789012345678901",
**kwargs
) -> LinkedPATemplatePostSummaryRoot:
"""Update a linked PA template # noqa: E501
This endpoint allows the user to change the request body and description from an existing template. Remarks: * Mandatory fields are required to be passed in POST requests and Optional fields are not necessary. If no mandatory fields are passed, then we can use the template as a component and skip the component creation. * Mandatory, optional and locked fields can be \"accounts\", \"benchmarks\", \"groups\", \"columns\", \"datasources\", \"dates\", \"currencyisocode\" and \"componentdetail\". * We cannot override the Locked fields when creating the Component. * Mandatory and locked strings are mutually exclusive. * Multi-horizon frequencies are not supported through this endpoint. # noqa: E501
This method makes a synchronous HTTP request. Returns the http data only
Args:
linked_pa_template_update_parameters_root (LinkedPATemplateUpdateParametersRoot): Request Parameters
id (str): Unique identifier for a linked PA template. defaults to "01234567890123456789012345678901", must be one of ["01234567890123456789012345678901"]
Keyword Args:
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): timeout setting for this request. If
one number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
| |
1 : the address that was referenced
"""
dif = end - start
called_list = []
func_name = _getFunctionNameAt(start)
for indx in range(0, dif):
addr = start + indx
func_refs_from = XrefsFrom(addr, 1)
for ref in func_refs_from:
if _getFunctionNameAt(ref.to) == func_name:
# skip jumps inside self
continue
called_list.append(ref.to)
calling_list = self._getCallingOffset(func, called_list)
return calling_list
def _loadLocals(self) -> None:
"""Enumerates functions using IDA API and loads them into the internal mapping.
"""
self._loadImports()
for func in Functions():
start = get_func_attr(func, FUNCATTR_START)
end = prev_addr(get_func_attr(func, FUNCATTR_END))
is_import = self._isImportStart(start)
refs_list = self._listRefsTo(start)
calling_list = self._listRefsFrom(func, start, end)
func_info = FunctionInfo_t(start, end, refs_list, calling_list, is_import)
self._functionsMap[va_to_rva(start)] = func_info
self._functionsMap[va_to_rva(end)] = func_info
self.funcList.append(func_info)
# public
def __init__(self, parent=None) -> None:
super(FunctionsMapper_t, self).__init__(parent=parent)
self._functionsMap = dict()
self.funcList = [] # public
self._loadLocals()
def funcAt(self, rva: int) -> FunctionInfo_t:
func_info = self._functionsMap[rva]
return func_info
class FunctionsListForm_t(PluginForm):
"""The main form of the IFL plugin.
"""
# private
_LIVE_FILTER = True
def _listFunctionsAddr(self) -> List[int]:
"""Lists all the starting addresses of the functions using IDA API.
"""
fn_list = list()
for func in Functions():
start = get_func_attr(func, FUNCATTR_START)
fn_list.append(start)
return fn_list
def _saveFunctionsNames(self, file_name: Optional[str], ext: str) -> bool:
"""Saves functions names and offsets from the internal mappings into a file.
Fromats: CSV (default), or TAG (PE-bear, PE-sieve compatibile).
"""
if file_name is None or len(file_name) == 0:
return False
delim = ","
if ".tag" in ext: # a TAG format was chosen
delim = ";"
fn_list = list()
for func in Functions():
start = get_func_attr(func, FUNCATTR_START)
func_name = _getFunctionNameAt(start)
start_rva = va_to_rva(start)
line = "%lx%c%s" % (start_rva, delim, func_name)
fn_list.append(line)
idaapi.msg(str(file_name))
with open(file_name, 'w') as f:
for item in fn_list:
f.write("%s\n" % item)
return True
return False
def _stripImportName(self, func_name) -> str:
"""Keep only ImportName, without the DLL name, and the ordinal.
"""
fn1 = func_name.split('.')
if len(fn1) >= 2:
func_name = fn1[1].strip()
fn1 = func_name.split('#')
if len(fn1) >= 2:
func_name = fn1[0].strip()
return func_name
def _defineImportThunk(self, start, thunk_val):
"""If the binary has the Import Thunk filled, define it as a data chunk of appropriate size.
"""
info = idaapi.get_inf_structure()
if info.is_64bit():
curr_val = idc.get_qword(start)
if (curr_val == thunk_val):
return ida_bytes.create_data(start, idaapi.FF_QWORD, 8, idaapi.BADADDR)
elif info.is_32bit():
curr_val = ida_bytes.get_dword(start)
if (curr_val == thunk_val):
return ida_bytes.create_data(start, idaapi.FF_DWORD, 4, idaapi.BADADDR)
return False
def _loadFunctionsNames(self, file_name: Optional[str], ext: str) -> Optional[Tuple[int, int]]:
"""Loads functions names from the given file into the internal mappings.
Fromats: CSV (default), or TAG (PE-bear, PE-sieve compatibile).
"""
if file_name is None or len(file_name) == 0:
return None
curr_functions = self._listFunctionsAddr()
delim = "," # new delimiter (for CSV format)
delim2 = ":" # old delimiter
rva_indx = 0
cmt_indx = 1
is_imp_list = False
if ".imports.txt" in ext:
is_imp_list = True
cmt_indx = 2
if ".tag" in ext: # a TAG format was chosen
delim2 = ";"
functions = 0
comments = 0
with open(file_name, 'r') as f:
for line in f.readlines():
line = line.strip()
fn = line.split(delim)
if len(fn) < 2:
fn = line.split(delim2) # try old delimiter
if len(fn) < 2:
continue
start = 0
addr_chunk = fn[rva_indx].strip()
if not _is_hex_str(addr_chunk):
continue
try:
start = int(addr_chunk, 16)
except ValueError:
# this line doesn't start from an offset, so skip it
continue
func_name = fn[cmt_indx].strip()
if start < idaapi.get_imagebase(): # it is RVA
start = rva_to_va(start) # convert to VA
if is_imp_list or (start in curr_functions):
if is_imp_list:
func_name = self._stripImportName(func_name)
thunk_val = int(fn[1].strip(), 16)
self._defineImportThunk(start, thunk_val)
if self.subDataManager.setFunctionName(start, func_name):
functions += 1
continue
set_cmt(start, func_name, 1) # set the name as a comment
comments += 1
return (functions, comments)
def _setup_sorted_model(self, view, model) -> QtCore.QSortFilterProxyModel:
"""Connects the given sorted data model with the given view.
"""
sorted_model = QtCore.QSortFilterProxyModel()
sorted_model.setDynamicSortFilter(True)
sorted_model.setSourceModel(model)
view.setModel(sorted_model)
view.setSortingEnabled(True)
#
sorted_model.setParent(view)
model.setParent(sorted_model)
return sorted_model
def _update_current_offset(self, view, refs_model, offset) -> None:
"""Update the given data model to follow given offset.
"""
if offset:
index = refs_model.findOffsetIndex(offset)
else:
index = (-1)
refs_model.setCurrentIndex(index)
refs_model.reset()
view.reset()
view.repaint()
def _update_function_name(self, ea: int) -> None:
"""Sets on the displayed label the name of the function and it's arguments.
"""
try:
func_info = self.funcMapper.funcAt(va_to_rva(ea))
except KeyError:
return
func_type = func_info.type
func_args = _getArgsDescription(ea)
func_name = _getFunctionNameAt(ea)
self.refs_label.setText(f"{func_type} <b>{func_name}</b> {func_args}")
def _update_ref_tabs(self, ea: int) -> None:
"""Sets on the tabs headers the numbers of references to the selected function.
"""
tocount = 0
fromcount = 0
try:
func_info = self.funcMapper.funcAt(va_to_rva(ea))
tocount = len(func_info.refs_list)
fromcount = len(func_info.called_list)
except KeyError:
pass
self.refs_tabs.setTabText(0, "Is referred by %d:" % tocount)
self.refs_tabs.setTabText(1, "Refers to %d:" % fromcount)
def adjustColumnsToContents(self) -> None:
"""Adjusts columns' sizes to fit the data.
"""
self.addr_view.resizeColumnToContents(0)
self.addr_view.resizeColumnToContents(1)
self.addr_view.resizeColumnToContents(2)
#
self.addr_view.resizeColumnToContents(5)
self.addr_view.resizeColumnToContents(6)
self.addr_view.resizeColumnToContents(7)
# public
# @pyqtSlot()
def longoperationcomplete(self) -> None:
"""A callback executed when the current RVA has changed.
"""
global g_DataManager
data = g_DataManager.currentRva
self.setRefOffset(data)
def setRefOffset(self, data: Any) -> None:
"""Updates the views to follow to the given RVA.
"""
if not data:
return
self._update_current_offset(self.refs_view, self.refsto_model, data)
self._update_current_offset(self.refsfrom_view, self.refsfrom_model, data)
self._update_ref_tabs(data)
self._update_function_name(data)
def filterByColumn(self, col_num, str) -> None:
"""Applies a filter defined by the string on data model.
"""
filter_type = QtCore.QRegExp.FixedString
sensitivity = QtCore.Qt.CaseInsensitive
if self.criterium_id != 0:
filter_type = QtCore.QRegExp.RegExp
self.addr_sorted_model.setFilterRegExp(QtCore.QRegExp(str, sensitivity, filter_type))
self.addr_sorted_model.setFilterKeyColumn(col_num)
def filterChanged(self) -> None:
"""A wrapper for the function: filterByColumn(self, col_num, str)
"""
self.filterByColumn(self.filter_combo.currentIndex(), self.filter_edit.text())
def filterKeyEvent(self, event: Any = None) -> None:
if event is not None:
QtWidgets.QLineEdit.keyReleaseEvent(self.filter_edit, event)
if event and (not self.is_livefilter and event.key() != QtCore.Qt.Key_Enter and event.key() != QtCore.Qt.Key_Return):
return
self.filterChanged()
def criteriumChanged(self) -> None:
"""A callback executed when the criterium of sorting has changed and the data has to be sorted again.
"""
self.criterium_id = self.criterium_combo.currentIndex()
if self.criterium_id == 0:
self.filter_edit.setPlaceholderText("keyword")
else:
self.filter_edit.setPlaceholderText("regex")
self.filterChanged()
def liveSearchCheckBox(self) -> None:
self.is_livefilter = self.livefilter_box.isChecked()
if self.is_livefilter:
self.filterByColumn(self.filter_combo.currentIndex(), self.filter_edit.text())
def alternateRowColors(self, enable):
self.refsfrom_view.setAlternatingRowColors(enable)
self.addr_view.setAlternatingRowColors(enable)
self.refs_view.setAlternatingRowColors(enable)
def OnCreate(self, form) -> None:
"""Called when the plugin form is created
"""
# init data structures:
self.funcMapper = FunctionsMapper_t()
self.criterium_id = 0
# Get parent widget
self.parent = self.FormToPyQtWidget(form)
# Create models
self.subDataManager = DataManager()
self.table_model = TableModel_t(self.funcMapper.funcList)
# init
self.addr_sorted_model = QtCore.QSortFilterProxyModel()
self.addr_sorted_model.setDynamicSortFilter(True)
self.addr_sorted_model.setSourceModel(self.table_model)
self.addr_view = FunctionsView_t(g_DataManager, COLOR_HILIGHT_FUNC, self.table_model)
self.addr_view.setModel(self.addr_sorted_model)
self.addr_view.setSortingEnabled(True)
self.addr_view.setWordWrap(False)
self.addr_view.horizontalHeader().setStretchLastSection(False)
self.addr_view.verticalHeader().show()
self.adjustColumnsToContents()
#
self.refsto_model = RefsTableModel_t(self.funcMapper.funcList, True)
self.refs_view = FunctionsView_t(self.subDataManager, COLOR_HILIGHT_REFTO, self.refsto_model)
self._setup_sorted_model(self.refs_view, self.refsto_model)
self.refs_view.setColumnHidden(RefsTableModel_t.COL_TOADDR, True)
self.refs_view.setWordWrap(False)
font = self.refs_view.font()
font.setPointSize(8)
self.refs_view.setFont(font)
self.refsfrom_model = RefsTableModel_t(self.funcMapper.funcList, False)
self.refsfrom_view = FunctionsView_t(self.subDataManager, COLOR_HILIGHT_REFFROM, self.refsfrom_model)
self._setup_sorted_model(self.refsfrom_view, self.refsfrom_model)
self.refsfrom_view.setColumnHidden(RefsTableModel_t.COL_TOADDR, True)
self.refsfrom_view.setWordWrap(False)
# add a box to enable/disable live filtering
self.livefilter_box = QtWidgets.QCheckBox("Live filtering")
self.livefilter_box.setToolTip("If live filtering is enabled, functions are searched as you type in the edit box.\nOtherwise they are searched when you press Enter.")
self.livefilter_box.setChecked(self._LIVE_FILTER)
self.is_livefilter = self._LIVE_FILTER
# connect SIGNAL
self.livefilter_box.stateChanged.connect(self.liveSearchCheckBox)
# important for proper order of objects destruction:
self.table_model.setParent(self.addr_sorted_model)
self.addr_sorted_model.setParent(self.addr_view)
# connect SIGNAL
g_DataManager.updateSignal.connect(self.longoperationcomplete)
# Create a Tab widget for references:
self.refs_tabs = QtWidgets.QTabWidget()
self.refs_tabs.insertTab(0, self.refs_view, "Is refered by")
self.refs_tabs.insertTab(1, self.refsfrom_view, "Refers to")
# Create filter
self.filter_edit = QtWidgets.QLineEdit()
self.filter_edit.setPlaceholderText("keyword")
self.filter_edit.keyReleaseEvent = self.filterKeyEvent
self.filter_combo = QtWidgets.QComboBox()
self.filter_combo.addItems(TableModel_t.header_names)
self.filter_combo.setCurrentIndex(TableModel_t.COL_NAME)
# connect SIGNAL
self.filter_combo.activated.connect(self.filterChanged)
self.criterium_combo = QtWidgets.QComboBox()
criteria = ["contains", "matches"]
self.criterium_combo.addItems(criteria)
self.criterium_combo.setCurrentIndex(0)
# connect SIGNAL
self.criterium_combo.activated.connect(self.criteriumChanged)
filter_panel = QtWidgets.QFrame()
filter_layout = QtWidgets.QHBoxLayout()
filter_layout.addWidget(QtWidgets.QLabel("Where "))
filter_layout.addWidget(self.filter_combo)
filter_layout.addWidget(self.criterium_combo)
filter_layout.addWidget(self.filter_edit)
filter_panel.setLayout(filter_layout)
self.filter_edit.setFixedHeight(20)
filter_panel.setFixedHeight(40)
filter_panel.setAutoFillBackground(True)
self.refs_label = QtWidgets.QLabel("Function")
self.refs_label.setTextFormat(QtCore.Qt.RichText)
self.refs_label.setWordWrap(True)
panel1 = QtWidgets.QFrame()
layout1 = QtWidgets.QVBoxLayout()
panel1.setLayout(layout1)
layout1.addWidget(filter_panel)
layout1.addWidget(self.livefilter_box)
layout1.addWidget(self.addr_view)
layout1.setContentsMargins(0, 0, 0, 0)
panel2 = QtWidgets.QFrame()
layout2 = QtWidgets.QVBoxLayout()
layout2.addWidget(self.refs_label)
layout2.addWidget(self.refs_tabs)
layout2.addWidget(self._makeButtonsPanel())
layout2.setContentsMargins(0, 10, 0, 0)
panel2.setLayout(layout2)
self.main_splitter = QtWidgets.QSplitter()
self.main_splitter.setOrientation(QtCore.Qt.Vertical)
self.main_splitter.addWidget(panel1)
self.main_splitter.addWidget(panel2)
# Populate PluginForm
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.main_splitter)
layout.setSpacing(0)
layout.setContentsMargins(0, 0, 0, 0)
self.parent.setLayout(layout)
self.alternateRowColors(IS_ALTERNATE_ROW)
idaapi.set_dock_pos(PLUGIN_NAME, None, idaapi.DP_RIGHT)
def _makeButtonsPanel(self) -> QtWidgets.QFrame:
"""Creates on the form's bottom the panel with buttons.
"""
buttons_panel = QtWidgets.QFrame()
buttons_layout = QtWidgets.QHBoxLayout()
buttons_panel.setLayout(buttons_layout)
importButton = QtWidgets.QPushButton("Load names")
importButton.clicked.connect(self.importNames)
buttons_layout.addWidget(importButton)
exportButton = QtWidgets.QPushButton("Save names")
exportButton.clicked.connect(self.exportNames)
buttons_layout.addWidget(exportButton)
return buttons_panel
def importNames(self) -> None:
"""Imports functions list from a file.
"""
file_name, ext = QtWidgets.QFileDialog.getOpenFileName(None, "Import functions names", QtCore.QDir.homePath(), "CSV Files (*.csv);;TAG Files: PE-bear, PE-sieve compatibile (*.tag);;IMPORTS.TXT: generated by PE-sieve (*.imports.txt);;All files (*)")
if file_name is not None and len(file_name) > 0:
| |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import cPickle
from ConfigParser import ConfigParser
import numpy as np
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg
from pylab import Figure
from CoolProp.HumidAirProp import HAProps, HAProps_Aux
from PyQt4.QtGui import (QDialog, QGridLayout, QProgressBar, QLabel,
QDialogButtonBox, QPushButton, QFileDialog, QApplication)
Preferences = ConfigParser()
config_path = os.path.join(os.path.dirname(__file__), "psyrc")
Preferences.read(config_path)
P = Preferences.getfloat("General", "P")
def _Pbar(Z):
"""
ASHRAE Fundamentals Handbook pag 1.1 eq. 3
input:
Z: altitude, m
return
standard atmosphere barometric pressure, Pa
"""
return 101325. * (1 - 2.25577e-5 * Z)**5.256
class PsychroPlot(FigureCanvasQTAgg):
"""
Plot widget for psychrometric chart
Add custom margins
Define a pointer to text state properties, to remove and redraw
"""
def __init__(self, parent=None, width=15, height=5, dpi=100):
self.fig = Figure(figsize=(width, height), dpi=dpi)
FigureCanvasQTAgg.__init__(self, self.fig)
self.setParent(parent)
self.axes2D = self.fig.add_subplot(111)
FigureCanvasQTAgg.updateGeometry(self)
self.axes2D.figure.subplots_adjust(left=0.01, right=0.92,
bottom=0.05, top=0.98)
self.notes = []
def plot(self, *args, **kwargs):
self.axes2D.plot(*args, **kwargs)
def config(self):
self.axes2D.set_autoscale_on(False)
self.axes2D.set_xlabel(u"Tdb, ºC")
self.axes2D.set_ylabel("Absolute humidity, kg/kg")
self.axes2D.yaxis.set_ticks_position("right")
self.axes2D.yaxis.set_label_position("right")
tmin = Preferences.getfloat("Psychr", "isotdbStart") - 273.15
tmax = Preferences.getfloat("Psychr", "isotdbEnd") - 273.15
self.axes2D.set_xlim(tmin, tmax)
self.axes2D.set_ylim(0, 0.04)
def showPointData(self, state):
self.clearPointData()
yi = 0.99
keys = "tdb", "tdp", "twb", "HR", "w", "h", "v", "rho"
units = u"ºC", u"ºC", u"ºC", "%", "kgw/kgda", "kJ/kg", u"m³/kg", u"kg/m³"
for key, txt in zip(keys, units):
self.notes.append(self.axes2D.annotate(
"%s: %0.4f %s" % (key, state.__getattribute__(key), txt), (0.01, yi),
xycoords='axes fraction', size="small", va="center"))
yi -= 0.025
self.draw()
def clearPointData(self):
while self.notes:
anotation = self.notes.pop()
anotation.remove()
self.draw()
class PsyCoolprop(object):
"""
Psychrometric state using coolprop library
kwargs definition parameters:
P: Pressure, Pa
z: altitude, m
tdp: dew-point temperature
tdb: dry-bulb temperature
twb: web-bulb temperature
w: Humidity Ratio [kg water/kg dry air]
HR: Relative humidity
h: Mixture enthalpy
v: Mixture specified volume
P: mandatory input for barometric pressure, z is an alternate pressure input
it needs other two input parameters:
0 - tdb, w
1 - tdb, HR
2 - tdb, twb
3 - tdb, tdp
4 - tdp, HR
5 - tdp, twb
6 - twb, w
"""
kwargs = {"z": 0.0,
"P": 0.0,
"tdb": 0.0,
"tdb": 0.0,
"twb": 0.0,
"w": None,
"HR": None,
"h": None,
"v": 0.0}
status = 0
msg = "Unknown variables"
def __init__(self, **kwargs):
self.kwargs = self.__class__.kwargs.copy()
self.__call__(**kwargs)
def __call__(self, **kwargs):
self.kwargs.update(kwargs)
if self.calculable:
self.status = 1
self.calculo()
self.msg = "Solved"
@property
def calculable(self):
tdp = self.kwargs.get("tdp", 0)
tdb = self.kwargs.get("tdb", 0)
twb = self.kwargs.get("twb", 0)
w = self.kwargs.get("w", None)
HR = self.kwargs.get("HR", None)
h = self.kwargs.get("h", None)
v = self.kwargs.get("v", 0)
self._mode = 0
if tdb and w is not None:
self._mode = ("Tdb", "W")
elif tdb and HR is not None:
self._mode = ("Tdb", "RH")
elif tdb and twb:
self._mode = ("Tdb", "Twb")
elif tdb and tdp:
self._mode = ("Tdb", "Tdp")
elif tdp and HR is not None:
self._mode = ("Tdp", "RH")
return bool(self._mode)
def calculo(self):
tdp, tdb, twb, P, Pvs, Pv, ws, w, HR, v, h = self._lib()
self.tdp = tdp - 273.15
self.tdb = tdb - 273.15
self.twb = twb - 273.15
self.P = P
self.Pvs = Pvs
self.Pv = Pv
self.ws = ws
self.w = w
self.HR = HR
self.mu = w / ws * 100
self.v = v
self.rho = 1 / v
self.h = h
self.Xa = 1 / (1 + self.w / 0.62198)
self.Xw = 1 - self.Xa
def args(self):
# Correct coolprop custom namespace versus pychemqt namespace
if "Tdb" in self._mode:
self.kwargs["Tdb"] = self.kwargs["tdb"]
if "Twb" in self._mode:
self.kwargs["Twb"] = self.kwargs["twb"]
if "Tdp" in self._mode:
self.kwargs["Tdp"] = self.kwargs["tdp"]
if "RH" in self._mode:
self.kwargs["RH"] = self.kwargs["HR"]
if "W" in self._mode:
self.kwargs["W"] = self.kwargs["w"]
var1 = self.kwargs[self._mode[0]]
var2 = self.kwargs[self._mode[1]]
# units conversion to coolprop expected unit:
# HR in 0-1, H in kJ/kg, S in kJ/kgK
if "RH" in self._mode[0]:
var1 /= 100.
if "RH" in self._mode[1]:
var2 /= 100.
args = ("P", self._P_kPa, self._mode[0], var1, self._mode[1], var2)
return args
def _P(self):
"""Barometric pressure calculation, Pa"""
if self.kwargs["P"]:
P = self.kwargs["P"]
elif self.kwargs["z"]:
P = _Pbar(self.kwargs["z"])
else:
P = 101325.
return P
@property
def _P_kPa(self):
"""Property for ease access to pressure in kPa"""
P = self._P()
return P / 1000.
def _lib(self):
args = self.args()
P = self._P()
if "Tdb" in self._mode:
tdb = self.kwargs["Tdb"]
else:
tdb = HAProps("Tdb", *args)
tdp = HAProps("Tdp", *args)
twb = HAProps("Twb", *args)
w = HAProps("W", *args)
HR = HAProps("RH", *args) * 100
Pvs = HAProps_Aux("p_ws", tdb, self._P_kPa, w)[0] * 1000
Pv = Pvs * HR / 100
ws = HAProps("W", "P", self._P_kPa, "Tdb", tdb, "RH", 1)
v = HAProps("V", *args)
h = HAProps("H", *args)
return tdp, tdb, twb, P, Pvs, Pv, ws, w, HR, v, h
@classmethod
def calculatePlot(cls, parent):
"""Function to calculate points in chart"""
data = {}
P = Preferences.getfloat("General", "P")
P_kPa = P / 1000
t = cls.LineList("isotdb", Preferences)
# Saturation line
Hs = []
for tdb in t:
Hs.append(HAProps("W", "P", P_kPa, "Tdb", tdb, "RH", 1))
parent.progressBar.setValue(5 * len(Hs) / len(t))
data["t"] = t
data["Hs"] = Hs
# left limit of isow lines
H = cls.LineList("isow", Preferences)
th = []
for w in H:
if w:
tdp = HAProps("Tdp", "P", 101.325, "W", w, "RH", 1)
th.append(tdp - 273.15)
else:
tmin = Preferences.getfloat("Psychr", "isotdbStart")
th.append(tmin - 273.15)
data["H"] = H
data["th"] = th
# Humidity ratio lines
hr = cls.LineList("isohr", Preferences)
Hr = {}
cont = 0
for i in hr:
Hr[i] = []
for tdb in t:
Hr[i].append(HAProps("W", "P", P_kPa, "Tdb", tdb, "RH", i / 100.))
cont += 1
parent.progressBar.setValue(5 + 10 * cont / len(hr) / len(Hs))
data["Hr"] = Hr
# Twb
lines = cls.LineList("isotwb", Preferences)
Twb = {}
cont = 0
for T in lines:
ws = HAProps("W", "P", P_kPa, "RH", 1, "Tdb", T)
H = [ws, 0]
Tw = [T - 273.15, HAProps("Tdb", "P", P_kPa, "Twb", T, "RH", 0) - 273.15]
cont += 1
parent.progressBar.setValue(15 + 75 * cont / len(lines))
Twb[T] = (H, Tw)
data["Twb"] = Twb
# v
lines = cls.LineList("isochor", Preferences)
V = {}
rh = np.arange(1, -0.05, -0.05)
for cont, v in enumerate(lines):
w = []
Td = []
for r in rh:
w.append(HAProps("W", "P", P_kPa, "RH", r, "V", v))
Td.append(HAProps("Tdb", "P", P_kPa, "RH", r, "V", v) - 273.15)
parent.progressBar.setValue(90 + 10 * cont / len(lines))
V[v] = (Td, w)
data["v"] = V
return data
@staticmethod
def LineList(name, Preferences):
"""Return a list with the values of isoline name to plot"""
if Preferences.getboolean("Psychr", name + "Custom"):
t = []
for i in Preferences.get("Psychr", name + 'List').split(','):
if i:
t.append(float(i))
else:
start = Preferences.getfloat("Psychr", name + "Start")
end = Preferences.getfloat("Psychr", name + "End")
step = Preferences.getfloat("Psychr", name + "Step")
t = np.arange(start, end, step)
return t
class UI_Psychrometry(QDialog):
"""Psychrometric charts tool"""
def __init__(self, parent=None):
super(UI_Psychrometry, self).__init__(parent)
self.showMaximized()
self.setWindowTitle("Psychrometric chart")
layout = QGridLayout(self)
self.diagrama2D = PsychroPlot(self, dpi=90)
self.diagrama2D.fig.canvas.mpl_connect('motion_notify_event', self.scroll)
layout.addWidget(self.diagrama2D, 1, 1, 1, 2)
self.progressBar = QProgressBar()
self.progressBar.setVisible(False)
layout.addWidget(self.progressBar, 2, 1)
self.status = QLabel()
layout.addWidget(self.status, 2, 1)
self.buttonBox = QDialogButtonBox(QDialogButtonBox.Close)
butonPNG = QPushButton("Save as PNG")
self.buttonBox.addButton(butonPNG, QDialogButtonBox.AcceptRole)
self.buttonBox.rejected.connect(self.reject)
self.buttonBox.accepted.connect(self.savePNG)
layout.addWidget(self.buttonBox, 2, 2)
self.plot()
def savePNG(self):
"""Save chart image to png file"""
fname = unicode(QFileDialog.getSaveFileName(
self, "Save chart to file",
"./", "Portable Network Graphics (*.png)"))
self.diagrama2D.fig.savefig(fname, facecolor='#eeeeee')
def drawlabel(self, name, Preferences, t, W, label, unit):
"""
Draw annotation for isolines
name: name of isoline
Preferences: Configparse instance of pychemqt preferences
t: x array of line
W: y array of line
label: text value to draw
unit: text units to draw
"""
if Preferences.getboolean("Psychr", name + "label"):
tmin = Preferences.getfloat("Psychr", "isotdbStart") - 273.15
tmax = Preferences.getfloat("Psychr", "isotdbEnd") - 273.15
x = tmax - tmin
wmin = Preferences.getfloat("Psychr", "isowStart")
wmax = Preferences.getfloat("Psychr", "isowEnd")
y = wmax - wmin
i = 0
for ti, wi in zip(t, W):
if tmin <= ti <= tmax and wmin <= wi <= wmax:
i += 1
label = str(label)
if Preferences.getboolean("Psychr", name + "units"):
label += unit
pos = Preferences.getfloat("Psychr", name + "position")
p = int(i * pos / 100 - 1)
rot = np.arctan((W[p] - W[p - 1]) / y / (t[p] - t[p - 1]) * x) * 360.0 / 2.0 / | |
# coding: utf-8
"""
Workflow Execution Service
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from libica.openapi.libwes.api_client import ApiClient
from libica.openapi.libwes.exceptions import ( # noqa: F401
ApiTypeError,
ApiValueError
)
class WorkflowRunsApi(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def abort_workflow_run(self, run_id, **kwargs): # noqa: E501
"""Abort a workflow run # noqa: E501
Aborts the workflow run with a given ID. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.abort_workflow_run(run_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str run_id: ID of the workflow run (required)
:param list[str] include: Comma-separated list of properties to include in the response
:param AbortWorkflowRunRequest body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: WorkflowRun
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.abort_workflow_run_with_http_info(run_id, **kwargs) # noqa: E501
def abort_workflow_run_with_http_info(self, run_id, **kwargs): # noqa: E501
"""Abort a workflow run # noqa: E501
Aborts the workflow run with a given ID. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.abort_workflow_run_with_http_info(run_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str run_id: ID of the workflow run (required)
:param list[str] include: Comma-separated list of properties to include in the response
:param AbortWorkflowRunRequest body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(WorkflowRun, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'run_id',
'include',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method abort_workflow_run" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'run_id' is set
if self.api_client.client_side_validation and ('run_id' not in local_var_params or # noqa: E501
local_var_params['run_id'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `run_id` when calling `abort_workflow_run`") # noqa: E501
collection_formats = {}
path_params = {}
if 'run_id' in local_var_params:
path_params['runId'] = local_var_params['run_id'] # noqa: E501
query_params = []
if 'include' in local_var_params and local_var_params['include'] is not None: # noqa: E501
query_params.append(('include', local_var_params['include'])) # noqa: E501
collection_formats['include'] = 'csv' # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/json', 'text/json', 'application/*+json']) # noqa: E501
# Authentication setting
auth_settings = ['Bearer'] # noqa: E501
return self.api_client.call_api(
'/v1/workflows/runs/{runId}:abort', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='WorkflowRun', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def get_workflow_run(self, run_id, **kwargs): # noqa: E501
"""Get the details of a workflow run # noqa: E501
Gets the details of a workflow run with a given ID. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_workflow_run(run_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str run_id: ID of the workflow run (required)
:param list[str] include: Comma-separated list of properties to include in the response
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: WorkflowRun
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.get_workflow_run_with_http_info(run_id, **kwargs) # noqa: E501
def get_workflow_run_with_http_info(self, run_id, **kwargs): # noqa: E501
"""Get the details of a workflow run # noqa: E501
Gets the details of a workflow run with a given ID. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_workflow_run_with_http_info(run_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str run_id: ID of the workflow run (required)
:param list[str] include: Comma-separated list of properties to include in the response
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(WorkflowRun, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'run_id',
'include'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method get_workflow_run" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'run_id' is set
if self.api_client.client_side_validation and ('run_id' not in local_var_params or # noqa: E501
local_var_params['run_id'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `run_id` when calling `get_workflow_run`") # noqa: E501
collection_formats = {}
path_params = {}
if 'run_id' in local_var_params:
path_params['runId'] = local_var_params['run_id'] # noqa: E501
query_params = []
if 'include' in local_var_params and local_var_params['include'] is not None: # noqa: E501
query_params.append(('include', local_var_params['include'])) # noqa: E501
collection_formats['include'] = 'csv' # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['Bearer'] # noqa: E501
return self.api_client.call_api(
'/v1/workflows/runs/{runId}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='WorkflowRun', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_workflow_run_history(self, run_id, **kwargs): # noqa: E501
"""Get a list of workflow run history events # noqa: E501
Gets a list of history events for a workflow run with a given ID. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_workflow_run_history(run_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str run_id: ID of the workflow run (required)
:param str sort:
:param list[str] include: Comma-separated list of properties to include in the response
:param int page_size: Number of items to include in a page. Value must be an integer between 1 and 1000. Only one of pageSize or pageToken can be specified.
:param str page_token: Page offset descriptor. Valid page tokens are included in the response. Only one of pageSize or pageToken can be specified.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: WorkflowRunHistoryEventList
If the method is called asynchronously,
returns | |
<filename>pyale/meta.py
# emacs: at the end of the file
# ex: set sts=4 ts=4 sw=4 et:
"""
ALE-related meta-analysis tools.
TODO: Improve conventions.
A few in-function suffix conventions:
- _values: 1d array matching dimensions of prior (211590). Filled with
meaningful values
- _vector: 1d array matching dimensions of prior. Not filled with values
(probably boolean-like or labels)
- _matrix: 3d array matching dimensions of template image (91, 109, 91)
- _mat: nd array *not* matching dimensions of template image
- _arr: 1d array *not* matching dimensions of prior
"""
from __future__ import division, print_function
import os
import copy
import numba
from time import time
import multiprocessing as mp
import numpy as np
from scipy import ndimage
from scipy.special import ndtri
from .due import due, Doi
from .utils import (round2, read_nifti, save_nifti, thresh_str,
get_resource_path, cite_mni152)
@due.dcite(Doi('10.1002/hbm.20718'),
description='Introduces the ALE algorithm.')
@due.dcite(Doi('10.1002/hbm.21186'),
description='Modifies ALE algorithm to eliminate within-experiment '
'effects and generate MA maps based on subject group '
'instead of experiment.')
@due.dcite(Doi('10.1016/j.neuroimage.2011.09.017'),
description='Modifies ALE algorithm to allow FWE correction and to '
'more quickly and accurately generate the null '
'distribution for significance testing.')
def ale(dataset, n_cores=1, voxel_thresh=0.001, clust_thresh=0.05,
corr='FWE', n_iters=10000, verbose=True, plot_thresh=True, prefix='',
template_file='Grey10.nii.gz'):
"""
Perform activation likelihood estimation[1]_[2]_[3]_ meta-analysis on dataset.
General steps:
- Create ALE image
- Create null distribution
- Convert ALE to Z/p
- Voxel-level threshold image
- Perform iterations for FWE correction
- Cluster-extent threshold image
Parameters
----------
dataset : ale.Dataset
Dataset to analyze.
voxel_thresh : float
Uncorrected voxel-level threshold.
clust_thresh : float
Corrected threshold. Used for both voxel- and cluster-level FWE.
corr : str
Correction type. Currently supported: FWE.
n_iters : int
Number of iterations for correction. Default 10000
verbose : bool
If True, prints out status updates.
prefix : str
String prepended to default output filenames. May include path.
Examples
----------
References
----------
.. [1] <NAME>., <NAME>., <NAME>., <NAME>.,
<NAME>., & <NAME>. (2009). Coordinate-based activation likelihood
estimation meta-analysis of neuroimaging data: A random-effects
approach based on empirical estimates of spatial uncertainty.
Human brain mapping, 30(9), 2907-2926.
.. [2] <NAME>., <NAME>., <NAME>., <NAME>.,
<NAME>., & <NAME>. (2012). Minimizing within-experiment and
within-group effects in activation likelihood estimation
meta-analyses. Human brain mapping, 33(1), 1-13.
.. [3] <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>.
(2012). Activation likelihood estimation meta-analysis revisited.
Neuroimage, 59(3), 2349-2361.
"""
name = dataset.name
experiments = dataset.experiments
# Cite MNI152 paper if default template is used
if template_file == 'Grey10.nii.gz':
cite_mni152()
# Check path for template file
if not os.path.dirname(template_file):
template_file = os.path.join(get_resource_path(), template_file)
max_cores = mp.cpu_count()
if not 1 <= n_cores <= max_cores:
print('Desired number of cores ({0}) outside range of acceptable values. '
'Setting number of cores to max ({1}).'.format(n_cores, max_cores))
n_cores = max_cores
if prefix == '':
prefix = name
if os.path.basename(prefix) == '':
prefix_sep = ''
else:
prefix_sep = '_'
max_poss_ale = 1
for exp in experiments:
max_poss_ale *= (1 - np.max(exp.kernel))
max_poss_ale = 1 - max_poss_ale
hist_bins = np.round(np.arange(0, max_poss_ale+0.001, 0.0001), 4)
# Compute ALE values
template_data, affine = read_nifti(template_file)
dims = template_data.shape
template_arr = template_data.flatten()
prior = np.where(template_arr != 0)[0]
shape = dims + np.array([30, 30, 30])
# Gray matter coordinates
perm_ijk = np.where(template_data)
perm_ijk = np.vstack(perm_ijk).transpose()
ale_values, null_distribution = _compute_ale(experiments, dims, shape, prior, hist_bins)
p_values, z_values = _ale_to_p(ale_values, hist_bins, null_distribution)
# Write out unthresholded value images
out_images = {'ale': ale_values,
'p': p_values,
'z': z_values,}
for (f, vals) in out_images.items():
mat = np.zeros(dims).ravel()
mat[prior] = vals
mat = mat.reshape(dims)
thresh_suffix = '{0}.nii.gz'.format(f)
filename = prefix + prefix_sep + thresh_suffix
save_nifti(mat, filename, affine)
if verbose:
print('File {0} saved.'.format(filename))
# Begin cluster-extent thresholding by thresholding matrix at cluster-
# defining voxel-level threshold
z_thresh = ndtri(1-voxel_thresh)
sig_idx = np.where(z_values > z_thresh)[0]
sig_vector = np.zeros(prior.shape)
sig_vector[sig_idx] = 1
sig_matrix = np.zeros(dims).ravel()
sig_matrix[prior] = sig_vector
sig_matrix = sig_matrix.reshape(dims)
out_vector = np.zeros(prior.shape)
out_vector[sig_idx] = z_values[sig_idx]
out_matrix = np.zeros(dims).ravel()
out_matrix[prior] = out_vector
out_matrix = out_matrix.reshape(dims)
thresh_suffix = 'thresh_{0}unc.nii.gz'.format(thresh_str(voxel_thresh))
filename = prefix + prefix_sep + thresh_suffix
save_nifti(out_matrix, filename, affine)
if verbose:
print('File {0} saved.'.format(filename))
# Find number of voxels per cluster (includes 0, which is empty space in
# the matrix)
conn_mat = np.ones((3, 3, 3)) # 18 connectivity
for i in [0, -1]:
for j in [0, -1]:
for k in [0, -1]:
conn_mat[i, j, k] = 0
labeled_matrix = ndimage.measurements.label(sig_matrix, conn_mat)[0]
labeled_vector = labeled_matrix.flatten()
labeled_vector = labeled_vector[prior]
clust_sizes = [len(np.where(labeled_vector == val)[0]) for val in np.unique(labeled_vector)]
clust_sizes = clust_sizes[1:] # First is zeros
## Multiple comparisons correction
if corr == 'FWE':
if verbose:
print('Performing FWE correction.')
rd_experiments = copy.deepcopy(experiments)
results = _FWE_correction(rd_experiments, perm_ijk, null_distribution, hist_bins,
prior, dims, n_cores, voxel_thresh, n_iters)
rd_max_ales, rd_clust_sizes = zip(*results)
percentile = 100 * (1 - clust_thresh)
# Generate plot of threshold convergence
if plot_thresh:
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('whitegrid')
plot_range = range(100, n_iters+1)
cFWE_thresholds = np.empty(len(plot_range))
vFWE_thresholds = np.empty(len(plot_range))
for i, n in enumerate(plot_range):
cFWE_thresholds[i] = np.percentile(rd_clust_sizes[:n], percentile)
vFWE_thresholds[i] = np.percentile(rd_max_ales[:n], percentile)
fig, axes = plt.subplots(2, sharex=True)
axes[0].plot(plot_range, cFWE_thresholds, 'b')
axes[0].set_ylabel('Minimum Cluster Size')
axes[1].plot(plot_range, vFWE_thresholds, 'r')
axes[1].set_ylabel('Minimum ALE Value')
axes[1].set_xlabel('Number of FWE Iterations')
fig.suptitle(os.path.basename(prefix), fontsize=20)
fig.savefig(prefix+prefix_sep+'thresholds.png', dpi=400)
## Cluster-level FWE
# Determine size of clusters in [1 - clust_thresh]th percentile (e.g. 95th)
clust_size_thresh = np.percentile(rd_clust_sizes, percentile)
sig_values = np.zeros(prior.shape)
for i, clust_size in enumerate(clust_sizes):
if clust_size >= clust_size_thresh:
clust_idx = np.where(labeled_vector == i+1)[0]
sig_values[clust_idx] = z_values[clust_idx]
sig_matrix = np.zeros(dims).ravel()
sig_matrix[prior] = sig_values
sig_matrix = sig_matrix.reshape(dims)
thresh_suffix = 'thresh_{0}cFWE_{1}unc.nii.gz'.format(thresh_str(clust_thresh),
thresh_str(voxel_thresh))
filename = prefix + prefix_sep + thresh_suffix
save_nifti(sig_matrix, filename, affine)
if verbose:
print('File {0} saved.'.format(filename))
## Voxel-level FWE
# Determine ALE values in [1 - clust_thresh]th percentile (e.g. 95th)
ale_value_thresh = np.percentile(rd_max_ales, percentile)
sig_idx = ale_values >= ale_value_thresh
sig_values = z_values * sig_idx
sig_matrix = np.zeros(dims).ravel()
sig_matrix[prior] = sig_values
sig_matrix = sig_matrix.reshape(dims)
thresh_suffix = 'thresh_{0}vFWE.nii.gz'.format(thresh_str(clust_thresh))
filename = prefix + prefix_sep + thresh_suffix
save_nifti(sig_matrix, filename, affine)
if verbose:
print('File {0} saved.'.format(filename))
elif corr == 'FDR':
print('Performing false discovery rate correction.')
_FDR_correction()
elif corr == 'TFCE':
print('Performing threshold-free cluster enhancement.')
_TFCE_correction()
else:
raise Exception('Unknown correction option: "{0}".'.format(corr))
@due.dcite(Doi('10.1016/j.neuroimage.2014.06.007'),
description='Introduces the specific co-activation likelihood '
'estimation (SCALE) algorithm.')
def scale(dataset, n_cores=1, voxel_thresh=0.001, n_iters=2500, verbose=True,
prefix='', database_file='grey_matter_ijk.txt',
template_file='Grey10.nii.gz'):
"""
Perform specific coactivation likelihood estimation[1]_ meta-analysis on dataset.
Parameters
----------
dataset : ale.Dataset
Dataset to analyze.
voxel_thresh : float
Uncorrected voxel-level threshold.
n_iters : int
Number of iterations for correction. Default 2500
verbose : bool
If True, prints out status updates.
prefix : str
String prepended to default output filenames. May include path.
database_file : str
Tab-delimited file of coordinates from database. Voxels are rows and
i, j, k (meaning matrix-space) values are the three columnns.
Examples
----------
References
----------
.. [1] <NAME>., <NAME>., <NAME>., <NAME>., &
<NAME>. (2014). Meta-analytic connectivity modeling
revisited: controlling for activation base rates.
NeuroImage, 99, 559-570.
"""
name = dataset.name
experiments = dataset.experiments
# Cite MNI152 paper if default template is used
if template_file == 'Grey10.nii.gz':
cite_mni152()
# Check paths for input files
if not os.path.dirname(template_file):
template_file = os.path.join(get_resource_path(), template_file)
if not os.path.dirname(database_file):
database_file = os.path.join(get_resource_path(), database_file)
max_cores = mp.cpu_count()
if not 1 <= n_cores <= max_cores:
print('Desired number of cores ({0}) outside range of acceptable values. '
'Setting number of cores to max ({1}).'.format(n_cores, max_cores))
n_cores = max_cores
if prefix == '':
prefix = name
if os.path.basename(prefix) == '':
prefix_sep = ''
else:
prefix_sep = '_'
max_poss_ale = 1
for exp in experiments:
max_poss_ale *= (1 - np.max(exp.kernel))
max_poss_ale = 1 - max_poss_ale
hist_bins = np.round(np.arange(0, max_poss_ale+0.001, 0.0001), 4)
# Compute ALE values
template_data, affine = read_nifti(template_file)
dims = template_data.shape
template_arr = template_data.flatten()
prior = np.where(template_arr != 0)[0]
shape = dims + np.array([30, 30, 30])
database_ijk = np.loadtxt(database_file, dtype=int)
if len(database_ijk.shape) != 2 or database_ijk.shape[-1] != 3:
raise Exception('Database coordinates not in voxelsX3 shape.')
elif np.any(database_ijk < 0):
raise Exception('Negative value(s) detected. Database coordinates must '
'be in matrix space.')
elif not np.all(np.equal(np.mod(database_ijk, 1), 0)): # pylint: disable=no-member
raise Exception('Float(s) detected. Database coordinates must all be '
'integers.')
ale_values, _ = _compute_ale(experiments, dims, shape, prior)
n_foci = np.sum([exp.ijk.shape[0] for exp in experiments])
np.random.seed(0) # pylint: disable=no-member
rand_idx = np.random.choice(database_ijk.shape[0], size=(n_foci, n_iters)) # pylint: disable=no-member
rand_ijk | |
can only add compute to existing"
f" collections."
)
def add_compute(
self,
dataset_name: str,
client: Union[str, FractalClient],
await_result: bool = False,
) -> None:
"""
A method that can add compute to an existing collection, this involves registering the QM settings and keywords
and running the compute.
Parameters:
dataset_name: The name of the collection in the qcarchive instance that the compute should be added to.
await_result: If the function should block until the calculations have finished.
client: The name of the file containing the client information or the client instance.
"""
import qcportal as ptl
target_client = self._activate_client(client)
collection = self._get_collection(
dataset_type="Dataset", dataset_name=dataset_name, client=target_client
)
kw = ptl.models.KeywordSet(
values=self.dict(include={"maxiter", "scf_properties"})
)
try:
# try add the keywords, if we get an error they have already been added.
collection.add_keywords(
alias=self.spec_name, program=self.program, keyword=kw, default=False
)
# save the keywords
collection.save()
except (KeyError, AttributeError):
pass
# submit the calculations
response = collection.compute(
method=self.method,
basis=self.basis,
keywords=self.spec_name,
program=self.program,
tag=self.compute_tag,
priority=self.priority,
)
collection.save()
return response
def _create_initial_component_result(
self, molecules: Union[str, off.Molecule, List[off.Molecule]]
) -> ComponentResult:
"""
Create the initial component result which is used for de-duplication.
Parameters:
molecules: The input molecules which can be a file name or list of molecule instances
Returns:
The initial component result used to start the workflow.
"""
# check if we have been given an input file with molecules inside
if isinstance(molecules, str):
if os.path.isfile(molecules):
workflow_molecules = ComponentResult(
component_name=self.Config.title,
component_description={"component_name": self.Config.title},
component_provenance=self.provenance(),
input_file=molecules,
)
elif os.path.isdir(molecules):
workflow_molecules = ComponentResult(
component_name=self.Config.title,
component_description={"component_name": self.Config.title},
component_provenance=self.provenance(),
input_directory=molecules,
)
elif isinstance(molecules, off.Molecule):
workflow_molecules = ComponentResult(
component_name=self.Config.title,
component_description={"component_name": self.Config.title},
component_provenance=self.provenance(),
molecules=[
molecules,
],
)
else:
workflow_molecules = ComponentResult(
component_name=self.Config.title,
component_description={"component_name": self.Config.title},
component_provenance=self.provenance(),
molecules=molecules,
)
return workflow_molecules
def create_dataset(
self,
dataset_name: str,
molecules: Union[str, List[off.Molecule], off.Molecule],
description: str,
tagline: str,
metadata: Optional[Metadata] = None,
processors: Optional[int] = None,
verbose: bool = True,
) -> BasicDataset:
"""
Process the input molecules through the given workflow then create and populate the dataset class which acts as
a local representation for the collection in qcarchive and has the ability to submit its self to a local or
public instance.
Parameters:
dataset_name: The name that will be given to the collection on submission to an archive instance.
molecules: The list of molecules which should be processed by the workflow and added to the dataset, this
can also be a file name which is to be unpacked by the openforcefield toolkit.
description: A string describing the dataset.
tagline: A tagline displayed with collection name in the QCArchive.
metadata: Any metadata which should be associated with this dataset this can be changed from the default
after making the dataset.
processors: The number of processors avilable to the workflow, note None will use all avilable processors.
verbose: If True a progress bar for each workflow component will be shown.
Example:
How to make a dataset from a list of molecules
```python
>>> from qcsubmit.factories import BasicDatasetFactory
>>> from qcsubmit.workflow_components import get_component
>>> from openforcefield.topology import Molecule
>>> factory = BasicDatasetFactory()
>>> gen = get_component("StandardConformerGenerator")
>>> gen.clear_exsiting = True
>>> gen.max_conformers = 1
>>> factory.add_workflow_component(gen)
>>> smiles = ['C', 'CC', 'CCO']
>>> mols = [Molecule.from_smiles(smile) for smile in smiles]
>>> dataset = factory.create_dataset(dataset_name='My collection', molecules=mols)
```
Returns:
A [DataSet][qcsubmit.datasets.DataSet] instance populated with the molecules that have passed through the
workflow.
Important:
The dataset once created does not allow mutation.
"""
# TODO set up a logging system to report the components
# create an initial component result
workflow_molecules = self._create_initial_component_result(molecules=molecules)
# create the dataset
# first we need to instance the dataset and assign the metadata
object_meta = self.dict(exclude={"workflow"})
# the only data missing is the collection name so add it here.
object_meta["dataset_name"] = dataset_name
object_meta["description"] = description
object_meta["provenance"] = self.provenance()
object_meta["dataset_tagline"] = tagline
if metadata is not None:
object_meta["metadata"] = metadata.dict()
dataset = self._dataset_type.parse_obj(object_meta)
# if the workflow has components run it
if self.workflow:
for component in self.workflow.values():
workflow_molecules = component.apply(
molecules=workflow_molecules.molecules,
processors=processors,
verbose=verbose,
)
dataset.filter_molecules(
molecules=workflow_molecules.filtered,
component_name=workflow_molecules.component_name,
component_description=workflow_molecules.component_description,
component_provenance=workflow_molecules.component_provenance,
)
# get a molecular complex filter
molecular_complex = self._get_molecular_complex_info()
# now add the molecules to the correct attributes
for molecule in tqdm.tqdm(
workflow_molecules.molecules,
total=len(workflow_molecules.molecules),
ncols=80,
desc="{:30s}".format("Preparation"),
disable=not verbose,
):
# order the molecule
order_mol = molecule.canonical_order_atoms()
attributes = self.create_cmiles_metadata(molecule=order_mol)
attributes["provenance"] = self.provenance()
# always put the cmiles in the extras from what we have just calculated to ensure correct order
extras = molecule.properties.get("extras", {})
keywords = molecule.properties.get("keywords", None)
# now submit the molecule
try:
dataset.add_molecule(
index=self.create_index(molecule=order_mol),
molecule=order_mol,
attributes=attributes,
extras=extras if bool(extras) else None,
keywords=keywords,
)
except MolecularComplexError:
molecular_complex["molecules"].append(molecule)
# add the complexes if there are any
if molecular_complex["molecules"]:
dataset.filter_molecules(**molecular_complex)
return dataset
def create_cmiles_metadata(self, molecule: off.Molecule) -> Dict[str, str]:
"""
Create the Cmiles metadata for the molecule in this dataset.
Parameters:
molecule: The molecule for which the cmiles data will be generated.
Returns:
The Cmiles identifiers generated for the input molecule.
Note:
The Cmiles identifiers currently include:
- `canonical_smiles`
- `canonical_isomeric_smiles`
- `canonical_explicit_hydrogen_smiles`
- `canonical_isomeric_explicit_hydrogen_smiles`
- `canonical_isomeric_explicit_hydrogen_mapped_smiles`
- `molecular_formula`
- `standard_inchi`
- `inchi_key`
"""
cmiles = {
"canonical_smiles": molecule.to_smiles(
isomeric=False, explicit_hydrogens=False, mapped=False
),
"canonical_isomeric_smiles": molecule.to_smiles(
isomeric=True, explicit_hydrogens=False, mapped=False
),
"canonical_explicit_hydrogen_smiles": molecule.to_smiles(
isomeric=False, explicit_hydrogens=True, mapped=False
),
"canonical_isomeric_explicit_hydrogen_smiles": molecule.to_smiles(
isomeric=True, explicit_hydrogens=True, mapped=False
),
"canonical_isomeric_explicit_hydrogen_mapped_smiles": molecule.to_smiles(
isomeric=True, explicit_hydrogens=True, mapped=True
),
"molecular_formula": molecule.hill_formula,
"standard_inchi": molecule.to_inchi(fixed_hydrogens=False),
"inchi_key": molecule.to_inchikey(fixed_hydrogens=False),
}
return cmiles
def create_index(self, molecule: off.Molecule) -> str:
"""
Create an index for the current molecule.
Parameters:
molecule: The molecule for which the dataset index will be generated.
Returns:
The canonical isomeric smiles for the molecule which is used as the dataset index.
Important:
Each dataset can have a different indexing system depending on the data, in this basic dataset each conformer
of a molecule is expanded into its own entry separately indexed entry. This is handled by the dataset however
so we just generate a general index for the molecule before adding to the dataset.
"""
index = molecule.to_smiles(
isomeric=True, explicit_hydrogens=False, mapped=False
)
return index
class OptimizationDatasetFactory(BasicDatasetFactory):
"""
This factory produces OptimisationDatasets which include settings associated with geometric which is used to run the
optimisation.
"""
# set the driver to be gradient this should not be changed when running
driver = DriverEnum.gradient
_dataset_type = OptimizationDataset
# use the default geometric settings during optimisation
optimization_program: GeometricProcedure = GeometricProcedure()
class Config:
title = "OptimizationDatasetFactory"
@validator("driver")
def _check_driver(cls, driver):
"""Make sure that the driver is set to gradient only and not changed."""
available_drivers = ["gradient"]
if driver not in available_drivers:
raise DriverError(
f"The requested driver ({driver}) is not in the list of available "
f"drivers: {available_drivers}"
)
return driver
def add_compute(
self,
dataset_name: str,
client: Union[str, FractalClient],
await_result: bool = False,
) -> None:
"""
A method that can add compute to an existing collection, this involves registering the QM settings and keywords
and running the compute.
Parameters:
dataset_name: The name of the collection in the qcarchive instance that the compute should be added to.
await_result: If the function should block until the calculations have finished.
client: The name of the file containing the client information or the client instance.
"""
import qcportal as ptl
target_client = self._activate_client(client)
# try and get the collection.
collection = self._get_collection(
dataset_type=self._dataset_type.__name__,
dataset_name=dataset_name,
client=target_client,
)
# create the keywords
kw = ptl.models.KeywordSet(
values=self.dict(include={"maxiter", "scf_properties"})
)
kw_id = target_client.add_keywords([kw])[0]
# create the spec
opt_spec = self.optimization_program.get_optimzation_spec()
qc_spec = ptl.models.common_models.QCSpecification(
driver=self.driver,
method=self.method,
basis=self.basis,
keywords=kw_id,
program=self.program,
)
# now add the compute tasks
collection.add_specification(
name=self.spec_name,
optimization_spec=opt_spec,
qc_spec=qc_spec,
description=self.spec_description,
overwrite=False,
)
response = collection.compute(
specification=self.spec_name, tag=self.compute_tag, priority=self.priority
)
return response
class TorsiondriveDatasetFactory(OptimizationDatasetFactory):
"""
This factory produces TorsiondriveDatasets which include settings associated with geometric which is used to run
the optimisation.
"""
grid_spacings: List[int] = [15]
energy_upper_limit: float = 0.05
dihedral_ranges: Optional[List[Tuple[int, int]]] = None
energy_decrease_thresh: Optional[float] = None
_dataset_type = TorsiondriveDataset
# set the default settings for a torsiondrive calculation.
optimization_program = GeometricProcedure.parse_obj(
{"enforce": 0.1, "reset": True, "qccnv": True, "epsilon": 0.0}
)
class Config:
title = "TorsiondriveDatasetFactory"
def create_dataset(
self,
| |
"""Create the Z3 expression `other >= self`.
>>> x, y = Ints('x y')
>>> x >= y
x >= y
>>> y = Real('y')
>>> x >= y
ToReal(x) >= y
"""
a, b = _coerce_exprs(self, other)
return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def is_arith(a):
"""Return `True` if `a` is an arithmetical expression.
>>> x = Int('x')
>>> is_arith(x)
True
>>> is_arith(x + 1)
True
>>> is_arith(1)
False
>>> is_arith(IntVal(1))
True
>>> y = Real('y')
>>> is_arith(y)
True
>>> is_arith(y + 1)
True
"""
return isinstance(a, ArithRef)
def is_int(a):
"""Return `True` if `a` is an integer expression.
>>> x = Int('x')
>>> is_int(x + 1)
True
>>> is_int(1)
False
>>> is_int(IntVal(1))
True
>>> y = Real('y')
>>> is_int(y)
False
>>> is_int(y + 1)
False
"""
return is_arith(a) and a.is_int()
def is_real(a):
"""Return `True` if `a` is a real expression.
>>> x = Int('x')
>>> is_real(x + 1)
False
>>> y = Real('y')
>>> is_real(y)
True
>>> is_real(y + 1)
True
>>> is_real(1)
False
>>> is_real(RealVal(1))
True
"""
return is_arith(a) and a.is_real()
def _is_numeral(ctx, a):
return Z3_is_numeral_ast(ctx.ref(), a)
def _is_algebraic(ctx, a):
return Z3_is_algebraic_number(ctx.ref(), a)
def is_int_value(a):
"""Return `True` if `a` is an integer value of sort Int.
>>> is_int_value(IntVal(1))
True
>>> is_int_value(1)
False
>>> is_int_value(Int('x'))
False
>>> n = Int('x') + 1
>>> n
x + 1
>>> n.arg(1)
1
>>> is_int_value(n.arg(1))
True
>>> is_int_value(RealVal("1/3"))
False
>>> is_int_value(RealVal(1))
False
"""
return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
def is_rational_value(a):
"""Return `True` if `a` is rational value of sort Real.
>>> is_rational_value(RealVal(1))
True
>>> is_rational_value(RealVal("3/5"))
True
>>> is_rational_value(IntVal(1))
False
>>> is_rational_value(1)
False
>>> n = Real('x') + 1
>>> n.arg(1)
1
>>> is_rational_value(n.arg(1))
True
>>> is_rational_value(Real('x'))
False
"""
return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
def is_algebraic_value(a):
"""Return `True` if `a` is an algebraic value of sort Real.
>>> is_algebraic_value(RealVal("3/5"))
False
>>> n = simplify(Sqrt(2))
>>> n
1.4142135623?
>>> is_algebraic_value(n)
True
"""
return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
def is_add(a):
"""Return `True` if `a` is an expression of the form b + c.
>>> x, y = Ints('x y')
>>> is_add(x + y)
True
>>> is_add(x - y)
False
"""
return is_app_of(a, Z3_OP_ADD)
def is_mul(a):
"""Return `True` if `a` is an expression of the form b * c.
>>> x, y = Ints('x y')
>>> is_mul(x * y)
True
>>> is_mul(x - y)
False
"""
return is_app_of(a, Z3_OP_MUL)
def is_sub(a):
"""Return `True` if `a` is an expression of the form b - c.
>>> x, y = Ints('x y')
>>> is_sub(x - y)
True
>>> is_sub(x + y)
False
"""
return is_app_of(a, Z3_OP_SUB)
def is_div(a):
"""Return `True` if `a` is an expression of the form b / c.
>>> x, y = Reals('x y')
>>> is_div(x / y)
True
>>> is_div(x + y)
False
>>> x, y = Ints('x y')
>>> is_div(x / y)
False
>>> is_idiv(x / y)
True
"""
return is_app_of(a, Z3_OP_DIV)
def is_idiv(a):
"""Return `True` if `a` is an expression of the form b div c.
>>> x, y = Ints('x y')
>>> is_idiv(x / y)
True
>>> is_idiv(x + y)
False
"""
return is_app_of(a, Z3_OP_IDIV)
def is_mod(a):
"""Return `True` if `a` is an expression of the form b % c.
>>> x, y = Ints('x y')
>>> is_mod(x % y)
True
>>> is_mod(x + y)
False
"""
return is_app_of(a, Z3_OP_MOD)
def is_le(a):
"""Return `True` if `a` is an expression of the form b <= c.
>>> x, y = Ints('x y')
>>> is_le(x <= y)
True
>>> is_le(x < y)
False
"""
return is_app_of(a, Z3_OP_LE)
def is_lt(a):
"""Return `True` if `a` is an expression of the form b < c.
>>> x, y = Ints('x y')
>>> is_lt(x < y)
True
>>> is_lt(x == y)
False
"""
return is_app_of(a, Z3_OP_LT)
def is_ge(a):
"""Return `True` if `a` is an expression of the form b >= c.
>>> x, y = Ints('x y')
>>> is_ge(x >= y)
True
>>> is_ge(x == y)
False
"""
return is_app_of(a, Z3_OP_GE)
def is_gt(a):
"""Return `True` if `a` is an expression of the form b > c.
>>> x, y = Ints('x y')
>>> is_gt(x > y)
True
>>> is_gt(x == y)
False
"""
return is_app_of(a, Z3_OP_GT)
def is_is_int(a):
"""Return `True` if `a` is an expression of the form IsInt(b).
>>> x = Real('x')
>>> is_is_int(IsInt(x))
True
>>> is_is_int(x)
False
"""
return is_app_of(a, Z3_OP_IS_INT)
def is_to_real(a):
"""Return `True` if `a` is an expression of the form ToReal(b).
>>> x = Int('x')
>>> n = ToReal(x)
>>> n
ToReal(x)
>>> is_to_real(n)
True
>>> is_to_real(x)
False
"""
return is_app_of(a, Z3_OP_TO_REAL)
def is_to_int(a):
"""Return `True` if `a` is an expression of the form ToInt(b).
>>> x = Real('x')
>>> n = ToInt(x)
>>> n
ToInt(x)
>>> is_to_int(n)
True
>>> is_to_int(x)
False
"""
return is_app_of(a, Z3_OP_TO_INT)
class IntNumRef(ArithRef):
"""Integer values."""
def as_long(self):
"""Return a Z3 integer numeral as a Python long (bignum) numeral.
>>> v = IntVal(1)
>>> v + 1
1 + 1
>>> v.as_long() + 1
2
"""
if z3_debug():
_z3_assert(self.is_int(), "Integer value expected")
return int(self.as_string())
def as_string(self):
"""Return a Z3 integer numeral as a Python string.
>>> v = IntVal(100)
>>> v.as_string()
'100'
"""
return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
class RatNumRef(ArithRef):
"""Rational values."""
def numerator(self):
""" Return the numerator of a Z3 rational numeral.
>>> is_rational_value(RealVal("3/5"))
True
>>> n = RealVal("3/5")
>>> n.numerator()
3
>>> is_rational_value(Q(3,5))
True
>>> Q(3,5).numerator()
3
"""
return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx)
def denominator(self):
""" Return the denominator of a Z3 rational numeral.
>>> is_rational_value(Q(3,5))
True
>>> n = Q(3,5)
>>> n.denominator()
5
"""
return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx)
def numerator_as_long(self):
""" Return the numerator as a Python long.
>>> v = RealVal(10000000000)
>>> v
10000000000
>>> v + 1
10000000000 + 1
>>> v.numerator_as_long() + 1 == 10000000001
True
"""
return self.numerator().as_long()
def denominator_as_long(self):
""" Return the denominator as a Python long.
>>> v = RealVal("1/3")
>>> v
1/3
>>> v.denominator_as_long()
3
"""
return self.denominator().as_long()
def is_int(self):
return False
def is_real(self):
return True
def is_int_value(self):
return self.denominator().is_int() and self.denominator_as_long() == 1
def as_long(self):
_z3_assert(self.is_int_value(), "Expected integer fraction")
return self.numerator_as_long()
def as_decimal(self, prec):
""" Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
>>> v = RealVal("1/5")
>>> v.as_decimal(3)
'0.2'
>>> v = RealVal("1/3")
>>> v.as_decimal(3)
'0.333?'
"""
return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
def as_string(self):
"""Return a Z3 rational numeral as a Python string.
>>> v = Q(3,6)
>>> v.as_string()
'1/2'
"""
return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
def as_fraction(self):
"""Return a Z3 rational as a Python Fraction object.
>>> v = RealVal("1/5")
>>> v.as_fraction()
Fraction(1, 5)
"""
return Fraction(self.numerator_as_long(), self.denominator_as_long())
class AlgebraicNumRef(ArithRef):
"""Algebraic irrational values."""
def approx(self, precision=10):
"""Return a Z3 rational number that approximates the algebraic number `self`.
The result `r` is such that |r - self| <= 1/10^precision
>>> x = simplify(Sqrt(2))
>>> x.approx(20)
6838717160008073720548335/4835703278458516698824704
>>> x.approx(5)
2965821/2097152
"""
return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx)
def as_decimal(self, prec):
"""Return a string representation of the algebraic number `self` in decimal notation using `prec` decimal places
>>> x = simplify(Sqrt(2))
>>> x.as_decimal(10)
'1.4142135623?'
>>> x.as_decimal(20)
'1.41421356237309504880?'
"""
return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
def _py2expr(a, ctx=None):
if isinstance(a, bool):
return BoolVal(a, ctx)
if _is_int(a):
return IntVal(a, ctx)
if isinstance(a, float):
return RealVal(a, ctx)
if is_expr(a):
return a
if z3_debug():
_z3_assert(False, "Python bool, int, long or float expected")
def IntSort(ctx=None):
"""Return the integer sort in the given context. If `ctx=None`, then the global context is used.
>>> IntSort()
Int
>>> x = Const('x', IntSort())
>>> is_int(x)
True
>>> x.sort() == IntSort()
True
>>> x.sort() == BoolSort()
False
"""
ctx = _get_ctx(ctx)
return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
def RealSort(ctx=None):
"""Return the real sort in the given context. If `ctx=None`, then the global context is used.
>>> RealSort()
Real
>>> x = Const('x', RealSort())
>>> is_real(x)
True
>>> is_int(x)
False
>>> x.sort() == RealSort()
True
"""
ctx = _get_ctx(ctx)
return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
def _to_int_str(val):
if isinstance(val, float):
return str(int(val))
elif isinstance(val, bool):
if val:
return "1"
else:
return "0"
elif _is_int(val):
return str(val)
elif isinstance(val, str):
return val
if z3_debug():
_z3_assert(False, "Python value cannot be used as | |
m4 = MassFunction(*[(x, 1.0/number) for x in random.sample(mediumElements, number)])
m5 = MassFunction(*[(x, 1.0/number) for x in random.sample(mediumElements, number)])
s = format_time("size 10, focals " + str(number) + ", 2 bbas", time_function(nb_iterations, m1.combination_dubois_prade_unsafe, m2, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10, focals " + str(number) + ", 3 bbas", time_function(nb_iterations, m1.combination_dubois_prade_unsafe, m2, m3, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10, focals " + str(number) + ", 4 bbas", time_function(nb_iterations, m1.combination_dubois_prade_unsafe, m2, m3, m4, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10, focals " + str(number) + ", 5 bbas", time_function(nb_iterations, m1.combination_dubois_prade_unsafe, m2, m3, m4, m5, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
for number in numberOfElements:
if number <= len(bigElements):
m1 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElements, number)])
m2 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElements, number)])
m3 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElements, number)])
m4 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElements, number)])
m5 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElements, number)])
s = format_time("size 10000, focals " + str(number) + ", 2 bbas", time_function(nb_iterations, m1.combination_dubois_prade_unsafe, m2, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10000, focals " + str(number) + ", 3 bbas", time_function(nb_iterations, m1.combination_dubois_prade_unsafe, m2, m3, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10000, focals " + str(number) + ", 4 bbas", time_function(nb_iterations, m1.combination_dubois_prade_unsafe, m2, m3, m4, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10000, focals " + str(number) + ", 5 bbas", time_function(nb_iterations, m1.combination_dubois_prade_unsafe, m2, m3, m4, m5, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
########################################################################################################################################################################################################
########################################################################################################################################################################################################
########################################################################################################################################################################################################
s = "- " * 40
print(s)
f.write(s + "\n")
s = "Murphy:"
print(s)
f.write(s + "\n")
for number in numberOfElements:
if number <= len(smallElements):
m1 = MassFunction(*[(x, 1.0/number) for x in random.sample(smallElements, number)])
m2 = MassFunction(*[(x, 1.0/number) for x in random.sample(smallElements, number)])
m3 = MassFunction(*[(x, 1.0/number) for x in random.sample(smallElements, number)])
m4 = MassFunction(*[(x, 1.0/number) for x in random.sample(smallElements, number)])
m5 = MassFunction(*[(x, 1.0/number) for x in random.sample(smallElements, number)])
s = format_time("size 3, focals " + str(number) + ", 2 bbas", time_function(nb_iterations, m1.combination_murphy, m2, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 3, focals " + str(number) + ", 3 bbas", time_function(nb_iterations, m1.combination_murphy, m2, m3, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 3, focals " + str(number) + ", 4 bbas", time_function(nb_iterations, m1.combination_murphy, m2, m3, m4, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 3, focals " + str(number) + ", 5 bbas", time_function(nb_iterations, m1.combination_murphy, m2, m3, m4, m5, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
for number in numberOfElements:
if number <= len(mediumElements):
m1 = MassFunction(*[(x, 1.0/number) for x in random.sample(mediumElements, number)])
m2 = MassFunction(*[(x, 1.0/number) for x in random.sample(mediumElements, number)])
m3 = MassFunction(*[(x, 1.0/number) for x in random.sample(mediumElements, number)])
m4 = MassFunction(*[(x, 1.0/number) for x in random.sample(mediumElements, number)])
m5 = MassFunction(*[(x, 1.0/number) for x in random.sample(mediumElements, number)])
s = format_time("size 10, focals " + str(number) + ", 2 bbas", time_function(nb_iterations, m1.combination_murphy, m2, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10, focals " + str(number) + ", 3 bbas", time_function(nb_iterations, m1.combination_murphy, m2, m3, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10, focals " + str(number) + ", 4 bbas", time_function(nb_iterations, m1.combination_murphy, m2, m3, m4, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10, focals " + str(number) + ", 5 bbas", time_function(nb_iterations, m1.combination_murphy, m2, m3, m4, m5, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
for number in numberOfElements:
if number <= len(bigElements):
m1 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElements, number)])
m2 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElements, number)])
m3 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElements, number)])
m4 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElements, number)])
m5 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElements, number)])
s = format_time("size 10000, focals " + str(number) + ", 2 bbas", time_function(nb_iterations, m1.combination_murphy, m2, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10000, focals " + str(number) + ", 3 bbas", time_function(nb_iterations, m1.combination_murphy, m2, m3, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10000, focals " + str(number) + ", 4 bbas", time_function(nb_iterations, m1.combination_murphy, m2, m3, m4, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10000, focals " + str(number) + ", 5 bbas", time_function(nb_iterations, m1.combination_murphy, m2, m3, m4, m5, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
########################################################################################################################################################################################################
########################################################################################################################################################################################################
########################################################################################################################################################################################################
s = "- " * 40
print(s)
f.write(s + "\n")
s = "Murphy (unsafe):"
print(s)
f.write(s + "\n")
for number in numberOfElements:
if number <= len(smallElements):
m1 = MassFunction(*[(x, 1.0/number) for x in random.sample(smallElements, number)])
m2 = MassFunction(*[(x, 1.0/number) for x in random.sample(smallElements, number)])
m3 = MassFunction(*[(x, 1.0/number) for x in random.sample(smallElements, number)])
m4 = MassFunction(*[(x, 1.0/number) for x in random.sample(smallElements, number)])
m5 = MassFunction(*[(x, 1.0/number) for x in random.sample(smallElements, number)])
s = format_time("size 3, focals " + str(number) + ", 2 bbas", time_function(nb_iterations, m1.combination_murphy_unsafe, m2, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 3, focals " + str(number) + ", 3 bbas", time_function(nb_iterations, m1.combination_murphy_unsafe, m2, m3, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 3, focals " + str(number) + ", 4 bbas", time_function(nb_iterations, m1.combination_murphy_unsafe, m2, m3, m4, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 3, focals " + str(number) + ", 5 bbas", time_function(nb_iterations, m1.combination_murphy_unsafe, m2, m3, m4, m5, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
for number in numberOfElements:
if number <= len(mediumElements):
m1 = MassFunction(*[(x, 1.0/number) for x in random.sample(mediumElements, number)])
m2 = MassFunction(*[(x, 1.0/number) for x in random.sample(mediumElements, number)])
m3 = MassFunction(*[(x, 1.0/number) for x in random.sample(mediumElements, number)])
m4 = MassFunction(*[(x, 1.0/number) for x in random.sample(mediumElements, number)])
m5 = MassFunction(*[(x, 1.0/number) for x in random.sample(mediumElements, number)])
s = format_time("size 10, focals " + str(number) + ", 2 bbas", time_function(nb_iterations, m1.combination_murphy_unsafe, m2, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10, focals " + str(number) + ", 3 bbas", time_function(nb_iterations, m1.combination_murphy_unsafe, m2, m3, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10, focals " + str(number) + ", 4 bbas", time_function(nb_iterations, m1.combination_murphy_unsafe, m2, m3, m4, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10, focals " + str(number) + ", 5 bbas", time_function(nb_iterations, m1.combination_murphy_unsafe, m2, m3, m4, m5, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
for number in numberOfElements:
if number <= len(bigElements):
m1 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElements, number)])
m2 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElements, number)])
m3 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElements, number)])
m4 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElements, number)])
m5 = MassFunction(*[(x, 1.0/number) for x in random.sample(bigElements, number)])
s = format_time("size 10000, focals " + str(number) + ", 2 bbas", time_function(nb_iterations, m1.combination_murphy_unsafe, m2, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10000, focals " + str(number) + ", 3 bbas", time_function(nb_iterations, m1.combination_murphy_unsafe, m2, m3, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10000, focals " + str(number) + ", 4 bbas", time_function(nb_iterations, m1.combination_murphy_unsafe, m2, m3, m4, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
s = format_time("size 10000, focals " + str(number) + ", 5 bbas", time_function(nb_iterations, m1.combination_murphy_unsafe, m2, m3, m4, m5, timeout=timeout, verbose=False), nb_iterations, timeout)
print(s)
f.write(s + "\n")
########################################################################################################################################################################################################
########################################################################################################################################################################################################
########################################################################################################################################################################################################
s = "- " * 40
print(s)
f.write(s + "\n")
s = "Chen:"
print(s)
f.write(s + "\n")
for number in numberOfElements:
if number <= len(smallElements):
m1 = MassFunction(*[(x, 1.0/number) for x in random.sample(smallElements, number)])
m2 = MassFunction(*[(x, 1.0/number) for x in random.sample(smallElements, number)])
m3 = MassFunction(*[(x, 1.0/number) for x in random.sample(smallElements, number)])
m4 = MassFunction(*[(x, 1.0/number) for | |
<gh_stars>0
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import numpy as np
import pandas as pd
from ..try_numba import try_numba_jit
import warnings
import logging
from ..utils import (validate_tuple, guess_pos_columns, default_pos_columns,
default_size_columns)
from ..masks import (binary_mask, r_squared_mask,
x_squared_masks, cosmask, sinmask)
from ..try_numba import NUMBA_AVAILABLE, range, int, round
logger = logging.getLogger(__name__)
def _safe_center_of_mass(x, radius, grids):
normalizer = x.sum()
if normalizer == 0: # avoid divide-by-zero errors
return np.array(radius)
return np.array([(x * grids[dim]).sum() / normalizer
for dim in range(x.ndim)])
def refine_com(raw_image, image, radius, coords, max_iterations=10,
engine='auto', shift_thresh=0.6, characterize=True,
pos_columns=None):
"""Find the center of mass of a bright feature starting from an estimate.
Characterize the neighborhood of a local maximum, and iteratively
hone in on its center-of-brightness. Return its coordinates, integrated
brightness, size (Rg), eccentricity (0=circular), and signal strength.
Parameters
----------
raw_image : array (any dimensions)
used for final characterization
image : array (any dimension)
processed image, used for locating center of mass
coords : array or DataFrame
estimated position
separation : float or tuple
Minimum separtion between features.
Default is 0. May be a tuple, see diameter for details.
max_iterations : integer
max number of loops to refine the center of mass, default 10
engine : {'python', 'numba'}
Numba is faster if available, but it cannot do walkthrough.
shift_thresh : float, optional
Default 0.6 (unit is pixels).
If the brightness centroid is more than this far off the mask center,
shift mask to neighboring pixel. The new mask will be used for any
remaining iterations.
characterize : boolean, True by default
Compute and return mass, size, eccentricity, signal.
pos_columns: list of strings, optional
Column names that contain the position coordinates.
Defaults to ``['y', 'x']`` or ``['z', 'y', 'x']``, if ``'z'`` exists.
"""
if isinstance(coords, pd.DataFrame):
if pos_columns is None:
pos_columns = guess_pos_columns(coords)
index = coords.index
coords = coords[pos_columns].values
else:
index = None
radius = validate_tuple(radius, image.ndim)
if pos_columns is None:
pos_columns = default_pos_columns(image.ndim)
columns = pos_columns + ['mass']
if characterize:
isotropic = radius[1:] == radius[:-1]
columns += default_size_columns(image.ndim, isotropic) + \
['ecc', 'signal', 'raw_mass']
if len(coords) == 0:
return pd.DataFrame(columns=columns)
refined = refine_com_arr(raw_image, image, radius, coords,
max_iterations=max_iterations,
engine=engine, shift_thresh=shift_thresh,
characterize=characterize)
return pd.DataFrame(refined, columns=columns, index=index)
def refine_com_arr(raw_image, image, radius, coords, max_iterations=10,
engine='auto', shift_thresh=0.6, characterize=True,
walkthrough=False):
"""Refine coordinates and return a numpy array instead of a DataFrame.
See also
--------
refine_com
"""
if max_iterations <= 0:
warnings.warn("max_iterations has to be larger than 0. setting it to 1.")
max_iterations = 1
if raw_image.ndim != coords.shape[1]:
raise ValueError("The image has a different number of dimensions than "
"the coordinate array.")
# ensure that radius is tuple of integers, for direct calls to refine_com_arr()
radius = validate_tuple(radius, image.ndim)
# Main loop will be performed in separate function.
if engine == 'auto':
if NUMBA_AVAILABLE and image.ndim in [2, 3]:
engine = 'numba'
else:
engine = 'python'
# In here, coord is an integer. Make a copy, will not modify inplace.
coords = np.round(coords).astype(np.int)
if engine == 'python':
results = _refine(raw_image, image, radius, coords, max_iterations,
shift_thresh, characterize, walkthrough)
elif engine == 'numba':
if not NUMBA_AVAILABLE:
warnings.warn("numba could not be imported. Without it, the "
"'numba' engine runs very slow. Use the 'python' "
"engine or install numba.", UserWarning)
if image.ndim not in [2, 3]:
raise NotImplementedError("The numba engine only supports 2D or 3D "
"images. You can extend it if you feel "
"like a hero.")
if walkthrough:
raise ValueError("walkthrough is not availabe in the numba engine")
# Do some extra prep in pure Python that can't be done in numba.
N = coords.shape[0]
mask = binary_mask(radius, image.ndim)
if image.ndim == 3:
if characterize:
if np.all(radius[1:] == radius[:-1]):
results_columns = 8
else:
results_columns = 10
else:
results_columns = 4
r2_mask = r_squared_mask(radius, image.ndim)[mask]
x2_masks = x_squared_masks(radius, image.ndim)
z2_mask = image.ndim * x2_masks[0][mask]
y2_mask = image.ndim * x2_masks[1][mask]
x2_mask = image.ndim * x2_masks[2][mask]
results = np.empty((N, results_columns), dtype=np.float64)
maskZ, maskY, maskX = np.asarray(np.asarray(mask.nonzero()),
dtype=np.int16)
_numba_refine_3D(np.asarray(raw_image), np.asarray(image),
radius[0], radius[1], radius[2], coords, N,
int(max_iterations), shift_thresh,
characterize,
image.shape[0], image.shape[1], image.shape[2],
maskZ, maskY, maskX, maskX.shape[0],
r2_mask, z2_mask, y2_mask, x2_mask, results)
elif not characterize:
mask_coordsY, mask_coordsX = np.asarray(mask.nonzero(), np.int16)
results = np.empty((N, 3), dtype=np.float64)
_numba_refine_2D(np.asarray(image), radius[0], radius[1], coords, N,
int(max_iterations), shift_thresh,
image.shape[0], image.shape[1],
mask_coordsY, mask_coordsX, mask_coordsY.shape[0],
results)
elif radius[0] == radius[1]:
mask_coordsY, mask_coordsX = np.asarray(mask.nonzero(), np.int16)
results = np.empty((N, 7), dtype=np.float64)
r2_mask = r_squared_mask(radius, image.ndim)[mask]
cmask = cosmask(radius)[mask]
smask = sinmask(radius)[mask]
_numba_refine_2D_c(np.asarray(raw_image), np.asarray(image),
radius[0], radius[1], coords, N,
int(max_iterations), shift_thresh,
image.shape[0], image.shape[1], mask_coordsY,
mask_coordsX, mask_coordsY.shape[0],
r2_mask, cmask, smask, results)
else:
mask_coordsY, mask_coordsX = np.asarray(mask.nonzero(), np.int16)
results = np.empty((N, 8), dtype=np.float64)
x2_masks = x_squared_masks(radius, image.ndim)
y2_mask = image.ndim * x2_masks[0][mask]
x2_mask = image.ndim * x2_masks[1][mask]
cmask = cosmask(radius)[mask]
smask = sinmask(radius)[mask]
_numba_refine_2D_c_a(np.asarray(raw_image), np.asarray(image),
radius[0], radius[1], coords, N,
int(max_iterations), shift_thresh,
image.shape[0], image.shape[1], mask_coordsY,
mask_coordsX, mask_coordsY.shape[0],
y2_mask, x2_mask, cmask, smask, results)
else:
raise ValueError("Available engines are 'python' and 'numba'")
return results
# (This is pure Python. A numba variant follows below.)
def _refine(raw_image, image, radius, coords, max_iterations,
shift_thresh, characterize, walkthrough):
if not np.issubdtype(coords.dtype, np.integer):
raise ValueError('The coords array should be of integer datatype')
ndim = image.ndim
isotropic = np.all(radius[1:] == radius[:-1])
mask = binary_mask(radius, ndim).astype(np.uint8)
# Declare arrays that we will fill iteratively through loop.
N = coords.shape[0]
final_coords = np.empty_like(coords, dtype=np.float64)
mass = np.empty(N, dtype=np.float64)
raw_mass = np.empty(N, dtype=np.float64)
if characterize:
if isotropic:
Rg = np.empty(N, dtype=np.float64)
else:
Rg = np.empty((N, len(radius)), dtype=np.float64)
ecc = np.empty(N, dtype=np.float64)
signal = np.empty(N, dtype=np.float64)
ogrid = np.ogrid[[slice(0, i) for i in mask.shape]] # for center of mass
ogrid = [g.astype(float) for g in ogrid]
for feat, coord in enumerate(coords):
for iteration in range(max_iterations):
# Define the circular neighborhood of (x, y).
rect = [slice(c - r, c + r + 1) for c, r in zip(coord, radius)]
neighborhood = mask*image[rect]
cm_n = _safe_center_of_mass(neighborhood, radius, ogrid)
cm_i = cm_n - radius + coord # image coords
off_center = cm_n - radius
logger.debug('off_center: %f', off_center)
if np.all(np.abs(off_center) < shift_thresh):
break # Accurate enough.
# If we're off by more than half a pixel in any direction, move..
coord[off_center > shift_thresh] += 1
coord[off_center < -shift_thresh] -= 1
# Don't move outside the image!
upper_bound = np.array(image.shape) - 1 - radius
coord = np.clip(coord, radius, upper_bound).astype(int)
# stick to yx column order
final_coords[feat] = cm_i
if walkthrough:
import matplotlib.pyplot as plt
plt.imshow(neighborhood)
# Characterize the neighborhood of our final centroid.
mass[feat] = neighborhood.sum()
if not characterize:
continue # short-circuit loop
if isotropic:
Rg[feat] = np.sqrt(np.sum(r_squared_mask(radius, ndim) *
neighborhood) / mass[feat])
else:
Rg[feat] = np.sqrt(ndim * np.sum(x_squared_masks(radius, ndim) *
neighborhood,
axis=tuple(range(1, ndim + 1))) /
mass[feat])
# I only know how to measure eccentricity in 2D.
if ndim == 2:
ecc[feat] = np.sqrt(np.sum(neighborhood*cosmask(radius))**2 +
np.sum(neighborhood*sinmask(radius))**2)
ecc[feat] /= (mass[feat] - neighborhood[radius] + 1e-6)
else:
ecc[feat] = np.nan
signal[feat] = neighborhood.max() # based on bandpassed image
raw_neighborhood = mask*raw_image[rect]
raw_mass[feat] = raw_neighborhood.sum() # based on raw image
if not characterize:
return np.column_stack([final_coords, mass])
else:
return np.column_stack([final_coords, mass, Rg, ecc, signal, raw_mass])
@try_numba_jit(nopython=True)
def _numba_refine_2D(image, radiusY, radiusX, coords, N, max_iterations,
shift_thresh, shapeY, shapeX, maskY, maskX, N_mask,
results):
# Column indices into the 'results' array
MASS_COL = 2
upper_boundY = shapeY - radiusY - 1
upper_boundX = shapeX - radiusX - 1
for feat in range(N):
# coord is an integer.
coordY = coords[feat, 0]
coordX = coords[feat, 1]
for iteration in range(max_iterations):
# Define the circular neighborhood of (x, y).
cm_nY = 0.
cm_nX = 0.
squareY = coordY - radiusY
squareX = coordX - radiusX
mass_ = 0.0
for i in range(N_mask):
px = image[squareY + maskY[i],
squareX + maskX[i]]
cm_nY += px*maskY[i]
cm_nX += px*maskX[i]
mass_ += px
cm_nY /= mass_
cm_nX /= mass_
cm_iY = cm_nY - radiusY + coordY
cm_iX = cm_nX - radiusX + coordX
off_centerY = cm_nY - radiusY
off_centerX = cm_nX - radiusX
if (abs(off_centerY) < shift_thresh and
abs(off_centerX) < shift_thresh):
break # Go to next feature
# If we're off by more than half a pixel in any direction, move.
oc = off_centerY
if oc > shift_thresh:
| |
#!/usr/bin/env python3
import netCDF4 as nc
import sys
import numpy as np
import matplotlib.pyplot as plt
import argparse
import scipy.ndimage as sn # contains the filters
from plotTools import addImagePlot
from netcdfTools import read3dDataFromNetCDF
from utilities import selectFromList
#==========================================================#
def readVar( fn, vstr, cl=1 ):
xDict = read3dDataFromNetCDF( fn , vstr , cl )
v = xDict['v']; x = xDict['x']; y = xDict['y']; z = xDict['z']
xDict = None
return v, x, y, z
#==========================================================#
def U_hd( fn, cl=1, direction=False ):
ut, xu, yu, zu = readVar( fn, 'u_xy', cl )
vt, xv, yv, zv = readVar( fn, 'v_xy', cl )
x = xv[:-1]; y = yu[:-1]; z = 0.5*(zu+zv)
uc = 0.5*( ut[:,:,:-1,1:] + ut[:,:,:-1,:-1] )
vc = 0.5*( vt[:,:,1:,:-1] + ut[:,:,:-1,:-1] )
if( direction ):
v = np.arctan( vc/(uc+1.E-5) ) * (180./np.pi)
else:
a = np.arctan( vc/(uc+1.E-5) )
v = uc * np.cos(a) + vc * np.sin(a)
return v, x, y, z
#==========================================================#
helpStr = '''
Diff mode:
'd': root mean square diff (RMSD),
'r': RMSD (relative delta),
's': RMSD (scaled delta),
'n': root normalized mean square diff.,
'f': fractional bias
'v': geometric variance
'''
methodList = ['d','r', 's','n','f','v','R']
parser = argparse.ArgumentParser(prog='compareNetCdf2D.py')
parser.add_argument("-f1", "--filename1",type=str, help="Name of the first (ref) input NETCDF file.")
parser.add_argument("-f2", "--filename2",type=str, help="Name of the second input NETCDF file.")
parser.add_argument("-v", "--varname", type=str, default='u',\
help="Name of the variable in NETCDF file. Default='u' ")
parser.add_argument("-v0", "--vref", type=float, nargs=2, default=[0.,0.],\
help="Reference values 'v0' in v+ = (v - v0)/v* for -f1 and -f2. Default = [0,0]")
parser.add_argument("-vs", "--vstar", type=float, nargs=2, default=[1.,1.],\
help="Characteristic value 'v*' in v+ = (v - v0)/v* for -f1 and -f2. Default = [1.,1.]")
parser.add_argument("-c", "--coarsen", type=int, nargs=2, default=[1,1],\
help="Factor for coarsening the -f1 and -f2 data when read from file. Default = [1,1]")
parser.add_argument("-m","--mode", type=str, default='d', choices=methodList,\
help=helpStr)
parser.add_argument("-w", "--writeFile", action="store_true", default=False,\
help="Write the root-mean-square of the differences to a file.")
parser.add_argument("-nxx1", "--nexclx1", type=int, nargs=2, default=[None,None],\
help="For -f1, exclude the [first,last] number of nodes from analysis in x-direction.")
parser.add_argument("-nxy1", "--nexcly1", type=int, nargs=2, default=[None,None],\
help="For -f1, exclude the [first,last] number of nodes from analysis in y-direction.")
parser.add_argument("-nxx2", "--nexclx2", type=int, nargs=2, default=[None,None],\
help="For -f2, exclude the [first,last] number of nodes from analysis in x-direction.")
parser.add_argument("-nxy2", "--nexcly2", type=int, nargs=2, default=[None,None],\
help="For -f2, exclude the [first,last] number of nodes from analysis in y-direction.")
parser.add_argument("-xs", "--exclsmall", help="Exclude values below |0.01| from analysis.",\
action="store_true", default=False)
parser.add_argument("-p", "--printOn", help="Print the numpy array data.",\
action="store_true", default=False)
parser.add_argument("-s", "--save", action="store_true", default=False,\
help="Save figures. Default=False")
parser.add_argument("--lims", help="User specified limits.", action="store_true", default=False)
parser.add_argument("--grid", help="Turn on grid.", action="store_true", default=False)
args = parser.parse_args()
#==========================================================#
# Rename ... that's all.
f1 = args.filename1 # './DATA_2D_XY_AV_NETCDF_N02-1.nc'
f2 = args.filename2 # './DATA_2D_XY_AV_NETCDF_N02-2.nc'
varname = args.varname
v0 = np.array(args.vref )
vs = np.array(args.vstar)
cl = np.array(args.coarsen)
mode = args.mode
nxx1 = args.nexclx1
nxy1 = args.nexcly1
nxx2 = args.nexclx2
nxy2 = args.nexcly2
exclSmall= args.exclsmall
writeFile= args.writeFile
printOn = args.printOn
saveOn = args.save
limsOn = args.lims
gridOn = args.grid
#----------------------------------------------------------#
Sdict = {'d':'RMSD','s':'RMSD (scaled)','r':'RMSD (rel)','n':'RNMSD','f':'FB',\
'v':'VG','R':'R'}
# Shorter name
vn = varname.split('_')[0]
dirOn = 'UD' in varname.upper()
horizOn = 'UH' in varname.upper()
# Default for excluded indices is [None,None]. If numerical values are given,
# the latter needs to be made negative.
if( nxx1.count(None) == 0 ): nxx1[1]*=-1
if( nxy1.count(None) == 0 ): nxy1[1]*=-1
if( nxx2.count(None) == 0 ): nxx2[1]*=-1
if( nxy2.count(None) == 0 ): nxy2[1]*=-1
if( (not horizOn) and (not dirOn) ):
#print('{}'.format(varname))
v1, x1, y1, z1 = readVar( f1, varname, cl[0] )
v2, x2, y2, z2 = readVar( f2, varname, cl[1] )
else:
v1, x1, y1, z1 = U_hd( f1, cl[0], dirOn )
v2, x2, y2, z2 = U_hd( f2, cl[1], dirOn )
if( not dirOn ):
v1 -= v0[0]; v1 /= vs[0]
v2 -= v0[1]; v2 /= vs[1]
idk = selectFromList( z1 )
if( writeFile ):
fout = open('{}_d{}.dat'.format(Sdict[mode],vn), 'w')
fout.write('# file1 = {}, file2 = {}\n'.format(f1, f2))
fout.write('# z_coord \t {}(d{})\n'.format(Sdict[mode],vn))
#fout.write('{:.2f}\t{:.2e}'.format( z1[k1], dv ))
for k1 in idk:
#k2 = np.where(z2==z1[k1])[0] # This outputs a list
k2 = np.where(np.abs(z2-z1[k1])==np.min(np.abs(z2-z1[k1])))[0]
if( len(k2) == 0 ):
print(' Coordinate {} not in file {}. Skipping.'.format(z1[k1],f2))
continue
else:
k2 = k2[0] # Take always the first term
if( len(v1.shape) == 4): v1x = np.mean(v1[:,k1,nxy1[0]:nxy1[1],nxx1[0]:nxx1[1]], axis=0)
else: v1x = v1[ k1,nxy1[0]:nxy1[1],nxx1[0]:nxx1[1]]
if( len(v2.shape) == 4): v2x = np.mean(v2[:,k2,nxy2[0]:nxy2[1],nxx2[0]:nxx2[1]], axis=0)
else: v2x = v2[ k2,nxy2[0]:nxy2[1],nxx2[0]:nxx2[1]]
# - - - - - - - - - - - - - - - - - - - - - - - - - - - #
dims1 = np.array( v1x.shape )
dims2 = np.array( v2x.shape )
if( all( dims1 == dims2 ) ):
print(' Dimensions of the two datasets match!: dims = {}'.format(dims1))
else:
print(' Caution! Dataset dimensions do not match. dims1 = {} vs. dims2 = {}'.format(dims1, dims2))
dx1 = (x1[2]-x1[1]); dy1 = (y1[2]-y1[1])
dx2 = (x2[2]-x2[1]); dy2 = (y2[2]-y2[1])
rr = int(np.round(dx2/dx1, decimals=0)); rry = int(np.round(dy2/dy1, decimals=0))
if( rr != rry ): sys.exit(' Resolution ratios are dissimilar. Exiting ...')
v2f = np.zeros( dims1 ) # Fine resolution
nc,ec = np.ogrid[ 0:dims1[0] , 0:dims1[1] ] # northing, easting ... fine resolution
nf,ef = np.ogrid[ 0:dims1[0] , 0:dims1[1] ] # northing, easting ... fine resolution
nc=nc//rr; ec=ec//rr # coarse indices
#nc = nc.astype(int); ec = ec.astype(int)
#nf = nf.astype(int); ef = ef.astype(int)
#np.savetxt('n.dat',np.c_[nf,nc], fmt='%.1f')
#np.savetxt('e.dat',np.c_[ef.T,ec.T], fmt='%.1f')
# Check bounds
nf = np.minimum( nf , dims1[0]-1)
ef = np.minimum( ef , dims1[1]-1)
nc = np.minimum( nc , dims2[0]-1)
ec = np.minimum( ec , dims2[1]-1)
# Perform value placement
v2f[nf, ef] += v2x[nc,ec]; v2x = None
v2x = v2f
# - - - - - - - - - - - - - - - - - - - - - - - - - - - #
if( not np.ma.isMaskedArray(v1x) and not np.ma.isMaskedArray(v2x) ):
idm = (v1x == v2x)
v1x = np.ma.masked_array( v1x, mask=idm )
v2x = np.ma.masked_array( v2x, mask=idm )
idm = None
idm = np.ma.getmask(v1x); print(' Nm = {}'.format(np.count_nonzero(idm)))
idz = (v2x == 0.0)
idm += idz
#idm = sn.binary_dilation(idm); print(' Nm = {}'.format(np.count_nonzero(idm)))
v1x = np.ma.masked_array( v1x, mask=idm)
v2x = np.ma.masked_array( v2x, mask=idm)
#v2x = np.ma.round( v2x, decimals=2 )
#v1x = np.ma.round( v1x, decimals=2 )
if( exclSmall ):
# Take values that are above 0.01 or below -0.01
idx = np.array( (v1x < 5.E-2) )
#idx = np.array( (v1x > -0.1) )
m1x = np.ma.getmask(v1x)
m1x += idx
m2 = np.ma.getmask(v2x)
m2 += idx
'''
id2x = np.array( np.abs(v2x) > 1E-2 )
vm2 = np.ma.mean( v2x[id2x] )
id1x = np.array( np.abs(v1x) > 1E-2 )
vm1 = np.ma.mean( v1x[id1x] )
dv = (v2x[id1x] - v1x[id1x] )
'''
vm1 = np.mean( v1x )
vm2 = np.mean( v2x )
print('k={}: vm1 = {}, vm2 = {} '.format(k1,vm1,vm2))
dv = (v2x - v1x)
# NOTE: We are using the desired indices obtained only from the reference (f1) data.
idnn = ~(dv == np.nan )
N = np.ma.count( np.ravel( dv[idnn] ) )
print('k={}: Number of good points, N = {}'.format(k1,N))
if( mode in ['r','s','d'] ):
if( mode == 'r' ): dv /= np.abs( v1x + 1E-5 )
if( mode == 's' ): dv /= ( vm1 + 1E-5 )
#if( mode == 'd' ): Keep as is: dv = (v2x - v1x)
RES = np.sqrt(np.sum(dv**2)/N)
SkewDiff = (1./N)*np.sum(dv**3) * ( 1./(N-1.)*np.sum(dv**2) )**(-1.5)
print('{} (d{}) = {}, Sk(d{}) = {} '.format(Sdict[mode], vn , RES, vn, SkewDiff ))
if( mode == 'n'):
v_min_th = np.sqrt(1.e-5)
vm1 = np.sign(vm1)*np.maximum( np.abs(vm1), v_min_th )
vm2 = np.sign(vm2)*np.maximum( np.abs(vm2), v_min_th )
denom = vm1*vm2
enum = np.sum(dv**2)/N
RES = np.sqrt( enum/np.abs(denom) )
#print(' enum = {}, denom = {} '.format(enum,denom))
print('{} (d{}) = {}'.format(Sdict[mode], vn , RES))
if( mode == 'f'):
denom_min_th = 1.e-2
dv = (vm2 - vm1) # Note, mean values
enum = np.maximum( dv, 1.e-3 )
denom = 0.5*(np.abs(vm2)+np.abs(vm1))
denom = np.sign(denom)*np.maximum( np.abs(denom), denom_min_th )
RES = dv/denom
#print(' enum = {}, denom = {} '.format(dv,denom))
print('{} (d{}) = {}'.format(Sdict[mode], vn , RES))
if( mode == 'v'):
v_min_th = 1.e-1
dv = np.log( np.maximum( np.abs(v2x), v_min_th)/(np.maximum( np.abs(v1x), v_min_th )) )
RES = np.exp( np.sum(dv**2)/N )
print('{} (d{}) = {}'.format(Sdict[mode], vn , RES))
if( | |
<reponame>gfuchedzhy/hyde
# -*- coding: utf-8 -*-
"""
Parses & holds information about the site to be generated.
"""
import os
import fnmatch
import sys
import urlparse
from functools import wraps
from urllib import quote
from hyde.exceptions import HydeException
from hyde.fs import FS, File, Folder
from hyde.model import Config
from hyde.util import getLoggerWithNullHandler
def path_normalized(f):
@wraps(f)
def wrapper(self, path):
return f(self, unicode(path).replace('/', os.sep))
return wrapper
logger = getLoggerWithNullHandler('hyde.engine')
class Processable(object):
"""
A node or resource.
"""
def __init__(self, source):
super(Processable, self).__init__()
self.source = FS.file_or_folder(source)
self.is_processable = True
self.uses_template = True
self._relative_deploy_path = None
@property
def name(self):
"""
The resource name
"""
return self.source.name
def __repr__(self):
return self.path
@property
def path(self):
"""
Gets the source path of this node.
"""
return self.source.path
def get_relative_deploy_path(self):
"""
Gets the path where the file will be created
after its been processed.
"""
return self._relative_deploy_path \
if self._relative_deploy_path is not None \
else self.relative_path
def set_relative_deploy_path(self, path):
"""
Sets the path where the file ought to be created
after its been processed.
"""
self._relative_deploy_path = path
self.site.content.deploy_path_changed(self)
relative_deploy_path = property(get_relative_deploy_path, set_relative_deploy_path)
@property
def url(self):
"""
Returns the relative url for the processable
"""
return '/' + self.relative_deploy_path
@property
def full_url(self):
"""
Returns the full url for the processable.
"""
return self.site.full_url(self.relative_deploy_path)
class Resource(Processable):
"""
Represents any file that is processed by hyde
"""
def __init__(self, source_file, node):
super(Resource, self).__init__(source_file)
self.source_file = source_file
if not node:
raise HydeException("Resource cannot exist without a node")
if not source_file:
raise HydeException("Source file is required"
" to instantiate a resource")
self.node = node
self.site = node.site
self.simple_copy = False
@property
def relative_path(self):
"""
Gets the path relative to the root folder (Content)
"""
return self.source_file.get_relative_path(self.node.root.source_folder)
@property
def slug(self):
#TODO: Add a more sophisticated slugify method
return self.source.name_without_extension
class Node(Processable):
"""
Represents any folder that is processed by hyde
"""
def __init__(self, source_folder, parent=None):
super(Node, self).__init__(source_folder)
if not source_folder:
raise HydeException("Source folder is required"
" to instantiate a node.")
self.root = self
self.module = None
self.site = None
self.source_folder = Folder(unicode(source_folder))
self.parent = parent
if parent:
self.root = self.parent.root
self.module = self.parent.module if self.parent.module else self
self.site = parent.site
self.child_nodes = []
self.resources = []
def contains_resource(self, resource_name):
"""
Returns True if the given resource name exists as a file
in this node's source folder.
"""
return File(self.source_folder.child(resource_name)).exists
def get_resource(self, resource_name):
"""
Gets the resource if the given resource name exists as a file
in this node's source folder.
"""
if self.contains_resource(resource_name):
return self.root.resource_from_path(
self.source_folder.child(resource_name))
return None
def add_child_node(self, folder):
"""
Creates a new child node and adds it to the list of child nodes.
"""
if folder.parent != self.source_folder:
raise HydeException("The given folder [%s] is not a"
" direct descendant of [%s]" %
(folder, self.source_folder))
node = Node(folder, self)
self.child_nodes.append(node)
return node
def add_child_resource(self, afile):
"""
Creates a new resource and adds it to the list of child resources.
"""
if afile.parent != self.source_folder:
raise HydeException("The given file [%s] is not"
" a direct descendant of [%s]" %
(afile, self.source_folder))
resource = Resource(afile, self)
self.resources.append(resource)
return resource
def walk(self):
"""
Walks the node, first yielding itself then
yielding the child nodes depth-first.
"""
yield self
for child in self.child_nodes:
for node in child.walk():
yield node
def walk_resources(self):
"""
Walks the resources in this hierarchy.
"""
for node in self.walk():
for resource in node.resources:
yield resource
@property
def relative_path(self):
"""
Gets the path relative to the root folder (Content, Media, Layout)
"""
return self.source_folder.get_relative_path(self.root.source_folder)
class RootNode(Node):
"""
Represents one of the roots of site: Content, Media or Layout
"""
def __init__(self, source_folder, site):
super(RootNode, self).__init__(source_folder)
self.site = site
self.node_map = {}
self.node_deploy_map = {}
self.resource_map = {}
self.resource_deploy_map = {}
@path_normalized
def node_from_path(self, path):
"""
Gets the node that maps to the given path.
If no match is found it returns None.
"""
if Folder(path) == self.source_folder:
return self
return self.node_map.get(unicode(Folder(path)), None)
@path_normalized
def node_from_relative_path(self, relative_path):
"""
Gets the content node that maps to the given relative path.
If no match is found it returns None.
"""
return self.node_from_path(
self.source_folder.child(unicode(relative_path)))
@path_normalized
def resource_from_path(self, path):
"""
Gets the resource that maps to the given path.
If no match is found it returns None.
"""
return self.resource_map.get(unicode(File(path)), None)
@path_normalized
def resource_from_relative_path(self, relative_path):
"""
Gets the content resource that maps to the given relative path.
If no match is found it returns None.
"""
return self.resource_from_path(
self.source_folder.child(relative_path))
def deploy_path_changed(self, item):
"""
Handles the case where the relative deploy path of a
resource has changed.
"""
self.resource_deploy_map[unicode(item.relative_deploy_path)] = item
@path_normalized
def resource_from_relative_deploy_path(self, relative_deploy_path):
"""
Gets the content resource whose deploy path maps to
the given relative path. If no match is found it returns None.
"""
if relative_deploy_path in self.resource_deploy_map:
return self.resource_deploy_map[relative_deploy_path]
return self.resource_from_relative_path(relative_deploy_path)
def add_node(self, a_folder):
"""
Adds a new node to this folder's hierarchy.
Also adds to to the hashtable of path to node associations
for quick lookup.
"""
folder = Folder(a_folder)
node = self.node_from_path(folder)
if node:
logger.debug("Node exists at [%s]" % node.relative_path)
return node
if not folder.is_descendant_of(self.source_folder):
raise HydeException("The given folder [%s] does not"
" belong to this hierarchy [%s]" %
(folder, self.source_folder))
p_folder = folder
parent = None
hierarchy = []
while not parent:
hierarchy.append(p_folder)
p_folder = p_folder.parent
parent = self.node_from_path(p_folder)
hierarchy.reverse()
node = parent if parent else self
for h_folder in hierarchy:
node = node.add_child_node(h_folder)
self.node_map[unicode(h_folder)] = node
logger.debug("Added node [%s] to [%s]" % (
node.relative_path, self.source_folder))
return node
def add_resource(self, a_file):
"""
Adds a file to the parent node. Also adds to to the
hashtable of path to resource associations for quick lookup.
"""
afile = File(a_file)
resource = self.resource_from_path(afile)
if resource:
logger.debug("Resource exists at [%s]" % resource.relative_path)
return resource
if not afile.is_descendant_of(self.source_folder):
raise HydeException("The given file [%s] does not reside"
" in this hierarchy [%s]" %
(afile, self.source_folder))
node = self.node_from_path(afile.parent)
if not node:
node = self.add_node(afile.parent)
resource = node.add_child_resource(afile)
self.resource_map[unicode(afile)] = resource
relative_path = resource.relative_path
resource.simple_copy = any(fnmatch.fnmatch(relative_path, pattern)
for pattern
in self.site.config.simple_copy)
logger.debug("Added resource [%s] to [%s]" %
(resource.relative_path, self.source_folder))
return resource
def load(self):
"""
Walks the `source_folder` and loads the sitemap.
Creates nodes and resources, reads metadata and injects attributes.
This is the model for hyde.
"""
if not self.source_folder.exists:
raise HydeException("The given source folder [%s]"
" does not exist" % self.source_folder)
with self.source_folder.walker as walker:
def dont_ignore(name):
for pattern in self.site.config.ignore:
if fnmatch.fnmatch(name, pattern):
return False
return True
@walker.folder_visitor
def visit_folder(folder):
if dont_ignore(folder.name):
self.add_node(folder)
else:
logger.debug("Ignoring node: %s" % folder.name)
return False
@walker.file_visitor
def visit_file(afile):
if dont_ignore(afile.name):
self.add_resource(afile)
class Site(object):
"""
Represents the site to be generated.
"""
def __init__(self, sitepath=None, config=None):
super(Site, self).__init__()
self.sitepath = Folder(Folder(sitepath).fully_expanded_path)
# Add sitepath to the list of module search paths so that
# local plugins can be included.
sys.path.insert(0, self.sitepath.fully_expanded_path)
self.config = config if config else Config(self.sitepath)
self.content = RootNode(self.config.content_root_path, self)
self.plugins = []
self.context = {}
def refresh_config(self):
"""
Refreshes config data if one or more config files have
changed. Note that this does not refresh the meta data.
"""
if self.config.needs_refresh():
logger.debug("Refreshing config data")
self.config = Config(self.sitepath,
self.config.config_file,
self.config.config_dict)
def reload_if_needed(self):
"""
Reloads if the site has not been loaded before or if the
configuration has changed since the last load.
"""
if not len(self.content.child_nodes):
self.load()
def load(self):
"""
Walks the content and media folders to load up the sitemap.
"""
self.content.load()
def content_url(self, path, safe=None):
"""
Returns the content url by appending the base url from the config
with the given path. The return value is url encoded.
"""
fpath = Folder(self.config.base_url) \
.child(path) \
.replace(os.sep, '/').encode("utf-8")
if safe is not None:
return quote(fpath, safe)
else:
return quote(fpath)
def media_url(self, path, safe=None):
"""
Returns the media url by appending the media base url from the config
with the given path. The return value is url encoded.
"""
fpath = Folder(self.config.media_url) \
.child(path) \
.replace(os.sep, '/').encode("utf-8")
if safe is not None:
return quote(fpath, safe)
else:
return quote(fpath)
def full_url(self, path, safe=None):
"""
Determines if the given path is media or content based on the
configuration | |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['LabArgs', 'Lab']
@pulumi.input_type
class LabArgs:
def __init__(__self__, *,
resource_group_name: pulumi.Input[str],
location: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
storage_type: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None):
"""
The set of arguments for constructing a Lab resource.
:param pulumi.Input[str] resource_group_name: The name of the resource group under which the Dev Test Lab resource has to be created. Changing this forces a new resource to be created.
:param pulumi.Input[str] location: Specifies the supported Azure location where the Dev Test Lab should exist. Changing this forces a new resource to be created.
:param pulumi.Input[str] name: Specifies the name of the Dev Test Lab. Changing this forces a new resource to be created.
:param pulumi.Input[str] storage_type: The type of storage used by the Dev Test Lab. Possible values are `Standard` and `Premium`. Defaults to `Premium`. Changing this forces a new resource to be created.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: A mapping of tags to assign to the resource.
"""
pulumi.set(__self__, "resource_group_name", resource_group_name)
if location is not None:
pulumi.set(__self__, "location", location)
if name is not None:
pulumi.set(__self__, "name", name)
if storage_type is not None:
pulumi.set(__self__, "storage_type", storage_type)
if tags is not None:
pulumi.set(__self__, "tags", tags)
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> pulumi.Input[str]:
"""
The name of the resource group under which the Dev Test Lab resource has to be created. Changing this forces a new resource to be created.
"""
return pulumi.get(self, "resource_group_name")
@resource_group_name.setter
def resource_group_name(self, value: pulumi.Input[str]):
pulumi.set(self, "resource_group_name", value)
@property
@pulumi.getter
def location(self) -> Optional[pulumi.Input[str]]:
"""
Specifies the supported Azure location where the Dev Test Lab should exist. Changing this forces a new resource to be created.
"""
return pulumi.get(self, "location")
@location.setter
def location(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "location", value)
@property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
"""
Specifies the name of the Dev Test Lab. Changing this forces a new resource to be created.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name", value)
@property
@pulumi.getter(name="storageType")
def storage_type(self) -> Optional[pulumi.Input[str]]:
"""
The type of storage used by the Dev Test Lab. Possible values are `Standard` and `Premium`. Defaults to `Premium`. Changing this forces a new resource to be created.
"""
return pulumi.get(self, "storage_type")
@storage_type.setter
def storage_type(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "storage_type", value)
@property
@pulumi.getter
def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
"""
A mapping of tags to assign to the resource.
"""
return pulumi.get(self, "tags")
@tags.setter
def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "tags", value)
@pulumi.input_type
class _LabState:
def __init__(__self__, *,
artifacts_storage_account_id: Optional[pulumi.Input[str]] = None,
default_premium_storage_account_id: Optional[pulumi.Input[str]] = None,
default_storage_account_id: Optional[pulumi.Input[str]] = None,
key_vault_id: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
premium_data_disk_storage_account_id: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
storage_type: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
unique_identifier: Optional[pulumi.Input[str]] = None):
"""
Input properties used for looking up and filtering Lab resources.
:param pulumi.Input[str] artifacts_storage_account_id: The ID of the Storage Account used for Artifact Storage.
:param pulumi.Input[str] default_premium_storage_account_id: The ID of the Default Premium Storage Account for this Dev Test Lab.
:param pulumi.Input[str] default_storage_account_id: The ID of the Default Storage Account for this Dev Test Lab.
:param pulumi.Input[str] key_vault_id: The ID of the Key used for this Dev Test Lab.
:param pulumi.Input[str] location: Specifies the supported Azure location where the Dev Test Lab should exist. Changing this forces a new resource to be created.
:param pulumi.Input[str] name: Specifies the name of the Dev Test Lab. Changing this forces a new resource to be created.
:param pulumi.Input[str] premium_data_disk_storage_account_id: The ID of the Storage Account used for Storage of Premium Data Disk.
:param pulumi.Input[str] resource_group_name: The name of the resource group under which the Dev Test Lab resource has to be created. Changing this forces a new resource to be created.
:param pulumi.Input[str] storage_type: The type of storage used by the Dev Test Lab. Possible values are `Standard` and `Premium`. Defaults to `Premium`. Changing this forces a new resource to be created.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: A mapping of tags to assign to the resource.
:param pulumi.Input[str] unique_identifier: The unique immutable identifier of the Dev Test Lab.
"""
if artifacts_storage_account_id is not None:
pulumi.set(__self__, "artifacts_storage_account_id", artifacts_storage_account_id)
if default_premium_storage_account_id is not None:
pulumi.set(__self__, "default_premium_storage_account_id", default_premium_storage_account_id)
if default_storage_account_id is not None:
pulumi.set(__self__, "default_storage_account_id", default_storage_account_id)
if key_vault_id is not None:
pulumi.set(__self__, "key_vault_id", key_vault_id)
if location is not None:
pulumi.set(__self__, "location", location)
if name is not None:
pulumi.set(__self__, "name", name)
if premium_data_disk_storage_account_id is not None:
pulumi.set(__self__, "premium_data_disk_storage_account_id", premium_data_disk_storage_account_id)
if resource_group_name is not None:
pulumi.set(__self__, "resource_group_name", resource_group_name)
if storage_type is not None:
pulumi.set(__self__, "storage_type", storage_type)
if tags is not None:
pulumi.set(__self__, "tags", tags)
if unique_identifier is not None:
pulumi.set(__self__, "unique_identifier", unique_identifier)
@property
@pulumi.getter(name="artifactsStorageAccountId")
def artifacts_storage_account_id(self) -> Optional[pulumi.Input[str]]:
"""
The ID of the Storage Account used for Artifact Storage.
"""
return pulumi.get(self, "artifacts_storage_account_id")
@artifacts_storage_account_id.setter
def artifacts_storage_account_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "artifacts_storage_account_id", value)
@property
@pulumi.getter(name="defaultPremiumStorageAccountId")
def default_premium_storage_account_id(self) -> Optional[pulumi.Input[str]]:
"""
The ID of the Default Premium Storage Account for this Dev Test Lab.
"""
return pulumi.get(self, "default_premium_storage_account_id")
@default_premium_storage_account_id.setter
def default_premium_storage_account_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "default_premium_storage_account_id", value)
@property
@pulumi.getter(name="defaultStorageAccountId")
def default_storage_account_id(self) -> Optional[pulumi.Input[str]]:
"""
The ID of the Default Storage Account for this Dev Test Lab.
"""
return pulumi.get(self, "default_storage_account_id")
@default_storage_account_id.setter
def default_storage_account_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "default_storage_account_id", value)
@property
@pulumi.getter(name="keyVaultId")
def key_vault_id(self) -> Optional[pulumi.Input[str]]:
"""
The ID of the Key used for this Dev Test Lab.
"""
return pulumi.get(self, "key_vault_id")
@key_vault_id.setter
def key_vault_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "key_vault_id", value)
@property
@pulumi.getter
def location(self) -> Optional[pulumi.Input[str]]:
"""
Specifies the supported Azure location where the Dev Test Lab should exist. Changing this forces a new resource to be created.
"""
return pulumi.get(self, "location")
@location.setter
def location(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "location", value)
@property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
"""
Specifies the name of the Dev Test Lab. Changing this forces a new resource to be created.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name", value)
@property
@pulumi.getter(name="premiumDataDiskStorageAccountId")
def premium_data_disk_storage_account_id(self) -> Optional[pulumi.Input[str]]:
"""
The ID of the Storage Account used for Storage of Premium Data Disk.
"""
return pulumi.get(self, "premium_data_disk_storage_account_id")
@premium_data_disk_storage_account_id.setter
def premium_data_disk_storage_account_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "premium_data_disk_storage_account_id", value)
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> Optional[pulumi.Input[str]]:
"""
The name of the resource group under which the Dev Test Lab resource has to be created. Changing this forces a new resource to be created.
"""
return pulumi.get(self, "resource_group_name")
@resource_group_name.setter
def resource_group_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "resource_group_name", value)
@property
@pulumi.getter(name="storageType")
def storage_type(self) -> Optional[pulumi.Input[str]]:
"""
The type of storage used by the Dev Test Lab. Possible values are `Standard` and `Premium`. Defaults to `Premium`. Changing this forces a new resource to be created.
"""
return pulumi.get(self, "storage_type")
@storage_type.setter
def storage_type(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "storage_type", value)
@property
@pulumi.getter
def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
"""
A mapping of tags to assign to the resource.
"""
return pulumi.get(self, "tags")
@tags.setter
def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "tags", value)
@property
@pulumi.getter(name="uniqueIdentifier")
def unique_identifier(self) -> Optional[pulumi.Input[str]]:
"""
The unique immutable identifier of the Dev Test Lab.
"""
return pulumi.get(self, "unique_identifier")
@unique_identifier.setter
def unique_identifier(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "unique_identifier", value)
class Lab(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
location: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
storage_type: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
__props__=None):
"""
Manages a Dev Test Lab.
## Example Usage
```python
import pulumi
import pulumi_azure as azure
example_resource_group = azure.core.ResourceGroup("exampleResourceGroup", location="West Europe")
example_lab = azure.devtest.Lab("exampleLab",
location=example_resource_group.location,
resource_group_name=example_resource_group.name,
tags={
"Sydney": "Australia",
})
```
## Import
Dev Test Labs can be imported using the `resource id`, e.g.
```sh
$ pulumi import azure:devtest/lab:Lab lab1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.DevTestLab/labs/lab1
```
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] location: Specifies the supported Azure location where the Dev Test Lab should exist. Changing | |
<reponame>ghanashyamchalla/cis_interface
"""
Small scanf implementation.
Python has powerful regular expressions but sometimes they are totally overkill
when you just want to parse a simple-formatted string.
C programmers use the scanf-function for these tasks (see link below).
This implementation of scanf translates the simple scanf-format into
regular expressions. Unlike C you can be sure that there are no buffer overflows
possible.
For more information see
* http://www.python.org/doc/current/lib/node49.html
* http://en.wikipedia.org/wiki/Scanf
Original code from:
http://code.activestate.com/recipes/502213-simple-scanf-implementation/
Modified original to make the %f more robust, as well as added %* modifier to
skip fields.
Version: 1.3.3
Releases:
1.0
2010-10-11
* Initial release
1.1
2010-10-13
* Changed regex from 'match' (only matches at beginning of line)
to 'search' (matches anywhere in line)
* Bugfix - ignore cast for skipped fields
1.2
2013-05-30
* Added 'collapseWhitespace' flag (defaults to True) to take the search
string and replace all whitespace with regex string to match repeated
whitespace. This enables better matching in log files where the data
has been formatted for easier reading. These cases have variable
amounts of whitespace between the columns, depending on the number
of characters in the data itself.
1.3
2016-01-18
* Add 'extractdata' function.
1.3.1
2016-06-23
* Release to PyPi, now including README.md
Updates by Me<NAME>:
2018-04-12
* Added ability to parse components of field specifiers and cope with
whitespace padding.
"""
import re
import sys
from yggdrasil import tools
__version__ = '1.3.3'
__all__ = ["scanf", 'scanf_translate', 'scanf_compile']
DEBUG = False
def no_cast(s):
r"""Dummy function to cast a string to a string.
Args:
s (str): String to cast.
Returns:
str: Cast string.
"""
return s
def cast_str(s):
r"""Cast a string value to a string, stripping whitespace.
Args:
s (str): String to cast.
Returns:
str: Cast string.
"""
return s.strip()
def cast_hex(s):
r"""Cast a string value to a hex integer.
Args:
s (str): String to cast.
Returns:
int: Base 16 integer for provided string.
"""
return int(s, 16)
def cast_oct(s):
r"""Cast a string value to an octal.
Args:
s (str): String to cast.
Returns:
int: Base 8 integer for provided string.
"""
return int(s, 8)
def cformat2regex(flags, width, precision, length, specifier):
r"""Get regex substring that will match the given cformat components.
Args:
flags (str): Format flags.
width (str): Minimum field width.
precision (str): Field precision.
length (str): Field value size (e.g. short, long).
specifier (str): Field specifier.
Returns:
str: Regex expression that will match the provided components.
"""
pat_dec = '[-+]?\\d+(?:\\.\\d+)?'
pat_sub = ''
pad_zero = 0
# Left padding specified in flags
if '0' in flags:
if '+' in flags:
pat_sub += '[-+]'
if width and specifier in 'diueEfgGoxX':
pad_zero = int(width)
else:
if ('-' not in flags) and width and (specifier != 's'):
pat_sub += "\\s{,%s}" % width
if '+' in flags:
pat_sub += '[-+]'
if precision and specifier in 'diuoxX':
pad_zero = max(pad_zero, int(precision[1:]))
# Casts
if pad_zero and specifier in 'diueEfgG':
pat_sub += '0{,%d}' % pad_zero
if specifier == 'f':
pat_sub += pat_dec
elif specifier in 'eE':
pat_sub += '%s%s[+-]\\d+' % (pat_dec, specifier)
elif specifier in 'gG':
pat_sub += '%s(?:[eE][+-]\\d+)?' % (pat_dec)
elif specifier in 'diu':
pat_sub += '\\d+'
elif specifier in 'cs':
if not width:
if specifier == 'c':
pat_sub += '.'
else:
pat_sub += '\\S+'
else:
pat_sub += '.{%s}' % width
elif specifier in 'xX':
if '#' in flags:
pat_sub += '0%s' % specifier
if pad_zero:
pat_sub += '0{,%d}' % pad_zero
pat_sub += '[\\dA-Za-f]+'
elif specifier == 'o':
if '#' in flags:
pat_sub += '0'
if pad_zero:
pat_sub += '0{,%d}' % pad_zero
pat_sub += '[0-7]*'
if ('-' in flags) and ('0' not in flags) and width:
pat_sub += "\\s{,%s}" % width
return pat_sub
def parse_cformat(format, i):
pattern = None
cast = None
# %[flags][width][.precision][length]specifier
# float_format = "%([ -\\+0]{,4})(\\d*)((?:\\.\\d+)?)(L?)([eEfgG])"
# First check for match to complex
complex_format = ("%([ -0]{,3})(\\d*)((?:\\.\\d+)?)([hlL]{,2})([eEfgG])"
+ "%(\\+?[ -0]{,3}\\+?)(\\d*)((?:\\.\\d+)?)([hlL]{,2})([eEfgG])j")
token = re.compile(complex_format)
found = token.match(format, i)
if found:
cast = complex
groups = found.groups()
pat_sub1 = cformat2regex(*groups[:5])
pat_sub2 = cformat2regex(*groups[5:])
pattern = "(%s%sj)" % (pat_sub1, pat_sub2)
return found, pattern, cast
# Then check for generic
any_format = "%([\\* \\-\\+#0]{,6})(\\d*)((?:\\.\\d+)?)([hlL]{,2})([cdieEfgGosuxX])"
token = re.compile(any_format)
found = token.match(format, i)
if found:
groups = found.groupdict() or found.groups()
# Get cast
specifier = groups[-1]
if specifier in 'eEfgG':
cast = float
elif specifier in 'diu':
cast = int
elif specifier == 'c':
cast = no_cast
elif specifier == 's':
cast = cast_str
elif specifier in ['x', 'X']:
cast = cast_hex
elif specifier in ['o']:
cast = cast_oct
else: # pragma: debug
raise Exception('No cast for specifier %s.' % specifier)
# Get pattern
pat_sub = cformat2regex(*groups)
if '*' in groups[0]:
pattern = "(?:%s)" % pat_sub
cast = None
else:
pattern = "(%s)" % pat_sub
return found, pattern, cast
return found, pattern, cast
# As you can probably see it is relatively easy to add more format types.
# Make sure you add a second entry for each new item that adds the extra
# few characters needed to handle the field ommision.
scanf_translate = [
(re.compile(_token), _pattern, _cast) for _token, _pattern, _cast in [
("%c", "(.)", lambda x:x),
("%\\*c", "(?:.)", None),
("%(\\d)c", "(.{%s})", lambda x:x),
("%\\*(\\d)c", "(?:.{%s})", None),
("%(\\d)[di]", "([+-]?\\d{%s})", int),
("%\\*(\\d)[di]", "(?:[+-]?\\d{%s})", None),
("%-(\\d)[di]", "(.{%s})", int),
("%\\*-(\\d)[di]", "(?:.{%s})", None),
("%[di]", "([+-]?\\d+)", int),
("%\\*[di]", "(?:[+-]?\\d+)", None),
("%u", "(\\d+)", int),
("%\\*u", "(?:\\d+)", None),
# langmm: complex
("%[fgeE]%[+-][fgeE]j",
"("
+ "(?:[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?)"
+ "[+-]"
+ "(?:(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?)"
+ "j)",
complex),
("%\\*[fgeE]%[+-][fgeE]j",
"(?:"
+ "(?:[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?)"
+ "[+-]"
+ "(?:(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?)"
+ "j)",
None),
("%[fgeE]", "([-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?)", float),
("%\\*[fgeE]", "(?:[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?)", None),
# langmm: Added to allows matching of %5s
("%(\\d)s", "(.{%s})", lambda x:x.strip()),
("%\\*(\\d)s", "(?:.{%s})", None),
("%s", "(\\S+)", lambda x:x),
("%\\*s", "(?:\\S+)", None),
("%([xX])", "(0%s[\\dA-Za-f]+)", lambda x:int(x, 16)),
("%\\*([xX])", "(?:0%s[\\dA-Za-f]+)", None),
("%o", "(0[0-7]*)", lambda x:int(x, 8)),
("%\\*o", "(?:0[0-7]*)", None),
]]
# Cache formats
SCANF_CACHE_SIZE = 1000
scanf_cache = {}
def scanf_compile(format, collapseWhitespace=True):
"""
Translate the format into a regular expression
For example:
>>> format_re, casts = _scanf_compile('%s - %d errors, %d warnings')
>>> print format_re.pattern
(\\S+) \\- ([+-]?\\d+) errors, ([+-]?\\d+) warnings
Translated formats are cached for faster reuse
"""
compiled = scanf_cache.get(format)
if compiled:
return compiled
format_pat = ""
cast_list = []
i = 0
length = len(format)
while i < length:
found = None
found, pattern, cast = parse_cformat(format, i)
if found:
if cast:
cast_list.append(cast)
format_pat += pattern
i = found.end()
# for token, pattern, cast in scanf_translate:
# found = token.match(format, i)
# if found:
# print('found', pattern)
# if cast: # cast != None
# cast_list.append(cast)
# groups = found.groupdict() or found.groups()
# if groups:
# pattern = pattern % groups
# format_pat += pattern
# i = found.end()
# break
if not found:
char = format[i]
# escape special characters
if char in "()[]-.+*?{}<>\\":
format_pat += "\\"
format_pat += char
i += 1
if DEBUG:
print("DEBUG: %r -> %s" % (format, format_pat))
if collapseWhitespace:
format_pat = re.sub('\\s+', r'\\s+', format_pat)
format_re = re.compile(format_pat)
if len(scanf_cache) > SCANF_CACHE_SIZE:
scanf_cache.clear()
scanf_cache[format] = (format_re, cast_list)
return format_re, cast_list
def scanf(format, s=None, collapseWhitespace=True):
"""
scanf supports the following formats:
%c One character
%5c 5 characters
%d, %i int value
%7d, %7i int value with length 7
%f float value
%o octal value
%X, %x hex value
%s string terminated by whitespace
Examples:
>>> scanf("%s - %d errors, %d warnings", "/usr/sbin/sendmail - 0 errors, 4 warnings")
('/usr/sbin/sendmail', 0, 4)
>>> scanf("%o %x %d", "0123 0x123 123")
(66, 291, 123)
If the parameter s is a file-like object, s.readline is called.
If s is not specified, stdin is assumed.
The function returns a tuple of found values
or None if the format does not match.
"""
if s is None:
s = sys.stdin
if hasattr(s, "readline"):
s = s.readline()
as_bytes = False
if isinstance(s, bytes):
as_bytes = True
s = s.decode("utf-8")
format = tools.bytes2str(format)
# print(s, format)
format_re, casts = scanf_compile(format, collapseWhitespace)
found = format_re.search(s)
if found:
groups = found.groups()
out = [casts[i](groups[i]) for i in range(len(groups))]
if as_bytes:
for i in range(len(out)):
if isinstance(out[i], str):
out[i] = out[i].encode("utf-8")
return tuple(out)
def extractdata(pattern, text=None, filepath=None):
"""
Read | |
= prevnext in ["", "0"]
if not should_stop:
self.logger.warning("Unexpected to have prevnext for order tr data.")
def ResponseForOnReceiveChejanData(self, gubun, itemcnt, fidlist):
fids = fidlist.rstrip(";")
fids = fids.split(";") if fids else []
fids = [int(fid) for fid in fids]
assert itemcnt == len(fids)
names = [
KiwoomOpenApiPlusRealType.Fid.get_name_by_fid(fid, str(fid)) for fid in fids
]
values = [self.control.GetChejanData(fid).strip() for fid in fids]
response = KiwoomOpenApiPlusService_pb2.ListenResponse()
response.name = "OnReceiveChejanData" # pylint: disable=no-member
response.arguments.add().string_value = gubun # pylint: disable=no-member
response.arguments.add().long_value = itemcnt # pylint: disable=no-member
response.arguments.add().string_value = fidlist # pylint: disable=no-member
response.single_data.names.extend(names) # pylint: disable=no-member
response.single_data.values.extend(values) # pylint: disable=no-member
return response
def OnReceiveChejanData(self, gubun, itemcnt, fidlist):
response = self.ResponseForOnReceiveChejanData(gubun, itemcnt, fidlist)
self.observer.on_next(response)
def OnEventConnect(self, errcode):
if errcode < 0:
error = KiwoomOpenApiPlusNegativeReturnCodeError(errcode)
self.observer.on_error(error)
return
class KiwoomOpenApiPlusAllOrderEventHandler(KiwoomOpenApiPlusBaseOrderEventHandler):
pass
class KiwoomOpenApiPlusOrderEventHandler(
KiwoomOpenApiPlusBaseOrderEventHandler, Logging
):
def __init__(self, control, request, context, screen_manager):
super().__init__(control, context)
self._request = request
self._screen_manager = screen_manager
self._rqname = request.request_name
self._scrnno = request.screen_no
self._accno = request.account_no
self._ordertype = request.order_type
self._code = request.code
self._qty = request.quantity
self._price = request.price
self._hogagb = request.quote_type
self._orgorderno = request.original_order_no
self._order_no = None
self._should_stop = False
def on_enter(self):
self._scrnno = self._screen_manager.borrow_screen(self._scrnno)
self.add_callback(self._screen_manager.return_screen, self._scrnno)
self.add_callback(self.control.DisconnectRealData, self._scrnno)
KiwoomOpenApiPlusError.try_or_raise(
self.control.RateLimitedSendOrder.async_call(
self._rqname,
self._scrnno,
self._accno,
self._ordertype,
self._code,
self._qty,
self._price,
self._hogagb,
self._orgorderno,
)
)
def OnReceiveMsg(self, scrnno, rqname, trcode, msg):
if (rqname, scrnno) == (self._rqname, self._scrnno):
response = self.ResponseForOnReceiveMsg(scrnno, rqname, trcode, msg)
self.observer.on_next(response)
def OnReceiveTrData(
self,
scrnno,
rqname,
trcode,
recordname,
prevnext,
datalength,
errorcode,
message,
splmmsg,
):
if (rqname, scrnno) == (self._rqname, self._scrnno):
response = self.ResponseForOnReceiveTrData(
scrnno,
rqname,
trcode,
recordname,
prevnext,
datalength,
errorcode,
message,
splmmsg,
)
self.observer.on_next(response)
self._order_no = self.control.GetCommData(
trcode, recordname, 0, "주문번호"
).strip()
if not self._order_no:
e = KiwoomOpenApiPlusError("Cannot specify order no")
self.observer.on_error(e)
return
should_stop = prevnext in ["", "0"]
if not should_stop:
self.logger.warning("Unexpected to have prevnext for order tr data.")
def OnReceiveChejanData(self, gubun, itemcnt, fidlist):
# TODO: 정정 케이스에 대해 테스트 해보지 않음
# TODO: 취소를 취소하는 케이스 같은건 고려하지 않음
# TODO: 서로 같은 원주문을 정정 혹은 취소하는 케이스 사이에는 이벤트 전파가 필요할지 모르겠음
accno = self.control.GetChejanData(9201).strip()
code = self.control.GetChejanData(9001).strip()
if accno == self._accno and code.endswith(
self._code
): # code 비교시에 앞에 prefix 가 붙어오기 때문에 endswith 으로 비교해야됨
if gubun == "0": # 접수와 체결시 (+ 취소 확인)
order_no = self.control.GetChejanData(9203).strip()
original_order_no = self.control.GetChejanData(904).strip()
status = self.control.GetChejanData(913).strip()
scrnno = self.control.GetChejanData(920).strip()
is_last = self.control.GetChejanData(819).strip() == "1"
if order_no in [self._order_no, self._orgorderno] or self._order_no in [
order_no,
original_order_no,
]:
response = self.ResponseForOnReceiveChejanData(
gubun, itemcnt, fidlist
)
self.observer.on_next(response)
if (
order_no == self._order_no
): # 자기 주문 처리하는 입장 OR 취소 및 정정 당한 뒤 원주문 정보를 받는 입장
if is_last and self._shold_stop: # 취소 확인 이후 원주문 정보 받고 종료 (타)
self.observer.on_completed()
return
elif status == "접수":
pass
elif status == "체결":
orders_left = self.control.GetChejanData(902).strip()
orders_left = int(orders_left) if orders_left.isdigit() else 0
if orders_left == 0:
self._should_stop = True # 미체결수량이 더 이상 없다면 이후 잔고 이벤트 후 종료
elif status == "확인":
self._should_stop = True # 취소 확인 이후 원주문 정보 받고 종료 (자)
else:
e = KiwoomOpenApiPlusError(
"Unexpected order status: %s" % status
)
self.observer.on_error(e)
return
elif order_no == self._orgorderno: # 취소하는 입장에서 원주문 정보 받는 케이스
if is_last and self._shold_stop: # 취소 확인 이후 원주문 정보 받고 종료 (자)
self.observer.on_completed()
return
elif status in ["접수", "체결"]:
pass
else:
e = KiwoomOpenApiPlusError(
"Unexpected order status: %s" % status
)
self.observer.on_error(e)
return
elif self._order_no == original_order_no: # 취소 혹은 정정 당하는 케이스
if status == "접수":
pass
elif status == "확인":
self._should_stop = True # 취소 확인 이후 원주문 정보 받고 종료 (타)
else:
e = KiwoomOpenApiPlusError(
"Unexpected order status: %s" % status
)
self.observer.on_error(e)
return
elif gubun == "1": # 국내주식 잔고전달
response = self.ResponseForOnReceiveChejanData(gubun, itemcnt, fidlist)
self.observer.on_next(response)
if self._should_stop: # 미체결수량이 더 이상 없다면 잔고 이벤트 후 종료
self.observer.on_completed()
return
elif gubun == "4": # 파생 잔고전달
response = self.ResponseForOnReceiveChejanData(gubun, itemcnt, fidlist)
self.observer.on_next(response)
if self._should_stop: # 미체결수량이 더 이상 없다면 잔고 이벤트 후 종료
self.observer.on_completed()
return
else:
e = KiwoomOpenApiPlusError("Unexpected gubun value: %s" % gubun)
self.observer.on_error(e)
return
class KiwoomOpenApiPlusRealEventHandler(KiwoomOpenApiPlusEventHandlerForGrpc, Logging):
_num_codes_per_screen = 100
_default_opt_type = "0"
def __init__(self, control, request, context, screen_manager):
super().__init__(control, context)
self._request = request
self._screen_manager = screen_manager
self._screen_no = request.screen_no
self._code_list = request.code_list
self._fid_list = request.fid_list
self._opt_type = request.opt_type
self._infer_fids = request.flags.infer_fids
self._readable_names = request.flags.readable_names
self._fast_parse = request.flags.fast_parse
self._code_lists = [
codes for codes in chunk(self._code_list, self._num_codes_per_screen)
]
if len(self._screen_no) == 0:
self._screen_nos = [None for i in range(len(self._code_lists))]
elif len(self._screen_no) < len(self._code_lists):
self.logger.warning("Given screen nos are not sufficient.")
self._screen_nos = list(self._screen_no) + [
None for i in range(len(self._code_lists) - len(self._screen_no))
]
else:
self._screen_nos = self._screen_no
self._fid_list_joined = ";".join([str(fid) for fid in self._fid_list])
self._opt_type_final = self._opt_type or self._default_opt_type
def on_enter(self):
for screen_no, code_list in zip(self._screen_nos, self._code_lists):
code_list_joined = ";".join(code_list)
screen_no = self._screen_manager.borrow_screen(screen_no)
self.add_callback(self._screen_manager.return_screen, screen_no)
for code in code_list:
self.add_callback(
self.control.SetRealRemove.async_call, screen_no, code
)
KiwoomOpenApiPlusError.try_or_raise(
self.control.SetRealReg(
screen_no,
code_list_joined,
self._fid_list_joined,
self._opt_type_final,
)
)
def OnReceiveRealData(self, code, realtype, realdata):
if code in self._code_list:
response = KiwoomOpenApiPlusService_pb2.ListenResponse()
response.name = "OnReceiveRealData" # pylint: disable=no-member
response.arguments.add().string_value = code # pylint: disable=no-member
response.arguments.add().string_value = (
realtype # pylint: disable=no-member
)
response.arguments.add().string_value = (
realdata # pylint: disable=no-member
)
if self._infer_fids:
fids = KiwoomOpenApiPlusRealType.get_fids_by_realtype_name(realtype)
else:
fids = self._fid_list
if self._readable_names:
names = [
KiwoomOpenApiPlusRealType.Fid.get_name_by_fid(fid, str(fid))
for fid in fids
]
else:
names = [str(fid) for fid in fids]
if self._infer_fids and self._fast_parse:
values = realdata.split("\t")
else:
values = [self.control.GetCommRealData(code, fid) for fid in fids]
assert len(names) == len(values)
response.single_data.names.extend(names) # pylint: disable=no-member
response.single_data.values.extend(values) # pylint: disable=no-member
self.observer.on_next(response) # pylint: disable=no-member
def OnEventConnect(self, errcode):
if errcode < 0:
error = KiwoomOpenApiPlusNegativeReturnCodeError(errcode)
self.observer.on_error(error)
return
class KiwoomOpenApiPlusLoadConditionEventHandler(KiwoomOpenApiPlusEventHandlerForGrpc):
def __init__(self, control, context, request):
super().__init__(control, context)
self._request = request
def on_enter(self):
KiwoomOpenApiPlusError.try_or_raise_boolean(
self.control.GetConditionLoad(), "Failed to load condition"
)
def OnReceiveConditionVer(self, ret, msg):
if ret != 1:
error = KiwoomOpenApiPlusError(msg)
self.observer.on_error(error)
response = KiwoomOpenApiPlusService_pb2.ListenResponse()
response.name = "OnReceiveConditionVer" # pylint: disable=no-member
response.arguments.add().long_value = ret # pylint: disable=no-member
response.arguments.add().string_value = msg # pylint: disable=no-member
self.observer.on_next(response) # pylint: disable=no-member
self.observer.on_completed()
class KiwoomOpenApiPlusConditionEventHandler(
KiwoomOpenApiPlusEventHandlerForGrpc, Logging
):
def __init__(self, control, request, context, screen_manager):
super().__init__(control, context)
self._request = request
self._screen_manager = screen_manager
self._screen_no = request.screen_no
self._condition_name = request.condition_name
self._condition_index = request.condition_index
self._search_type = request.search_type
self._request_name = request.request_name or "관심종목정보요청"
self._with_info = request.flags.with_info
self._is_future_option = request.flags.is_future_option
self._type_flag = 3 if self._is_future_option else 0
self._trcode = {0: "OPTKWFID", 3: "OPTFOFID"}[self._type_flag]
self._trinfo = KiwoomOpenApiPlusTrInfo.get_trinfo_by_code(self._trcode)
if self._trinfo is None:
self.logger.error("Cannot find names for trcode %s", self._trinfo)
self._single_names = self._trinfo.get_single_output_names()
self._multi_names = self._trinfo.get_multi_output_names()
def on_enter(self):
self.control.EnsureConditionLoaded()
condition_names = self.control.GetConditionNameListAsList()
assert (self._condition_index, self._condition_name) in condition_names
self._screen_no = self._screen_manager.borrow_screen(self._screen_no)
self.add_callback(self._screen_manager.return_screen, self._screen_no)
self.add_callback(self.control.DisconnectRealData, self._screen_no)
self.add_callback(
self.control.SendConditionStop,
self._screen_no,
self._condition_name,
self._condition_index,
)
KiwoomOpenApiPlusError.try_or_raise_boolean(
self.control.RateLimitedSendCondition.async_call(
self._screen_no,
self._condition_name,
self._condition_index,
self._search_type,
),
"Failed to send condition",
)
def OnReceiveTrCondition(
self, scrnno, codelist, condition_name, condition_index, prevnext
):
if (scrnno, condition_name, condition_index) == (
self._screen_no,
self._condition_name,
self._condition_index,
):
response = KiwoomOpenApiPlusService_pb2.ListenResponse()
response.name = "OnReceiveTrCondition" # pylint: disable=no-member
response.arguments.add().string_value = scrnno # pylint: disable=no-member
response.arguments.add().string_value = (
codelist # pylint: disable=no-member
)
response.arguments.add().string_value = (
condition_name # pylint: disable=no-member
)
response.arguments.add().long_value = (
condition_index # pylint: disable=no-member
)
response.arguments.add().long_value = prevnext # pylint: disable=no-member
self.observer.on_next(response) # pylint: disable=no-member
if self._with_info:
codes = codelist.rstrip(";").split(";") if codelist else []
KiwoomOpenApiPlusError.try_or_raise(
self.control.RateLimitedCommKwRqData.async_call(
codelist,
0,
len(codes),
self._type_flag,
self._request_name,
self._screen_no,
)
)
should_continue = str(prevnext) not in ["", "0"]
should_not_complete = (
self._search_type == 1 or self._with_info or should_continue
)
should_complete = not should_not_complete
if should_complete:
self.observer.on_completed()
return
elif should_continue:
try:
raise KiwoomOpenApiPlusError("Should not reach here")
self.control.RateLimitedSendCondition.async_call(
self._screen_no,
self._condition_name,
self._condition_index,
int(prevnext),
) # pylint: disable=unreachable
except KiwoomOpenApiPlusError as e:
self.observer.on_error(e)
return
def OnReceiveRealCondition(
self, code, condition_type, condition_name, condition_index
):
if (condition_name, condition_index) == (
self._condition_name,
self._condition_index,
):
response = KiwoomOpenApiPlusService_pb2.ListenResponse()
response.name = "OnReceiveRealCondition" # pylint: disable=no-member
response.arguments.add().string_value = code # pylint: disable=no-member
response.arguments.add().string_value = (
condition_type # pylint: disable=no-member
)
response.arguments.add().string_value = (
condition_name # pylint: disable=no-member
)
response.arguments.add().string_value = (
condition_index # pylint: disable=no-member
)
self.observer.on_next(response) # pylint: disable=no-member
if self._with_info:
codelist = code
codes = [code]
KiwoomOpenApiPlusError.try_or_raise(
self.control.RateLimitedCommKwRqData.async_call(
codelist,
0,
len(codes),
self._type_flag,
self._request_name,
self._screen_no,
)
)
def OnReceiveTrData(
self,
scrnno,
rqname,
trcode,
recordname,
prevnext,
_datalength,
_errorcode,
| |
<reponame>teddylfwu/AAAI21-Virtual-Conference<filename>miniconf/load_site_data.py
import copy
import csv
import glob
import itertools
import json
import os
from collections import OrderedDict, defaultdict
from datetime import timedelta
# from scripts.dataentry.tutorials import Session
from typing import Any, DefaultDict, Dict, List, Optional, Tuple
import jsons
import pytz
import yaml
from miniconf.site_data import (
CommitteeMember,
Paper,
PaperContent,
PlenarySession,
PlenaryVideo,
QaSession,
QaSubSession,
SessionInfo,
SocialEvent,
SocialEventOrganizers,
Tutorial,
TutorialSessionInfo,
TutorialAuthorInfo,
Workshop,
WorkshopPaper,
DoctoralConsortium,
PosterInfo,
Award,
Awardee,
Demonstrations,
AiInPractice
)
def load_site_data(
site_data_path: str, site_data: Dict[str, Any], by_uid: Dict[str, Any],
) -> List[str]:
"""Loads all site data at once.
Populates the `committee` and `by_uid` using files under `site_data_path`.
NOTE: site_data[filename][field]
"""
registered_sitedata = {
"config",
# index.html
"committee",
# schedule.html
"overall_calendar",
"plenary_sessions",
"opening_remarks",
# tutorials.html
"tutorials",
# papers.html
"AI for Social Impact Track_papers",
"Demos_papers",
"Doctoral Consortium_papers",
"doctoral_consortium",
"EAAI_papers",
"IAAI_papers",
"Main Track_papers",
"Senior Member Track_papers",
"Sister Conference_papers",
"Student Abstracts_papers",
"Undergraduate Consortium_papers",
"award_papers",
"poster_infos",
"paper_recs",
"papers_projection",
"paper_sessions",
# socials.html
"socials",
# workshops.html
"workshops",
"workshop_papers",
# sponsors.html
"sponsors",
# about.html
"awards",
"code_of_conduct",
"faq",
"demonstrations",
"ai_in_practice"
}
extra_files = []
# Load all for your sitedata one time.
for f in glob.glob(site_data_path + "/*"):
filename = os.path.basename(f)
if filename == "inbox":
continue
name, typ = filename.split(".")
if name not in registered_sitedata:
continue
extra_files.append(f)
if typ == "json":
site_data[name] = json.load(open(f, encoding="utf-8"))
elif typ in {"csv", "tsv"}:
site_data[name] = list(csv.DictReader(open(f, encoding="utf-8")))
elif typ == "yml":
site_data[name] = yaml.load(open(f, encoding="utf-8").read(), Loader=yaml.SafeLoader)
assert set(site_data.keys()) == registered_sitedata, registered_sitedata - set(
site_data.keys()
)
display_time_format = "%H:%M"
# index.html
site_data["committee"] = build_committee(site_data["committee"]["committee"])
# overall_schedule_week = copy.deepcopy(site_data["overall_calendar"])
# for event in overall_schedule_week:
# event["view"] = "day"
# site_data["overall_calendar"].extend(overall_schedule_week)
# schedule.html
generate_plenary_events(site_data) # cha-cha Plenary
generate_tutorial_events(site_data) # chenqian Tutorials
generate_workshop_events(site_data) # haiying Workshops
generate_dc_events(site_data) # haiying Doctoral Consortium
# TODO: generate_uc_events(site_data) chenqian Undergraduate Consortium
generate_paper_events(site_data) # en-yue, mingkai Posters
# TODO: generate_diversity_events(site_data) # liu-xiao Diversity and Inclusion
generate_social_events(site_data)
site_data["calendar"] = build_schedule(site_data["overall_calendar"])
# site_data["event_types"] = list(
# {event["type"] for event in site_data["overall_calendar"]}
# )
site_data["event_types"] = ["AAAI Plenary", "IAAI Plenary", "EAAI", "Posters", "Workshops", "Tutorials", "Doctoral Consortium",
"Undergraduate Consortium", "Diversity and Inclusion",
"Meet with a Fellow", "Sponsors/Exhibitors", "AI Job Fair"
]
# plenary_sessions.html
plenary_sessions = build_plenary_sessions(
raw_plenary_sessions=site_data["plenary_sessions"],
raw_plenary_videos={"opening_remarks": site_data["opening_remarks"]},
)
invited_panels = build_invited_panels_sessions(
raw_plenary_sessions=site_data["plenary_sessions"],
raw_plenary_videos={"opening_remarks": site_data["opening_remarks"]},
)
invited_speakers = build_invited_speakers_sessions(
raw_plenary_sessions=site_data["plenary_sessions"],
raw_plenary_videos={"opening_remarks": site_data["opening_remarks"]},
)
ai_in_practice = build_ai_in_practice_sessions(
raw_plenary_sessions=site_data["plenary_sessions"],
raw_plenary_videos={"opening_remarks": site_data["opening_remarks"]},
)
site_data["plenary_sessions"] = plenary_sessions
by_uid["plenary_sessions"] = {
plenary_session.id: plenary_session
for _, plenary_sessions_on_date in plenary_sessions.items()
for plenary_session in plenary_sessions_on_date
}
site_data["plenary_session_days"] = [
[day.replace(" ", "").lower(), day, ""] for day in plenary_sessions
]
site_data["plenary_session_days"][0][-1] = "active"
# invited panels
site_data["invited_panels"] = invited_panels
site_data["invited_panels_days"] = [
#update by mankind 2021/02/01
[day.replace(" ", "").lower(), day, ""] for day in invited_panels if day.replace(" ", "").lower() not in ["feb4","feb6"]
]
site_data["invited_panels_days"][0][-1] = "active"
# invited speaker
site_data["invited_speakers"] = invited_speakers
site_data["invited_speakers_days"] = [
[day.replace(" ", "").lower(), day, ""] for day in invited_speakers
]
site_data["invited_speakers_days"][0][-1] = "active"
# Ai in practice
# ai_in_practice=build_tutorials(site_data["ai_in_practice"])
# site_data["ai_in_practice"] = ai_in_practice
site_data["ai_in_practice"] = ai_in_practice
site_data["ai_in_practice_days"] = [
[day.replace(" ", "").lower(), day, ""] for day in ai_in_practice
]
site_data["ai_in_practice_days"][0][-1] = "active"
# Papers' progam to their data
for p in site_data["AI for Social Impact Track_papers"]:
p["program"] = "AISI"
for p in site_data["Demos_papers"]:
p["program"] = "Demo"
for p in site_data["Doctoral Consortium_papers"]:
p["program"] = "DC"
for p in site_data["EAAI_papers"]:
p["program"] = "EAAI"
for p in site_data["IAAI_papers"]:
p["program"] = "IAAI"
for p in site_data["Main Track_papers"]:
p["program"] = "Main"
for p in site_data["Senior Member Track_papers"]:
p["program"] = "SMT"
for p in site_data["Sister Conference_papers"]:
p["program"] = "SC"
for p in site_data["Student Abstracts_papers"]:
p["program"] = "SA"
for p in site_data["Undergraduate Consortium_papers"]:
p["program"] = "UC"
for p in site_data["award_papers"]:
p["program"] = "Award"
site_data["programs"] = ["AISI", "Demo", "DC",
"EAAI", "IAAI","Main","SMT","SC",
"SA","UC","Award","Best"]
# tutorials.html
tutorial_MQ = []
tutorial_MH = []
tutorial_AQ = []
tutorial_AH = []
# IAAI poster presentation
iaai_poster_schedule = {}
iaai_poster_schedule['Feb 4'] = {}
iaai_poster_schedule['Feb 5'] = {}
iaai_poster_schedule['Feb 6'] = {}
iaai_poster_schedule['Feb 4']['Aerospace'] = [74,132,171]
iaai_poster_schedule['Feb 4']['Commerce'] = [23,84,87,92,93,101,140,179,190]
iaai_poster_schedule['Feb 4']['Security'] = [98,113,142]
iaai_poster_schedule['Feb 5']['General'] = [104]
iaai_poster_schedule['Feb 5']['Engineering'] = [100,105,165,176]
iaai_poster_schedule['Feb 5']['Knowledge'] = [21,37,59,65,119,151,157,174]
iaai_poster_schedule['Feb 5']['Natural Language Processing'] = [89]
iaai_poster_schedule['Feb 5']['Prediction'] = [43,55]
iaai_poster_schedule['Feb 6']['Artificial Intelligence'] = [17,31,60,73,167]
iaai_poster_schedule['Feb 6']['Bioscience'] = [76,77,124,145,146,149]
iaai_poster_schedule['Feb 6']['COVID'] = [152,154]
iaai_poster_schedule['Feb 6']['Driving'] = [34]
iaai_poster_schedule['Feb 6']['Intelligent Technology'] = [99]
site_data["iaai_poster_schedule"] = iaai_poster_schedule
site_data["iaai_poster_schedule_days"] = [[day] for day in list(iaai_poster_schedule.keys())]
site_data["iaai_poster_schedule_days"] = site_data['plenary_session_days'][:-1]
# site_data["iaai_poster_schedule_days"] = [1,2,3,4]
site_data["iaai_poster_schedule_days"][0][-1] = "active"
# for i in range(len(site_data["iaai_poster_schedule_days"])):
# site_data["iaai_poster_schedule_days"][i][-1] = "active"
# site_data["iaai_poster_schedule_days"] = site_data['plenary_session_days'][:]
# [[day.replace(" ", "").lower(), day, ""] for day in iaai_poster_schedule.keys()]
# undergraduate_consortium.html
tutorial_UC = []
tutorial_OTHER = []
tutorial_FH = []
for item in site_data["tutorials"]:
if "MQ" in item["UID"]:
tutorial_MQ.append(item)
if "MH" in item["UID"]:
tutorial_MH.append(item)
if "AQ" in item["UID"]:
tutorial_AQ.append(item)
if "AH" in item["UID"]:
tutorial_AH.append(item)
if item["UID"] == "UC":
tutorial_OTHER.append(item)
if "UC" in item["UID"]:
tutorial_UC.append(item)
if "FH" in item["UID"]:
tutorial_FH.append(item)
tutorials = build_tutorials(site_data["tutorials"])
site_data["tutorials"] = tutorials
site_data["tutorial_calendar"] = build_tutorial_schedule(
site_data["overall_calendar"]
)
site_data["tutorials_MQ"] = build_tutorials(tutorial_MQ)
site_data["tutorials_MH"] = build_tutorials(tutorial_MH)
site_data["tutorials_AQ"] = build_tutorials(tutorial_AQ)
site_data["tutorials_AH"] = build_tutorials(tutorial_AH)
site_data["tutorials_UC"] = build_tutorials(tutorial_UC)
site_data["tutorials_FH"] = build_tutorials(tutorial_FH)
site_data["tutorials_OTHER"] = build_tutorials(tutorial_OTHER)
# tutorial_<uid>.html
by_uid["tutorials"] = {tutorial.id: tutorial for tutorial in tutorials}
# workshops.html
workshops = build_workshops(
raw_workshops=site_data["workshops"],
raw_workshop_papers=site_data["workshop_papers"],
)
site_data["workshops"] = workshops
# workshop_<uid>.html
# by_uid["workshops"] = {workshop.id: workshop for workshop in workshops}
by_uid["workshops"] = {
workshop.id: workshop
for _, workshops_on_date in workshops.items()
for workshop in workshops_on_date
}
site_data["workshop_days"] = [
[day.replace(" ", "").lower(), day, ""] for day in workshops
]
site_data["workshop_days"][0][-1] = "active"
# Doctoral Consortium
doctoral_consortium=build_doctoral_consortium(site_data["doctoral_consortium"])
site_data["doctoral_consortium"] = doctoral_consortium
# Demonstrations
demonstrations=build_tutorials(site_data["demonstrations"])
site_data["demonstrations"] = demonstrations
# socials.html/diversity_programs.html
diversity_programs = build_socials(site_data["socials"])
site_data["diversity_programs"] = diversity_programs
by_uid["diversity_programs"] = {
dp.id: dp for _, dp_day in diversity_programs.items() for dp in dp_day
}
site_data["diversity_programs_days"] = [
[day.replace(" ", "").lower(), day, ""] for day in diversity_programs
]
site_data["diversity_programs_days"].sort()
site_data["diversity_programs_days"][0][-1] = "active"
# organization awards
awards = build_awards(site_data['awards'])
site_data['awards'] = awards
# papers.{html,json}
# print(site_data["Main Track_papers"])
papers = build_papers(
raw_papers=site_data["AI for Social Impact Track_papers"]+
site_data["Demos_papers"]+
site_data["Doctoral Consortium_papers"]+
site_data["EAAI_papers"]+
site_data["IAAI_papers"]+
site_data["Main Track_papers"]+
site_data["Senior Member Track_papers"]+
site_data["Sister Conference_papers"]+
site_data["Student Abstracts_papers"]+
site_data["award_papers"]+
site_data["Undergraduate Consortium_papers"],
poster_infos=site_data["poster_infos"],
paper_recs=site_data["paper_recs"],
paper_images_path=site_data["config"]["paper_images_path"],
default_image_path=site_data["config"]["logo"]["image"]
)
# remove workshop paper in papers.html
# for wsh in site_data["workshops"]:
# papers.extend(wsh.papers)
site_data["papers"] = papers
site_data["tracks"] = list(
sorted(track for track in {paper.content.track for paper in papers})
)
site_data["main_program_tracks"] = list(
sorted(
track
for track in {
paper.content.track
for paper in papers
if paper.content.program == "main"
}
)
)
# paper_<uid>.html
papers_by_uid: Dict[str, Any] = {}
for paper in papers:
assert paper.id not in papers_by_uid, paper.id
papers_by_uid[paper.id] = paper
by_uid["papers"] = papers_by_uid
# serve_papers_projection.json
all_paper_ids_with_projection = {
item["id"] for item in site_data["papers_projection"]
}
for paper_id in set(by_uid["papers"].keys()) - all_paper_ids_with_projection:
paper = by_uid["papers"][paper_id]
if paper.content.program == "main":
print(f"WARNING: {paper_id} does not have a projection")
# about.html
site_data["faq"] = site_data["faq"]["FAQ"]
site_data["code_of_conduct"] = site_data["code_of_conduct"]["CodeOfConduct"]
# sponsors.html
build_sponsors(site_data, by_uid, display_time_format)
# posters.html
site_data["poster_info_by_day"], site_data["poster_days"], site_data["room_list_by_day"] = build_poster_infos(
site_data["poster_infos"],by_uid["papers"],site_data["papers"]
)
# site_data["main_aisi_smt_by_day"] = {
# day: list(sessions)
# for day, sessions in itertools.groupby(
# site_data["main_aisi_smt"], lambda qa: qa.day
# )
# }
print("Data Successfully Loaded")
return extra_files
def extract_list_field(v, key):
value = v.get(key, "")
if isinstance(value, list):
return value
else:
return value.split("|")
def build_committee(
raw_committee: List[Dict[str, Any]]
) -> Dict[str, List[CommitteeMember]]:
# We want to show the committee grouped by role. Grouping has to be done in python since jinja's groupby sorts
# groups by name, i.e. the general chair would not be on top anymore because it doesn't start with A.
# See https://github.com/pallets/jinja/issues/250
committee = [jsons.load(item, cls=CommitteeMember) for item in raw_committee]
committee_by_role = OrderedDict()
for role, members in itertools.groupby(committee, lambda member: member.role):
member_list = list(members)
# add plural 's' to "chair" roles with multiple members
if role.lower().endswith("chair") and len(member_list) > 1:
role += "s"
committee_by_role[role] = member_list
return committee_by_role
def build_awards(raw_awards: List[Dict[str, Any]]) -> List[Award]:
# print(raw_awards)
return [
Award(
id=award["id"],
name=award["name"],
description=award["description"],
awardees=[Awardee(
name=awardee['name'],
id=awardee['id'],
link=awardee['link'] if 'link' in awardee.keys() else None,
description=awardee['description'] if 'description' in awardee.keys() else None,
paperlink=awardee['paperlink'] if 'paperlink' in awardee.keys() else None,
image=awardee['image'] if 'image' in awardee.keys() else None,
organization=awardee['organization'],
talk=[SessionInfo(session_name = awardee['talk'][idx]['session_name'],
start_time=awardee['talk'][idx]['start_time'],
end_time=awardee['talk'][idx]['end_time'],
link=awardee['talk'][idx]['link']) for idx in range(len(awardee['talk']))]
if 'talk' in awardee.keys() else None
) for awardee in award['awardees']]
)
for award in raw_awards
]
def build_plenary_sessions(
| |
<reponame>dcripplinger/rotj
# -*- coding: UTF-8 -*-
from six import string_types
from math import ceil
from datetime import datetime
import os
import time
import pygame
from pygame.locals import *
from constants import BLACK, ITEMS, WHITE
from helpers import is_half_second, load_image
CHARS = {
# numbers
'0': load_image(os.path.join('font', '0.png')),
'1': load_image(os.path.join('font', '1.png')),
'2': load_image(os.path.join('font', '2.png')),
'3': load_image(os.path.join('font', '3.png')),
'4': load_image(os.path.join('font', '4.png')),
'5': load_image(os.path.join('font', '5.png')),
'6': load_image(os.path.join('font', '6.png')),
'7': load_image(os.path.join('font', '7.png')),
'8': load_image(os.path.join('font', '8.png')),
'9': load_image(os.path.join('font', '9.png')),
# lower case letters
'a': load_image(os.path.join('font', 'a.png')),
'b': load_image(os.path.join('font', 'b.png')),
'c': load_image(os.path.join('font', 'c.png')),
'd': load_image(os.path.join('font', 'd.png')),
'e': load_image(os.path.join('font', 'e.png')),
'f': load_image(os.path.join('font', 'f.png')),
'g': load_image(os.path.join('font', 'g.png')),
'h': load_image(os.path.join('font', 'h.png')),
'i': load_image(os.path.join('font', 'i.png')),
'j': load_image(os.path.join('font', 'j.png')),
'k': load_image(os.path.join('font', 'k.png')),
'l': load_image(os.path.join('font', 'l.png')),
'm': load_image(os.path.join('font', 'm.png')),
'n': load_image(os.path.join('font', 'n.png')),
'o': load_image(os.path.join('font', 'o.png')),
'p': load_image(os.path.join('font', 'p.png')),
'q': load_image(os.path.join('font', 'q.png')),
'r': load_image(os.path.join('font', 'r.png')),
's': load_image(os.path.join('font', 's.png')),
't': load_image(os.path.join('font', 't.png')),
'u': load_image(os.path.join('font', 'u.png')),
'v': load_image(os.path.join('font', 'v.png')),
'w': load_image(os.path.join('font', 'w.png')),
'x': load_image(os.path.join('font', 'x.png')),
'y': load_image(os.path.join('font', 'y.png')),
'z': load_image(os.path.join('font', 'z.png')),
# uppercase letters
'A': load_image(os.path.join('font', 'caps', 'a.png')),
'B': load_image(os.path.join('font', 'caps', 'b.png')),
'C': load_image(os.path.join('font', 'caps', 'c.png')),
'D': load_image(os.path.join('font', 'caps', 'd.png')),
'E': load_image(os.path.join('font', 'caps', 'e.png')),
'F': load_image(os.path.join('font', 'caps', 'f.png')),
'G': load_image(os.path.join('font', 'caps', 'g.png')),
'H': load_image(os.path.join('font', 'caps', 'h.png')),
'I': load_image(os.path.join('font', 'caps', 'i.png')),
'J': load_image(os.path.join('font', 'caps', 'j.png')),
'K': load_image(os.path.join('font', 'caps', 'k.png')),
'L': load_image(os.path.join('font', 'caps', 'l.png')),
'M': load_image(os.path.join('font', 'caps', 'm.png')),
'N': load_image(os.path.join('font', 'caps', 'n.png')),
'O': load_image(os.path.join('font', 'caps', 'o.png')),
'P': load_image(os.path.join('font', 'caps', 'p.png')),
'Q': load_image(os.path.join('font', 'caps', 'q.png')),
'R': load_image(os.path.join('font', 'caps', 'r.png')),
'S': load_image(os.path.join('font', 'caps', 's.png')),
'T': load_image(os.path.join('font', 'caps', 't.png')),
'U': load_image(os.path.join('font', 'caps', 'u.png')),
'V': load_image(os.path.join('font', 'caps', 'v.png')),
'W': load_image(os.path.join('font', 'caps', 'w.png')),
'X': load_image(os.path.join('font', 'caps', 'x.png')),
'Y': load_image(os.path.join('font', 'caps', 'y.png')),
'Z': load_image(os.path.join('font', 'caps', 'z.png')),
# as-is ascii punctuation (images look like their ascii characters)
' ': load_image(os.path.join('font', 'space.png')),
'.': load_image(os.path.join('font', 'period.png')),
',': load_image(os.path.join('font', 'comma.png')),
':': load_image(os.path.join('font', 'colon.png')),
"'": load_image(os.path.join('font', 'apostrophe.png')),
'"': load_image(os.path.join('font', 'quote.png')),
'?': load_image(os.path.join('font', 'question.png')),
'!': load_image(os.path.join('font', 'exclamation.png')),
'/': load_image(os.path.join('font', 'slash.png')),
'*': load_image(os.path.join('font', 'asterisk.png')),
'-': load_image(os.path.join('font', 'mdash.png')), # yes, the game uses mdashes like they were hyphens
# what looks like a hyphen in the game is not used as a hyphen, but it appears as a character you can
# include in creating a save file. Since what looks like an mdash in the game is used as a hyphen, I'm
# using the unicode character "ndash", or U+2013, to invoke this character that looks like a hyphen and
# is not commonly used in the game. Note that in some editors, like sublime, the ndash and mdash look
# the same. This unicode character is an ndash.
# as-is unicode punctuation (images look like their unicode characters)
u'–': load_image(os.path.join('font', 'hyphen.png')), # this unicode is an ndash, U+2013
u'©': load_image(os.path.join('font', 'copyright.png')),
u'▶': load_image(os.path.join('font', 'arrow.png')),
u'▼': load_image(os.path.join('font', 'down_arrow.png')),
u'★': load_image(os.path.join('font', 'star.png')),
# characters used for drawing feature switches inline with text ("[]" is an off switch and "<>" is an on switch)
'[': load_image(os.path.join('font', 'left_off_switch.png')),
']': load_image(os.path.join('font', 'right_off_switch.png')),
'<': load_image(os.path.join('font', 'left_on_switch.png')),
'>': load_image(os.path.join('font', 'right_on_switch.png')),
# cheap way to force space integrity by making multiple words and spaces look like one word
'~': load_image(os.path.join('font', 'space.png')),
# this is a hack to show hyphens without capitalizing the next letter (used in sword name shamshir-e)
u'ŕ': load_image(os.path.join('font', 'mdash.png')),
}
class TextBox(object):
def __init__(
self, text, width=None, height=None, adjust='left', border=False, double_space=False, appear='instant', fade_speed=1.5,
title=None, indent=0, silent=False,
):
self.text = text
self.title = title
self.lines = text.split('\n')
self.words = {}
self.indent = indent
for line in self.lines:
self.words[line] = line.split()
self.width = width if width else max([len(line) for line in self.lines])*8 + (16 if border else 0) + 8*indent
self.adjust = adjust
self.border = border
self.double_space = double_space
self.text_width = (self.width - (16 if border else 0) - 8*indent) // 8
if width:
self.fix_lines()
self.height = height if height else (
len(self.lines) * (2 if double_space else 1) * 8 + (24 if border else 0) - (8 if border and double_space else 0)
)
self.time_elapsed = 0
self.fade_speed = fade_speed
# These variables are only relevant when appear == 'scroll'
self.lines_available_now = int(ceil((self.height/8 - (3 if border else 0)) / (2.0 if double_space else 1.0)))
self.scroll_speed = 0.02 # seconds per character printed
self.starting_line = 0
self.max_starting_line = 0
self.lines_available = (
len(self.lines) if appear=='scroll'
else self.lines_available_now
)
self.appear = appear
self.lines_to_show = (
2 if appear=='fade' and not double_space
else 1 if appear=='fade' and double_space
else 1 if appear=='scroll'
else len(self.lines)
)
self.typing_sound = pygame.mixer.Sound(os.path.join('data', 'audio', 'typing.wav'))
self.needs_update = False if appear=='instant' else True
self.started = False
# chars to show on the last line to show
self.chars_to_show = 0
self.lines_to_show = min(self.lines_to_show, self.lines_available)
self.update_surface()
self.silent = silent
def fix_lines(self):
new_lines = []
for line in self.lines:
fitting_words = []
left_over = self.text_width
for words_index, word in enumerate(self.words[line]):
account_for_space = 0 if words_index==len(self.words[line])-1 else 1
to_consume = len(word) + account_for_space
if to_consume <= left_over:
fitting_words.append(word)
left_over = left_over - to_consume
else:
new_lines.append(u' '.join(fitting_words))
fitting_words = [word]
left_over = self.text_width - to_consume
if len(fitting_words) > 0:
new_lines.append(u' '.join(fitting_words))
self.lines = new_lines
self.words = {}
for line in self.lines:
self.words[line] = line.split()
def update_surface(self):
y_space = 2 if self.double_space else 1
surface = pygame.Surface((self.width, self.height))
surface.fill(BLACK)
for y, line in enumerate(self.lines[self.starting_line:]):
chars_printed = 0
if self.lines_to_show == y:
break
x = (1 if self.border else 0) + self.indent + (
(self.text_width-len(line))/2 if self.adjust=='center'
else self.text_width-len(line) if self.adjust=='right'
else 0
)
vertical_pos = (y * y_space + (2 if self.border else 0)) * 8
for word in self.words[line]:
# if word.endswith('1052'):
# import pdb; pdb.set_trace()
# is_number is used for displaying numbers in a more readable format, where every other triplet of
# characters is a bit transparent over a black background, making them a bit gray.
is_number = True
for char in word:
if char not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',', '.', '?', '!', ' ', '~', '/']:
is_number = False
break
if is_number:
numbers_left = 0
# This is just in case there is a space or punctuation somewhere in the word.
for char in word:
if char in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
numbers_left += 1
else:
break
for char in word:
if self.appear == 'scroll' and y == self.lines_to_show - 1 and chars_printed == self.chars_to_show:
break
if char not in CHARS:
raise Exception(u'char not in CHARS. char={}, text="{}"'.format(char, self.text))
if (
is_number
and numbers_left > 3
and char in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
and (numbers_left-1) % 3 == 0
):
char_image = pygame.Surface((8, 8))
char_image.blit(CHARS[char], (0, 0))
pygame.draw.rect(char_image, WHITE, (7, 7, 1, 1), 1)
numbers_left -= 1
else:
char_image = CHARS[char]
if is_number and char in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
numbers_left -= 1
surface.blit(char_image, (x*8, vertical_pos))
x += 1
chars_printed += 1
if is_number and numbers_left == 0 and chars_printed < len(word):
for remaining_char in word[chars_printed:]:
if remaining_char in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
numbers_left += 1
else:
break
if self.appear == 'scroll' and y == self.lines_to_show - 1 and chars_printed == self.chars_to_show:
break
surface.blit(CHARS[' '], (x*8, vertical_pos))
x += 1
chars_printed += 1
if self.border:
pygame.draw.rect(surface, WHITE, (3, 3, self.width-6, self.height-6), 2)
if self.show_down_arrow() and is_half_second():
surface.blit(CHARS[u'▼'], (self.width/2, vertical_pos + (16 if self.double_space else 8)))
if self.title:
for i, char in enumerate(self.title):
surface.blit(CHARS[char], (i*8+16, 0))
self.surface = surface
def show_down_arrow(self):
return self.appear == 'scroll' and not self.has_more_stuff_to_show_now() and self.has_more_stuff_to_show()
def has_more_stuff_to_show(self):
lines_shown = self.lines_to_show + self.starting_line
has_more_lines_to_show = lines_shown < self.lines_available and lines_shown < len(self.lines)
has_more_chars_to_show = self.appear == 'scroll' and self.chars_to_show < len(self.lines[lines_shown - 1])
return has_more_lines_to_show or has_more_chars_to_show
def has_more_stuff_to_show_now(self):
'''
Only ever use this in the case of appear == 'scroll'
'''
# This is to make room for the continuation arrow if it isn't the end of the whole text.
lines_available_now = (
self.lines_available_now if self.starting_line + self.lines_available_now >= len(self.lines)
else self.lines_available_now - 1
)
has_more_lines_to_show_now = | |
Record 70: Address = 0x3300, Length = 128
0x3300,0x80,
0x9e,0x3,0x7f,0x33,0xfd,0x1c,0x8b,0xc9,0x2,0xed,0x28,0x61,0x19,0xb4,0xf6,0x8d,
0x65,0xd7,0xa,0x4d,0x1b,0xa3,0xc9,0x88,0x47,0x75,0x90,0x32,0x94,0x2d,0x42,0xdd,
0x71,0x1d,0x68,0x10,0xab,0x6f,0x99,0x5f,0x25,0x86,0xf5,0xce,0xac,0x56,0x40,0x29,
0x5f,0xec,0x72,0x3e,0x13,0x92,0x3c,0xfb,0xde,0x8f,0xd5,0x77,0x24,0x5a,0xe4,0x68,
0x87,0xf2,0x14,0xa6,0x94,0xe6,0x55,0x50,0x89,0xab,0xaa,0xe3,0x8f,0x72,0x0,0x31,
0x68,0x74,0x7c,0xd4,0x4,0xe8,0x3,0xb3,0x2c,0x62,0x69,0x2b,0x5d,0xda,0x2b,0x61,
0x42,0x83,0xd2,0xc5,0x1b,0x7a,0x39,0xa6,0xb3,0xea,0x1c,0xe9,0xf1,0xdb,0xcb,0x3a,
0x45,0xdf,0x29,0xc7,0x56,0x9c,0x59,0xb1,0xc,0xa1,0xfd,0x1,0x14,0x11,0x61,0x52],[
# Record 71: Address = 0x3380, Length = 128
0x3380,0x80,
0xa7,0x9c,0x31,0xb,0x43,0xa2,0x4,0x9a,0x46,0x99,0x6d,0x50,0x75,0x3b,0xe5,0xf0,
0x45,0xce,0x49,0x1e,0x69,0xa4,0x5a,0xba,0x94,0x6c,0xfa,0x49,0xef,0xd3,0x83,0xd6,
0x93,0xea,0x73,0xb6,0x43,0x86,0x8e,0x6e,0x31,0x82,0x1d,0x28,0x73,0x29,0x6b,0x47,
0xbb,0xa0,0x6c,0xfe,0x8e,0x88,0xf4,0x90,0xd,0x64,0x56,0x6c,0x7f,0x46,0x41,0x93,
0xa8,0x7b,0x1a,0xf6,0x1f,0x24,0x3e,0x57,0xa7,0xab,0xd,0x4e,0x85,0x7e,0x34,0xdc,
0x39,0xa9,0x0,0xd8,0x36,0x5e,0xfe,0x42,0x3c,0x7b,0x1a,0x1d,0x3f,0xe5,0x68,0x7b,
0x4c,0x83,0xa4,0x90,0x29,0x40,0x78,0xba,0x8e,0x3a,0x85,0x44,0xdf,0x1,0xbd,0xc2,
0x7a,0x46,0x46,0x9c,0x14,0x59,0xd1,0x86,0x45,0xe1,0x24,0xd5,0x7e,0xe6,0x46,0xea],[
# Record 72: Address = 0x3400, Length = 128
0x3400,0x80,
0x70,0x15,0x70,0x57,0x99,0xd4,0xd5,0x12,0x63,0x79,0x5d,0x6c,0x5d,0x8b,0xff,0x25,
0x98,0xef,0x8d,0xbe,0xe8,0xb5,0xcd,0x58,0xb0,0x26,0xa3,0x3d,0xca,0x1e,0x54,0xd3,
0x55,0xe1,0x1e,0x97,0x80,0x96,0x65,0xca,0x2f,0xf7,0x1f,0x8a,0xee,0xa5,0xd5,0x6b,
0x8,0xbb,0xe3,0xb,0x8,0xc4,0xef,0x7c,0x73,0xc8,0xa6,0xfe,0xd1,0xc9,0x54,0xd1,
0xe9,0xc3,0x63,0xd,0x6a,0xc,0x1c,0xde,0x31,0x65,0xe9,0xeb,0x43,0x62,0x3e,0xfe,
0x36,0xe0,0xe7,0x81,0xe3,0x5c,0xdc,0xbd,0xcf,0x97,0xfb,0xc5,0xfe,0x71,0xdd,0x5d,
0xb0,0x4e,0xbb,0xf6,0x39,0x6b,0xed,0x84,0x6f,0x9c,0x5a,0x8d,0xa,0x8b,0x7d,0x61,
0x7b,0x4b,0x0,0xab,0x11,0x5e,0xb0,0x9f,0x8f,0x39,0xc6,0x3f,0x65,0xc7,0x2c,0xbc],[
# Record 73: Address = 0x3480, Length = 128
0x3480,0x80,
0x5a,0x87,0x32,0xd,0xd4,0x19,0x91,0x75,0xed,0x4f,0x68,0xbb,0x87,0x22,0xc6,0x62,
0x79,0x4c,0xcd,0xc6,0xc5,0xf9,0x33,0xe8,0xa,0x6,0x2e,0xb6,0xa0,0x90,0x3b,0xfa,
0xb5,0xe9,0x32,0xbe,0x61,0x60,0xe2,0x2c,0xc2,0x4b,0xee,0x6c,0x5a,0x33,0x91,0xfa,
0x9e,0xf,0x94,0x6f,0x87,0x3a,0x29,0xd2,0x64,0x2,0xf6,0x93,0xa6,0x86,0x76,0x7a,
0xf3,0xfb,0x33,0x72,0xe6,0x9c,0x82,0xff,0xc7,0xac,0xa4,0x21,0x25,0x2f,0x2e,0x8f,
0x1b,0x5d,0xe1,0xdb,0x43,0xe6,0xdd,0x64,0xa3,0x87,0xc3,0xd7,0x3,0xcf,0x3f,0x26,
0x6f,0xf8,0x88,0x30,0xb5,0xba,0xa0,0x12,0x5d,0x89,0xd6,0x1d,0x11,0x8d,0x48,0x90,
0x74,0x4c,0xc7,0x6f,0xb,0x56,0xa4,0xf2,0x5c,0x6,0x26,0xd7,0xd5,0x9e,0x6a,0xa8],[
# Record 74: Address = 0x3500, Length = 128
0x3500,0x80,
0x1e,0xbb,0xe5,0x42,0xf4,0xc7,0xc8,0x3c,0xd,0x9d,0xde,0x3a,0xe2,0x82,0xf5,0xe6,
0x97,0x5a,0x94,0x80,0x36,0x83,0x60,0x61,0x7a,0x4a,0xaa,0xb2,0xa7,0x5e,0x5d,0x37,
0x5,0xec,0x5b,0x36,0x22,0x71,0xb5,0xca,0xe3,0xd3,0x7c,0xef,0x43,0x3f,0xd4,0xd4,
0x86,0xe0,0xfa,0x3a,0x64,0x2d,0xe2,0x98,0xcc,0xa2,0x1d,0x5c,0xc7,0x2c,0xcd,0x4c,
0xdb,0x48,0xfc,0xf1,0xbf,0x65,0x31,0x14,0x7e,0x30,0xb5,0xa8,0x10,0x22,0xe5,0xec,
0x46,0x4f,0x37,0xc3,0xeb,0xbd,0x12,0xd8,0x15,0x36,0xe5,0x7c,0x95,0xeb,0xf5,0xbb,
0x78,0x59,0x1d,0xc5,0x89,0xc2,0x96,0x84,0x4a,0x63,0x24,0x6c,0x3b,0x63,0x4,0x1e,
0x60,0xc1,0xc2,0x50,0xb1,0xfd,0x52,0xf4,0x9e,0xb1,0x7c,0x78,0xd7,0xce,0x59,0xcf],[
# Record 75: Address = 0x3580, Length = 128
0x3580,0x80,
0xfe,0x50,0xc6,0x85,0xee,0xe0,0xb3,0xd8,0x9d,0x50,0xb7,0xa5,0x8d,0xfb,0xaa,0xd7,
0x66,0xe4,0xf4,0xf4,0x7e,0xfd,0x99,0x94,0x7d,0xc2,0x2,0x1,0x39,0x41,0xa4,0xf2,
0xaf,0x45,0x14,0xd5,0x3,0x65,0x88,0xea,0x49,0x1a,0xd7,0xdc,0x25,0x34,0x42,0xb0,
0x1e,0x86,0x21,0xa5,0x2d,0xc8,0x7,0x63,0x48,0xe9,0xa1,0x48,0x9a,0xe6,0x7,0xd9,
0x28,0xfe,0x4a,0x43,0xe,0x83,0xbe,0xa6,0x17,0x5e,0x5,0xff,0xfc,0x45,0x9b,0xd0,
0x9,0x88,0x57,0xdb,0xd2,0x46,0x4a,0x4,0xd0,0xff,0x77,0xe0,0x68,0x32,0x9e,0x91,
0xcc,0x65,0xa5,0x76,0x47,0x1e,0xeb,0x2d,0x5f,0x8a,0x5,0x9f,0x4b,0xc5,0xb,0x20,
0x71,0x9,0xf6,0x94,0xfc,0x87,0x6a,0xad,0x6a,0xe,0x6b,0x11,0xda,0x2f,0xc2,0x8f],[
# Record 76: Address = 0x3600, Length = 128
0x3600,0x80,
0xe5,0x4f,0xcc,0x7f,0xd8,0xcf,0xc6,0xe3,0x2d,0x22,0xf,0xb5,0x86,0x4e,0x7d,0x64,
0x74,0x97,0x61,0xc5,0x49,0x78,0x49,0x5b,0x5c,0xcf,0x2e,0x5b,0xde,0xfc,0xa0,0x9e,
0x90,0x6b,0x4d,0xec,0x18,0x6e,0x94,0x3b,0x94,0x3a,0x3f,0xb2,0x41,0xf8,0xf1,0x3e,
0x29,0x4f,0x50,0xff,0xe0,0x8c,0xde,0x1d,0xf1,0x6f,0xc3,0x0,0x81,0xa9,0x92,0xa3,
0x71,0xb,0x2d,0x39,0xb5,0x9c,0xf9,0xcd,0xff,0xd2,0xd7,0xdf,0x95,0x1c,0x79,0x3,
0x49,0x72,0x6c,0xf9,0xb0,0x72,0x66,0x25,0xc9,0x84,0xde,0xce,0xcd,0x70,0x59,0x8c,
0x81,0x10,0x53,0x6a,0x6c,0x4e,0x4f,0x43,0xd9,0x43,0x3b,0x92,0x8a,0x75,0x8b,0xff,
0xc8,0x7f,0x68,0x8a,0x81,0x1e,0xe2,0x95,0x82,0x2d,0xb2,0xda,0x65,0x16,0x12,0xba],[
# Record 77: Address = 0x3680, Length = 128
0x3680,0x80,
0x9d,0x72,0xf7,0x13,0x62,0x8e,0x3d,0xe,0x72,0x6f,0x5e,0xab,0x74,0x69,0xfd,0x12,
0x8,0xf6,0xbe,0x68,0xe1,0xce,0xf4,0xc1,0xca,0x1b,0x1,0x8b,0xce,0x7f,0x9a,0xdc,
0x33,0xb7,0xc6,0x10,0x70,0x6e,0x98,0xf1,0xc6,0x82,0xda,0x97,0x35,0x3c,0x6f,0xa4,
0x32,0x21,0x4e,0xa7,0x81,0x77,0x99,0x38,0x2b,0xc4,0x49,0x62,0xcf,0x9c,0xd6,0x1e,
0x7d,0x3d,0xa1,0x8,0x4d,0x17,0x56,0x82,0x37,0x3e,0xe3,0x9e,0xa3,0xdc,0x34,0xa6,
0xf0,0x22,0xa1,0x85,0x70,0xe3,0x3e,0x2f,0x5e,0xb6,0x6b,0x62,0x88,0xe8,0x39,0x2,
0x45,0x1d,0xa9,0x2f,0x39,0x73,0xd2,0xf8,0x1f,0xf1,0x78,0x84,0xec,0x3,0xd2,0x6a,
0xae,0xdd,0x61,0x45,0xb7,0xc9,0x96,0x15,0xa1,0x2a,0xb8,0xfc,0xb5,0xc9,0xec,0x9d],[
# Record 78: Address = 0x3700, Length = 128
0x3700,0x80,
0x91,0x29,0x4,0x57,0x84,0x9a,0xc8,0x5c,0xb1,0x67,0xb2,0xdf,0xd0,0x7d,0xc5,0x7b,
0xc9,0xd0,0xc5,0x4c,0x56,0x12,0xac,0x8b,0xa7,0xe,0x80,0xa8,0xaa,0x8f,0x8,0xdd,
0x6d,0x2a,0x3a,0xc5,0xc,0x96,0x38,0xfc,0xec,0xaf,0x53,0xe,0x16,0x63,0x24,0x19,
0xbb,0xf8,0x9a,0x11,0x43,0x97,0x27,0x52,0xf5,0x91,0x70,0x77,0x82,0xcd,0x59,0x9d,
0xdb,0xfe,0x8,0xf2,0x50,0x34,0xa7,0xde,0x20,0x16,0x38,0xb5,0x2f,0xae,0xd6,0xbc,
0x28,0x91,0x85,0xd5,0x40,0xc2,0xa0,0x7a,0x4d,0x51,0xe9,0xc6,0x8,0x8c,0xf4,0x28,
0x2d,0xd4,0xcd,0x92,0xf3,0xed,0xfb,0x97,0x87,0x7d,0xb6,0x2b,0xff,0x72,0x6f,0x32,
0xf5,0x89,0xcd,0xbc,0xff,0xc5,0x94,0xdd,0x2,0x94,0x7c,0x7b,0x11,0x44,0x4f,0x4c],[
# Record 79: Address = 0x3780, Length = 128
0x3780,0x80,
0xf9,0x5e,0x71,0xb2,0x62,0xaa,0xc3,0xd7,0x35,0xf1,0xe2,0x43,0xdd,0xaa,0x60,0x7f,
0xca,0xe2,0x81,0x4,0x60,0xbc,0xa1,0xac,0xb0,0x72,0xf9,0xfe,0x77,0x2a,0xbd,0x62,
0xc4,0xaa,0x7c,0xff,0x3a,0x93,0xa7,0xcf,0xed,0xb1,0xcb,0xd4,0x51,0x1e,0x59,0x79,
0xa4,0xe9,0xc0,0xfa,0xf4,0xd2,0x37,0xe3,0x8b,0xe5,0xb2,0xdb,0x32,0xc2,0x18,0x13,
0x68,0x45,0xd7,0x37,0x14,0x98,0x89,0x66,0x36,0x4f,0x34,0xeb,0x13,0xb2,0xbd,0x28,
0xcf,0x1d,0xf0,0x14,0xf3,0xf,0x3f,0x98,0x86,0xac,0x45,0x9d,0x44,0x94,0x12,0x12,
0x90,0x43,0xd7,0x3f,0xe,0xa9,0x7a,0x3f,0x65,0xfb,0xaf,0xf1,0xef,0xcb,0xf9,0x23,
0xa7,0x29,0x42,0xca,0x7d,0xfb,0xee,0xad,0xfd,0x3c,0xab,0xa3,0x4c,0xf6,0xb5,0xb2],[
# Record 80: Address = 0x3800, Length = 128
0x3800,0x80,
0xb0,0x5,0x2b,0xcd,0x29,0x70,0xd8,0x42,0x4e,0xc6,0x1a,0x8c,0xc6,0x7b,0xc,0x55,
0x97,0x8c,0x4a,0x26,0x93,0x88,0x8a,0x67,0x73,0xc7,0xde,0xa3,0x11,0x34,0xe3,0x13,
0xeb,0xba,0xe0,0x18,0x3c,0xe8,0xca,0xc8,0xab,0x93,0x2b,0xd3,0xd2,0xd6,0xd,0x66,
0x27,0x81,0x3b,0xa2,0x76,0x46,0x2a,0x35,0x71,0xa1,0xa2,0x83,0xe,0x56,0xf2,0x60,
0x70,0x48,0x1d,0xfe,0x6e,0x81,0xdd,0x72,0xac,0x97,0xe8,0x99,0xff,0xf6,0xfe,0xca,
0x8e,0xc1,0x6e,0xb5,0x55,0x58,0xb9,0xe1,0x90,0xdb,0x41,0x61,0x64,0x1d,0x5f,0x51,
0x72,0x2e,0x9a,0x1b,0xde,0x90,0x43,0xa0,0x6d,0x2c,0x8e,0x40,0x3,0x44,0xad,0xc9,
0x5f,0xd8,0xe6,0x38,0xa1,0xe7,0xa9,0xce,0x7e,0xcb,0xec,0xb9,0x6c,0xb3,0x47,0x9c],[
# Record 81: Address = 0x3880, Length = 128
0x3880,0x80,
0x73,0xa9,0x34,0x6a,0x94,0x8e,0x7d,0xee,0x8c,0xc4,0x92,0x36,0xfe,0xac,0x78,0xfd,
0x7,0xd2,0xe,0xf3,0x8f,0xf6,0xf8,0x2d,0xd9,0x4a,0xc0,0xfa,0xa6,0x14,0xe,0xce,
0x82,0xa7,0x7c,0x2f,0x1c,0x9,0x41,0xc9,0x92,0xea,0x8d,0xf3,0x15,0x36,0x3e,0xc3,
0xa6,0x2c,0x88,0xbb,0x1,0x82,0x7d,0xdc,0x4a,0x39,0x55,0x10,0x28,0xda,0x6c,0x42,
0x92,0x35,0x10,0x55,0x9c,0x42,0x41,0x8a,0xe0,0x22,0x26,0x73,0x60,0x4d,0x49,0x55,
0x56,0x6a,0x1f,0x36,0x5b,0x93,0x3f,0x6d,0xba,0xba,0x49,0xa2,0xe0,0x8e,0x67,0x2,
0x4b,0xf5,0x5c,0x1b,0x2f,0xe1,0xf5,0xd2,0xd0,0xf7,0xb1,0xb6,0x1d,0x9,0x7f,0xd,
0xaa,0xd,0xd,0x4c,0xf6,0xdb,0x53,0x29,0xe3,0xae,0xe0,0xdf,0x13,0x5a,0xcf,0x10],[
# Record 82: Address = 0x3900, Length = 128
0x3900,0x80,
0x1b,0x9f,0x4b,0xec,0xdb,0x20,0x2e,0x9,0x53,0xea,0x30,0xff,0x5d,0x38,0xe6,0x98,
0xb6,0x96,0x42,0x16,0x48,0x51,0x29,0xa0,0x58,0xbc,0xb7,0x2e,0x63,0x73,0x28,0xac,
0x74,0x4d,0xff,0x1d,0xe6,0x56,0x1,0x52,0xa3,0xc4,0x17,0xa8,0x4,0x9b,0x6c,0x2b,
0xfc,0x53,0xb2,0xb1,0x4c,0x3b,0x85,0x6c,0x46,0xfa,0x1e,0xee,0x14,0x21,0xac,0x11,
0xc4,0xc,0x9b,0x76,0xfa,0xba,0x1e,0xcc,0x4e,0xa7,0x83,0x61,0x15,0x9e,0xfe,0x5a,
0xf7,0x18,0x3b,0xf3,0x35,0xb7,0x3e,0x4,0xe6,0xb4,0x6f,0x86,0xe1,0x90,0x2a,0x1f,
0x98,0x0,0xe6,0x34,0x43,0xf3,0xa0,0xaa,0xa2,0x9d,0x9a,0xb7,0x5e,0xb8,0xe9,0xd1,
0x45,0x45,0x2e,0x8d,0x2a,0xb0,0x81,0x7,0x81,0x40,0x6f,0xd2,0x97,0xda,0x4f,0x7],[
# Record 83: Address = 0x3980, Length = 128
0x3980,0x80,
0xdd,0xfb,0x12,0x21,0x31,0x5d,0xf5,0x7e,0x33,0xd7,0x14,0x1a,0xfd,0x2b,0xc9,0x3d,
0x4,0x7,0xb9,0x41,0xdd,0x1d,0xe3,0x65,0xab,0x4c,0x42,0xeb,0x2e,0x7d,0x23,0x59,
0x8e,0xf6,0x9c,0xbf,0x2d,0xe2,0xa0,0x21,0xea,0xa6,0xe5,0x7a,0x8e,0x6a,0x9b,0x13,
0x87,0x2f,0xce,0xea,0xc3,0x43,0x7c,0x7f,0xf,0x59,0x1e,0xf8,0x74,0x62,0x42,0xac,
0x8a,0x89,0x41,0xc5,0xc0,0x11,0xc1,0x5f,0x82,0x14,0xdd,0xc8,0x6d,0xaa,0xf,0x9a,
0x53,0x31,0xc4,0xe8,0x45,0xca,0xa5,0xa8,0xd9,0x72,0x88,0xac,0xc,0x89,0x2e,0x5,
0x8d,0xcc,0xa2,0x50,0x91,0x84,0x75,0x41,0x28,0x75,0xfb,0xcd,0xf5,0xc7,0xee,0xb,
0xed,0xac,0xff,0xb2,0x28,0x68,0x33,0xbe,0xd4,0x34,0x30,0xba,0xef,0xc4,0x8a,0xc1],[
# Record 84: Address = 0x3a00, Length = 128
0x3a00,0x80,
0x27,0xfa,0xe,0x12,0x15,0x90,0x21,0x64,0x3c,0xb4,0xda,0x7c,0xd3,0x9d,0x94,0xf8,
0x8b,0x25,0xec,0xc9,0x18,0xb7,0x88,0x42,0x9,0xdd,0x23,0x2a,0x3,0x96,0xa4,0x8e,
0xb2,0xc4,0xe1,0x8c,0xd0,0x90,0x21,0x93,0x16,0x5,0xd1,0x56,0x82,0xa0,0x4b,0xf5,
0xa6,0x18,0x25,0xb8,0xd1,0xb7,0x66,0xd3,0xd6,0x74,0x38,0xc,0x8a,0x92,0x27,0x14,
0xf6,0xfd,0x68,0x4a,0x31,0x57,0x2a,0xa2,0xf3,0x45,0x33,0x8f,0xfe,0x2d,0x31,0x3f,
0xb9,0xb3,0x17,0x75,0xdf,0x18,0x41,0x16,0xe0,0x81,0x8f,0x9c,0x9e,0x75,0x92,0xa7,
0x91,0xda,0xd0,0x33,0x6a,0x83,0x73,0x31,0x63,0x5f,0x82,0x1,0xd9,0xb1,0xe9,0x25,
0x8f,0x6e,0xe7,0xba,0xfc,0xa7,0x1e,0x22,0x1a,0xc3,0x76,0xc5,0xfc,0x6b,0x25,0xde],[
# Record 85: Address = 0x3a80, Length = 128
0x3a80,0x80,
0xff,0x0,0x1f,0x22,0x76,0x93,0x6d,0xc6,0x2c,0x4,0x84,0xb,0xa6,0x72,0x8e,0xca,
0xa4,0x6b,0xbe,0xd7,0x68,0x2f,0x53,0x1c,0x11,0x2c,0xac,0x49,0xcf,0xce,0x37,0xa9,
0x74,0xe3,0x15,0x3a,0x8c,0x9f,0x29,0x57,0x36,0xe5,0x83,0x36,0x4c,0xe4,0xf5,0x76,
0xf7,0xa1,0x68,0xfb,0x64,0xd1,0x69,0xf7,0x19,0xc2,0x93,0x6c,0x6a,0xb8,0x7,0xf4,
0xf0,0x49,0xb6,0x9c,0x36,0x5,0x1,0x31,0x4b,0xa4,0xc4,0xa2,0x51,0x9a,0x12,0x5,
0xfb,0xc8,0x73,0x73,0x72,0x23,0x3c,0xdb,0xab,0x96,0xaa,0xf8,0x6f,0x24,0x7e,0x6e,
0x66,0xc7,0xc0,0x5b,0xdb,0x9a,0x5e,0xfe,0x96,0xb0,0xc1,0xcf,0xdd,0x81,0xae,0x87,
0x4b,0xac,0xfe,0xd,0xa2,0xf5,0x38,0xa2,0xff,0xdb,0x1a,0x28,0xfc,0x32,0x9c,0x4f],[
# Record 86: Address = 0x3b00, Length = 128
0x3b00,0x80,
0x1f,0xc2,0xb7,0x4a,0xfa,0x8c,0x8d,0x63,0xd7,0x4c,0xeb,0xfd,0x32,0x17,0x1,0x72,
0xf0,0xde,0xd1,0x64,0xab,0x3c,0xef,0x22,0xc1,0x0,0xf0,0xe0,0x55,0x54,0xc3,0x1d,
0x80,0x8f,0xb,0xeb,0xa4,0x65,0x9d,0xa9,0xb5,0xeb,0x3f,0x95,0x98,0xe8,0xc5,0x68,
0xc4,0x6b,0x20,0x90,0xcd,0xa3,0x96,0xe7,0xe4,0xf1,0x6a,0x14,0x2e,0xe7,0x7d,0x17,
0x99,0xc6,0xed,0xde,0xea,0x38,0x85,0xfa,0x1d,0x64,0x36,0x72,0x79,0xed,0x44,0x76,
0x26,0x51,0xf6,0x9,0x87,0xdb,0x6a,0xab,0x5,0xc8,0x8f,0x41,0xa6,0x2a,0x2f,0x96,
0x3c,0x8,0xc,0x3d,0x5a,0xcd,0xfb,0x2f,0xb2,0xcc,0xd1,0x2d,0x40,0xb0,0x40,0x48,
0xc2,0xd1,0x94,0x25,0xb4,0x70,0x6c,0x3,0x43,0x8b,0x1a,0xd6,0x89,0x9b,0x5a,0xc2],[
# Record 87: Address = 0x3b80, Length = 128
0x3b80,0x80,
0xa9,0x55,0xb1,0xdd,0xd7,0xea,0xcf,0x1c,0xce,0x19,0xa1,0x3,0x50,0xb3,0xdd,0x67,
0x11,0x25,0x58,0x55,0x85,0x8f,0xc0,0x87,0x44,0xc7,0x16,0xa3,0xcc,0x33,0x71,0xb2,
0xd1,0xea,0x7c,0x6c,0x36,0xec,0x91,0x58,0x5e,0x3d,0xd1,0xcd,0xa4,0x4d,0xe6,0x3b,
0x90,0x36,0x57,0xa7,0x9c,0x92,0xf8,0x22,0xc3,0x5,0xac,0x2c,0xe5,0x65,0x5b,0x19,
0x36,0xd6,0xa6,0x89,0xc9,0xbc,0xe,0x12,0x75,0x44,0xbf,0x68,0xa2,0x3c,0x7e,0x54,
0xc4,0x88,0xad,0xa7,0xe6,0x72,0xa7,0xe2,0xac,0x5d,0x61,0x6d,0xd2,0xa,0x23,0x7f,
0x92,0x4c,0x28,0x35,0xdc,0x19,0x1,0xcb,0x31,0xe5,0x6f,0x65,0x88,0xa6,0xd0,0xec,
0x87,0x7a,0x9f,0xd7,0x78,0xed,0x42,0x6b,0xb0,0x50,0x44,0x66,0x7a,0xc1,0xc7,0x6f],[
# Record 88: Address = 0x3c00, Length = 128
0x3c00,0x80,
0x6a,0x1a,0xdc,0xa8,0x71,0x5b,0x60,0x43,0x21,0x35,0xd8,0x72,0x2c,0x1,0x88,0x80,
0xe8,0x7c,0x32,0xe2,0xd4,0x54,0x1c,0x66,0xd0,0xe8,0xc0,0x40,0xfc,0x16,0xe2,0xa1,
0x3e,0x55,0x3e,0x8,0x57,0x7a,0x8c,0xfd,0x9c,0xca,0x3f,0x96,0x63,0x56,0xd8,0x97,
0xfc,0xa6,0x6a,0x2d,0xd9,0xd4,0xc0,0x16,0xb7,0x5d,0x21,0xee,0x1a,0x72,0xa,0xaa,
0xf1,0x7b,0xd0,0x6,0xb,0xca,0x94,0xde,0x4a,0xcf,0x97,0x7d,0xbf,0x6c,0x5,0x10,
0x3f,0xb3,0xb4,0x27,0x64,0x47,0xe1,0xb9,0xb1,0xfe,0xdd,0xb,0x0,0xf,0x93,0x35,
0xe8,0x78,0xb1,0x35,0xe1,0xea,0xaf,0xfd,0x44,0x1b,0xc9,0x8a,0xbd,0x1d,0xd2,0x44,
0x85,0xa2,0xde,0xf9,0x5,0x42,0x4c,0x76,0xf7,0x50,0x88,0x49,0xb9,0x4d,0x4f,0x56],[
# Record 89: Address = 0x3c80, Length = 128
0x3c80,0x80,
0x48,0xcf,0xe0,0xc5,0x45,0xbb,0x1b,0xa,0x9f,0xe,0x7d,0x1f,0x1a,0x9d,0x89,0x26,
0xab,0x15,0x74,0xba,0x64,0x12,0x13,0x7c,0xd5,0x8,0x14,0x7d,0xbf,0x78,0x9b,0x88,
0x4a,0xa5,0xf5,0x29,0x4f,0x9e,0x4c,0x23,0xaf,0x91,0x5,0x17,0xca,0x5f,0x8f,0x19,
0xf8,0x36,0xa1,0x3f,0x94,0xe9,0xc7,0x17,0x2e,0x25,0xd6,0xc2,0x11,0xac,0xc4,0xb,
0x46,0x3,0x33,0xbc,0x65,0xa6,0x38,0x97,0xa9,0xc0,0xef,0x56,0xf8,0x7b,0x42,0xd3,
0x22,0x9d,0x23,0xe8,0x5d,0x7e,0x47,0x88,0x2d,0x44,0xaa,0xd3,0x89,0xe4,0xfb,0xc4,
0x20,0xfd,0x56,0x9c,0xc4,0x4d,0x74,0xb4,0xd7,0x6f,0xfe,0x86,0x59,0x36,0x15,0xf4,
0xa5,0x17,0xd2,0x63,0x8b,0xff,0x32,0x47,0xce,0xc0,0xae,0x9b,0x38,0x90,0xeb,0x75],[
# Record 90: Address = 0x3d00, Length = 128
0x3d00,0x80,
0x22,0x7,0xbf,0x74,0x9a,0xa0,0x51,0x53,0xba,0x52,0xf5,0xb7,0x86,0x73,0x70,0xa,
0xc0,0x1d,0xe1,0x59,0x8d,0x1f,0xa9,0xc6,0xa7,0x64,0x6a,0xf4,0x6b,0xf5,0x84,0x34,
0xc4,0xd4,0xd1,0x6c,0xb2,0x35,0xb0,0x5e,0xd3,0xfb,0xf4,0xc9,0x67,0x46,0x47,0x18,
0x33,0xa1,0x18,0x61,0x39,0x6d,0x53,0x31,0x92,0x38,0xf2,0xe2,0x4b,0xdf,0x69,0xd4,
0xff,0x7d,0x97,0xe5,0xcc,0x6f,0x3a,0x24,0xaf,0x93,0xb9,0x4a,0x17,0x3e,0x12,0x28,
0xb2,0x14,0xcc,0x71,0x5e,0x71,0xcf,0xc2,0x7e,0xe2,0xb1,0x80,0x6d,0xb4,0x3e,0xf8,
0x10,0xda,0xe9,0x64,0x46,0x48,0xe7,0x2d,0xd2,0x96,0x92,0xdb,0xe1,0xc2,0x72,0xb0,
0x16,0x54,0x27,0x79,0x6a,0x15,0x7d,0x59,0xb7,0x9,0xbb,0xb,0x44,0x68,0xea,0x93],[
# Record 91: Address = 0x3d80, Length = 128
0x3d80,0x80,
0x21,0x88,0x27,0x82,0x2d,0xd2,0x35,0xc3,0xfa,0xd7,0x64,0x98,0x6e,0x86,0xdc,0x1d,
0x9e,0x8b,0xc1,0x5,0x7f,0xfe,0x91,0xe5,0x10,0xad,0x6c,0x35,0x43,0x89,0x64,0xed,
0xb3,0x51,0xf1,0xac,0xe6,0x1b,0x1f,0xc7,0xae,0x22,0xa4,0xd8,0xfb,0xcf,0xd3,0x96,
0xc6,0x4c,0xc2,0x30,0x9e,0x76,0xbc,0x2,0x7b,0xf7,0x73,0xf0,0x17,0x1e,0xaf,0xec,
0x4a,0x2c,0xcf,0xad,0xd9,0xfe,0xe3,0xe,0xba,0x5c,0x22,0x2d,0xa2,0x99,0x80,0x21,
0xdd,0x5f,0x6c,0xa3,0xea,0xe2,0xf9,0x3b,0x24,0x11,0x7b,0x80,0x97,0xe3,0x49,0x48,
0xfd,0xce,0x3c,0xf9,0xa3,0x2f,0x3d,0x71,0x5a,0x72,0x6,0x74,0x7e,0x6c,0x4f,0xc7,
0x42,0x40,0x31,0x85,0x47,0xa3,0x8c,0x3d,0x8b,0x93,0xa4,0xef,0xa3,0x8b,0x3e,0xca],[
# Record 92: Address = 0x3e00, Length = 128
0x3e00,0x80,
0x9c,0x39,0x93,0x78,0x5e,0xbd,0x32,0xc6,0x4e,0x2f,0x43,0xb9,0xda,0xa4,0x34,0x2e,
0xb7,0x1f,0x8e,0x28,0x26,0x72,0xf,0xdd,0xd6,0xae,0xae,0x35,0xd4,0x29,0x2f,0xa3,
0x70,0x82,0xe4,0x30,0x46,0xee,0x12,0x4c,0xb2,0x64,0xf8,0xcb,0x79,0x52,0xa4,0xb9,
0x2,0x64,0xca,0x7,0x54,0xe4,0xf0,0xf8,0x97,0x5f,0x12,0x4c,0x2c,0x49,0xea,0xba,
0x90,0x10,0x66,0xf2,0x84,0xf2,0xa9,0xee,0x4f,0x45,0x35,0x8d,0xd3,0x4b,0x39,0x52,
0x7b,0xa7,0x1b,0x66,0x1c,0xd7,0xe3,0x5,0x88,0x85,0xbb,0x83,0xc2,0xb2,0x89,0xf7,
0x1e,0x60,0xad,0x6d,0x53,0x11,0x4,0x13,0xcd,0x4c,0x61,0x1c,0x2a,0x94,0x8d,0xfa,
0xd0,0xfe,0x58,0xaf,0x8b,0x91,0x5d,0x81,0xea,0xda,0x20,0x3b,0x94,0x4,0xec,0xb],[
# Record 93: Address = 0x3e80, Length = 128
0x3e80,0x80,
0x31,0x55,0xc5,0x4f,0x85,0xb7,0xf2,0x9e,0xa8,0x11,0xac,0xb9,0x9f,0xa,0xe5,0x2c,
0x6f,0xba,0x75,0xf6,0xc2,0x90,0xe7,0x7,0x28,0x62,0xbf,0x3a,0x2c,0xd4,0xd0,0xd,
0xcc,0x50,0x4b,0xe6,0x10,0xc9,0x80,0x32,0x4,0x55,0xec,0x52,0x37,0x24,0x8f,0x20,
0xc0,0x8e,0x8a,0x1d,0x27,0x24,0xac,0x18,0x3a,0x6b,0x9c,0xc8,0x7a,0x3d,0x61,0x20,
0xdc,0x36,0x73,0x9d,0xde,0xc3,0x84,0xcd,0x70,0x82,0x7a,0x8d,0xe5,0xa3,0x89,0xe5,
0x16,0xdb,0xa7,0x25,0x47,0x3c,0xd3,0xbf,0x79,0x38,0xb0,0x55,0xe5,0xac,0x5f,0xb7,
0x34,0x71,0x6a,0xb6,0x75,0xca,0xf,0xa5,0xe6,0x42,0xc9,0xc9,0x31,0x81,0x50,0x5b,
0xb9,0x40,0x52,0x75,0x71,0x9b,0x78,0x70,0xf5,0x3d,0xb7,0x1b,0x13,0x1a,0xa3,0x89],[
# Record 94: Address = 0x3f00, Length = 128
0x3f00,0x80,
0xe2,0x33,0xfd,0xc5,0xc6,0x32,0xfd,0x27,0xff,0x19,0xe,0x3d,0xa3,0x51,0xb0,0xa4,
0xa1,0xa1,0x4c,0x60,0xc,0xfe,0x51,0x71,0x41,0x9,0x4a,0xe4,0xbb,0x11,0xe9,0x2a,
0x7d,0xaf,0x45,0xba,0xcf,0x54,0x52,0x54,0xee,0x45,0x12,0xb,0x8,0x98,0x61,0x8b,
0xab,0x6b,0x81,0xcf,0x2,0x4b,0xa1,0x90,0xa4,0x70,0xb2,0xae,0xf0,0x73,0x2,0xdb,
0xe7,0xb3,0xb,0xb3,0x22,0x64,0xf8,0x1e,0xdc,0x58,0x2,0xf5,0xa3,0xe,0x98,0xf7,
0x70,0x35,0x42,0x2c,0xe6,0x26,0x78,0x79,0x2c,0x14,0x44,0xd3,0x2e,0xec,0x16,0xdc,
0x58,0xd8,0x9e,0x8e,0xfe,0xa7,0xdf,0x8b,0x2d,0x6d,0x5,0x4d,0x7d,0xd0,0x5,0xb6,
0x60,0x8b,0x71,0x9f,0x78,0xa7,0x99,0x37,0x60,0xc3,0x8d,0x69,0x1d,0x83,0x17,0xfe],[
# Record 95: Address = 0x3f80, Length = 128
0x3f80,0x80,
0xaf,0x71,0xa,0xa5,0x44,0x5,0xa0,0x2,0xd8,0x55,0x79,0xc,0x1,0x6,0x93,0xbe,
0x27,0x39,0x28,0x69,0xf0,0xc5,0x38,0x2b,0x17,0x33,0x44,0x1e,0xfa,0x88,0xa6,0xb7,
0xed,0x37,0x81,0x38,0xcf,0xd3,0xb1,0x3d,0xd6,0x22,0x41,0xd7,0x8f,0x12,0xd6,0xe7,
0xb1,0xb7,0x46,0x99,0x4d,0x50,0x1f,0x99,0x6e,0xf3,0x89,0x5d,0xdb,0x22,0x11,0xa8,
0xb6,0x36,0xfd,0x5d,0xb4,0x24,0x14,0x5a,0xb1,0x1c,0x88,0x76,0xfa,0xc1,0x92,0x3f,
0x61,0x20,0x85,0x3,0xd4,0x89,0x67,0x70,0xd5,0x16,0xe9,0xdc,0x6d,0x73,0xbb,0x1f,
0x58,0x38,0xff,0x1,0x12,0xae,0x17,0xa,0x5,0x53,0xa4,0x7b,0x5a,0x4b,0xdc,0x1,
0xbe,0x39,0xe0,0x26,0xd2,0xfe,0x79,0x84,0xc8,0x8a,0x4b,0xce,0xce,0xe7,0x33,0x66],[
# Record 96: Address = 0x4000, Length = 128
0x4000,0x80,
0x7b,0xfc,0x7e,0x76,0x42,0x27,0x38,0xb4,0x5f,0x9e,0xe8,0xb2,0xfc,0x95,0x6,0x6a,
0xa0,0x7b,0xf0,0x10,0x72,0x31,0x15,0x92,0x92,0x96,0xde,0x54,0x91,0x2e,0x6c,0x43,
0xb6,0x87,0xa1,0x6d,0x9e,0x42,0x1,0x95,0x7,0xcb,0xab,0xa8,0xd3,0x9c,0xe3,0x98,
0x91,0x36,0x3c,0xed,0xa9,0xcf,0x70,0x1b,0x72,0xc3,0x1c,0x74,0x7a,0x18,0xda,0x6d,
0x10,0xda,0xce,0xc3,0x47,0xb7,0x73,0xc6,0x8e,0x53,0xff,0x42,0xe5,0x93,0x49,0xcc,
0x21,0x44,0x38,0x39,0xe5,0x6,0x2e,0x7d,0xfb,0x25,0x11,0xe3,0xea,0x91,0x8a,0x75,
0xfa,0x92,0x6e,0x6a,0xcf,0x91,0x3a,0xb8,0x17,0xaf,0x71,0x49,0x71,0x10,0x49,0xec,
0xb4,0xd3,0x15,0xd1,0x58,0x6b,0x44,0xfd,0xac,0xd7,0x4d,0xb3,0x20,0xb7,0x82,0x21],[
# Record 97: Address = 0x4080, Length = 128
0x4080,0x80,
0xa3,0xe2,0x76,0xc2,0x37,0xd9,0x2,0xa9,0x46,0x3c,0x46,0x28,0xc4,0x86,0x5d,0x98,
0xe,0xc2,0xd6,0x8f,0x11,0x3c,0xad,0xbc,0xda,0x2f,0xf0,0xf,0x72,0x43,0xc5,0x9a,
0x12,0x8e,0xc4,0xe4,0x50,0xbd,0x1d,0xa7,0xa1,0xb1,0x1a,0x23,0xbf,0xe,0xc1,0xab,
0xf7,0x7b,0x9e,0x1f,0xcf,0x96,0x6b,0x6e,0x1b,0x5d,0x99,0x8b,0xbf,0xef,0x36,0x14,
0xbd,0xf8,0x1d,0x29,0xd0,0x25,0xd1,0xe0,0xd2,0x2e,0x7e,0x74,0x68,0x31,0x78,0x25,
0x10,0x1d,0xdb,0x90,0xe3,0x4a,0xc1,0x52,0x65,0x82,0xfd,0xf8,0x6f,0xf0,0xf9,0x4e,
0x1d,0xdf,0x79,0xb7,0x65,0xa0,0x1a,0x8b,0xe0,0xcb,0x74,0x77,0xd0,0x1d,0x24,0x6f,
0x37,0xe0,0x5,0xeb,0xf7,0x98,0x49,0x3d,0xf9,0xaf,0x7f,0x6c,0xc6,0x99,0x9a,0xb2],[
# Record 98: Address = 0x4100, Length = 128
0x4100,0x80,
0xc3,0x59,0x93,0xc6,0xb2,0x0,0x9b,0x4e,0x5f,0x28,0xdc,0xe5,0x44,0x58,0xa8,0xd8,
0xbc,0x20,0x41,0xbc,0x4f,0x9d,0x5b,0x2e,0x9b,0x85,0x7e,0x65,0xc4,0x4b,0x65,0x52,
0x50,0xc6,0x2d,0xba,0xe5,0xc6,0x78,0x18,0x7,0xe5,0x13,0x7f,0x83,0x1b,0xd5,0x69,
0x6d,0x5d,0x36,0x4,0x8c,0x37,0x9,0x91,0xa9,0xf4,0x64,0x3,0x4b,0x89,0x84,0xf3,
0xd5,0x62,0xe0,0x8d,0x4a,0x47,0x28,0x4f,0x30,0x41,0x97,0x95,0x93,0x12,0x16,0xee,
0xbb,0x61,0xf6,0xfa,0xa2,0xee,0x30,0x25,0x8c,0xe0,0xeb,0x43,0xf9,0xe7,0x74,0x1e,
0x39,0x9b,0xe7,0xc8,0x61,0xbf,0x8d,0x54,0xc1,0x3c,0x88,0xd7,0xb0,0xfe,0x27,0x97,
0x4f,0x49,0x89,0x62,0xc0,0x35,0xc4,0xe3,0xb3,0xcf,0x9b,0x1,0xa3,0xb5,0xbe,0x21],[
# Record 99: Address = 0x4180, Length = 128
0x4180,0x80,
0x12,0x55,0x46,0x50,0x3c,0xaa,0x8a,0xb3,0xae,0x4b,0x83,0xe6,0x68,0xaa,0xab,0xad,
0x7a,0x2c,0xdf,0x59,0x38,0x6,0x41,0xf4,0x38,0x6f,0xfe,0xfd,0xe5,0xc0,0x87,0x63,
0x7,0x7e,0xab,0x6e,0x5d,0x9b,0x65,0x19,0x1c,0xef,0xf8,0x9c,0xa9,0xb5,0x21,0x18,
0x2f,0x78,0xa1,0xca,0x38,0xb0,0x81,0x2c,0x9,0xd3,0x4d,0xec,0x75,0xae,0xa6,0x8a,
0x3d,0x36,0xa2,0x60,0x90,0xc9,0x97,0x25,0xf0,0x28,0xc3,0x5e,0x97,0xc9,0xe,0x3,
0x2a,0x67,0x34,0x19,0x7,0x25,0x44,0x6f,0xf8,0x75,0x58,0xf6,0xfe,0x16,0xb0,0x44,
0xa5,0xa8,0xa2,0xec,0x5b,0xc2,0x67,0x40,0x8a,0xea,0xd2,0xaa,0x4f,0x72,0xfc,0x88,
0xf1,0xf0,0x18,0x1f,0x6a,0xa5,0xbd,0xae,0x13,0xaa,0x6b,0x78,0x7c,0x1c,0xb4,0x8],[
# Record 100: Address = 0x4200, Length = 128
0x4200,0x80,
0xa2,0xab,0xee,0x61,0x36,0x1a,0x40,0xb0,0x74,0x12,0xac,0x6b,0xe3,0xf6,0xd1,0x93,
0x17,0x99,0xad,0x87,0xa4,0x63,0x2b,0xed,0x84,0x71,0x4,0x16,0x1d,0x9b,0xd2,0xc5,
0xd5,0xbe,0x20,0x11,0xa8,0x7c,0xac,0xcb,0xab,0xd4,0xb5,0x3c,0xca,0x8e,0x6e,0x9c,
0x73,0xd9,0xf9,0x50,0x16,0x33,0xc5,0x4f,0x1,0x15,0xae,0xbd,0x59,0x58,0x82,0xff,
0x3e,0xa2,0xcb,0xf0,0x2f,0xf0,0x50,0x65,0x0,0x48,0x8b,0x10,0x3,0x7e,0xbe,0x7a,
0xbc,0x6e,0x1b,0x6,0x21,0x63,0x9b,0x82,0x3c,0x53,0xf8,0x69,0x20,0xb0,0x0,0xbc,
0x28,0xf2,0x69,0xcc,0x71,0xa5,0x69,0x2d,0xf2,0xf9,0x26,0xc7,0xd1,0xd7,0xa0,0xb2,
0x7c,0xda,0x43,0xf0,0xb2,0xd,0x0,0x23,0x41,0xd2,0x95,0x15,0xbe,0xd8,0xac,0xa2],[
# Record 101: Address = 0x4280, Length = 128
0x4280,0x80,
0x99,0x74,0x2d,0x47,0x65,0x85,0x4e,0xd9,0xc9,0x8a,0xab,0xe8,0x3a,0xbc,0x4,0x46,
0x1a,0x34,0x67,0x3c,0x87,0x3a,0xa1,0xdb,0x44,0xdc,0xdd,0x68,0x7b,0x99,0x52,0x2c,
0x6f,0x7e,0x5a,0x20,0xf4,0x88,0x52,0xe3,0xae,0x26,0xf2,0xd3,0xb1,0x73,0x1f,0xa7,
0x23,0x8,0x70,0xd7,0x44,0xe,0x7b,0xa1,0xdd,0x28,0xdf,0x4c,0xba,0xfd,0xc2,0xde,
0x22,0x2,0x95,0x8d,0x22,0xc6,0x87,0x2a,0xf0,0x65,0x9f,0xf7,0x6e,0x13,0x4d,0xc0,
0x6b,0xb2,0x85,0xda,0xb1,0x5a,0xa1,0x83,0x52,0x8e,0xfe,0xd4,0xaf,0xf7,0x38,0x99,
0x11,0x84,0x16,0x53,0x1,0xc0,0x8c,0x23,0x2f,0x3d,0x46,0x3c,0xe9,0x47,0xc9,0x1,
0xe7,0xf8,0xa6,0x2e,0x7d,0xc7,0xeb,0x67,0x22,0x77,0x44,0x4b,0x12,0xb3,0xfb,0x20],[
# Record 102: Address = 0x4300, Length = 128
0x4300,0x80,
0xe2,0xed,0x70,0x24,0xb6,0xd2,0x6b,0x5f,0xc1,0xe7,0xea,0x4d,0x25,0x3a,0x66,0xd4,
0x8f,0xf4,0xac,0x7f,0x55,0x81,0xa6,0x8,0x88,0x41,0x3b,0xfb,0x4b,0xbd,0x75,0x1c,
0x61,0xaf,0xa9,0x16,0x57,0x8d,0x31,0x82,0x2d,0xc9,0xdb,0x3d,0x8d,0xef,0x1e,0x1,
0xe2,0xeb,0xde,0xb2,0xbe,0x38,0xff,0x39,0x56,0xe1,0x98,0x0,0x79,0x36,0x8f,0xef,
0x85,0x6e,0xae,0xc8,0x98,0xb4,0xd7,0xa0,0xea,0x27,0xd9,0xae,0x63,0xbb,0xf4,0xc1,
0x11,0xd5,0xae,0xe2,0xc7,0xd6,0xdb,0xb5,0x67,0x3b,0xe7,0x22,0x2a,0xdb,0xbd,0xcf,
0x19,0xf4,0x31,0x39,0x5f,0x49,0xee,0xeb,0x37,0xc1,0x5,0x84,0x96,0xf3,0x4e,0xe4,
0xdb,0x75,0x76,0x87,0xd6,0x2a,0x2e,0x4b,0x54,0x30,0xf0,0x18,0x29,0x29,0xd8,0x3a],[
# Record 103: Address = 0x4380, Length = 128
0x4380,0x80,
0xcb,0x22,0x8d,0xa4,0xe,0xdc,0x3f,0x8f,0x8f,0x14,0xa7,0xe3,0xf1,0x85,0xc8,0xb1,
0x15,0x5c,0xc8,0x78,0x3,0x8,0xa7,0x7c,0xe1,0x5f,0x17,0x35,0xb1,0xa1,0xc8,0x60,
0x84,0x15,0xd4,0x3e,0x21,0x51,0x3,0x73,0x1f,0x3a,0xb2,0x9d,0xda,0x5c,0x38,0xce,
0x53,0xb8,0x36,0x2a,0x7b,0x8b,0x77,0x7b,0x11,0xa8,0xb1,0x48,0xc4,0xed,0x89,0x56,
0xf1,0xc0,0x89,0xe5,0xdb,0xbe,0xeb,0xb4,0xf4,0x6a,0x21,0x7f,0x62,0x9d,0xcd,0x39,
0x74,0x63,0x8a,0x26,0xeb,0x20,0x83,0xaa,0xc2,0x20,0xdf,0x86,0xfb,0x62,0xdc,0x1f,
0xd3,0xf4,0xeb,0x41,0x2d,0x92,0x67,0x23,0xc2,0x93,0x81,0x69,0x24,0x8d,0x89,0x20,
0x6f,0x81,0x31,0xc0,0x7d,0xc6,0x77,0x83,0xb2,0x25,0x6,0xcf,0xcb,0x8c,0x41,0x8a],[
# Record 104: Address = 0x4400, Length = 128
0x4400,0x80,
0x3f,0x77,0x26,0xa8,0x8a,0x3e,0x4f,0x8d,0xa3,0x6a,0x92,0x6,0xad,0x8f,0xb9,0xb4,
0x5a,0x69,0xfb,0x60,0x4f,0x31,0xd9,0x7a,0x7a,0x40,0xcf,0xee,0x4a,0x9e,0x4,0xb0,
0xcb,0x9e,0xfb,0xc3,0x99,0x1a,0x6,0x23,0x9b,0x49,0x53,0x98,0xb9,0x4b,0xa2,0x8a,
0x3c,0x5d,0x16,0x21,0x8c,0x99,0x15,0x89,0xb1,0x8a,0xee,0x67,0xcc,0x7c,0x6f,0xe5,
0x6b,0x2b,0xff,0x43,0xd3,0xd6,0x7a,0x5,0xb9,0xa5,0x96,0x4b,0xf5,0xf1,0x33,0x3b,
0x2,0xe4,0x45,0xce,0x67,0x43,0xc4,0xfe,0xab,0x67,0x3f,0x3c,0x29,0x7d,0x9c,0x27,
0x70,0x58,0xc5,0xf,0x8d,0x30,0xe2,0x96,0xbf,0xb9,0xa1,0x2b,0x89,0x26,0x1a,0x68,
0x75,0x9e,0xf9,0xc0,0xad,0x72,0x52,0xf7,0x57,0xfd,0x73,0x0,0xd8,0xe9,0xb9,0x1b],[
# Record 105: Address = 0x4480, Length = 128
0x4480,0x80,
0xf,0x58,0xc2,0x78,0x6a,0x9a,0xee,0xc8,0x67,0xb2,0xb9,0xf6,0x7d,0x81,0x71,0xd4,
0x2,0x9e,0x56,0x0,0xe9,0xd4,0xdd,0xf9,0xc4,0xef,0x1c,0x47,0xe0,0x6c,0xb4,0xb3,
0xe,0x3b,0x8f,0x86,0x85,0x70,0xc5,0xd4,0x8e,0x40,0x58,0xd5,0x2b,0xea,0x29,0x39,
0x26,0xfe,0x63,0xee,0xc2,0x7d,0xcf,0xe2,0xd,0xae,0xcd,0x8,0xaf,0x4f,0x6d,0x30,
0xf1,0x47,0xef,0xb,0x3d,0x63,0xfe,0xce,0xc3,0xb7,0x24,0x55,0xf1,0x9c,0xa9,0xdc,
0xc0,0x9a,0xe1,0xe6,0xc1,0x33,0xd7,0x7b,0x71,0xaf,0xda,0x2e,0x2c,0x7b,0x3f,0x35,
0xa8,0x2d,0x79,0x3e,0xee,0x38,0x4e,0x3e,0xab,0x7a,0x70,0x13,0x96,0x30,0x9f,0xf7,
0x2a,0xaf,0x0,0x69,0x47,0xfe,0x7a,0x86,0x2e,0xd2,0xac,0xaf,0xfa,0x16,0x6f,0xcd],[
# Record 106: Address = 0x4500, Length = 128
0x4500,0x80,
0xbc,0x3a,0x3f,0x45,0x49,0x39,0x7,0x9b,0x41,0x45,0x1f,0xeb,0xe7,0xcb,0x58,0x4c,
0x35,0x94,0xc2,0x10,0x7d,0xb6,0xe0,0x53,0xa,0xca,0x4d,0xf1,0x6b,0x2c,0x86,0x0,
0x29,0x9,0x4b,0x73,0x4f,0xf2,0xc7,0x7,0xbe,0x55,0x1e,0x79,0x1,0x85,0xd1,0xdd,
0xdb,0x88,0xd9,0x25,0x32,0xea,0xc1,0x7f,0xe,0x69,0xf6,0xb7,0xa8,0x8b,0x61,0x3,
0x4b,0xc9,0x21,0xc4,0x6,0x9e,0xf1,0x17,0x2d,0x96,0xbc,0x3f,0x43,0x6,0x2b,0xe1,
0x17,0x94,0xf6,0x25,0x61,0x65,0xd5,0x96,0x70,0x16,0xb7,0x60,0x3,0xb6,0xdf,0x67,
0x88,0x5a,0x67,0x1a,0xb5,0x37,0x38,0xdc,0x5d,0xfb,0x0,0x2,0x5e,0x57,0xf7,0xfb,
0xca,0x76,0x25,0x96,0x8f,0x9f,0x28,0xe7,0x29,0x5a,0x67,0x3b,0x57,0xe0,0x20,0xe],[
# Record 107: Address = 0x4580, Length = 128
0x4580,0x80,
0x43,0x49,0xb0,0x38,0x48,0x69,0x91,0xb8,0xb2,0x5f,0xa6,0xeb,0x34,0xf7,0x7f,0x9d,
0xac,0xd1,0xd5,0x33,0x70,0x12,0x1e,0xff,0x7a,0x37,0x66,0x0,0x91,0xc4,0xb5,0xaa,
0xad,0xdc,0xab,0x8b,0x80,0x3d,0x49,0xc1,0x64,0xb4,0xf1,0xb0,0x6d,0xf4,0x3a,0xd8,
0x2,0x4b,0xbc,0xae,0x6,0xee,0xb3,0x64,0x1,0x0,0xb5,0xbf,0xa4,0x6a,0xed,0x50,
0xa7,0x23,0xcd,0x71,0x8c,0xdf,0xe8,0xb4,0x6b,0x97,0x4d,0x1c,0x3f,0x5b,0x63,0xdd,
0x1,0x3a,0xf4,0x48,0x2f,0x28,0x57,0x19,0xef,0x68,0xee,0x5b,0x9c,0x39,0x20,0x61,
0xa3,0xf8,0xe3,0xd9,0xe,0x14,0x80,0x78,0x65,0x54,0x28,0x63,0xea,0x1,0xa5,0x91,
0xc4,0xbc,0xde,0xf4,0x8e,0xd4,0xf1,0x8e,0x8c,0xf4,0xd0,0x79,0xce,0x1b,0xba,0x5c],[
# Record 108: Address = 0x4600, Length = 128
0x4600,0x80,
0x68,0xa,0x28,0xf7,0x12,0x11,0x2e,0x71,0x98,0xef,0x19,0xb2,0x1c,0x7b,0x87,0x56,
0x68,0xeb,0x83,0xd0,0xd3,0xd0,0x32,0xd6,0x9,0x7c,0x32,0xfa,0x9,0x62,0xec,0x3d,
0x65,0x44,0xd3,0xd8,0xc4,0x1d,0x6e,0x33,0xdd,0x88,0xfe,0xc9,0xc9,0x41,0x5d,0x3,
0xf3,0x93,0x7a,0x7d,0x33,0x46,0x90,0x3f,0xb3,0x2c,0x8b,0xe4,0xc7,0x69,0xe8,0xa6,
0x6f,0xec,0xa,0x7b,0x75,0x59,0x35,0x6f,0x92,0x9f,0xd1,0x8a,0xed,0x87,0x68,0x5d,
0x98,0x89,0xab,0x4b,0xdc,0x5,0x8d,0x86,0x9,0xa8,0xee,0xf7,0x24,0xcf,0x1c,0x6f,
0xdc,0x97,0x21,0xb2,0xbc,0x5d,0x57,0x5b,0x10,0x60,0x8,0xda,0xf0,0xd1,0x23,0x9b,
0xa5,0xda,0x39,0x49,0x26,0x4d,0xc3,0xb2,0xed,0xf9,0x25,0x3a,0x1a,0xe4,0x19,0x64],[
# Record 109: Address = 0x4680, Length = 128
0x4680,0x80,
0x7f,0x11,0xa5,0x8f,0xe5,0x50,0x6c,0x7e,0x98,0xa1,0xed,0x3c,0xe,0xe0,0xb5,0x8,
0x53,0xf,0xd2,0x3a,0xfe,0x7e,0xb6,0x42,0x44,0x9c,0xdd,0x87,0x5a,0x60,0xff,0x1e,
0xaa,0x38,0xee,0x75,0x40,0x62,0x3c,0x45,0xa3,0x5c,0xb2,0x26,0xec,0x7c,0x6c,0xc2,
0xac,0x46,0x44,0xf9,0xec,0xaa,0xcf,0x5e,0x16,0xf9,0x94,0x84,0x6a,0xe4,0x63,0xb,
0xbe,0x46,0x55,0xe3,0x6f,0x9d,0x60,0x74,0x6f,0xd7,0x23,0xd2,0xe,0xb4,0x42,0x31,
0xdc,0x35,0xea,0x80,0x4e,0xf1,0xa2,0x1c,0x3f,0x3c,0x12,0x7b,0x88,0x55,0x89,0x18,
0xc0,0xba,0x1e,0xfe,0xed,0xa1,0xdd,0x47,0x6d,0x59,0x74,0xdb,0x4e,0x7f,0x5c,0xbb,
0x9a,0xc4,0xcf,0x3a,0x45,0x21,0xc6,0xe8,0x3c,0xd1,0xf2,0xdc,0x25,0x7,0x52,0x67],[
# Record 110: Address = 0x4700, Length = 128
0x4700,0x80,
0x4d,0x37,0x95,0xeb,0x64,0xf3,0x63,0x18,0x76,0x3b,0xb5,0xda,0xa,0x38,0x82,0x8,
0x89,0xe4,0xda,0xba,0xa0,0x41,0x7d,0x75,0x4f,0xc,0xe9,0x29,0xb9,0xa6,0xeb,0x4d,
0x61,0x83,0x3,0x93,0xde,0x8a,0xe6,0x90,0xe0,0x8b,0xd2,0xa3,0x82,0xc1,0x7a,0x65,
0x10,0x58,0x93,0x84,0x1,0x7f,0x61,0x54,0x8e,0xe6,0xb6,0x0,0xe1,0x5f,0x2f,0x7,
0xfb,0xab,0x7b,0x46,0xfd,0xcb,0x2,0xee,0xba,0x62,0x2,0xcf,0x2,0x45,0xf8,0xab,
0xd9,0x6,0xd0,0x33,0x5,0x58,0x4,0xc7,0xd7,0xa1,0xe,0x84,0xec,0x23,0x59,0xdf,
0xed,0x43,0x33,0x81,0x1b,0xbd,0xdd,0x6,0xab,0xab,0x3e,0x76,0x2d,0x30,0x2d,0x79,
0xf8,0x33,0x59,0xd,0x7e,0x47,0x32,0x88,0x2e,0x32,0x81,0x40,0x96,0xaf,0xf9,0xb],[
# Record 111: Address = 0x4780, Length = 128
0x4780,0x80,
0x9b,0xd,0x4a,0x75,0xad,0x22,0x8d,0xa1,0xe4,0xa1,0x5d,0x8,0x42,0xc9,0x6a,0xf8,
0x29,0xe5,0x27,0xa7,0xf8,0x46,0x20,0xe,0x42,0xdc,0xb3,0x15,0xee,0xe8,0x31,0x88,
0xc,0x7e,0xb0,0x21,0x77,0x9d,0x3d,0x46,0x93,0x41,0xf3,0xf2,0xf1,0xc7,0xd4,0xba,
0x7f,0xa0,0xb6,0xda,0xd3,0x49,0xd1,0x67,0x1c,0x76,0xbe,0x0,0x18,0xd1,0xe5,0x72,
0xb4,0x7f,0xaa,0x6f,0x32,0x97,0xc,0x8c,0xd4,0x4c,0xed,0xbc,0x5f,0xc4,0x92,0xfc,
0xf1,0xab,0xf2,0x5d,0xf0,0x9,0x5e,0x24,0x79,0x28,0x9d,0x28,0x1b,0x3a,0x49,0x16,
0x4d,0x19,0x74,0x75,0x1f,0xa,0x41,0xf0,0xd8,0x29,0xbc,0x83,0x3d,0xdc,0xc1,0xf4,
0xd,0xdb,0xc2,0x7,0xf8,0xb1,0xba,0x1a,0x74,0xd1,0xa2,0x38,0xeb,0xe4,0xf3,0x46],[
# Record 112: Address = 0x4800, Length = 128
0x4800,0x80,
0x6a,0xc7,0x90,0x81,0xe0,0x7d,0x1f,0xd8,0x18,0xb3,0x2a,0x8d,0xe5,0x44,0xff,0xb,
0x3f,0x16,0x74,0xf1,0x2d,0x15,0xd1,0x94,0xc4,0x38,0x47,0x17,0x9a,0x13,0xc4,0x9e,
0x2d,0xa4,0x14,0x70,0xe2,0x81,0xe9,0xcf,0xea,0x6,0x92,0xd8,0x7f,0x2e,0xfb,0xd9,
0xc9,0x76,0x7d,0xb6,0x37,0xd1,0xf8,0x24,0x40,0xb6,0xa1,0x6d,0x19,0x8b,0x8f,0xf9,
0x91,0x82,0x91,0x7c,0xd4,0xd7,0xbe,0x48,0x13,0xe6,0xe0,0xd6,0xa,0x36,0xa3,0x40,
0xdd,0xbe,0x71,0x3,0x7f,0x37,0xc6,0x43,0x48,0x28,0xcd,0x92,0xe1,0xd,0x92,0xc9,
0xb1,0x7d,0xda,0x5b,0x90,0x45,0xc2,0x7c,0x45,0x43,0x90,0x7e,0x97,0x5c,0xfe,0xc4,
0x13,0x64,0x49,0xb6,0xf6,0x68,0x9c,0x65,0x1c,0xc6,0xec,0xfa,0xc8,0xa3,0xcf,0x6],[
# Record 113: Address = 0x4880, Length = 128
0x4880,0x80,
0x35,0xc6,0xa5,0x61,0xc2,0x9d,0x19,0x9a,0xee,0xda,0xe6,0xab,0xa6,0xfd,0x12,0x23,
0xf8,0x62,0x7c,0x3f,0x25,0xc3,0xb2,0x5d,0x3f,0xb,0x1a,0x9b,0x44,0xe1,0x92,0x86,
0x18,0x4c,0x49,0xd6,0xd7,0x54,0xee,0xdd,0x87,0x3e,0xea,0x2,0xa,0x4e,0x8c,0x3f,
0x44,0xa5,0x84,0x7,0x1e,0x8b,0xea,0x1f,0xb2,0x7d,0x55,0x0,0xde,0x4f,0xed,0x26,
0x73,0x19,0xac,0x50,0x4e,0x99,0xa0,0x2,0xfa,0x1d,0x5e,0xfe,0xcd,0x15,0x94,0x9d,
0x90,0xc5,0xb0,0x7f,0x6d,0x31,0x1f,0x37,0x79,0x1c,0xcc,0xc7,0xfc,0x6d,0x1,0x90,
0xa4,0xbc,0xef,0xae,0x34,0x4f,0x4b,0x9b,0xc3,0x4b,0x9c,0x21,0x5d,0xe1,0x80,0x5b,
0xd2,0xf4,0x5e,0x42,0x4c,0x60,0x0,0x99,0x18,0xaf,0xbf,0x86,0x89,0x35,0xd,0x1],[
# Record 114: Address = 0x4900, Length = 128
0x4900,0x80,
0x36,0xfa,0xce,0xbd,0x23,0xe3,0xf0,0xb2,0x49,0x4c,0xfb,0x72,0x41,0x22,0xaf,0xca,
0xd,0xd0,0xfd,0x3,0x7e,0x29,0x7,0xcd,0x9,0xef,0x11,0x16,0x25,0xba,0xbe,0xf3,
0x77,0x9f,0x35,0xd6,0x74,0x53,0x74,0x76,0xc1,0xc1,0x38,0xe2,0xdf,0xc3,0x48,0xc4,
0x1b,0xea,0x0,0x45,0xf5,0x8b,0xb1,0x8b,0x44,0x10,0xe4,0x15,0x6,0xf6,0xc1,0x89,
0xa0,0x93,0x8c,0xca,0x7f,0x6e,0x74,0xbe,0xfd,0x70,0x1e,0x8b,0xae,0xdb,0xc8,0x8c,
0x60,0x73,0xb8,0x36,0xb9,0xd4,0xf3,0x7,0xcb,0xb3,0xc3,0xf4,0x2e,0x71,0x50,0xb2,
0xef,0xb7,0x9e,0x68,0x19,0x2,0x78,0x1a,0xa6,0x50,0xc8,0x28,0x43,0x14,0xaa,0x5e,
0x98,0xdf,0xc8,0xfd,0x3c,0x94,0xdb,0xbd,0xe5,0x14,0xa2,0x5,0x17,0x44,0x29,0xf],[
# Record 115: Address = 0x4980, Length = 128
0x4980,0x80,
0x5e,0x8a,0xba,0x6c,0x73,0xc9,0x75,0x4d,0x3,0xf5,0x6e,0x6d,0xe4,0x63,0x47,0x3d,
0xc8,0x6d,0x4d,0xb6,0x48,0xc8,0x41,0xcb,0xd4,0xe3,0xae,0x17,0x41,0xa0,0x30,0xaf,
0xcb,0xd0,0x3f,0x15,0x1f,0x9d,0x83,0x14,0xd2,0x9d,0x86,0xae,0x7c,0x2d,0xe0,0x6a,
0x6d,0xc5,0xdc,0x9,0xc6,0x23,0xdf,0xb0,0x88,0x4d,0xad,0xa7,0x4f,0xb0,0xb0,0x46,
0x95,0x44,0x87,0x1f,0x8b,0x34,0x69,0x80,0x24,0xcc,0x6c,0x33,0x73,0xbe,0x43,0x3e,
0xf,0xee,0x64,0xd8,0xb1,0x6,0x43,0x2f,0x47,0xdc,0x70,0x2f,0xc9,0x3a,0xc7,0x6a,
0xf1,0x97,0xe,0x25,0xa2,0xaa,0x72,0xa1,0x83,0xea,0xad,0xf0,0xb4,0x2c,0x87,0x87,
0x1b,0x15,0xed,0x90,0xdd,0x3c,0xca,0x75,0xc,0xe4,0xc3,0xb1,0xa1,0x1e,0xfd,0xb4],[
# Record 116: Address = 0x4a00, Length = 128
0x4a00,0x80,
0x2a,0xb3,0xaa,0x9b,0x2a,0x6c,0xd9,0xfe,0xc,0xb8,0x8b,0x58,0x42,0xd5,0x62,0x6d,
0x76,0xdc,0xd2,0x6d,0x7b,0x0,0xf2,0x56,0xc6,0x38,0x43,0xd,0x8b,0x64,0x85,0x2b,
0x77,0x33,0xb,0x20,0x3d,0x98,0x5d,0xb4,0xca,0xb3,0x68,0x53,0x84,0xd4,0x38,0x72,
0xf6,0x19,0x36,0x4d,0x94,0x93,0xd0,0x7d,0xc7,0x66,0x5d,0xc0,0xd0,0xa2,0x33,0x33,
0x77,0x6b,0xed,0x10,0x5,0x31,0x67,0x21,0x3c,0xe4,0xa6,0xd7,0xec,0xe0,0x8a,0x73,
0x6a,0x7d,0xce,0xa2,0xae,0xce,0xbb,0x80,0x4b,0x19,0xad,0x9e,0x6d,0xab,0xb8,0x45,
0x34,0xb,0x44,0x31,0x8a,0x54,0xd6,0x79,0x93,0x5b,0x24,0x80,0x36,0x28,0xc9,0x90,
0x4e,0xbf,0x9e,0xa9,0x1c,0x7d,0xc3,0xb8,0x88,0xce,0x49,0xdb,0x2e,0xe8,0xc6,0xe9],[
# Record 117: Address = 0x4a80, Length = 128
0x4a80,0x80,
0xc0,0xd4,0xb7,0xbb,0xa8,0x99,0xaf,0x13,0x1a,0x1a,0x9,0x45,0x10,0x3,0x42,0x49,
0x47,0x46,0x12,0x4b,0x77,0xb9,0x9c,0xd1,0xfd,0x6f,0xf8,0x2c,0x81,0x26,0xc,0x3f,
0xf6,0xd8,0x74,0x67,0x92,0x23,0xcf,0xbb,0xba,0x3c,0xf6,0x38,0xa5,0x1b,0x5f,0x1c,
0x70,0xea,0xcd,0xda,0x38,0xa,0xb9,0x2,0x37,0x13,0xc7,0x4d,0x0,0x85,0x8c,0x1d,
0xb7,0xa4,0xfc,0x9,0x7e,0xe0,0xff,0x57,0x6a,0xfa,0x75,0x88,0x1c,0x60,0x1d,0x38,
0xbc,0xed,0xe0,0xe3,0xca,0x9e,0xff,0xa7,0x18,0xbd,0x4d,0x2e,0xaf,0xfc,0x60,0xf5,
0xc0,0x9f,0xe4,0x5a,0xa1,0xb3,0xd3,0x64,0x3a,0x17,0x66,0x50,0x3,0x8d,0xa4,0x1f,
0xa6,0x67,0xc0,0x5b,0xa1,0x47,0x9a,0x9d,0x34,0x69,0xa,0x40,0x1c,0xec,0xab,0xd9],[
# Record 118: Address = 0x4b00, Length = 128
0x4b00,0x80,
0x8d,0x65,0x34,0x47,0x16,0x83,0x9f,0xae,0x21,0x5a,0x76,0x5b,0xaf,0xc8,0x8e,0xb6,
0x31,0x3f,0x1d,0x6f,0x60,0xea,0x3a,0x59,0xb0,0x6b,0xca,0xc2,0x84,0xbe,0x6,0xaa,
0xb7,0x84,0x4f,0x19,0x83,0xfb,0xef,0xa1,0xff,0x45,0x97,0x6d,0x87,0x8,0x47,0xbd,
0x3c,0xa0,0x3f,0x93,0xa0,0x5e,0x9e,0x3d,0xd9,0xba,0xe6,0x2d,0x90,0x39,0xf3,0x7,
0x52,0x34,0x9f,0xab,0x60,0xbe,0xc6,0x1b,0xab,0xc6,0x79,0x7c,0x65,0x89,0xf0,0xa,
0x87,0xe8,0x18,0x19,0xfd,0x7,0x3c,0xe0,0xcc,0xdf,0xd7,0x1a,0x13,0xf5,0x4d,0xf7,
0x30,0xb5,0xf3,0x4e,0x8,0x1b,0x40,0x6c,0x64,0xd0,0xc7,0xb8,0x5d,0xb0,0xf1,0xb,
0xb6,0xe4,0x13,0xe6,0x53,0x34,0x65,0x76,0x9a,0xe0,0xcb,0x1b,0x4d,0x5c,0xb7,0x48],[
# Record 119: Address = 0x4b80, Length = 128
0x4b80,0x80,
0xeb,0xc2,0x2c,0x29,0x80,0xd0,0x65,0x68,0xac,0x50,0x47,0xb7,0xe2,0xbd,0x97,0x66,
0x7,0x95,0xef,0x7a,0xd4,0x41,0xa6,0xd6,0xbf,0x8f,0xff,0x86,0x25,0x7f,0x1,0x15,
0x85,0x58,0x64,0x9,0x61,0x9a,0xc,0x4c,0xdc,0xb9,0x4d,0x4,0xe6,0x36,0x7c,0x12,
0x79,0xe2,0x54,0xee,0x81,0x16,0xf3,0x65,0xeb,0x4,0x5a,0x18,0xc7,0x97,0x86,0x7,
0x8a,0xa4,0xb7,0xe5,0x33,0x3d,0x43,0x66,0x77,0x53,0x3,0x22,0xe8,0xb2,0x5b,0x2a,
0xac,0xb1,0x92,0xe9,0x83,0xc1,0x4b,0x7f,0x27,0x2f,0xde,0xc3,0xb7,0x65,0xae,0x6,
0x1d,0x4b,0xe6,0x16,0xdd,0xd8,0xbb,0x29,0x85,0x13,0xd8,0x48,0xa,0xea,0x8b,0x90,
0xcc,0x47,0xba,0x0,0xb4,0x7b,0x80,0x94,0xd3,0xf7,0x72,0x33,0xe3,0xa5,0x6d,0xa4],[
# Record 120: Address = 0x4c00, Length = 128
0x4c00,0x80,
0x8d,0x97,0xcb,0x42,0x72,0x57,0x49,0x98,0xa2,0x78,0x2,0x8e,0x72,0x42,0x39,0x60,
0x7,0xfc,0xc0,0x7e,0xcb,0xdb,0x7e,0xa0,0x3,0xdf,0xd5,0xdf,0x0,0xb6,0x60,0xc9,
0xee,0x11,0xb7,0xe5,0x69,0xc9,0xdb,0x18,0xf2,0x19,0xe2,0xc8,0xe7,0xfb,0xee,0xc1,
0xb5,0xab,0xd9,0x3c,0x44,0xc4,0x2b,0xbe,0xd5,0x6e,0xe0,0x12,0x51,0x5f,0x32,0x35,
0x4c,0x9a,0xdf,0x9c,0x45,0xd,0x9a,0x2,0xb1,0xe7,0x5a,0x6a,0x0,0xa,0x72,0x61,
0xe,0x2d,0xfd,0x11,0xc8,0xb7,0xe3,0x1f,0x54,0x47,0x58,0xe9,0x4,0xef,0xa7,0xaf,
0x3,0xf,0x38,0x6b,0xd,0xdc,0xd9,0x14,0x7b,0x75,0x2d,0x24,0x1a,0x3b,0x7b,0x1e,
0x57,0x37,0x55,0xd2,0x6e,0x90,0x19,0x9a,0xf8,0xb0,0xdc,0x1a,0x54,0x13,0xfe,0x1c],[
# Record 121: Address = 0x4c80, Length = 128
0x4c80,0x80,
0x15,0x53,0xf3,0x6c,0xbe,0x27,0xf4,0xab,0x52,0x6,0xc0,0x7b,0x3b,0xb4,0x56,0xe1,
0x87,0xb6,0xe4,0xb0,0xf0,0x21,0xf9,0xd1,0xfd,0xb7,0xa9,0x55,0x2d,0x25,0x6d,0xaa,
0xbc,0x53,0x46,0x42,0xbd,0x3f,0xf3,0xa0,0x79,0x41,0x9c,0x77,0x6a,0xf6,0x28,0xd2,
0x5a,0xf,0xdf,0xb1,0x8,0xe5,0xed,0xde,0xf7,0x6c,0x89,0x40,0x39,0xf5,0x48,0x4,
0x12,0x2e,0xce,0xcf,0x55,0xb0,0x49,0xe1,0x4,0xb0,0xd1,0x8f,0x1,0x4b,0x78,0xd6,
0x9d,0x64,0xca,0x76,0x16,0xd3,0x27,0xce,0xc2,0x52,0xd5,0x50,0x36,0x3b,0xda,0x95,
0x63,0xaf,0x32,0x2,0xed,0x48,0xfb,0x84,0x66,0x9f,0xd4,0xf2,0xfd,0x9b,0x13,0x12,
0xa,0xcc,0x56,0x80,0x92,0xb0,0x68,0x17,0xeb,0xb8,0x3c,0x48,0xa0,0x55,0x10,0x90],[
# Record 122: Address = 0x4d00, Length = 128
0x4d00,0x80,
0x7c,0x2e,0xe7,0xfb,0x43,0x1b,0x2f,0x32,0x10,0x4,0xfb,0x72,0x60,0xaa,0xc9,0x46,
0xc6,0x66,0x44,0x35,0x6c,0x3c,0xfb,0x86,0xe8,0xd8,0xbf,0x7,0xf9,0x1,0xa0,0x43,
0xc1,0x7c,0xa6,0xdb,0x14,0xfc,0x50,0x38,0x70,0x21,0x13,0x23,0xe2,0x39,0x25,0x41,
0x37,0x80,0xa2,0xc8,0xf8,0x64,0x96,0x5a,0x6d,0xe8,0x99,0xc4,0x6f,0xe2,0x8e,0x7b,
0x9c,0x71,0x73,0x74,0x6,0x2c,0xb4,0x28,0xf1,0xaf,0x34,0xc2,0xce,0x9a,0xb0,0x8e,
0x76,0x64,0x22,0xb3,0x84,0xeb,0xe8,0x5d,0xc3,0xea,0xe,0x9b,0xf6,0xdc,0x5d,0x9d,
0xf3,0x29,0xd6,0x82,0xb7,0x27,0xda,0xba,0xf2,0xd4,0x57,0x41,0x19,0xef,0xcd,0x70,
0xc0,0x26,0xe1,0x4,0x1a,0x60,0xf7,0x18,0x33,0xff,0xc9,0xda,0x55,0x6b,0xbc,0x57],[
# Record 123: Address = 0x4d80, Length = 128
0x4d80,0x80,
0x9f,0xf7,0x88,0x15,0x36,0x89,0x8e,0xd2,0xab,0xd4,0xaf,0x5b,0xcc,0xd7,0x60,0x78,
0x34,0xb1,0x40,0x8c,0xf1,0x60,0x3f,0x81,0x6c,0x7c,0x6,0x9f,0xca,0xe1,0x98,0xbf,
0x1f,0x6d,0xbd,0x6e,0x40,0x6d,0x63,0x3e,0x66,0x31,0xfb,0x96,0xcb,0x29,0x77,0x2d,
0xc7,0x9c,0x49,0xb5,0x35,0xd2,0x3a,0x69,0x1d,0x26,0xe7,0x6d,0xe6,0xc3,0xa1,0x9b,
0x1b,0xfc,0x36,0x31,0xf4,0x7,0xe5,0x43,0x3c,0xd0,0x41,0xb,0x5,0x5e,0x38,0x2f,
0xec,0x89,0x70,0x7,0x2,0x7d,0xfb,0xca,0x33,0x9d,0x14,0x17,0xbd,0x5e,0x9b,0xb4,
0x26,0xfd,0x84,0xb8,0x3b,0x2e,0xf3,0x2c,0x90,0x50,0x72,0x39,0x4f,0xd6,0x32,0x1b,
0x8d,0xff,0x25,0x10,0xfe,0x6b,0xe0,0xff,0xa4,0x99,0x36,0xfb,0xb5,0x3f,0xd4,0x4f],[
# Record 124: Address = 0x4e00, Length = 128
0x4e00,0x80,
0x8d,0xe4,0xa8,0x5d,0xa8,0x3a,0x5d,0x99,0x67,0xe7,0xe5,0xdd,0x33,0x9b,0x5c,0x50,
0xaa,0x4a,0x9e,0xc6,0x84,0x30,0xa0,0x9d,0x7d,0x73,0x3c,0x3c,0x50,0xd9,0x72,0xd8,
0xdc,0x4,0x2f,0x28,0x95,0x79,0x5,0x4,0xb2,0xf0,0x33,0x7a,0x2a,0xcc,0x4c,0xfd,
0xdb,0x39,0xc4,0x9b,0x29,0x63,0xfd,0x66,0xa6,0x71,0x91,0x1f,0x74,0x96,0x5b,0xc7,
0x8a,0xf6,0x29,0x1c,0x1b,0x2c,0x3a,0xdc,0x7e,0xf,0xf3,0x8f,0xa3,0x53,0xcb,0xa3,
0x2e,0xab,0xd,0x50,0x9b,0x29,0xe8,0xa8,0x26,0x31,0x96,0x59,0x75,0x26,0x94,0xa,
0x5a,0x11,0xd,0xc3,0xc,0x59,0xe,0xbe,0x3c,0xfd,0xf,0x97,0x2c,0x13,0x91,0x3d,
0xa7,0xe9,0xd0,0xad,0x28,0x67,0xe6,0x43,0xa4,0x54,0x50,0x90,0x7,0x4a,0xd3,0xfd],[
# Record 125: Address = 0x4e80, Length = 128
0x4e80,0x80,
0xbb,0x88,0x54,0xb8,0x93,0x24,0xa,0x99,0x39,0x53,0xfb,0x11,0xd5,0x83,0xaf,0x9a,
0x76,0x84,0xa9,0x9e,0x98,0xe6,0x61,0x86,0xda,0x9b,0xe,0x0,0xf6,0x91,0x4a,0xe7,
0xac,0xf8,0x8e,0x40,0x15,0xa6,0x3e,0xe5,0x67,0x27,0xf6,0x96,0xc4,0x62,0x1c,0x26,
0x52,0x3c,0x4d,0xdc,0x5,0x37,0xe2,0xc4,0x9d,0x63,0xb7,0xe,0x1a,0x35,0xd4,0x17,
0xd6,0x42,0x84,0x38,0xe2,0x66,0x40,0xdf,0x70,0xd6,0xe,0x79,0x4d,0xf,0x52,0x9d,
0xb5,0xbf,0x20,0x91,0x27,0xe4,0x29,0x47,0x81,0x3b,0xba,0x1c,0xa9,0xdb,0x6a,0x4f,
0x1b,0xa6,0x6c,0x68,0xbd,0x7b,0x93,0xfe,0x1e,0x17,0xf5,0xfe,0x1a,0x1d,0xef,0x5c,
0x6f,0x59,0xe5,0xd9,0x54,0x65,0x1d,0x8c,0xff,0x52,0xc,0xe4,0xdd,0xe0,0x88,0xf8],[
# Record 126: Address = 0x4f00, Length = 128
0x4f00,0x80,
0x3c,0x5a,0x92,0x8d,0x6,0xd9,0x34,0x97,0xf5,0x37,0xe9,0xfb,0x54,0x50,0x8b,0x1,
0x17,0xb,0x2d,0x78,0x7,0xd8,0xe3,0x5a,0x72,0x63,0x77,0x6,0x8,0x66,0xf,0x11,
0x1,0x19,0x68,0x6b,0x7,0x74,0x43,0x62,0xa,0xb0,0x8f,0x5,0xee,0xd,0xe4,0x83,
0x3e,0xd2,0xc8,0x2e,0x4a,0xf5,0xe9,0x60,0x3d,0x97,0xa2,0x8e,0x18,0x2e,0x4b,0xe0,
0x26,0x6f,0x22,0x94,0xa5,0x12,0xa0,0x26,0x64,0x50,0xec,0x77,0x8b,0xcf,0xf3,0xa3,
0x8f,0xb3,0x64,0x31,0x28,0x2d,0xd,0x9b,0x1e,0x82,0x94,0x93,0x16,0x3d,0x1a,0x48,
0x28,0xf0,0xda,0x5a,0xca,0x6f,0x12,0x56,0x3c,0xde,0xe8,0x98,0x6e,0x7c,0x20,0x1c,
0xd2,0xe5,0x15,0xd6,0xc4,0xdd,0xb4,0x72,0x87,0x1c,0x53,0xa9,0xb6,0x11,0x71,0x59],[
# Record 127: Address = 0x4f80, Length = 128
0x4f80,0x80,
0xe7,0x83,0x7,0xce,0x68,0x90,0xba,0x22,0xdf,0xb0,0x0,0x68,0x86,0xe5,0x9b,0x49,
0x23,0x67,0x73,0xff,0x38,0xfb,0xff,0xfd,0x6f,0xb9,0xcc,0x3f,0x2e,0xac,0x55,0x11,
0xdd,0xb9,0xde,0xab,0x50,0x6f,0xe7,0x72,0xdd,0xd2,0xb5,0xd6,0xbe,0xe7,0x9b,0x7d,
0x7e,0x67,0x85,0xce,0x7a,0x1c,0x87,0xf8,0x57,0xed,0x33,0xde,0x3a,0x1f,0x7,0x21,
0xc0,0x5d,0x43,0xa8,0x91,0xfe,0xec,0x88,0xda,0x81,0xb0,0x22,0x7b,0xea,0xf8,0x6,
0x24,0xe2,0x5a,0x15,0x9e,0xa7,0xc1,0xfe,0xf2,0x76,0x55,0x1a,0xba,0x67,0x5,0xc,
0x33,0xaf,0x49,0x9f,0xef,0xc3,0xf,0x18,0xb2,0x5f,0x3d,0x39,0x39,0xee,0xf1,0x43,
0xe,0xb4,0xa,0xfc,0x81,0xc5,0x6f,0x4d,0xb3,0x24,0x91,0x9b,0xc1,0xce,0xf1,0xbf],[
# Record 128: Address = 0x5000, Length = 128
0x5000,0x80,
0x48,0x3b,0x33,0xec,0xa5,0xb3,0xa3,0x89,0xf,0xd,0x81,0xd5,0x73,0xab,0x17,0x31,
0x5b,0x90,0x4b,0x28,0xd7,0xb0,0x2b,0xda,0x64,0x96,0x15,0x84,0xc8,0x6c,0xb4,0xb8,
0x4d,0x0,0x26,0x6f,0xf4,0xc9,0x4f,0xbe,0xeb,0xd8,0xaa,0x9b,0x30,0x8c,0x48,0x25,
0xdc,0x3d,0xa3,0x1a,0xbe,0xbf,0x64,0x94,0x7,0x5a,0x99,0x53,0x78,0xca,0x2,0x68,
0xee,0x84,0xe1,0xbc,0x6f,0x6e,0xb6,0xbd,0x32,0x68,0xae,0x62,0xfa,0x94,0x4d,0xf0,
0x65,0x95,0x18,0xca,0xca,0xb7,0x34,0xe,0x8a,0x78,0x1e,0x53,0x3,0xd6,0xb4,0xee,
0x80,0x64,0xfa,0xb4,0xd4,0xbe,0xe6,0xfa,0x4b,0x79,0x59,0x3e,0xf7,0x9d,0x4e,0x94,
0xf9,0x3f,0x90,0x4f,0x5f,0x17,0x7a,0x6d,0xd7,0xfa,0xc3,0x5,0x95,0x93,0x88,0x6a],[
# Record 129: Address = 0x5080, Length = 128
0x5080,0x80,
0x60,0xdc,0x98,0x77,0xe7,0x8a,0x7f,0x98,0x66,0x42,0xf8,0x89,0x14,0xf3,0xe,0xec,
0x31,0x45,0x65,0x99,0x8,0x1e,0xfe,0xfe,0x12,0xf9,0x3d,0xf2,0x19,0x9a,0x0,0x22,
0x70,0x7a,0x88,0x27,0x33,0xfd,0xa0,0x23,0x7b,0x6d,0xb9,0x85,0xf1,0xa5,0xfc,0x43,
0x9,0x4e,0x2c,0xb0,0x63,0x9a,0xc3,0x13,0x3d,0xbf,0x88,0xa0,0x1f,0xea,0xe3,0x76,
0x50,0x8a,0x55,0x3e,0xbc,0xfc,0x25,0x1e,0x62,0x93,0x14,0x9d,0xde,0x48,0x17,0xf4,
0x1c,0x93,0xe3,0x8e,0xe,0xd3,0xc8,0x21,0x63,0xfe,0xdd,0xc9,0x89,0xce,0xc8,0xb4,
0x92,0x52,0x35,0x5d,0xcf,0x50,0xa,0x81,0x22,0x23,0xd9,0xf9,0x6e,0x3f,0x1f,0x17,
0x2c,0x16,0xcf,0x25,0x1f,0x6,0x17,0x1f,0xc4,0xc4,0x11,0x6e,0x9e,0x10,0x51,0x72],[
# Record 130: Address = 0x5100, Length = 128
0x5100,0x80,
0x55,0x39,0xeb,0xf6,0xfe,0xdc,0x3c,0xf1,0xfa,0x82,0xa9,0xe8,0x2b,0xbe,0x1e,0xdd,
0x9f,0xc3,0x36,0xea,0x28,0xa2,0x24,0xd3,0x5,0xeb,0xe7,0xdd,0x12,0x16,0xb3,0x39,
0x83,0x3,0x2c,0x81,0x9f,0xde,0xf2,0xe0,0xf3,0x6e,0x21,0x46,0xae,0x49,0x1c,0xa2,
0x4d,0xfb,0xc8,0xcb,0xc2,0xbb,0x1e,0x5f,0x1d,0x5f,0x8f,0x60,0x2e,0x1c,0x50,0x6d,
0xb9,0x9,0x98,0x6a,0x64,0x2c,0x4d,0xf9,0x85,0x89,0x14,0x7a,0x41,0xf4,0xab,0x86,
0x37,0xbd,0x1d,0x44,0xaa,0x72,0xb3,0x82,0xd6,0x31,0x8,0x2c,0xea,0xb0,0x23,0x5c,
0xd2,0x24,0x15,0x74,0x94,0xc9,0x2d,0x82,0x85,0x97,0x4d,0xd6,0xa7,0xd8,0xf3,0x5,
0x5b,0x6,0x6e,0xd,0x54,0x9,0xe4,0xc0,0xd6,0x8d,0x53,0xc3,0x17,0xc8,0x60,0xc7],[
# Record 131: Address = 0x5180, Length = 128
0x5180,0x80,
0x59,0x76,0x89,0x5e,0x4c,0x77,0x51,0x95,0x24,0xbf,0xf,0xd,0x4b,0xb8,0xd6,0x18,
0x93,0xde,0xd8,0xd3,0x4e,0xe4,0xb5,0x11,0x9f,0x3b,0x25,0x25,0x49,0xa3,0x2f,0x1,
0xa,0x47,0x1b,0x39,0xfa,0xe6,0xf0,0x73,0x73,0x78,0x78,0xb6,0x9f,0x1c,0x7c,0x2e,
0xf7,0xcb,0xb6,0x8,0xd1,0x6,0x32,0x6a,0x15,0xc5,0x57,0x20,0xa7,0x6,0x9,0x3d,
0x6a,0x68,0x45,0x4b,0xb,0x6c,0x17,0x2b,0x1d,0x23,0xf1,0xe2,0xa2,0x7c,0x15,0xb2,
0xdc,0x45,0xe6,0xf2,0x78,0x59,0xa8,0x89,0x16,0x31,0x99,0x6f,0x5a,0xce,0xf5,0xd9,
0x6a,0xb2,0x44,0xf8,0x8e,0x90,0x21,0x26,0xe4,0x21,0xf2,0xd5,0x31,0x98,0xae,0xc9,
0x2e,0x3a,0xba,0xc,0x6c,0xf3,0x8a,0x22,0x46,0x3f,0x17,0x2f,0x77,0x86,0x4b,0x14],[
# Record 132: Address = 0x5200, Length = 128
0x5200,0x80,
0x43,0x63,0xc,0x9e,0x79,0x4,0x62,0x14,0x8b,0xe4,0xf9,0x54,0xc4,0x82,0xc3,0x39,
0x6e,0xd1,0xf2,0x24,0x72,0x96,0x9b,0x74,0x50,0x4,0x95,0xf2,0xd0,0x1a,0x4,0x71,
0xf4,0xaa,0x6c,0xa7,0x21,0x59,0x8,0xe9,0xa3,0x46,0xa8,0x76,0xe5,0x0,0x85,0x28,
0x89,0x31,0x3a,0x52,0xc2,0x15,0x23,0x41,0x38,0xef,0xee,0x8e,0x28,0x10,0xee,0x85,
0xf3,0xff,0x5d,0xfd,0x25,0x86,0xe4,0x26,0x4e,0xdd,0x24,0x3e,0x4e,0x15,0x86,0x70,
0x6,0x78,0xb3,0xb2,0xa4,0x29,0xc9,0x89,0x40,0x55,0xd6,0x64,0xe5,0xb,0x9b,0x82,
0x86,0x1c,0xc6,0x60,0x7e,0x55,0xc,0xd3,0xc4,0xfa,0x6,0xa9,0x48,0x11,0xb3,0xb,
0x17,0x33,0x21,0x74,0x2a,0xbd,0x1e,0x4,0x5d,0x84,0x9a,0x75,0x20,0x24,0xc6,0x9a],[
# Record 133: Address = 0x5280, Length = 128
0x5280,0x80,
0x35,0x32,0x65,0x2a,0x9b,0x3b,0x7d,0x20,0x97,0xad,0x76,0x1,0xfb,0x6b,0x7b,0x86,
0xb,0xe0,0x11,0x9c,0x40,0x20,0x20,0x6d,0x87,0x72,0xdb,0x7e,0x63,0x96,0x1b,0x98,
0x18,0x50,0x9c,0xaa,0x30,0xf2,0x8b,0x2e,0x29,0x77,0xcc,0xb7,0xc6,0x96,0x35,0xf3,
0xc7,0xf,0x51,0xf0,0xdb,0x60,0x7,0xeb,0x6c,0x8f,0xb3,0xc2,0x23,0xc4,0xa0,0xe,
0x9a,0xb,0x7a,0x64,0x26,0x3,0x4f,0xbf,0xa7,0xc6,0x7f,0x2e,0xc,0xef,0xe,0x68,
0x6c,0x32,0xb2,0x10,0x39,0x95,0x56,0xac,0x35,0x3d,0xb3,0x3,0xd2,0x9,0x28,0x27,
0xd,0xc1,0xb9,0xef,0x7b,0x23,0x30,0x13,0x17,0x4a,0x3,0xbd,0x18,0x68,0x9a,0x5,
0x5,0x8a,0xcc,0x92,0xcb,0xe3,0xb5,0x88,0x48,0x4c,0x7e,0xbb,0xa0,0x4e,0x6d,0x17],[
# Record 134: Address = 0x5300, Length = 128
0x5300,0x80,
0xff,0x95,0x38,0x48,0x3d,0xe3,0xf7,0x59,0xe2,0x13,0x5a,0x5c,0xf6,0x91,0xe6,0x64,
0xe,0x91,0x64,0xb4,0x26,0xfc,0x7,0xc5,0xbe,0x95,0xd7,0xb5,0xfd,0xa6,0x57,0x2,
0xd1,0x9c,0x80,0xd8,0xc9,0xa0,0x80,0xd3,0x1f,0xb6,0x7f,0xf9,0x9d,0x4,0xf7,0x3e,
0x7c,0x37,0x74,0xc7,0xeb,0xe9,0x73,0x55,0x29,0x6a,0x5e,0x8d,0x84,0xda,0x8c,0xf0,
0xe7,0x9e,0x14,0xbc,0xf3,0xfc,0x6,0xc8,0x1b,0xca,0x32,0xef,0xdf,0x63,0x3c,0xf9,
0x1f,0x3f,0xf3,0x44,0x7e,0x8f,0x26,0x28,0x20,0x36,0x1,0xa9,0xa3,0x5d,0x46,0x42,
0xb0,0x8f,0xc6,0x1e,0x24,0x58,0x5c,0xe,0x2c,0x5a,0xea,0x1b,0xf4,0x16,0xf1,0xd1,
0x71,0x10,0xca,0xa6,0xa9,0xd5,0x6,0x3f,0x44,0x7f,0x8f,0xbd,0xae,0x4e,0x3d,0xa7],[
# Record 135: Address = 0x5380, Length = 128
0x5380,0x80,
0xc6,0xf3,0x54,0x9b,0x7f,0xaf,0x24,0x2f,0xf2,0x98,0x1a,0xba,0x93,0xef,0xb5,0xef,
0xe7,0xf0,0x1f,0x3a,0x13,0x17,0xd8,0x73,0x7c,0x91,0xef,0x86,0x90,0x50,0xda,0x93,
0x58,0xdc,0x96,0x42,0x3d,0x32,0x96,0xd8,0x70,0x66,0x1a,0xae,0x99,0x47,0x52,0xd8,
0xff,0xc4,0xe,0x66,0xf,0xb5,0x77,0xa4,0x21,0xe,0x50,0xfa,0xe4,0xb6,0x38,0x24,
0x3f,0xce,0xfe,0xa4,0x6c,0x6d,0xe5,0x15,0x8,0xb6,0x46,0x68,0xe2,0xe1,0x10,0x4e,
0x7c,0x98,0x9e,0x14,0x21,0xf6,0xe8,0xd,0xf3,0x86,0x48,0xe6,0xf0,0x5b,0x86,0xc6,
0x42,0x6e,0x27,0xb4,0x4d,0x51,0x9e,0x88,0x46,0xa,0x63,0xcd,0x45,0x7f,0xc4,0x29,
0xf1,0xb8,0x22,0x42,0xc5,0x67,0xa4,0xa2,0xed,0xd2,0x49,0xc,0xbd,0x60,0x59,0xb],[
# Record 136: Address = 0x5400, Length = 128
0x5400,0x80,
0x7b,0x58,0x47,0xf4,0x34,0xfd,0xa5,0x23,0x66,0x5a,0x4c,0x27,0x49,0xb3,0x19,0xfa,
0xa7,0x5,0xdc,0xe3,0x24,0x40,0x88,0xc1,0x95,0xe0,0xf8,0xed,0x6b,0x8a,0xfd,0x70,
0x9d,0x8f,0xa,0x17,0x9f,0xd6,0x2,0xe4,0xec,0xb2,0xba,0xed,0xa6,0xc7,0xb,0x29,
0x92,0x1c,0x3f,0x18,0xc1,0x9c,0x67,0x79,0x29,0x4f,0x6a,0x24,0x15,0xc9,0xab,0x58,
0x96,0x49,0x50,0x21,0x4a,0xac,0x81,0xc1,0xb3,0xe1,0xea,0xd5,0xa1,0x86,0xd5,0x45,
0x1c,0xe6,0xea,0x92,0x4e,0xa5,0xcf,0xec,0x6,0x47,0x43,0xa7,0x0,0x71,0xc2,0x14,
0x15,0x7e,0xab,0x5b,0x3d,0x1b,0x8,0x2b,0xaf,0x80,0x0,0x20,0x5f,0x99,0xd0,0xf0,
0x9,0x2c,0xca,0x4,0xc,0xd0,0xad,0x26,0x5e,0x5,0xa7,0x50,0x84,0x38,0xb0,0x6c],[
# Record 137: Address = 0x5480, Length = 128
0x5480,0x80,
0x70,0x5c,0x5b,0xe1,0xd8,0x29,0x46,0xc8,0x72,0xf8,0x85,0xbd,0xab,0x9f,0xeb,0x5,
0xca,0x7f,0xb3,0xd2,0x2e,0x99,0x95,0x9,0xdb,0xd3,0x25,0x5c,0xd8,0x51,0x1b,0x9d,
0x56,0x55,0x20,0xbd,0x1,0x97,0x65,0x55,0x5a,0x5a,0xe6,0xa1,0x58,0x72,0x2d,0x77,
0xfd,0x84,0xea,0x6e,0x3d,0x9d,0x58,0xf8,0xd3,0x60,0x1d,0x83,0xf8,0x1f,0x7d,0x8f,
0x83,0xfc,0x18,0xcc,0xcc,0xde,0xe9,0x3d,0x90,0x37,0xae,0x99,0x17,0xa8,0x4,0x30,
0x9b,0xa7,0xd8,0xe5,0x16,0x45,0xf0,0xed,0x4b,0x95,0xce,0x36,0x96,0xa6,0x7b,0x86,
0xf8,0x2c,0x40,0xee,0x53,0xfa,0xb1,0xc,0xd4,0x12,0x9,0x9c,0x3b,0xde,0xd1,0x27,
0xfd,0xad,0x24,0xc7,0xbf,0x25,0xc5,0xb8,0x42,0x8f,0x99,0xc,0x47,0xee,0x8e,0x11],[
# Record 138: Address = 0x5500, Length = 128
0x5500,0x80,
0x2,0x86,0xc6,0xd1,0xe5,0x21,0xf7,0xf8,0x87,0xab,0x9e,0x39,0x70,0x8d,0x0,0x29,
0x31,0x27,0x5e,0xa,0xb3,0x7f,0x7c,0xcb,0x21,0x6a,0x41,0x7e,0x26,0xfa,0xbd,0x46,
0x13,0xde,0x88,0x30,0x83,0xe7,0x83,0x44,0xc6,0xe2,0xc1,0xd1,0xbb,0xa2,0x8,0x7b,
0xc,0xef,0x14,0x9c,0xd0,0x27,0x80,0x75,0xef,0xcf,0x27,0x18,0xcb,0x1a,0x29,0xbc,
0x5a,0x6c,0xee,0x45,0x68,0x94,0x65,0x98,0x4d,0x7a,0x81,0x9b,0x46,0x19,0xb9,0x9c,
0xee,0x59,0x17,0x25,0xc6,0x10,0x90,0x4a,0x12,0x16,0x24,0x7,0x58,0x93,0x7e,0xd0,
0x48,0x8a,0x80,0x22,0x84,0x71,0xdf,0xde,0xbe,0xbe,0x6b,0x94,0x43,0x21,0xa1,0xe8,
0xb,0xa0,0xc2,0x65,0x37,0x32,0xdf,0xa4,0x69,0x76,0xb2,0x30,0x4d,0x3a,0x1,0x47],[
# Record 139: Address = 0x5580, Length = 128
0x5580,0x80,
0x52,0x4,0xfc,0x1a,0x7b,0x21,0x28,0x1,0x39,0xa2,0xf0,0x76,0x49,0xbb,0xd0,0x44,
0xf,0x4c,0x6d,0xf4,0x2b,0x97,0xd5,0x43,0x67,0x54,0x93,0xfa,0xbb,0xea,0xf5,0xbf,
0xd8,0x37,0xcb,0x8a,0x1,0x7,0x54,0x31,0xbb,0xc8,0x6,0x5e,0x8c,0x4f,0x52,0xf7,
0x40,0x57,0x13,0x91,0xcd,0xc5,0x83,0xff,0xad,0x74,0x8e,0xa0,0xfc,0x4,0xeb,0xf7,
0xeb,0xf6,0x58,0xc1,0x1d,0x7b,0x1,0xc7,0x2f,0xe3,0xa1,0x5b,0xec,0x35,0x22,0x8c,
0x1c,0x78,0x78,0x81,0xe2,0xff,0xfa,0x3d,0xf6,0xc9,0x35,0xed,0xc1,0x30,0x39,0x0,
0x85,0xb5,0x34,0xc3,0x18,0x20,0x81,0x8f,0x4f,0x2f,0x90,0xce,0x7,0x98,0x9b,0x23,
0xad,0x52,0x1f,0xb5,0xf,0x2f,0x54,0x1a,0x72,0x3c,0x13,0x35,0xbe,0xa3,0xd1,0xd4],[
# Record 140: Address = 0x5600, Length = 128
0x5600,0x80,
0xdd,0x7b,0x4b,0x2e,0xda,0xc2,0xb5,0xd0,0xef,0xd5,0x8f,0x8a,0x9b,0xde,0x5a,0x70,
0x49,0x4d,0x7d,0x38,0xe7,0xe6,0xe7,0x96,0x77,0xc8,0x32,0xb2,0x62,0xd6,0xee,0xba,
0xfe,0x46,0xce,0x40,0x71,0xb5,0xea,0xc2,0x3b,0x2,0x4b,0x3b,0x8f,0xd2,0x7c,0x4c,
0xbc,0xda,0x82,0xc7,0x7d,0xc0,0x68,0x36,0xdb,0x28,0xb2,0x51,0x83,0x3b,0x4d,0xc0,
0xda,0x31,0x1f,0xdc,0x78,0xf4,0x24,0x20,0x24,0x3e,0x0,0xf8,0x31,0x8b,0xb4,0x20,
0x1b,0x77,0xf8,0x5e,0xb2,0xa8,0x5a,0x4e,0x8c,0xb,0xe7,0x2a,0xbf,0x8e,0x62,0x8c,
0xb5,0xe,0xe5,0x7a,0xe1,0x8c,0x28,0x6e,0xe9,0x57,0x32,0xa1,0x91,0xa7,0x7c,0xe,
0x18,0x29,0x2c,0x31,0xa0,0x8a,0x4b,0xe1,0x83,0xda,0x8f,0xf8,0x44,0x1e,0x6d,0xd5],[
# Record 141: | |
[]
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/vnd.orcid+xml; qs=5', 'application/orcid+xml; qs=3', 'application/xml', 'application/vnd.orcid+json; qs=4', 'application/orcid+json; qs=2', 'application/json']) # noqa: E501
# Authentication setting
auth_settings = ['orcid_auth'] # noqa: E501
return self.api_client.call_api(
'/v3.0/{orcid}/other-names', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_peer_reviewv3(self, orcid, **kwargs): # noqa: E501
"""Create a Peer Review # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_peer_reviewv3(orcid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str orcid: (required)
:param PeerReviewV30 body:
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.create_peer_reviewv3_with_http_info(orcid, **kwargs) # noqa: E501
else:
(data) = self.create_peer_reviewv3_with_http_info(orcid, **kwargs) # noqa: E501
return data
def create_peer_reviewv3_with_http_info(self, orcid, **kwargs): # noqa: E501
"""Create a Peer Review # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_peer_reviewv3_with_http_info(orcid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str orcid: (required)
:param PeerReviewV30 body:
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['orcid', 'body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_peer_reviewv3" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'orcid' is set
if ('orcid' not in params or
params['orcid'] is None):
raise ValueError("Missing the required parameter `orcid` when calling `create_peer_reviewv3`") # noqa: E501
collection_formats = {}
path_params = {}
if 'orcid' in params:
path_params['orcid'] = params['orcid'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/vnd.orcid+xml; qs=5', 'application/orcid+xml; qs=3', 'application/xml', 'application/vnd.orcid+json; qs=4', 'application/orcid+json; qs=2', 'application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/vnd.orcid+xml; qs=5', 'application/orcid+xml; qs=3', 'application/xml', 'application/vnd.orcid+json; qs=4', 'application/orcid+json; qs=2', 'application/json']) # noqa: E501
# Authentication setting
auth_settings = ['orcid_auth'] # noqa: E501
return self.api_client.call_api(
'/v3.0/{orcid}/peer-review', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_qualificationv3(self, orcid, **kwargs): # noqa: E501
"""Create an Qualification # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_qualificationv3(orcid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str orcid: (required)
:param QualificationV30 body:
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.create_qualificationv3_with_http_info(orcid, **kwargs) # noqa: E501
else:
(data) = self.create_qualificationv3_with_http_info(orcid, **kwargs) # noqa: E501
return data
def create_qualificationv3_with_http_info(self, orcid, **kwargs): # noqa: E501
"""Create an Qualification # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_qualificationv3_with_http_info(orcid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str orcid: (required)
:param QualificationV30 body:
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['orcid', 'body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_qualificationv3" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'orcid' is set
if ('orcid' not in params or
params['orcid'] is None):
raise ValueError("Missing the required parameter `orcid` when calling `create_qualificationv3`") # noqa: E501
collection_formats = {}
path_params = {}
if 'orcid' in params:
path_params['orcid'] = params['orcid'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/vnd.orcid+xml; qs=5', 'application/orcid+xml; qs=3', 'application/xml', 'application/vnd.orcid+json; qs=4', 'application/orcid+json; qs=2', 'application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/vnd.orcid+xml; qs=5', 'application/orcid+xml; qs=3', 'application/xml', 'application/vnd.orcid+json; qs=4', 'application/orcid+json; qs=2', 'application/json']) # noqa: E501
# Authentication setting
auth_settings = ['orcid_auth'] # noqa: E501
return self.api_client.call_api(
'/v3.0/{orcid}/qualification', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_research_resourcev3(self, orcid, **kwargs): # noqa: E501
"""Create a Research Resource # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_research_resourcev3(orcid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str orcid: (required)
:param ResearchResourceV30 body:
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.create_research_resourcev3_with_http_info(orcid, **kwargs) # noqa: E501
else:
(data) = self.create_research_resourcev3_with_http_info(orcid, **kwargs) # noqa: E501
return data
def create_research_resourcev3_with_http_info(self, orcid, **kwargs): # noqa: E501
"""Create a Research Resource # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_research_resourcev3_with_http_info(orcid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str orcid: (required)
:param ResearchResourceV30 body:
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['orcid', 'body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_research_resourcev3" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'orcid' is set
if ('orcid' not in params or
params['orcid'] is None):
raise ValueError("Missing the required parameter `orcid` when calling `create_research_resourcev3`") # noqa: E501
collection_formats = {}
path_params = {}
if 'orcid' in params:
path_params['orcid'] = params['orcid'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/vnd.orcid+xml; qs=5', 'application/orcid+xml; qs=3', 'application/xml', 'application/vnd.orcid+json; qs=4', 'application/orcid+json; qs=2', 'application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/vnd.orcid+xml; qs=5', 'application/orcid+xml; qs=3', 'application/xml', 'application/vnd.orcid+json; qs=4', 'application/orcid+json; qs=2', 'application/json']) # noqa: E501
# Authentication setting
auth_settings = ['orcid_auth'] # noqa: E501
return self.api_client.call_api(
'/v3.0/{orcid}/research-resource', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_researcher_urlv3(self, orcid, **kwargs): # noqa: E501
"""Add a new researcher url for an ORCID ID # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_researcher_urlv3(orcid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str orcid: (required)
:param ResearcherUrlV30 body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.create_researcher_urlv3_with_http_info(orcid, **kwargs) # noqa: E501
else:
(data) = self.create_researcher_urlv3_with_http_info(orcid, **kwargs) # noqa: E501
return data
def create_researcher_urlv3_with_http_info(self, orcid, **kwargs): # noqa: E501
"""Add a new researcher url for an ORCID ID # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_researcher_urlv3_with_http_info(orcid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str orcid: (required)
:param ResearcherUrlV30 body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['orcid', 'body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_researcher_urlv3" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'orcid' is | |
#!/usr/bin/python
#
# Perform optical character recognition, usage:
# python3 ./image2text.py train-image-file.png train-text.txt test-image-file.png
#
# Authors: <NAME> (aagond), <NAME> (hatha), <NAME> (saimorap)
# (based on skeleton code by D. Crandall, Oct 2020)
#
from PIL import Image, ImageDraw, ImageFont
import sys
import numpy as np
#import matplotlib.pyplot as plt
#import scipy
#from scipy.signal import convolve2d
CHARACTER_WIDTH=14
CHARACTER_HEIGHT=25
def load_letters(fname):
'''
To load the image into a list of list of pixel matrix of each character in
the image.
PARAMETERS : fname STRING
RETURNS : result LIST
'''
im = Image.open(fname)
px = im.load()
(x_size, y_size) = im.size
print(im.size)
print(int(x_size / CHARACTER_WIDTH) * CHARACTER_WIDTH)
result = []
for x_beg in range(0, int(x_size / CHARACTER_WIDTH) * CHARACTER_WIDTH, CHARACTER_WIDTH):
result += [ [ "".join([ '*' if px[x, y] < 1 else ' ' for x in range(x_beg, x_beg+CHARACTER_WIDTH) ]) for y in range(0, CHARACTER_HEIGHT) ], ]
return result
def load_training_letters(fname):
'''
To load the train image in a dictionary.
The key in this dictionary is the character from the possible (allowed) characters TRAIN_LETTERS
The values in the dictionary is the list of list of image pixel matrix.
PARAMETERS : fname STRING
RETURNS : DICTIONARY
'''
# Declaring TRAIN_LETTERS as a global variable to be accessed in other functions.
global TRAIN_LETTERS
TRAIN_LETTERS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789(),.-!?\"' "
letter_images = load_letters(fname)
return { TRAIN_LETTERS[i]: letter_images[i] for i in range(0, len(TRAIN_LETTERS) ) }
'''
# Function to estimate the noise in a image. Uses SCIPY. (Not used in this version.)
def estimate_noise(I):
# Noise estimator from https://stackoverflow.com/questions/2440504/noise-estimation-noise-measurement-in-image
# Using the estimates noise from the function to calculate the emission probabilites results in poor predictions
# for Naive Bayes and subseqently Hidden Markov Model using Viterbi.
H, W = I.shape
M = [[1, -2, 1],
[-2, 4, -2],
[1, -2, 1]]
sigma = np.sum(np.sum(np.absolute(convolve2d(I, M)))) # convolve2d can be imported from scipy.
sigma = sigma * np.sqrt(0.5 * np.pi) / (6 * (W-2) * (H-2))
return sigma
'''
def convert_to_num(train_char : list, test_char : list):
'''
Function to convert character to numpy array of 1's and 0's. (Used alongwith estimate_noise function)
PARAMETERS : train_char LIST, test_char LIST
RETURNS : num_train_char np.array, num_test_char np.array
'''
num_train_char = np.array([[1 if (train_char[x][y] == '*') else 0 for y in range(CHARACTER_WIDTH)] for x in range(CHARACTER_HEIGHT)])
num_test_char = np.array([[1 if (test_char[x][y] == '*') else 0 for y in range(CHARACTER_WIDTH)] for x in range(CHARACTER_HEIGHT)])
return num_train_char, num_test_char
def get_emission_prob(train_letters : list, test_letters : list) -> np.array:
'''
This is the function to calculate the emission probability.
The emission probability is estimated by comparing each test character pixel matrix
with the pixel matrix of each train character and return the similarity that exists.
4 counts are maintained to extract the most information from the comparison.
1. matched_star --------- count of matched '*' pixel in train and test sub-images.
2. matched_blank --------- count of matched ' ' pixel in train and test sub-images.
3. matched_star_blank ----- count of instances where pixel in train is '*' and the same coordinate pixel is ' '
4. matched_blank_star ----- count of instances where pixel in train is ' ' and the same coordinate pixel is '*'
matched_star_blank gives the idea about the missed information by the test image which can prove to be vital in prediction.
matched_blank_star gives the idea about the noise in the image, where the pixel value in train is ' ' but for the same
coordinate pixel the pixel value is '*', which should not be the case ideally (for same character in train sub-image and
test sub-image).
FROM THE QUESTION FILE :
"
If we assume that m% of the pixels are noisy, then a naive Bayes classifier could
assume that each pixel of a given noisy image of a letter will match the corresponding pixel in the reference
letter with probability (100 −m)%.
"
Using this, we can account for noise in the image as well, and hence the emission probabilities can be
calculated for each pixel based on the summation of the exponentiation of the matching pixels over 1-noise
and the exponentiation of the non-matching pixels over the noise. The noise estimation of the image was
done using different functions referred from : https://stackoverflow.com/questions/2440504/noise-estimation-noise-measurement-in-image
The noise on average for the test images was approximately 11 %. The assumption taken here is that 10% of pixels in the test images
are noisy.
Additionally the weights for matched_star, matched_blank, matched_star_blank and matched_blank_star have been calibrated
based on intuition and experimentation.
The emissions probability is calculated after applying Laplace Smoothing(alpha=1).
'''
emissions = np.zeros((len(train_letters), len(test_letters)))
total_pixels = CHARACTER_HEIGHT * CHARACTER_WIDTH
'''
# Best Weights for train_set.txt
weights = {
'matched_star' : 0.9,
'matched_blank' : 0.3,
'mismatch_star_blank' : 0.9,
'mismatch_blank_star' : -0.5,
}
weights = {
'matched_star' : 1.0,
'matched_blank' : 0.26,
'mismatch_star_blank' : 0.9,
'mismatch_blank_star' : -0.5,
}
'''
noise = 0.1
weights = {
'matched_star' : 0.9,
'matched_blank' : 0.32,
'mismatch_star_blank' : 1.3,
'mismatch_blank_star' : -0.5,
}
for i in range(len(test_letters)):
#test_image_stars = sum([sum([1 if (test_letters[i][x][y] == '*') else 0 for y in range(CHARACTER_WIDTH)]) for x in range(CHARACTER_HEIGHT)])
#test_image_blanks = (CHARACTER_HEIGHT * CHARACTER_WIDTH) - test_image_stars
#noise = estimate_noise(plt.imread(test_img_fname[i]))
for j in range(len(train_letters)):
#sum_matched_pixels = sum([sum([1 if (test_letters[i][x][y] == list(train_letters.values())[j][x][y]) else 0 for y in range(CHARACTER_WIDTH)]) for x in range(CHARACTER_HEIGHT)])
#sum_miss_pixels = total_pixels - sum_matched_pixels
matched_star = 0
matched_blank = 0
mismatch_star_blank = 0 # Train - Star ::: Test - Blank ---- Missed important information
mismatch_blank_star = 0 # Train - Blank ::: Test - Star ---- Noise.
train_letter = list(train_letters.values())[j]
test_letter = test_letters[i]
for m in range(CHARACTER_HEIGHT):
for n in range(CHARACTER_WIDTH):
if train_letter[m][n] == test_letter[m][n]:
# Matched
if train_letter[m][n] == '*':
matched_star += 1
else:
matched_blank += 1
else:
# Mismatched
if train_letter[m][n] == '*' and test_letter[m][n] == ' ':
# Train : '*', Test : ' ', Information missed by the test sub-image.
mismatch_star_blank += 1
else:
# Train : ' ', Test : '*', Information that represent the noise in the test sub-image.
mismatch_blank_star += 1
emissions[j][i] = (1-noise) * (matched_star * weights['matched_star'] \
+ matched_blank * weights['matched_blank'] )\
+ noise * (mismatch_star_blank * weights['mismatch_star_blank'] \
+ mismatch_blank_star * weights['mismatch_blank_star'])
emissions = (emissions + 1) / (total_pixels + len(TRAIN_LETTERS))
return emissions
def preprocess_text(train_set_filename : str) -> list:
'''
Create a word list from the train text file.
The function generates the word list based on the input file name.
If the filename has 'bc.train' or 'bc.test' as a substring in the filename,
every second word will be skipped. Adapted
PARAMETERS : train_set_filename STRING
RETURNS : words LIST
'''
words = []
if (('bc.train' in train_set_filename.lower()) or ('bc.test' in train_set_filename.lower())):
# For train-set files from part1.
# 'bc.train', 'bc.test', 'bc.test.tiny'
# Refactored code snippet from A3P1 Skeleton code.
with open(train_set_filename, 'r') as file :
for line in file:
data =[w for w in line.split()]
words += data[0::2]
words += ' '
file.close()
else:
with open(train_set_filename, 'r') as file:
lines = file.readlines()
for line in lines:
words += [word + ' ' for word in line.split()]
#words += [word for word in line.split()]
file.close()
return words
def get_initial_probs(words : list):
'''
Function to get initial probabilities of each character in the TRAIN_LETTERS.
The initial probabilities are computed from the train set. The initial probabilities
of a given character is typically the occurence of word starting with that character.
Laplace Smoothing is applied on the initial probabilities to calculate the initial probabilities.
PARAMETERS : words LIST
RETURNS : intial_probs np.array
'''
initial_probs_raw = [0] * len(TRAIN_LETTERS)
for word in words:
if word[0] in TRAIN_LETTERS:
initial_probs_raw[TRAIN_LETTERS.index(word[0])] += 1
#dict_a = {TRAIN_LETTERS[i] : initial_probs_raw[i] for i in range(len(TRAIN_LETTERS))}
# Laplace(alpha= +1) Smoothing.
initial_probs = np.array([((initial_probs_raw[i_p] + 1) / (len(words) + len(TRAIN_LETTERS))) for i_p in | |
pass
elif (tuple_idx[0] <= list_start_end_2[-1][0]) & (
tuple_idx[1] >= list_start_end_2[-1][1]
):
list_start_end_2[-1] = tuple_idx
else:
list_start_end_2.append(tuple_idx)
basepalette = [
"#E73F74",
"#7F3C8D",
"#11A579",
"#3969AC",
"#F2B701",
"#80BA5A",
"#E68310",
]
palette = basepalette[: len(methods) - 2] + [
"#a0a0a0",
"#505050",
]
dict_palette = dict(zip(methods, palette[: len(methods)]))
fig, (axl, axr) = plt.subplots(1, 2, figsize=figsize)
for method_idx, method in enumerate(methods):
axl.plot(
[0, len(list_start_end_1) + 1],
[df_ranks_1.mean(0)[method], df_ranks_1.mean(0)[method]],
c=dict_palette[method],
)
axr.plot(
[0, len(list_start_end_2) + 1],
[df_ranks_2.mean(0)[method], df_ranks_2.mean(0)[method]],
c=dict_palette[method],
)
for idx, tuple_list in enumerate(list_start_end_1):
axl.plot(
[idx + 1, idx + 1],
[
df_ranks_means_1.iloc[tuple_list[0]] - 0.03,
df_ranks_means_1.iloc[tuple_list[1]] + 0.03,
],
c="#808080",
linewidth=5,
)
for idx, tuple_list in enumerate(list_start_end_2):
axr.plot(
[idx + 1, idx + 1],
[
df_ranks_means_2.iloc[tuple_list[0]] - 0.03,
df_ranks_means_2.iloc[tuple_list[1]] + 0.03,
],
c="#808080",
linewidth=5,
)
# Axis formatting
for ax in [axl, axr]:
ax.set_ylabel("Rank (lower is better)")
ax.set_xticks([])
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.set_ylim(
min([axl.get_ylim()[0], axr.get_ylim()[0]]),
max([axl.get_ylim()[1], axr.get_ylim()[1]]),
)
for ax in [axl, axr]:
ax.invert_yaxis()
l1 = axr.legend(
bbox_to_anchor=(1, 0.75),
handles=[
Line2D(
[0], [0], marker="o", color=palette[method_idx], label=method
)
for method_idx, method in enumerate(methods)
],
)
ax.add_artist(l1)
axl.set_title(title1)
axr.set_title(title2)
plt.suptitle(title, y=1.03)
plt.tight_layout()
for fmt in ["png", "pdf"]:
fig.savefig(
f"{os.getcwd()}/figures/comparison_figs/{fmt}/{filename}.{fmt}",
bbox_inches="tight",
)
def compare_values(
list_files_1,
list_files_2,
read_dir,
title="",
title1="",
title2="",
variables=[],
increasing=False,
alpha=0.1,
figsize=(16, 4),
filename="",
mode="normal",
):
list_diffs, list_methods = [], []
for file_idx in range(len(list_files_1)):
df_1, df_2 = (
pd.read_csv(read_dir + list_files_1[file_idx], index_col=0),
pd.read_csv(read_dir + list_files_2[file_idx], index_col=0),
)
list_diffs += (
df_1.loc[variables[0], :] - df_2.loc[variables[0], :]
).tolist()
list_methods += df_1.columns.tolist()
methods = df_1.columns
basepalette = [
"#E73F74",
"#7F3C8D",
"#11A579",
"#3969AC",
"#F2B701",
"#80BA5A",
"#E68310",
]
palette = basepalette[: len(methods) - 2] + [
"#a0a0a0",
"#505050",
]
# dict_palette = dict(zip(methods, palette[: len(methods)]))
df_val_diffs = pd.DataFrame({"diff": list_diffs, "method": list_methods})
fig, ax = plt.subplots(figsize=figsize)
sns.swarmplot(
x="method", y="diff", data=df_val_diffs, palette=palette, ax=ax, s=4
)
fig.suptitle(title)
for method_idx, method in enumerate(methods):
values_method = df_val_diffs["diff"][
df_val_diffs["method"] == method
].values
if np.sum(values_method) == 0:
p = 0.5
else:
t, p = wilcoxon(values_method)
if (
np.median(values_method) >= 0
): # THIS IS BECAUSE WE WAN'T A SINGLE-TAILED TEST WITH MU > 0!!!!
p = 1 / 2 * p
else:
p = 1 - 1 / 2 * p
if np.isnan(p):
p = 0.5
if p < 0.01:
pstr = f"{p:.3e}"
elif p > 0.9:
pstr = "~1"
else:
pstr = f"{p:.2f}"
xmov = -0.5 if p < 0.01 else -0.2
ax.text(method_idx + xmov, 0.1 + max(values_method), f"{pstr}")
ax.plot([-0.5, len(methods) - 0.2], [0, 0], c="#bcbcbc")
ax.set_ylim(ax.get_ylim()[0], ax.get_ylim()[1] + 0.15)
ax.set_xlim(-0.8, len(methods) + 0.1)
for fmt in ["png", "pdf"]:
fig.savefig(
f"{os.getcwd()}/figures/comparison_figs/{fmt}/{filename}.{fmt}",
bbox_inches="tight",
)
def create_UMAP_adataset_libprep_org(
adata_dir, df_rank_dir, lib_prep, org, lab, log
):
list_methods = [
"triku",
"m3drop",
"nbumi",
"scanpy",
"brennecke",
"scry",
"std",
]
adata = sc.read_h5ad(f"{adata_dir}/{lib_prep}_{org}.h5ad")
df_rank = pd.read_csv(
f"{df_rank_dir}/{lab}_{lib_prep}_{org}_feature_ranks.csv", index_col=0
)
if log:
sc.pp.log1p(adata)
tk.tl.triku(
adata, n_procs=1,
)
n_HVG = np.sum(adata.var["highly_variable"].values)
print("n_HVG", n_HVG)
col_cell_types = "cell_types" if "cell_types" in adata.obs else "CellType"
cell_types = adata.obs[col_cell_types]
dict_return = {}
dict_other_stuff = {
"cell_types": cell_types.values,
"mean": adata.X.mean(0).ravel(),
"std": adata.X.std(0).ravel(),
"per_0": (adata.X == 0).mean(0).ravel(),
"CV2": (adata.X.mean(0).ravel() / adata.X.std(0).ravel()) ** 2,
}
for method in list_methods:
adata_copy = adata.copy()
apply_log = not log
if method == "scanpy":
sc.pp.log1p(
adata_copy
) # We need scanpy to calculate the dispersions, so we take advantage of log being already calculated
apply_log = False
ret = sc.pp.highly_variable_genes(
adata_copy, n_top_genes=n_HVG, inplace=False
)
dict_other_stuff["disp"], dict_other_stuff["disp_norm"] = (
ret["dispersions"],
ret["dispersions_norm"],
)
if method != "triku":
adata_copy.var["highly_variable"] = [
i in df_rank[method].sort_values().index[:n_HVG]
for i in adata_copy.var_names
]
leiden_sol, res_sol = clustering_binary_search(
adata_copy,
min_res=0.1,
max_res=2,
max_depth=7,
seed=0,
n_target_c=len(set(cell_types)),
features=adata_copy[
:, adata_copy.var["highly_variable"] == True # noqa
].var_names,
apply_log=apply_log,
transform_adata=True,
)
sc.tl.umap(adata_copy)
dict_return[method] = {
"UMAP": adata_copy.obsm["X_umap"],
"leiden": leiden_sol.values,
"highly_variable": adata_copy.var["highly_variable"].values,
}
del adata_copy
gc.collect()
dict_return["other_stuff"] = dict_other_stuff
return f"{lib_prep} {org}", dict_return
def create_dict_UMAPs_datasets(
adata_dir,
df_rank_dir,
lab,
lib_preps,
list_orgs=["human", "mouse"],
log=False,
):
list_org_preps_all = list(product(*[lib_preps, list_orgs]))
list_org_preps_exist = []
for lib_prep, org in list_org_preps_all:
for file in os.listdir(adata_dir):
if org in file and lib_prep in file:
list_org_preps_exist.append((lib_prep, org))
break
create_UMAP_adataset_libprep_org_remote = ray.remote(
create_UMAP_adataset_libprep_org
)
ray.init(ignore_reinit_error=True)
list_ids = [
create_UMAP_adataset_libprep_org_remote.remote(
adata_dir, df_rank_dir, lib_prep, org, lab, log
)
for lib_prep, org in list_org_preps_exist
]
list_returns = ray.get(list_ids)
ray.shutdown()
return dict(list_returns)
def plot_UMAPs_datasets(dict_returns, fig_save_dir, lab, figsize=(25, 40)):
list_rows = list(dict_returns.keys())
list_methods = list(dict_returns[list_rows[0]].keys())[:-1]
fig_leiden, axs_leiden = plt.subplots(
len(list_rows), len(list_methods), figsize=figsize
)
fig_cell_types, axs_cell_types = plt.subplots(
len(list_rows), len(list_methods), figsize=figsize
)
for row_idx, row_name in enumerate(list_rows):
for col_idx, col_name in enumerate(list_methods):
UMAP_coords = dict_returns[row_name][col_name]["UMAP"]
leiden_labels = dict_returns[row_name][col_name]["leiden"]
cell_types = dict_returns[row_name]["other_stuff"]["cell_types"]
# Names are too long for plots, so we are goinf to simplify them
set_cell_types = list(dict.fromkeys(cell_types))
cell_types = pd.Categorical(
[f"C{set_cell_types.index(i)}" for i in cell_types]
)
# We will create the adata to plot the labels, its much easier than programming the feature by yourself.
adata = sc.AnnData(X=np.zeros((UMAP_coords.shape[0], 100)))
(
adata.obsm["X_umap"],
adata.obs["leiden"],
adata.obs["cell_type"],
) = (
UMAP_coords,
leiden_labels,
cell_types,
)
sc.pl.umap(
adata,
color="leiden",
ax=axs_leiden[row_idx][col_idx],
legend_loc="on data",
show=False,
s=35,
legend_fontweight=1000,
)
sc.pl.umap(
adata,
color="cell_type",
ax=axs_cell_types[row_idx][col_idx],
legend_loc="on data",
show=False,
s=35,
legend_fontweight=1000,
)
for axs in [axs_leiden, axs_cell_types]:
axs[row_idx][col_idx].set_xlabel("")
axs[row_idx][col_idx].set_ylabel("")
axs[row_idx][col_idx].set_title("")
if row_idx == 0:
axs[row_idx][col_idx].set_xlabel(f"{col_name}")
axs[row_idx][col_idx].xaxis.set_label_position("top")
if col_idx == 0:
axs[row_idx][col_idx].set_ylabel(f"{row_name}")
axs[row_idx][col_idx].yaxis.set_label_position("left")
plt.tight_layout()
fig_leiden.savefig(
f"{fig_save_dir}/pdf/{lab}_UMAP_leiden.pdf", bbox_inches="tight"
)
fig_cell_types.savefig(
f"{fig_save_dir}/pdf/{lab}_UMAP_cell_types.pdf", bbox_inches="tight"
)
fig_leiden.savefig(
f"{fig_save_dir}/png/{lab}_UMAP_leiden.png",
bbox_inches="tight",
dpi=400,
)
fig_cell_types.savefig(
f"{fig_save_dir}/png/{lab}_UMAP_cell_types.png",
bbox_inches="tight",
dpi=400,
)
# for fmt in ['png', 'pdf']:
# os.makedirs(f'{fig_save_dir}/{fmt}', exist_ok=True)
# fig_leiden.savefig(f'{fig_save_dir}/{fmt}/{lab}_UMAP_leiden.{fmt}', bbox_inches='tight')
# fig_cell_types.savefig(f'{fig_save_dir}/{fmt}/{lab}_UMAP_cell_types.{fmt}', bbox_inches='tight')
def plot_XY(
dict_returns,
x_var,
y_var,
fig_save_dir,
lab,
figsize=(20, 35),
logx=True,
logy=True,
title="",
):
list_rows = list(dict_returns.keys())
list_methods = list(dict_returns[list_rows[0]].keys())[:-1]
fig, axs = plt.subplots(len(list_rows), len(list_methods), figsize=figsize)
for row_idx, row_name in enumerate(list_rows):
for col_idx, col_name in enumerate(list_methods):
x_coords = dict_returns[row_name]["other_stuff"][x_var]
y_coords = dict_returns[row_name]["other_stuff"][y_var]
highly_variable = dict_returns[row_name][col_name][
"highly_variable"
]
if logx:
x_coords = np.log10(x_coords)
if logy:
y_coords = np.log10(y_coords)
axs[row_idx][col_idx].scatter(
x_coords[highly_variable is False],
y_coords[highly_variable is False],
c="#cbcbcb",
alpha=0.05,
s=2,
)
axs[row_idx][col_idx].scatter(
x_coords[highly_variable is True],
y_coords[highly_variable is True],
c="#007ab7",
alpha=0.2,
s=2,
)
if row_idx == 0:
axs[row_idx][col_idx].set_title(f"{col_name}")
if col_idx == 0:
axs[row_idx][col_idx].set_ylabel(
f"{row_name}".replace(" ", "\n")
)
axs[row_idx][col_idx].yaxis.set_label_position("left")
fig.suptitle(title)
plt.tight_layout()
for fmt in ["png", "pdf"]:
os.makedirs(f"{fig_save_dir}/{fmt}", exist_ok=True)
fig.savefig(
f"{fig_save_dir}/{fmt}/{lab}_{x_var}-VS-{y_var}.{fmt}",
bbox_inches="tight",
)
plt.show()
def get_ranking_stats_CV(
dir_comparisons,
list_files,
):
dict_df = {}
for file in list_files:
df = pd.read_csv(f"{dir_comparisons}/{file}", index_col=0)
columns = df.columns
list_vals = df.mean().values.tolist()
dict_df[file] = np.argsort(np.argsort(list_vals)[::-1]) + 1
df_ranks = pd.DataFrame.from_dict(dict_df, orient="index", columns=columns)
F, pval = friedman_test(df_ranks.values)
# Posthoc tests
df_posthoc = posthoc_quade(df_ranks.values) # First use array
df_posthoc = df_posthoc.set_index(columns) # Then set columns and rows
df_posthoc.columns = columns
df_posthoc[
df_posthoc == -1
] = 1 # Identical elements in comparison matrix are -1 instead of 1
return df_ranks, F, pval, df_posthoc
def plot_CV_scores(
lab,
org,
CV_method,
FS_methods,
palette,
read_dir="",
alpha=0.05,
figsize=(16, 4),
title="",
filename="",
do_return=False,
sort_values=False
):
list_files = sorted(
[
i
for i in os.listdir(read_dir)
if org in i and CV_method in i and "10-fold" in i
]
)
# For the plot on the left (test + post-hoc test)
df_ranks, F, pval, df_posthoc = get_ranking_stats_CV(
read_dir, list_files
)
df_ranks = df_ranks[FS_methods]
df_ranks_means = df_ranks.mean(0).sort_values()
columns_sorted = df_ranks_means.index.values
df_posthoc = df_posthoc.loc[columns_sorted, columns_sorted]
list_start_end = []
for idx, col in enumerate(columns_sorted):
idx_nonsignificant = np.argwhere(
df_posthoc.loc[col, :].values > alpha
).ravel()
tuple_idx = (idx_nonsignificant[0], idx_nonsignificant[-1])
if tuple_idx[0] != tuple_idx[1]:
if (
len(list_start_end) == 0
): # This part is to remove elements that are inside other elements, and take the biggest one.
list_start_end.append(tuple_idx)
else:
if (tuple_idx[0] >= list_start_end[-1][0]) & (
tuple_idx[1] <= list_start_end[-1][1]
):
pass
elif (tuple_idx[0] <= list_start_end[-1][0]) & (
tuple_idx[1] >= list_start_end[-1][1]
):
list_start_end[-1] = tuple_idx
else:
list_start_end.append(tuple_idx)
dict_palette = dict(zip(FS_methods, palette))
fig, (axl, axr) = plt.subplots(
1, 2, figsize=figsize, gridspec_kw={"width_ratios": [1, 8]}
)
list_libpreps = list(
dict.fromkeys(
[i.split("_")[2] + " " + i.split("_")[3] for i in list_files]
)
)
# For the plot on the right
if sort_values != False:
list_vals = []
for libprep in list_libpreps:
method, org = libprep.split(' ')[0], libprep.split(' ')[1]
file = [i for i in list_files if method in i and org in i][0]
df = pd.read_csv(f'{read_dir}/{file}', index_col=0)
list_vals.append(df.median().median())
if sort_values == 'ascending':
list_libpreps = np.array(list_libpreps)[np.argsort(list_vals)]
elif sort_values == 'descending':
list_libpreps = np.array(list_libpreps)[np.argsort(list_vals)[::-1]]
for method_idx, method in enumerate(FS_methods):
axl.plot(
[0, len(list_start_end) + 1],
[df_ranks.mean(0)[method], df_ranks.mean(0)[method]],
c=dict_palette[method],
)
for idx, tuple_list in enumerate(list_start_end):
axl.plot(
[idx + 1, | |
that supports the newer
version of the API, you instantiate this class. See :ref:`enumerated
type description page <enumeration_description>`.
"""
orange = None
"""
The service health is degraded. The service might have serious problems.
"""
gray = None
"""
No health data is available for this service.
"""
green = None
"""
Service is healthy.
"""
red = None
"""
The service is unavaiable, not functioning properly, or will stop
functioning soon.
"""
yellow = None
"""
The service is healthy state, but experiencing some levels of problems.
"""
def __init__(self, string):
"""
:type string: :class:`str`
:param string: String value for the :class:`HealthLevel` instance.
"""
Enum.__init__(string)
HealthLevel._set_values([
HealthLevel('orange'),
HealthLevel('gray'),
HealthLevel('green'),
HealthLevel('red'),
HealthLevel('yellow'),
])
HealthLevel._set_binding_type(type.EnumType(
'com.vmware.appliance.health.storage.health_level',
HealthLevel))
def get(self):
"""
Get storage health.
:rtype: :class:`Storage.HealthLevel`
:return: Storage health.
:raise: :class:`com.vmware.vapi.std.errors_client.Error`
Generic error
"""
return self._invoke('get', None)
class Swap(VapiInterface):
"""
``Swap`` class provides methods Get swap health.
"""
_VAPI_SERVICE_ID = 'com.vmware.appliance.health.swap'
"""
Identifier of the service in canonical form.
"""
def __init__(self, config):
"""
:type config: :class:`vmware.vapi.bindings.stub.StubConfiguration`
:param config: Configuration to be used for creating the stub.
"""
VapiInterface.__init__(self, config, _SwapStub)
class HealthLevel(Enum):
"""
``Swap.HealthLevel`` class Defines health levels.
.. note::
This class represents an enumerated type in the interface language
definition. The class contains class attributes which represent the
values in the current version of the enumerated type. Newer versions of
the enumerated type may contain new values. To use new values of the
enumerated type in communication with a server that supports the newer
version of the API, you instantiate this class. See :ref:`enumerated
type description page <enumeration_description>`.
"""
orange = None
"""
The service health is degraded. The service might have serious problems.
"""
gray = None
"""
No health data is available for this service.
"""
green = None
"""
Service is healthy.
"""
red = None
"""
The service is unavaiable, not functioning properly, or will stop
functioning soon.
"""
yellow = None
"""
The service is healthy state, but experiencing some levels of problems.
"""
def __init__(self, string):
"""
:type string: :class:`str`
:param string: String value for the :class:`HealthLevel` instance.
"""
Enum.__init__(string)
HealthLevel._set_values([
HealthLevel('orange'),
HealthLevel('gray'),
HealthLevel('green'),
HealthLevel('red'),
HealthLevel('yellow'),
])
HealthLevel._set_binding_type(type.EnumType(
'com.vmware.appliance.health.swap.health_level',
HealthLevel))
def get(self):
"""
Get swap health.
:rtype: :class:`Swap.HealthLevel`
:return: Swap health
:raise: :class:`com.vmware.vapi.std.errors_client.Error`
Generic error
"""
return self._invoke('get', None)
class System(VapiInterface):
"""
``System`` class provides methods Get overall health of the system.
"""
_VAPI_SERVICE_ID = 'com.vmware.appliance.health.system'
"""
Identifier of the service in canonical form.
"""
def __init__(self, config):
"""
:type config: :class:`vmware.vapi.bindings.stub.StubConfiguration`
:param config: Configuration to be used for creating the stub.
"""
VapiInterface.__init__(self, config, _SystemStub)
class HealthLevel(Enum):
"""
``System.HealthLevel`` class Defines health levels.
.. note::
This class represents an enumerated type in the interface language
definition. The class contains class attributes which represent the
values in the current version of the enumerated type. Newer versions of
the enumerated type may contain new values. To use new values of the
enumerated type in communication with a server that supports the newer
version of the API, you instantiate this class. See :ref:`enumerated
type description page <enumeration_description>`.
"""
orange = None
"""
The service health is degraded. The service might have serious problems.
"""
gray = None
"""
No health data is available for this service.
"""
green = None
"""
Service is healthy.
"""
red = None
"""
The service is unavaiable, not functioning properly, or will stop
functioning soon.
"""
yellow = None
"""
The service is healthy state, but experiencing some levels of problems.
"""
def __init__(self, string):
"""
:type string: :class:`str`
:param string: String value for the :class:`HealthLevel` instance.
"""
Enum.__init__(string)
HealthLevel._set_values([
HealthLevel('orange'),
HealthLevel('gray'),
HealthLevel('green'),
HealthLevel('red'),
HealthLevel('yellow'),
])
HealthLevel._set_binding_type(type.EnumType(
'com.vmware.appliance.health.system.health_level',
HealthLevel))
def lastcheck(self):
"""
Get last check timestamp of the health of the system.
:rtype: :class:`datetime.datetime`
:return: System health last check timestamp
:raise: :class:`com.vmware.vapi.std.errors_client.Error`
Generic error
"""
return self._invoke('lastcheck', None)
def get(self):
"""
Get overall health of system.
:rtype: :class:`System.HealthLevel`
:return: System health
:raise: :class:`com.vmware.vapi.std.errors_client.Error`
Generic error
"""
return self._invoke('get', None)
class _ApplmgmtStub(ApiInterfaceStub):
def __init__(self, config):
# properties for get operation
get_input_type = type.StructType('operation-input', {})
get_error_dict = {
'com.vmware.vapi.std.errors.error':
type.ReferenceType('com.vmware.vapi.std.errors_client', 'Error'),
}
get_input_value_validator_list = [
]
get_output_validator_list = [
]
get_rest_metadata = OperationRestMetadata(
http_method='GET',
url_template='/appliance/health/applmgmt',
path_variables={
},
query_parameters={
}
)
operations = {
'get': {
'input_type': get_input_type,
'output_type': type.StringType(),
'errors': get_error_dict,
'input_value_validator_list': get_input_value_validator_list,
'output_validator_list': get_output_validator_list,
'task_type': TaskType.NONE,
},
}
rest_metadata = {
'get': get_rest_metadata,
}
ApiInterfaceStub.__init__(
self, iface_name='com.vmware.appliance.health.applmgmt',
config=config, operations=operations, rest_metadata=rest_metadata,
is_vapi_rest=True)
class _DatabasestorageStub(ApiInterfaceStub):
def __init__(self, config):
# properties for get operation
get_input_type = type.StructType('operation-input', {})
get_error_dict = {
'com.vmware.vapi.std.errors.error':
type.ReferenceType('com.vmware.vapi.std.errors_client', 'Error'),
}
get_input_value_validator_list = [
]
get_output_validator_list = [
]
get_rest_metadata = OperationRestMetadata(
http_method='GET',
url_template='/appliance/health/database-storage',
path_variables={
},
query_parameters={
}
)
operations = {
'get': {
'input_type': get_input_type,
'output_type': type.ReferenceType(__name__, 'Databasestorage.HealthLevel'),
'errors': get_error_dict,
'input_value_validator_list': get_input_value_validator_list,
'output_validator_list': get_output_validator_list,
'task_type': TaskType.NONE,
},
}
rest_metadata = {
'get': get_rest_metadata,
}
ApiInterfaceStub.__init__(
self, iface_name='com.vmware.appliance.health.databasestorage',
config=config, operations=operations, rest_metadata=rest_metadata,
is_vapi_rest=True)
class _LoadStub(ApiInterfaceStub):
def __init__(self, config):
# properties for get operation
get_input_type = type.StructType('operation-input', {})
get_error_dict = {
'com.vmware.vapi.std.errors.error':
type.ReferenceType('com.vmware.vapi.std.errors_client', 'Error'),
}
get_input_value_validator_list = [
]
get_output_validator_list = [
]
get_rest_metadata = OperationRestMetadata(
http_method='GET',
url_template='/appliance/health/load',
path_variables={
},
query_parameters={
}
)
operations = {
'get': {
'input_type': get_input_type,
'output_type': type.ReferenceType(__name__, 'Load.HealthLevel'),
'errors': get_error_dict,
'input_value_validator_list': get_input_value_validator_list,
'output_validator_list': get_output_validator_list,
'task_type': TaskType.NONE,
},
}
rest_metadata = {
'get': get_rest_metadata,
}
ApiInterfaceStub.__init__(
self, iface_name='com.vmware.appliance.health.load',
config=config, operations=operations, rest_metadata=rest_metadata,
is_vapi_rest=True)
class _MemStub(ApiInterfaceStub):
def __init__(self, config):
# properties for get operation
get_input_type = type.StructType('operation-input', {})
get_error_dict = {
'com.vmware.vapi.std.errors.error':
type.ReferenceType('com.vmware.vapi.std.errors_client', 'Error'),
}
get_input_value_validator_list = [
]
get_output_validator_list = [
]
get_rest_metadata = OperationRestMetadata(
http_method='GET',
url_template='/appliance/health/mem',
path_variables={
},
query_parameters={
}
)
operations = {
'get': {
'input_type': get_input_type,
'output_type': type.ReferenceType(__name__, 'Mem.HealthLevel'),
'errors': get_error_dict,
'input_value_validator_list': get_input_value_validator_list,
'output_validator_list': get_output_validator_list,
'task_type': TaskType.NONE,
},
}
rest_metadata = {
'get': get_rest_metadata,
}
ApiInterfaceStub.__init__(
self, iface_name='com.vmware.appliance.health.mem',
config=config, operations=operations, rest_metadata=rest_metadata,
is_vapi_rest=True)
class _SoftwarepackagesStub(ApiInterfaceStub):
def __init__(self, config):
# properties for get operation
get_input_type = type.StructType('operation-input', {})
get_error_dict = {
'com.vmware.vapi.std.errors.error':
type.ReferenceType('com.vmware.vapi.std.errors_client', 'Error'),
}
get_input_value_validator_list = [
]
get_output_validator_list = [
]
get_rest_metadata = OperationRestMetadata(
http_method='GET',
url_template='/appliance/health/software-packages',
path_variables={
},
query_parameters={
}
)
operations = {
'get': {
'input_type': get_input_type,
'output_type': type.ReferenceType(__name__, 'Softwarepackages.HealthLevel'),
'errors': get_error_dict,
'input_value_validator_list': get_input_value_validator_list,
'output_validator_list': get_output_validator_list,
'task_type': TaskType.NONE,
},
}
rest_metadata = {
'get': get_rest_metadata,
}
ApiInterfaceStub.__init__(
self, iface_name='com.vmware.appliance.health.softwarepackages',
config=config, operations=operations, rest_metadata=rest_metadata,
is_vapi_rest=True)
class _StorageStub(ApiInterfaceStub):
def __init__(self, config):
# properties for get operation
get_input_type = type.StructType('operation-input', {})
get_error_dict = {
'com.vmware.vapi.std.errors.error':
type.ReferenceType('com.vmware.vapi.std.errors_client', 'Error'),
}
get_input_value_validator_list = [
]
get_output_validator_list = [
]
get_rest_metadata = OperationRestMetadata(
http_method='GET',
url_template='/appliance/health/storage',
path_variables={
},
query_parameters={
}
)
operations = {
'get': {
'input_type': get_input_type,
'output_type': type.ReferenceType(__name__, 'Storage.HealthLevel'),
'errors': get_error_dict,
'input_value_validator_list': get_input_value_validator_list,
'output_validator_list': get_output_validator_list,
'task_type': TaskType.NONE,
},
}
rest_metadata = {
'get': get_rest_metadata,
}
ApiInterfaceStub.__init__(
self, iface_name='com.vmware.appliance.health.storage',
config=config, operations=operations, rest_metadata=rest_metadata,
is_vapi_rest=True)
class _SwapStub(ApiInterfaceStub):
def __init__(self, config):
# properties for get operation
get_input_type = type.StructType('operation-input', {})
get_error_dict = {
'com.vmware.vapi.std.errors.error':
type.ReferenceType('com.vmware.vapi.std.errors_client', 'Error'),
}
get_input_value_validator_list = [
]
get_output_validator_list = [
]
get_rest_metadata = OperationRestMetadata(
http_method='GET',
url_template='/appliance/health/swap',
path_variables={
},
query_parameters={
}
)
operations = {
'get': {
'input_type': get_input_type,
'output_type': type.ReferenceType(__name__, 'Swap.HealthLevel'),
'errors': get_error_dict,
'input_value_validator_list': get_input_value_validator_list,
'output_validator_list': get_output_validator_list,
'task_type': TaskType.NONE,
},
}
rest_metadata = {
'get': get_rest_metadata,
}
ApiInterfaceStub.__init__(
self, iface_name='com.vmware.appliance.health.swap',
config=config, operations=operations, rest_metadata=rest_metadata,
is_vapi_rest=True)
class _SystemStub(ApiInterfaceStub):
def __init__(self, config):
# properties for lastcheck operation
lastcheck_input_type = type.StructType('operation-input', {})
lastcheck_error_dict = {
'com.vmware.vapi.std.errors.error':
type.ReferenceType('com.vmware.vapi.std.errors_client', 'Error'),
}
lastcheck_input_value_validator_list = [
]
lastcheck_output_validator_list = [
]
lastcheck_rest_metadata = OperationRestMetadata(
http_method='GET',
url_template='/appliance/health/system/lastcheck',
path_variables={
},
query_parameters={
}
)
# properties for get operation
get_input_type = type.StructType('operation-input', {})
get_error_dict = {
'com.vmware.vapi.std.errors.error':
type.ReferenceType('com.vmware.vapi.std.errors_client', 'Error'),
}
get_input_value_validator_list = [
]
get_output_validator_list = [
]
get_rest_metadata = OperationRestMetadata(
http_method='GET',
url_template='/appliance/health/system',
path_variables={
},
query_parameters={
}
)
operations = {
'lastcheck': {
'input_type': lastcheck_input_type,
'output_type': type.DateTimeType(),
'errors': lastcheck_error_dict,
'input_value_validator_list': lastcheck_input_value_validator_list,
'output_validator_list': lastcheck_output_validator_list,
'task_type': TaskType.NONE,
},
'get': {
'input_type': get_input_type,
'output_type': type.ReferenceType(__name__, 'System.HealthLevel'),
'errors': get_error_dict,
'input_value_validator_list': get_input_value_validator_list,
'output_validator_list': get_output_validator_list,
'task_type': TaskType.NONE,
},
}
rest_metadata = {
'lastcheck': lastcheck_rest_metadata,
'get': get_rest_metadata,
}
ApiInterfaceStub.__init__(
self, iface_name='com.vmware.appliance.health.system',
config=config, operations=operations, rest_metadata=rest_metadata,
is_vapi_rest=True)
class StubFactory(StubFactoryBase):
_attrs = {
'Applmgmt': Applmgmt,
'Databasestorage': Databasestorage,
'Load': Load,
'Mem': | |
the same number of 0's and 1's, and all the 0's and all the 1's in these
substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.
Example 1:
Input: s = "00110011"
Output: 6
Explanation: There are 6 substrings that have equal number of consecutive 1's
and 0's: "0011", "01", "1100", "10", "0011", and "01".
Notice that some of these substrings repeat and are counted the number of
times they occur.
Also, "00110011" is not a valid substring because all the 0's (and 1's) are
not grouped together.
Example 2:
Input: s = "10101"
Output: 4
Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal
number of consecutive 1's and 0's.
"""
def countBinarySubstrings(self, s: str) -> int:
"""O(n) time, O(n) space"""
groups = [len(list(values)) for _, values in groupby(s)]
return sum(min(a, b) for a, b in zip(groups, groups[1:]))
def countBinarySubstrings_(self, s: str) -> int:
"""O(n) time, O(1) space"""
ans, prev, cur = 0, 0, 1
for i in range(1, len(s)):
if s[i - 1] == s[i]:
cur += 1
else:
ans += min(prev, cur)
prev, cur = cur, 1
return ans + min(prev, cur)
class _17:
"""
# - Letter Combinations of a Phone Number -
# https://leetcode.com/problems/letter-combinations-of-a-phone-number/
"""
...
class _54:
"""
# - Spiral Matrix -
# https://leetcode.com/problems/spiral-matrix/
Given an m x n matrix, return all elements of the matrix in spiral order.
Example 1:
Input: [[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: [[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
"""
...
class _312:
"""
# - Burst Balloons -
# https://leetcode.com/problems/burst-balloons/
"""
...
class _13:
"""
# - Roman to Integer -
# https://leetcode.com/problems/roman-to-integer/
"""
...
class _938:
"""
# - Range Sum of BST -
# https://leetcode.com/problems/range-sum-of-bst/
Given the root node of a binary search tree and two integers low and high,
return the sum of values of all nodes with a value in the inclusive range
[low, high].
Example 1:
10
5 15
3 7 18
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.
Example 2:
10
5 15
3 7 13 18
1 6
Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23
Explanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.
# NOTE All Node.val are unique.
"""
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
def dfs(node):
nonlocal ans
if node:
if low <= node.val <= high:
ans += node.val
if low < node.val:
dfs(node.left)
if node.val < high:
dfs(node.right)
ans = 0
dfs(root)
return ans
def rangeSumBST_(self, root: Optional[TreeNode], low: int, high: int) -> int:
ans = 0
queue: Deque[Optional[TreeNode]] = deque([root])
while queue:
node = queue.popleft()
if node:
if low <= node.val <= high:
ans += node.val
if low < node.val:
queue.append(node.left)
if node.val < high:
queue.append(node.right)
return ans
class _71:
"""
# - Simplify Path -
# https://leetcode.com/problems/simplify-path/
Given a string path, which is an absolute path (starting with a slash '/') to a file
or directory in a Unix-style file system, convert it to the simplified canonical
path.
In a Unix-style file system, a period '.' refers to the current directory, a double
period '..' refers to the directory up a level, and any multiple consecutive slashes
(i.e. '//') are treated as a single slash '/'. For this problem, any other format of
periods such as '...' are treated as file/directory names.
The canonical path should have the following format:
* The path starts with a single slash '/'.
* Any two directories are separated by a single slash '/'.
* The path does not end with a trailing '/'.
* The path only contains the directories on the path from the root directory to the
target file or directory (i.e., no period '.' or double period '..')
Return the simplified canonical path.
Example 1:
Input: path = "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: path = "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root
level is the highest level you can go.
Example 3:
Input: path = "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a
single one.
NOTE path consists of English letters, digits, period '.', slash '/' or '_'.
NOTE path is a valid absolute Unix path.
"""
def simplifyPath(self, path: str) -> str:
stack = []
for x in path.split("/"):
if x == "..":
if stack:
stack.pop()
elif x and x != ".":
stack.append(x)
return "/" + "/".join(stack)
class _217:
"""
# - Contains Duplicate -
# https://leetcode.com/problems/contains-duplicate/
Given an integer array nums, return true if any value appears at least
twice in the array, and return false if every element is distinct.
Example 1:
Input: nums = [1,2,3,1]
Output: true
Example 2:
Input: nums = [1,2,3,4]
Output: false
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
"""
...
class _1650:
"""
# - Lowest Common Ancestor of a Binary Tree III -
# https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-iii/
"""
...
class _224:
"""
# - Basic Calculator -
# https://leetcode.com/problems/basic-calculator/
"""
...
class _7:
"""
# - Reverse Integer -
# https://leetcode.com/problems/reverse-integer/
"""
...
class _347:
"""
# - Top K Frequent Elements -
# https://leetcode.com/problems/top-k-frequent-elements/
Given an integer array nums and an integer k, return the k most frequent
elements. You may return the answer in any order.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
"""
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
"""Bucket sort O(n) time, O(n) space"""
bucket: List[List[int]] = [[] for _ in range(len(nums))]
count = Counter(nums).items()
for num, freq in count:
bucket[freq - 1].append(num)
return list(chain(*bucket))[::-1][:k]
def topKFrequent_(self, nums: List[int], k: int) -> List[int]:
"""Heapq way, O(nlogn) or nlogk time, O(n) space"""
count = Counter(nums)
return nlargest(k, count.keys(), key=count.__getitem__)
def topKFrequent__(self, nums: List[int], k: int) -> List[int]:
"""Calls heapq under the hood"""
return [x for x, y in Counter(nums).most_common(k)]
class _443:
"""
# - String Compression -
# https://leetcode.com/problems/string-compression/
Given an array of characters chars, compress it using the following algorithm:
Begin with an empty string s. For each group of consecutive repeating
characters in chars:
- If the group's length is 1, append the character to s.
- Otherwise, append the character followed by the group's length.
The compressed string s should not be returned separately, but instead, be
stored in the input character array chars. Note that group lengths that are
10 or longer will be split into multiple characters in chars.
After you are done modifying the input array, return the new length of the array.
You must write an algorithm that uses only constant extra space.
Example 1:
Input: chars = ["a","a","b","b","c","c","c"]
Output: Return 6, and the first 6 characters of the input
array should be: ["a","2","b","2","c","3"]
Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".
Example 2:
Input: chars = ["a"]
Output: Return 1, and the first character of the input array should be: ["a"]
Explanation: The only group is "a", which remains uncompressed since
it's a single character.
Example 3:
Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output: Return 4, and the first 4 characters of the input array
should be: ["a","b","1","2"].
Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".
"""
def compress(self, chars: List[str]) -> int:
"""O(n) time, O(1) extra space"""
slow = fast = 0
while fast < len(chars):
chars[slow] = chars[fast]
| |
m.x714 == 0)
m.c1044 = Constraint(expr=-m.x26*m.x1171 + m.x715 == 0)
m.c1045 = Constraint(expr=-m.x27*m.x1172 + m.x716 == 0)
m.c1046 = Constraint(expr=-m.x28*m.x1172 + m.x717 == 0)
m.c1047 = Constraint(expr=-m.x29*m.x1172 + m.x718 == 0)
m.c1048 = Constraint(expr=-m.x30*m.x1172 + m.x719 == 0)
m.c1049 = Constraint(expr=-m.x31*m.x1172 + m.x720 == 0)
m.c1050 = Constraint(expr=-m.x32*m.x1172 + m.x721 == 0)
m.c1051 = Constraint(expr=-m.x33*m.x1172 + m.x722 == 0)
m.c1052 = Constraint(expr=-m.x34*m.x1172 + m.x723 == 0)
m.c1053 = Constraint(expr=-m.x35*m.x1172 + m.x724 == 0)
m.c1054 = Constraint(expr=-m.x36*m.x1173 + m.x725 == 0)
m.c1055 = Constraint(expr=-m.x37*m.x1173 + m.x726 == 0)
m.c1056 = Constraint(expr=-m.x38*m.x1173 + m.x727 == 0)
m.c1057 = Constraint(expr=-m.x39*m.x1173 + m.x728 == 0)
m.c1058 = Constraint(expr=-m.x40*m.x1173 + m.x729 == 0)
m.c1059 = Constraint(expr=-m.x41*m.x1173 + m.x730 == 0)
m.c1060 = Constraint(expr=-m.x42*m.x1173 + m.x731 == 0)
m.c1061 = Constraint(expr=-m.x43*m.x1174 + m.x732 == 0)
m.c1062 = Constraint(expr=-m.x44*m.x1174 + m.x733 == 0)
m.c1063 = Constraint(expr=-m.x45*m.x1174 + m.x734 == 0)
m.c1064 = Constraint(expr=-m.x46*m.x1174 + m.x735 == 0)
m.c1065 = Constraint(expr=-m.x47*m.x1174 + m.x736 == 0)
m.c1066 = Constraint(expr=-m.x48*m.x1174 + m.x737 == 0)
m.c1067 = Constraint(expr=-m.x49*m.x1174 + m.x738 == 0)
m.c1068 = Constraint(expr=-m.x50*m.x1174 + m.x739 == 0)
m.c1069 = Constraint(expr=-m.x51*m.x1174 + m.x740 == 0)
m.c1070 = Constraint(expr=-m.x52*m.x1175 + m.x741 == 0)
m.c1071 = Constraint(expr=-m.x53*m.x1175 + m.x742 == 0)
m.c1072 = Constraint(expr=-m.x54*m.x1175 + m.x743 == 0)
m.c1073 = Constraint(expr=-m.x55*m.x1175 + m.x744 == 0)
m.c1074 = Constraint(expr=-m.x56*m.x1175 + m.x745 == 0)
m.c1075 = Constraint(expr=-m.x57*m.x1175 + m.x746 == 0)
m.c1076 = Constraint(expr=-m.x58*m.x1175 + m.x747 == 0)
m.c1077 = Constraint(expr=-m.x59*m.x1175 + m.x748 == 0)
m.c1078 = Constraint(expr=-m.x2*m.x1181 + m.x749 == 0)
m.c1079 = Constraint(expr=-m.x3*m.x1181 + m.x750 == 0)
m.c1080 = Constraint(expr=-m.x4*m.x1181 + m.x751 == 0)
m.c1081 = Constraint(expr=-m.x5*m.x1181 + m.x752 == 0)
m.c1082 = Constraint(expr=-m.x6*m.x1181 + m.x753 == 0)
m.c1083 = Constraint(expr=-m.x7*m.x1181 + m.x754 == 0)
m.c1084 = Constraint(expr=-m.x8*m.x1181 + m.x755 == 0)
m.c1085 = Constraint(expr=-m.x9*m.x1181 + m.x756 == 0)
m.c1086 = Constraint(expr=-m.x10*m.x1182 + m.x757 == 0)
m.c1087 = Constraint(expr=-m.x11*m.x1182 + m.x758 == 0)
m.c1088 = Constraint(expr=-m.x12*m.x1182 + m.x759 == 0)
m.c1089 = Constraint(expr=-m.x13*m.x1182 + m.x760 == 0)
m.c1090 = Constraint(expr=-m.x14*m.x1182 + m.x761 == 0)
m.c1091 = Constraint(expr=-m.x15*m.x1182 + m.x762 == 0)
m.c1092 = Constraint(expr=-m.x16*m.x1182 + m.x763 == 0)
m.c1093 = Constraint(expr=-m.x17*m.x1182 + m.x764 == 0)
m.c1094 = Constraint(expr=-m.x18*m.x1182 + m.x765 == 0)
m.c1095 = Constraint(expr=-m.x19*m.x1182 + m.x766 == 0)
m.c1096 = Constraint(expr=-m.x20*m.x1183 + m.x767 == 0)
m.c1097 = Constraint(expr=-m.x21*m.x1183 + m.x768 == 0)
m.c1098 = Constraint(expr=-m.x22*m.x1183 + m.x769 == 0)
m.c1099 = Constraint(expr=-m.x23*m.x1183 + m.x770 == 0)
m.c1100 = Constraint(expr=-m.x24*m.x1183 + m.x771 == 0)
m.c1101 = Constraint(expr=-m.x25*m.x1183 + m.x772 == 0)
m.c1102 = Constraint(expr=-m.x26*m.x1183 + m.x773 == 0)
m.c1103 = Constraint(expr=-m.x43*m.x1184 + m.x774 == 0)
m.c1104 = Constraint(expr=-m.x44*m.x1184 + m.x775 == 0)
m.c1105 = Constraint(expr=-m.x45*m.x1184 + m.x776 == 0)
m.c1106 = Constraint(expr=-m.x46*m.x1184 + m.x777 == 0)
m.c1107 = Constraint(expr=-m.x47*m.x1184 + m.x778 == 0)
m.c1108 = Constraint(expr=-m.x48*m.x1184 + m.x779 == 0)
m.c1109 = Constraint(expr=-m.x49*m.x1184 + m.x780 == 0)
m.c1110 = Constraint(expr=-m.x50*m.x1184 + m.x781 == 0)
m.c1111 = Constraint(expr=-m.x51*m.x1184 + m.x782 == 0)
m.c1112 = Constraint(expr=-m.x52*m.x1185 + m.x783 == 0)
m.c1113 = Constraint(expr=-m.x53*m.x1185 + m.x784 == 0)
m.c1114 = Constraint(expr=-m.x54*m.x1185 + m.x785 == 0)
m.c1115 = Constraint(expr=-m.x55*m.x1185 + m.x786 == 0)
m.c1116 = Constraint(expr=-m.x56*m.x1185 + m.x787 == 0)
m.c1117 = Constraint(expr=-m.x57*m.x1185 + m.x788 == 0)
m.c1118 = Constraint(expr=-m.x58*m.x1185 + m.x789 == 0)
m.c1119 = Constraint(expr=-m.x59*m.x1185 + m.x790 == 0)
m.c1120 = Constraint(expr=-m.x2*m.x1190 + m.x791 == 0)
m.c1121 = Constraint(expr=-m.x3*m.x1190 + m.x792 == 0)
m.c1122 = Constraint(expr=-m.x4*m.x1190 + m.x793 == 0)
m.c1123 = Constraint(expr=-m.x5*m.x1190 + m.x794 == 0)
m.c1124 = Constraint(expr=-m.x6*m.x1190 + m.x795 == 0)
m.c1125 = Constraint(expr=-m.x7*m.x1190 + m.x796 == 0)
m.c1126 = Constraint(expr=-m.x8*m.x1190 + m.x797 == 0)
m.c1127 = Constraint(expr=-m.x9*m.x1190 + m.x798 == 0)
m.c1128 = Constraint(expr=-m.x10*m.x1191 + m.x799 == 0)
m.c1129 = Constraint(expr=-m.x11*m.x1191 + m.x800 == 0)
m.c1130 = Constraint(expr=-m.x12*m.x1191 + m.x801 == 0)
m.c1131 = Constraint(expr=-m.x13*m.x1191 + m.x802 == 0)
m.c1132 = Constraint(expr=-m.x14*m.x1191 + m.x803 == 0)
m.c1133 = Constraint(expr=-m.x15*m.x1191 + m.x804 == 0)
m.c1134 = Constraint(expr=-m.x16*m.x1191 + m.x805 == 0)
m.c1135 = Constraint(expr=-m.x17*m.x1191 + m.x806 == 0)
m.c1136 = Constraint(expr=-m.x18*m.x1191 + m.x807 == 0)
m.c1137 = Constraint(expr=-m.x19*m.x1191 + m.x808 == 0)
m.c1138 = Constraint(expr=-m.x36*m.x1192 + m.x809 == 0)
m.c1139 = Constraint(expr=-m.x37*m.x1192 + m.x810 == 0)
m.c1140 = Constraint(expr=-m.x38*m.x1192 + m.x811 == 0)
m.c1141 = Constraint(expr=-m.x39*m.x1192 + m.x812 == 0)
m.c1142 = Constraint(expr=-m.x40*m.x1192 + m.x813 == 0)
m.c1143 = Constraint(expr=-m.x41*m.x1192 + m.x814 == 0)
m.c1144 = Constraint(expr=-m.x42*m.x1192 + m.x815 == 0)
m.c1145 = Constraint(expr=-m.x43*m.x1193 + m.x816 == 0)
m.c1146 = Constraint(expr=-m.x44*m.x1193 + m.x817 == 0)
m.c1147 = Constraint(expr=-m.x45*m.x1193 + m.x818 == 0)
m.c1148 = Constraint(expr=-m.x46*m.x1193 + m.x819 == 0)
m.c1149 = Constraint(expr=-m.x47*m.x1193 + m.x820 == 0)
m.c1150 = Constraint(expr=-m.x48*m.x1193 + m.x821 == 0)
m.c1151 = Constraint(expr=-m.x49*m.x1193 + m.x822 == 0)
m.c1152 = Constraint(expr=-m.x50*m.x1193 + m.x823 == 0)
m.c1153 = Constraint(expr=-m.x51*m.x1193 + m.x824 == 0)
m.c1154 = Constraint(expr=-m.x60*m.x1194 + m.x825 == 0)
m.c1155 = Constraint(expr=-m.x61*m.x1194 + m.x826 == 0)
m.c1156 = Constraint(expr=-m.x62*m.x1194 + m.x827 == 0)
m.c1157 = Constraint(expr=-m.x63*m.x1194 + m.x828 == 0)
m.c1158 = Constraint(expr=-m.x64*m.x1194 + m.x829 == 0)
m.c1159 = Constraint(expr=-m.x65*m.x1194 + m.x830 == 0)
m.c1160 = Constraint(expr=-m.x66*m.x1194 + m.x831 == 0)
m.c1161 = Constraint(expr=-m.x67*m.x1194 + m.x832 == 0)
m.c1162 = Constraint(expr=-m.x68*m.x1194 + m.x833 == 0)
m.c1163 = Constraint(expr=-m.x69*m.x1194 + m.x834 == 0)
m.c1164 = Constraint(expr=-m.x76*m.x1195 + m.x835 == 0)
m.c1165 = Constraint(expr=-m.x77*m.x1195 + m.x836 == 0)
m.c1166 = Constraint(expr=-m.x78*m.x1195 + m.x837 == 0)
m.c1167 = Constraint(expr=-m.x79*m.x1195 + m.x838 == 0)
m.c1168 = Constraint(expr=-m.x80*m.x1195 + m.x839 == 0)
m.c1169 = Constraint(expr=-m.x81*m.x1195 + m.x840 == 0)
m.c1170 = Constraint(expr=-m.x82*m.x1195 + m.x841 == 0)
m.c1171 = Constraint(expr=-m.x83*m.x1195 + m.x842 == 0)
m.c1172 = Constraint(expr=-m.x84*m.x1195 + m.x843 == 0)
m.c1173 = Constraint(expr=-m.x85*m.x1195 + m.x844 == 0)
m.c1174 = Constraint(expr=-m.x86*m.x1195 + m.x845 == 0)
m.c1175 = Constraint(expr=-m.x87*m.x1195 + m.x846 == 0)
m.c1176 = Constraint(expr=-m.x76*m.x1199 + m.x847 == 0)
m.c1177 = Constraint(expr=-m.x77*m.x1199 + m.x848 == 0)
m.c1178 = Constraint(expr=-m.x78*m.x1199 + m.x849 == 0)
m.c1179 = Constraint(expr=-m.x79*m.x1199 + m.x850 == 0)
m.c1180 = Constraint(expr=-m.x80*m.x1199 + m.x851 == 0)
m.c1181 = Constraint(expr=-m.x81*m.x1199 + m.x852 == 0)
m.c1182 = Constraint(expr=-m.x82*m.x1199 + m.x853 == 0)
m.c1183 = Constraint(expr=-m.x83*m.x1199 + m.x854 == 0)
m.c1184 = Constraint(expr=-m.x84*m.x1199 + m.x855 == 0)
m.c1185 = Constraint(expr=-m.x85*m.x1199 + m.x856 == 0)
m.c1186 = Constraint(expr=-m.x86*m.x1199 + m.x857 == 0)
m.c1187 = Constraint(expr=-m.x87*m.x1199 + m.x858 == 0)
m.c1188 = Constraint(expr=-m.x2*m.x1205 + m.x859 == 0)
m.c1189 = Constraint(expr=-m.x3*m.x1205 + m.x860 == 0)
m.c1190 = Constraint(expr=-m.x4*m.x1205 + m.x861 == 0)
m.c1191 = Constraint(expr=-m.x5*m.x1205 + m.x862 == 0)
m.c1192 = Constraint(expr=-m.x6*m.x1205 + m.x863 == 0)
m.c1193 = Constraint(expr=-m.x7*m.x1205 + m.x864 == 0)
m.c1194 = Constraint(expr=-m.x8*m.x1205 + m.x865 == 0)
m.c1195 = Constraint(expr=-m.x9*m.x1205 + m.x866 == 0)
m.c1196 = Constraint(expr=-m.x10*m.x1206 + m.x867 == 0)
m.c1197 = Constraint(expr=-m.x11*m.x1206 + m.x868 == 0)
m.c1198 = Constraint(expr=-m.x12*m.x1206 + m.x869 == 0)
m.c1199 = Constraint(expr=-m.x13*m.x1206 + m.x870 == 0)
m.c1200 = Constraint(expr=-m.x14*m.x1206 + m.x871 == 0)
m.c1201 = Constraint(expr=-m.x15*m.x1206 + m.x872 == 0)
m.c1202 = Constraint(expr=-m.x16*m.x1206 + m.x873 == 0)
m.c1203 = Constraint(expr=-m.x17*m.x1206 + m.x874 == 0)
m.c1204 = Constraint(expr=-m.x18*m.x1206 + m.x875 == 0)
m.c1205 = Constraint(expr=-m.x19*m.x1206 + m.x876 == 0)
m.c1206 = Constraint(expr=-m.x27*m.x1207 + m.x877 == 0)
m.c1207 = Constraint(expr=-m.x28*m.x1207 + m.x878 == 0)
m.c1208 = Constraint(expr=-m.x29*m.x1207 + m.x879 == 0)
m.c1209 = Constraint(expr=-m.x30*m.x1207 + m.x880 == 0)
m.c1210 = Constraint(expr=-m.x31*m.x1207 + m.x881 == 0)
m.c1211 = Constraint(expr=-m.x32*m.x1207 + m.x882 == 0)
m.c1212 = Constraint(expr=-m.x33*m.x1207 + m.x883 == 0)
m.c1213 = Constraint(expr=-m.x34*m.x1207 + m.x884 == 0)
m.c1214 = Constraint(expr=-m.x35*m.x1207 + m.x885 == 0)
m.c1215 = Constraint(expr=-m.x70*m.x1208 + m.x886 == 0)
m.c1216 = Constraint(expr=-m.x71*m.x1208 + m.x887 == 0)
m.c1217 = Constraint(expr=-m.x72*m.x1208 + m.x888 == 0)
m.c1218 = Constraint(expr=-m.x73*m.x1208 + m.x889 == 0)
m.c1219 = Constraint(expr=-m.x74*m.x1208 + m.x890 == 0)
m.c1220 = Constraint(expr=-m.x75*m.x1208 + m.x891 == 0)
m.c1221 = Constraint(expr=-m.x27*m.x1212 + m.x892 == 0)
m.c1222 = Constraint(expr=-m.x28*m.x1212 + m.x893 == 0)
m.c1223 = Constraint(expr=-m.x29*m.x1212 + m.x894 == 0)
m.c1224 = Constraint(expr=-m.x30*m.x1212 + m.x895 == 0)
m.c1225 = Constraint(expr=-m.x31*m.x1212 + m.x896 == 0)
m.c1226 = Constraint(expr=-m.x32*m.x1212 + m.x897 == 0)
m.c1227 = Constraint(expr=-m.x33*m.x1212 + m.x898 == 0)
m.c1228 = Constraint(expr=-m.x34*m.x1212 + m.x899 == 0)
m.c1229 = Constraint(expr=-m.x35*m.x1212 + m.x900 == 0)
m.c1230 = Constraint(expr=-m.x43*m.x1213 + m.x901 == 0)
m.c1231 = Constraint(expr=-m.x44*m.x1213 + m.x902 == 0)
m.c1232 = Constraint(expr=-m.x45*m.x1213 + m.x903 == 0)
m.c1233 = Constraint(expr=-m.x46*m.x1213 + m.x904 == 0)
m.c1234 = Constraint(expr=-m.x47*m.x1213 + m.x905 == 0)
m.c1235 = Constraint(expr=-m.x48*m.x1213 + m.x906 == 0)
m.c1236 = Constraint(expr=-m.x49*m.x1213 + m.x907 == 0)
m.c1237 = Constraint(expr=-m.x50*m.x1213 + m.x908 == 0)
m.c1238 = Constraint(expr=-m.x51*m.x1213 + m.x909 == 0)
m.c1239 = Constraint(expr=-m.x60*m.x1214 + m.x910 == 0)
m.c1240 = Constraint(expr=-m.x61*m.x1214 + m.x911 == 0)
m.c1241 = Constraint(expr=-m.x62*m.x1214 + m.x912 == 0)
m.c1242 = Constraint(expr=-m.x63*m.x1214 + m.x913 == 0)
m.c1243 = Constraint(expr=-m.x64*m.x1214 + m.x914 == 0)
m.c1244 = Constraint(expr=-m.x65*m.x1214 + m.x915 == 0)
m.c1245 = Constraint(expr=-m.x66*m.x1214 + m.x916 == 0)
m.c1246 = Constraint(expr=-m.x67*m.x1214 + m.x917 == 0)
m.c1247 = Constraint(expr=-m.x68*m.x1214 + m.x918 == 0)
m.c1248 = Constraint(expr=-m.x69*m.x1214 + m.x919 == 0)
m.c1249 = Constraint(expr=-m.x70*m.x1215 + m.x920 == 0)
m.c1250 = Constraint(expr=-m.x71*m.x1215 + m.x921 == 0)
m.c1251 = Constraint(expr=-m.x72*m.x1215 + m.x922 == 0)
m.c1252 = Constraint(expr=-m.x73*m.x1215 + m.x923 == 0)
m.c1253 = Constraint(expr=-m.x74*m.x1215 + m.x924 == 0)
m.c1254 = Constraint(expr=-m.x75*m.x1215 + m.x925 == 0)
m.c1255 = Constraint(expr=-m.x76*m.x1216 + m.x926 == 0)
m.c1256 = Constraint(expr=-m.x77*m.x1216 + m.x927 == | |
<gh_stars>100-1000
# Create your models here.
import os
import tempfile
import uuid
from datetime import timedelta
from django.contrib.contenttypes.fields import GenericRelation, GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.files import File
from django.core.files.storage import default_storage
from django.core.files.uploadedfile import InMemoryUploadedFile, TemporaryUploadedFile, SimpleUploadedFile
from django.db import models
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.db.models import Count
import ffmpy
# Create your views here.
from ordered_model.models import OrderedModel
from pilkit.processors import ResizeToFit
from rest_framework.exceptions import ValidationError
from django.conf import settings
from openbook_common.peekalink_client import peekalink_client
from openbook_posts.validators import post_text_validators, post_comment_text_validators
from video_encoding.backends import get_backend
from video_encoding.fields import VideoField
from video_encoding.models import Format
from openbook.storage_backends import S3PrivateMediaStorage
from openbook_auth.models import User
from openbook_common.models import Emoji, Language
from openbook_common.utils.helpers import delete_file_field, sha256sum, extract_usernames_from_string, get_magic, \
write_in_memory_file_to_disk, extract_hashtags_from_string, normalize_url
from openbook_common.utils.model_loaders import get_emoji_model, \
get_circle_model, get_community_model, get_post_comment_notification_model, \
get_post_comment_reply_notification_model, get_post_reaction_notification_model, get_moderated_object_model, \
get_post_user_mention_notification_model, get_post_comment_user_mention_notification_model, get_user_model, \
get_post_user_mention_model, get_post_comment_user_mention_model, get_community_notifications_subscription_model, \
get_community_new_post_notification_model, get_user_new_post_notification_model, \
get_hashtag_model, get_user_notifications_subscription_model, get_trending_post_model, \
get_post_comment_reaction_notification_model
from imagekit.models import ProcessedImageField
from openbook_moderation.models import ModeratedObject
from openbook_notifications.helpers import send_post_comment_user_mention_push_notification, \
send_post_user_mention_push_notification, send_community_new_post_push_notification, \
send_user_new_post_push_notification
from openbook_posts.checkers import check_can_be_updated, check_can_add_media, check_can_be_published, \
check_mimetype_is_supported_media_mimetypes
from openbook_posts.helpers import upload_to_post_image_directory, upload_to_post_video_directory, \
upload_to_post_directory
from openbook_posts.jobs import process_post_media
magic = get_magic()
from openbook_common.helpers import get_language_for_text, extract_urls_from_string
post_image_storage = S3PrivateMediaStorage() if settings.IS_PRODUCTION else default_storage
class Post(models.Model):
moderated_object = GenericRelation(ModeratedObject, related_query_name='posts')
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, db_index=True)
text = models.TextField(_('text'), max_length=settings.POST_MAX_LENGTH, blank=False, null=True,
validators=post_text_validators)
created = models.DateTimeField(editable=False, db_index=True)
modified = models.DateTimeField(db_index=True, default=timezone.now)
creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
comments_enabled = models.BooleanField(_('comments enabled'), default=True, editable=False, null=False)
public_reactions = models.BooleanField(_('public reactions'), default=True, editable=False, null=False)
community = models.ForeignKey('openbook_communities.Community', on_delete=models.CASCADE, related_name='posts',
null=True,
blank=False)
language = models.ForeignKey(Language, on_delete=models.SET_NULL, null=True, related_name='posts')
is_edited = models.BooleanField(default=False)
is_closed = models.BooleanField(default=False)
is_deleted = models.BooleanField(default=False)
STATUS_DRAFT = 'D'
STATUS_PROCESSING = 'PG'
STATUS_PUBLISHED = 'P'
STATUSES = (
(STATUS_DRAFT, 'Draft'),
(STATUS_PROCESSING, 'Processing'),
(STATUS_PUBLISHED, 'Published'),
)
status = models.CharField(blank=False, null=False, choices=STATUSES, default=STATUS_DRAFT, max_length=2)
media_height = models.PositiveSmallIntegerField(_('media height'), null=True)
media_width = models.PositiveSmallIntegerField(_('media width'), null=True)
media_thumbnail = ProcessedImageField(verbose_name=_('thumbnail'), storage=post_image_storage,
upload_to=upload_to_post_directory,
blank=False, null=True, format='JPEG', options={'quality': 30},
processors=[ResizeToFit(width=512, upscale=False)])
class Meta:
index_together = [
('creator', 'community'),
]
@classmethod
def get_post_id_for_post_with_uuid(cls, post_uuid):
post = cls.objects.values('id').get(uuid=post_uuid)
return post['id']
@classmethod
def post_with_id_has_public_reactions(cls, post_id):
return Post.objects.filter(pk=post_id, public_reactions=True).exists()
@classmethod
def is_post_with_id_a_community_post(cls, post_id):
return Post.objects.filter(pk=post_id, community__isnull=False).exists()
@classmethod
def create_post(cls, creator, circles_ids=None, community_name=None, image=None, text=None, video=None,
created=None, is_draft=False):
if not community_name and not circles_ids:
raise ValidationError(_('A post requires circles or a community to be posted to.'))
if community_name and circles_ids:
raise ValidationError(_('A post cannot be posted both to a community and to circles.'))
post = Post.objects.create(creator=creator, created=created)
if image and video:
raise ValidationError(_('A post must have an image or a video, not both.'))
if text:
post.text = text
post.language = get_language_for_text(text)
if image:
post.add_media(file=image)
elif video:
post.add_media(file=video)
if circles_ids:
post.circles.add(*circles_ids)
else:
Community = get_community_model()
post.community = Community.objects.get(name=community_name)
# If on create we have a video or image, we automatically publish it
# Backwards compat reasons.
if not is_draft:
post.publish()
else:
post.save()
return post
@classmethod
def get_emoji_counts_for_post_with_id(cls, post_id, emoji_id=None, reactor_id=None):
Emoji = get_emoji_model()
return Emoji.get_emoji_counts_for_post_with_id(post_id=post_id, emoji_id=emoji_id, reactor_id=reactor_id)
@classmethod
def get_trending_posts_for_user_with_id(cls, user_id, max_id=None, min_id=None):
"""
Gets trending posts (communities only) for authenticated user excluding reported, closed, blocked users posts
"""
Post = cls
TrendingPost = get_trending_post_model()
Community = get_community_model()
posts_select_related = ('post__creator', 'post__creator__profile', 'post__community', 'post__image')
posts_prefetch_related = ('post__circles', 'post__creator__profile__badges', 'post__reactions__reactor')
posts_only = ('id',
'post__text', 'post__id', 'post__uuid', 'post__created', 'post__image__width',
'post__image__height', 'post__image__image',
'post__creator__username', 'post__creator__id', 'post__creator__profile__name',
'post__creator__profile__avatar',
'post__creator__profile__badges__id', 'post__creator__profile__badges__keyword',
'post__creator__profile__id', 'post__community__id', 'post__community__name',
'post__community__avatar',
'post__community__color', 'post__community__title')
reported_posts_exclusion_query = ~Q(post__moderated_object__reports__reporter_id=user_id)
trending_community_posts_query = Q(post__is_closed=False,
post__is_deleted=False,
post__status=Post.STATUS_PUBLISHED)
trending_community_posts_query.add(~Q(Q(post__creator__blocked_by_users__blocker_id=user_id) | Q(
post__creator__user_blocks__blocked_user_id=user_id)), Q.AND)
trending_community_posts_query.add(Q(post__community__type=Community.COMMUNITY_TYPE_PUBLIC), Q.AND)
trending_community_posts_query.add(~Q(post__community__banned_users__id=user_id), Q.AND)
if max_id:
trending_community_posts_query.add(Q(id__lt=max_id), Q.AND)
elif min_id:
trending_community_posts_query.add(Q(id__gt=min_id), Q.AND)
ModeratedObject = get_moderated_object_model()
trending_community_posts_query.add(~Q(post__moderated_object__status=ModeratedObject.STATUS_APPROVED), Q.AND)
trending_community_posts_query.add(reported_posts_exclusion_query, Q.AND)
trending_community_posts_queryset = TrendingPost.objects. \
select_related(*posts_select_related). \
prefetch_related(*posts_prefetch_related). \
only(*posts_only). \
filter(trending_community_posts_query)
return trending_community_posts_queryset
@classmethod
def get_trending_posts_old_for_user_with_id(cls, user_id):
"""
For backwards compatibility reasons
"""
trending_posts_query = cls._get_trending_posts_old_query()
trending_posts_query.add(~Q(community__banned_users__id=user_id), Q.AND)
trending_posts_query.add(~Q(Q(creator__blocked_by_users__blocker_id=user_id) | Q(
creator__user_blocks__blocked_user_id=user_id)), Q.AND)
trending_posts_query.add(~Q(moderated_object__reports__reporter_id=user_id), Q.AND)
trending_posts_query.add(~Q(moderated_object__status=ModeratedObject.STATUS_APPROVED), Q.AND)
return cls._get_trending_posts_old_with_query(query=trending_posts_query)
@classmethod
def _get_trending_posts_old_with_query(cls, query):
return cls.objects.filter(query).annotate(Count('reactions')).order_by(
'-reactions__count', '-created')
@classmethod
def _get_trending_posts_old_query(cls):
trending_posts_query = Q(created__gte=timezone.now() - timedelta(
hours=12))
Community = get_community_model()
trending_posts_sources_query = Q(community__type=Community.COMMUNITY_TYPE_PUBLIC, status=cls.STATUS_PUBLISHED,
is_closed=False, is_deleted=False)
trending_posts_query.add(trending_posts_sources_query, Q.AND)
return trending_posts_query
@classmethod
def get_post_comment_notification_target_users(cls, post, post_commenter):
"""
Returns the users that should be notified of a post comment.
This includes the post creator and other post commenters
:return:
"""
# Add other post commenters, exclude replies to comments, the post commenter
other_commenters = User.objects.filter(
Q(posts_comments__post_id=post.pk, posts_comments__parent_comment_id=None, ) & ~Q(
id=post_commenter.pk))
post_creator = User.objects.filter(pk=post.creator_id)
return other_commenters.union(post_creator)
@classmethod
def get_post_comment_reply_notification_target_users(cls, post_commenter, parent_post_comment):
"""
Returns the users that should be notified of a post comment reply.
:return:
"""
# Add other post commenters, exclude non replies, the post commenter
other_repliers = User.objects.filter(
Q(posts_comments__parent_comment_id=parent_post_comment.pk, ) & ~Q(
id=post_commenter.pk))
# Add post comment creator
post_comment_creator = User.objects.filter(pk=parent_post_comment.commenter_id)
# Add post creator
post = parent_post_comment.post
post_creator = User.objects.filter(pk=post.creator.id)
return other_repliers.union(post_comment_creator, post_creator)
@classmethod
def get_community_notification_target_subscriptions(cls, post):
CommunityNotificationsSubscription = get_community_notifications_subscription_model()
community_subscriptions_query = Q(community=post.community, new_post_notifications=True)
exclude_blocked_users_query = Q(Q(subscriber__blocked_by_users__blocker_id=post.creator.pk) | Q(
subscriber__user_blocks__blocked_user_id=post.creator.pk))
community_members_query = Q(subscriber__communities_memberships__community_id=post.community.pk)
exclude_self_query = ~Q(subscriber=post.creator)
# Exclude banned users
exclude_blocked_users_query.add(Q(subscriber__banned_of_communities__id=post.community.pk), Q.OR)
# Subscriptions after excluding blocked users
target_subscriptions_excluding_blocked = CommunityNotificationsSubscription.objects. \
filter(community_subscriptions_query &
community_members_query &
exclude_self_query
). \
exclude(exclude_blocked_users_query)
staff_members_query = Q(subscriber__communities_memberships__community_id=post.community.pk,
subscriber__communities_memberships__is_administrator=True) | \
Q(subscriber__communities_memberships__community_id=post.community.pk,
subscriber__communities_memberships__is_moderator=True)
# Subscriptions from staff of community
target_subscriptions_with_staff = CommunityNotificationsSubscription.objects. \
filter(community_subscriptions_query &
community_members_query &
staff_members_query &
exclude_self_query
)
results = target_subscriptions_excluding_blocked.union(target_subscriptions_with_staff)
return results
@classmethod
def get_user_notification_target_subscriptions(cls, post):
UserNotificationsSubscription = get_user_notifications_subscription_model()
user_subscriptions_query = Q(user=post.creator, new_post_notifications=True)
exclude_blocked_users_query = Q(Q(subscriber__blocked_by_users__blocker_id=post.creator.pk) | Q(
subscriber__user_blocks__blocked_user_id=post.creator.pk))
exclude_self_query = ~Q(subscriber=post.creator)
if post.is_encircled_post():
circle_ids = [circle.pk for circle in post.circles.all()]
post_circles_query = Q(subscriber__connections__target_connection__circles__in=circle_ids)
user_subscriptions_query.add(post_circles_query, Q.AND)
user_subscriptions_query.add(exclude_self_query, Q.AND)
# Subscriptions after excluding blocked users
target_subscriptions = UserNotificationsSubscription.objects. \
filter(user_subscriptions_query). \
exclude(exclude_blocked_users_query)
return target_subscriptions
def count_comments(self):
return PostComment.count_comments_for_post_with_id(self.pk)
def count_comments_with_user(self, user):
# Count comments excluding users blocked by authenticated user
count_query = ~Q(Q(commenter__blocked_by_users__blocker_id=user.pk) | Q(
commenter__user_blocks__blocked_user_id=user.pk))
if self.community:
if not user.is_staff_of_community_with_name(community_name=self.community.name):
# Dont retrieve comments except from staff members
blocked_users_query_staff_members = Q(
commenter__communities_memberships__community_id=self.community.pk)
blocked_users_query_staff_members.add(Q(commenter__communities_memberships__is_administrator=True) | Q(
commenter__communities_memberships__is_moderator=True), Q.AND)
count_query.add(~blocked_users_query_staff_members, Q.AND)
# Don't count items that have been reported and approved by community moderators
ModeratedObject = get_moderated_object_model()
count_query.add(~Q(moderated_object__status=ModeratedObject.STATUS_APPROVED), Q.AND)
# Dont count soft deleted items
count_query.add(Q(is_deleted=False), Q.AND)
# Dont count items we have reported
count_query.add(~Q(moderated_object__reports__reporter_id=user.pk), Q.AND)
return self.comments.filter(count_query).count()
def count_reactions(self, reactor_id=None):
return PostReaction.count_reactions_for_post_with_id(self.pk, reactor_id=reactor_id)
def is_text_only_post(self):
return self.has_text() and not self.has_video() and not self.has_image()
def has_text(self):
if hasattr(self, 'text'):
if self.text:
return True
return False
def has_image(self):
if hasattr(self, 'image'):
if self.image:
return True
return False
def has_video(self):
if hasattr(self, 'video'):
if self.video:
return True
return False
def has_links(self):
return self.links.exists()
def comment(self, text, commenter):
return PostComment.create_comment(text=text, commenter=commenter, post=self)
def react(self, reactor, emoji_id):
return PostReaction.create_reaction(reactor=reactor, emoji_id=emoji_id, post=self)
def is_public_post(self):
Circle = get_circle_model()
world_circle_id = Circle.get_world_circle_id()
if self.circles.filter(id=world_circle_id).exists():
return True
return False
def is_public_community_post(self):
Community = get_community_model()
return Community.objects.filter(posts__id=self.pk, type=Community.COMMUNITY_TYPE_PUBLIC).exists()
def is_publicly_visible(self):
return self.is_public_post() or self.is_public_community_post()
def is_encircled_post(self):
return not self.is_public_post() and not self.community
def update(self, text=None):
check_can_be_updated(post=self, text=text)
self.text = text
self.is_edited = True
self.language = get_language_for_text(text)
self.save()
def get_media(self):
return self.media
def add_media(self, file, order=None):
check_can_add_media(post=self)
is_in_memory_file = isinstance(file, InMemoryUploadedFile) or isinstance(file, SimpleUploadedFile)
if is_in_memory_file:
file_mime = magic.from_buffer(file.read())
elif isinstance(file, TemporaryUploadedFile):
file_mime = magic.from_file(file.temporary_file_path())
else:
file_mime = magic.from_file(file.name)
check_mimetype_is_supported_media_mimetypes(file_mime)
# Mime check moved pointer
file.seek(0)
file_mime_types = file_mime.split('/')
file_mime_type = file_mime_types[0]
file_mime_subtype = file_mime_types[1]
temp_files_to_close = []
if file_mime_subtype == 'gif':
if is_in_memory_file:
file = write_in_memory_file_to_disk(file)
temp_dir = tempfile.gettempdir()
converted_gif_file_name = os.path.join(temp_dir, str(uuid.uuid4()) + '.mp4')
ff = ffmpy.FFmpeg(
inputs={file.temporary_file_path() if hasattr(file, 'temporary_file_path') else file.name: None},
outputs={converted_gif_file_name: None})
ff.run()
converted_gif_file = open(converted_gif_file_name, 'rb')
temp_files_to_close.append(converted_gif_file)
file = File(file=converted_gif_file)
file_mime_type = 'video'
has_other_media = self.media.exists()
if file_mime_type == 'image':
post_image = self._add_media_image(image=file, order=order)
if not has_other_media:
self.media_width = post_image.width
self.media_height = post_image.height
self.media_thumbnail = file
elif file_mime_type == 'video':
post_video = self._add_media_video(video=file, order=order)
if not has_other_media:
self.media_width = post_video.width
self.media_height = post_video.height
self.media_thumbnail = post_video.thumbnail.file
else:
raise ValidationError(
_('Unsupported media file type')
)
for file_to_close in temp_files_to_close:
file_to_close.close()
self.save()
def get_first_media(self):
return self.media.first()
def get_first_media_image(self):
return self.media.filter(type=PostMedia.MEDIA_TYPE_IMAGE).first()
def _add_media_image(self, image, order):
return PostImage.create_post_media_image(image=image, post_id=self.pk, order=order)
def _add_media_video(self, video, order):
return PostVideo.create_post_media_video(file=video, post_id=self.pk, order=order)
def count_media(self):
return self.media.count()
def publish(self):
check_can_be_published(post=self)
if self.has_media():
# After finishing, this will call _publish()
self.status = Post.STATUS_PROCESSING
self.save()
process_post_media.delay(post_id=self.pk)
else:
self._publish()
def _publish(self):
self.status = Post.STATUS_PUBLISHED
self.created = timezone.now()
self._process_post_subscribers()
self.save()
def is_draft(self):
return self.status == Post.STATUS_DRAFT
def is_empty(self):
return not self.text and not hasattr(self, 'image') and not hasattr(self, 'video') | |
264
-1.094041394294266e-01 -8.494081165558205e-02 -3.401176384013899e-04 0.000000000000000e+00 2.040516518390330e-03 -7.095200000000000e-01 -3.081000000000000e-02 0.000000000000000e+00
-1.992343996060021e-01 -1.121249882337864e-02 2.099237485641801e-04 0.000000000000000e+00 -7.976301500537214e-03 1.273900000000000e-01 1.743000000000000e-02 0.000000000000000e+00
6.082035236506877e-02 1.832024321079221e-02 -1.722582425683213e-01 0.000000000000000e+00 5.960522503827420e-04 1.228400000000000e-01 1.371440000000000e+00 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 265
-1.925742796527010e-01 -8.144675888678138e-02 -8.299317152201363e-03 0.000000000000000e+00 -1.550463908637639e-04 -3.828400000000000e-01 1.313200000000000e-01 0.000000000000000e+00
-2.333994896832758e-01 8.992166152206198e-03 -5.477160036803910e-02 0.000000000000000e+00 -4.266173854392003e-03 9.551000000000000e-02 6.349200000000000e-01 0.000000000000000e+00
-3.970266161090685e-02 4.548954343757043e-02 -6.642411310709320e-02 0.000000000000000e+00 7.504608353685394e-03 -2.784700000000000e-01 6.661200000000000e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 266
-2.037630633052456e-01 -1.079301590787044e-01 -1.113445115664057e-02 0.000000000000000e+00 6.836807521207466e-04 -2.916000000000000e-02 1.372600000000000e-01 0.000000000000000e+00
-3.073416212117938e-01 4.238327682732439e-02 -7.261755996900252e-02 0.000000000000000e+00 1.405466957440718e-04 4.070000000000000e-03 7.898600000000000e-01 0.000000000000000e+00
-6.265699233109558e-02 5.431040763386782e-02 1.400319625386754e-03 0.000000000000000e+00 1.067970314848744e-02 -3.559200000000000e-01 7.782000000000000e-02 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 267
-2.148431819659022e-01 -1.282364277614886e-01 -8.473143276953300e-03 0.000000000000000e+00 1.320071408385866e-03 2.813700000000000e-01 1.036700000000000e-01 0.000000000000000e+00
-3.786346096212872e-01 6.702109352271543e-02 -5.347841820623338e-02 0.000000000000000e+00 4.252519657091967e-03 -1.976700000000000e-01 6.945200000000000e-01 0.000000000000000e+00
-3.690202236016563e-02 5.177116671726126e-02 7.296336042854959e-02 0.000000000000000e+00 8.811371279325915e-03 -3.502500000000000e-01 -7.125800000000000e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 268
-2.207093498589941e-01 -1.394593254062511e-01 -2.555709741657378e-05 0.000000000000000e+00 1.778243905507071e-03 4.203500000000000e-01 1.668000000000000e-02 0.000000000000000e+00
-4.142984576242885e-01 7.577278561338190e-02 3.984508359600458e-04 0.000000000000000e+00 7.512440194246170e-03 -4.388700000000000e-01 -3.000000000000000e-03 0.000000000000000e+00
8.326972852602106e-02 7.067362310658453e-03 1.183730146793426e-01 0.000000000000000e+00 -6.223579239604711e-04 4.116000000000000e-02 -9.925100000000000e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 269
-2.148942961606928e-01 -1.273500318990488e-01 8.407868557016113e-03 0.000000000000000e+00 1.490982130866934e-03 3.905800000000000e-01 -1.200000000000000e-01 0.000000000000000e+00
-3.778377079493575e-01 6.687925005959924e-02 5.208282956463846e-02 0.000000000000000e+00 4.225668945057298e-03 -2.893200000000000e-01 -6.208600000000000e-01 0.000000000000000e+00
1.998440069985673e-01 -2.372863250186011e-02 9.017750725378891e-02 0.000000000000000e+00 -5.339193932418003e-03 3.503000000000000e-02 -6.049900000000000e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 270
-2.038936127449773e-01 -1.068880353029028e-01 1.083185512343543e-02 0.000000000000000e+00 3.864990373268241e-04 -3.590000000000000e-02 -2.263400000000000e-01 0.000000000000000e+00
-3.101327984949929e-01 4.303536009933121e-02 7.295052405420835e-02 0.000000000000000e+00 1.807846235817104e-04 -1.928000000000000e-02 -9.288300000000000e-01 0.000000000000000e+00
2.636247430336001e-01 -5.802739930331805e-02 1.512324608351627e-02 0.000000000000000e+00 -1.146681464943693e-02 3.870500000000000e-01 -1.511300000000000e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 271
-1.932305859138112e-01 -8.150237870314664e-02 8.364591872084957e-03 0.000000000000000e+00 -7.054137504771615e-04 -4.581700000000000e-01 -1.019100000000000e-01 0.000000000000000e+00
-2.319366598409673e-01 9.600960279102323e-03 5.616718900964543e-02 0.000000000000000e+00 -4.486014059054522e-03 1.721200000000000e-01 -6.350300000000000e-01 0.000000000000000e+00
2.300904991655955e-01 -3.964236407487513e-02 -9.671675457527396e-02 0.000000000000000e+00 -7.499518777730686e-03 2.330200000000000e-01 6.811800000000000e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 272
-1.871644290008057e-01 -6.932220684588894e-02 3.281531305681235e-04 0.000000000000000e+00 -7.244963831560432e-04 -4.544400000000000e-01 5.216000000000000e-02 0.000000000000000e+00
-1.977984204757181e-01 2.984166775861354e-03 -7.314149211544718e-04 0.000000000000000e+00 -6.828814963662347e-03 2.421700000000000e-01 2.095000000000000e-02 0.000000000000000e+00
7.019123388305711e-02 -9.237180072952794e-03 -1.348965803882743e-01 0.000000000000000e+00 -1.304418289338367e-04 1.243000000000000e-02 9.715200000000001e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 273
-2.632408276839526e-01 -7.065416703740732e-02 -2.068686119088293e-02 0.000000000000000e+00 -2.822336524508431e-03 -3.818600000000000e-01 3.128100000000000e-01 0.000000000000000e+00
-2.145993381598259e-01 4.070072120098539e-02 -2.953013847492277e-02 0.000000000000000e+00 -3.949266800115293e-03 -1.286600000000000e-01 4.932000000000000e-01 0.000000000000000e+00
-2.944482140506381e-02 -2.256883823050427e-02 -4.516232373339289e-02 0.000000000000000e+00 6.471538805276542e-03 1.268000000000000e-02 4.461900000000000e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 274
-2.894222755029856e-01 -7.749229974119033e-02 -2.353551206008050e-02 0.000000000000000e+00 -3.643495529058322e-04 -3.107000000000000e-02 4.648800000000000e-01 0.000000000000000e+00
-2.523263430040910e-01 5.985058036441260e-02 -3.380340640947758e-02 0.000000000000000e+00 -3.516527909954020e-04 -1.096400000000000e-01 6.534500000000000e-01 0.000000000000000e+00
-4.797865524767880e-02 -2.707025364730498e-02 8.226184415817784e-03 0.000000000000000e+00 7.340140707907486e-03 3.848000000000000e-01 -9.805999999999999e-02 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 275
-3.103118518041731e-01 -8.793879169827701e-02 -1.741388678015383e-02 0.000000000000000e+00 2.385594126796960e-03 2.863000000000000e-01 3.155000000000000e-01 0.000000000000000e+00
-2.822061509787829e-01 7.753207935424758e-02 -2.496574627207706e-02 0.000000000000000e+00 3.432047331697281e-03 -2.348000000000000e-02 4.347500000000000e-01 0.000000000000000e+00
-1.299245257344402e-02 -2.088739101587933e-02 5.430554680289879e-02 0.000000000000000e+00 4.801528840000624e-03 1.162700000000000e-01 -5.742699999999999e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 276
-3.242500490633164e-01 -9.285200168864793e-02 8.564467305587076e-05 0.000000000000000e+00 2.861145450174497e-03 3.798100000000000e-01 2.405000000000000e-02 0.000000000000000e+00
-3.022578355482127e-01 9.027319989239593e-02 1.747584694324136e-04 0.000000000000000e+00 4.116130244848824e-03 -7.496000000000000e-02 -1.824000000000000e-02 0.000000000000000e+00
6.063243835808677e-02 -4.180308922391436e-02 7.330373296951445e-02 0.000000000000000e+00 -1.449614170105100e-03 2.416000000000000e-02 -6.111500000000000e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 277
-3.101405624580752e-01 -9.139202883596932e-02 1.810305757538608e-02 0.000000000000000e+00 2.629692803676933e-03 2.981400000000000e-01 -2.924800000000000e-01 0.000000000000000e+00
-2.818566340398740e-01 8.132195819188251e-02 2.650264441372761e-02 0.000000000000000e+00 3.242109056309180e-03 6.601000000000000e-02 -3.761600000000000e-01 0.000000000000000e+00
1.336150133655696e-01 -7.032655977490215e-02 5.442295016754961e-02 0.000000000000000e+00 -5.643481951631762e-03 -1.465000000000000e-01 -4.311400000000000e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 278
-2.880439339125011e-01 -8.365481637701278e-02 2.373436520903252e-02 0.000000000000000e+00 -2.004812307114523e-04 1.362200000000000e-01 -4.599900000000000e-01 0.000000000000000e+00
-2.492525467207482e-01 6.583409372213185e-02 3.402751831835676e-02 0.000000000000000e+00 1.706774663374835e-04 4.494000000000000e-02 -5.921200000000000e-01 0.000000000000000e+00
1.694783386932096e-01 -9.008669549387195e-02 5.596417670488733e-03 0.000000000000000e+00 -8.168655051546000e-03 -5.128000000000000e-02 -9.873000000000000e-02 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 279
-2.626718320400178e-01 -7.402119156652040e-02 1.999769039567285e-02 0.000000000000000e+00 -2.478924860174349e-03 -1.371500000000000e-01 -3.278100000000000e-01 0.000000000000000e+00
-2.138015974031454e-01 4.457408897135421e-02 2.799324033323244e-02 0.000000000000000e+00 -3.434450165318549e-03 -3.323000000000000e-02 -5.419700000000000e-01 0.000000000000000e+00
1.448078487065786e-01 -8.299777396815763e-02 -6.356617323702768e-02 0.000000000000000e+00 -7.265912959570176e-03 -1.037700000000000e-01 6.045100000000000e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 280
-2.480485531212156e-01 -6.915739196449375e-02 -2.844978219857346e-04 0.000000000000000e+00 -3.426014096163311e-03 -1.601490000000000e+00 -3.322000000000000e-02 0.000000000000000e+00
-1.932660660542525e-01 3.325334821514209e-02 -3.988703783513702e-04 0.000000000000000e+00 -5.245538319409992e-03 1.449440000000000e+00 -4.942000000000000e-02 0.000000000000000e+00
4.234599221912488e-02 -3.746882920649713e-02 -8.712633505579315e-02 0.000000000000000e+00 7.498260680652118e-04 1.442400000000000e-01 8.519700000000000e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 281
-3.338826137275056e-01 -7.064178604352389e-02 -1.663422492893885e-02 0.000000000000000e+00 -4.892007065113529e-03 -2.763000000000000e-02 3.473500000000000e-01 0.000000000000000e+00
-1.519980472813331e-01 6.260129087852950e-02 -2.817436821871691e-02 0.000000000000000e+00 -5.287950239504485e-03 1.710000000000000e-03 5.983600000000000e-01 0.000000000000000e+00
-8.484033807193826e-02 -5.539551666685284e-02 -5.602553754783333e-02 0.000000000000000e+00 7.505637706163887e-03 1.509900000000000e-01 8.511900000000000e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 282
-3.587476627876671e-01 -6.932538728469273e-02 -2.841907581749745e-02 0.000000000000000e+00 -1.378455177576982e-03 -5.244000000000000e-02 8.702200000000000e-01 0.000000000000000e+00
-1.876404604829739e-01 6.468588252112034e-02 -3.578620181570014e-02 0.000000000000000e+00 2.866237228345836e-04 2.562800000000000e-01 1.134240000000000e+00 0.000000000000000e+00
-1.167974996257160e-01 -6.881884437803543e-02 3.081766840003816e-03 0.000000000000000e+00 1.632970433226399e-02 2.215000000000000e-01 1.853900000000000e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 283
-3.907207653624973e-01 -8.040891355830433e-02 -2.383284522430848e-02 0.000000000000000e+00 3.062459652942190e-03 3.181000000000000e-02 6.455000000000000e-01 0.000000000000000e+00
-2.235704509128309e-01 5.863570006598710e-02 -2.305579867821642e-02 0.000000000000000e+00 5.196718843023584e-03 3.148000000000000e-01 6.237400000000000e-01 0.000000000000000e+00
-7.867680439192665e-02 -6.568435181848965e-02 5.823052485193969e-02 0.000000000000000e+00 1.039188476832947e-02 9.427000000000001e-02 -1.023700000000000e+00 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 284
-4.064133532363171e-01 -8.216330417298863e-02 -3.478794235040161e-03 0.000000000000000e+00 5.605674811492267e-03 2.528100000000000e-01 1.619800000000000e-01 0.000000000000000e+00
-2.337520578394602e-01 6.850577770873985e-02 4.188329673582347e-03 0.000000000000000e+00 7.083934868107211e-03 3.394200000000000e-01 -1.224000000000000e-02 0.000000000000000e+00
-3.364499218321238e-04 -6.096888827991891e-02 6.893384592035316e-02 0.000000000000000e+00 -4.067657734739688e-04 -6.304000000000000e-02 -1.157460000000000e+00 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 285
-3.976783538326494e-01 -8.753779137454998e-02 1.760505386870731e-02 0.000000000000000e+00 4.760548928605307e-03 2.447200000000000e-01 -3.484700000000000e-01 0.000000000000000e+00
-2.151937915655260e-01 6.666284247428851e-02 2.764372339431295e-02 0.000000000000000e+00 5.069254241205440e-03 4.808000000000000e-02 -5.791100000000000e-01 0.000000000000000e+00
5.919088744877399e-02 -7.442412591679368e-02 4.189390098385455e-02 0.000000000000000e+00 -7.921095789126559e-03 -2.402400000000000e-01 -7.408600000000000e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 286
-3.712032454989532e-01 -8.315931158645157e-02 2.820269239284601e-02 0.000000000000000e+00 1.830001760577488e-03 1.969100000000000e-01 -7.025500000000000e-01 0.000000000000000e+00
-1.784646110507825e-01 7.078793567000219e-02 3.620265483367681e-02 0.000000000000000e+00 7.729877565742227e-04 -1.805800000000000e-01 -9.085500000000000e-01 0.000000000000000e+00
8.345135204585515e-02 -8.602698664734068e-02 2.452031890279344e-03 0.000000000000000e+00 -1.245287710297072e-02 -1.692500000000000e-01 -1.110900000000000e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 287
-3.412729690468841e-01 -7.860113700689013e-02 2.286201628451418e-02 0.000000000000000e+00 -2.654833415068808e-03 1.783600000000000e-01 -7.025900000000000e-01 0.000000000000000e+00
-1.427884818982474e-01 7.101311550490803e-02 2.358644350269125e-02 0.000000000000000e+00 -4.594065290805527e-03 -1.426800000000000e-01 -7.134000000000000e-01 0.000000000000000e+00
6.409495122928127e-02 -8.071289747728026e-02 -4.409888828790454e-02 0.000000000000000e+00 -9.717944849804261e-03 -3.404000000000000e-02 9.301600000000000e-01 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 288
-3.254792129297456e-01 -7.743065980858585e-02 3.695177659665760e-03 0.000000000000000e+00 -5.315421909867724e-03 -4.831000000000000e-02 -2.119500000000000e-01 0.000000000000000e+00
-1.312917240454440e-01 6.197434200883061e-02 -4.604782691488146e-03 0.000000000000000e+00 -6.535516703039118e-03 -1.444600000000000e-01 -6.562999999999999e-02 0.000000000000000e+00
-4.746424529994821e-03 -4.709241674911273e-02 -7.446764465057995e-02 0.000000000000000e+00 1.836421943472347e-03 -1.713600000000000e-01 1.078440000000000e+00 0.000000000000000e+00
1.570796326794897e+00 7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
#Fields=2
1) coordinates, coordinate, rectangular cartesian, real, #Components=3
x. #Values=8 (value,d/ds1,d/ds2,d2/ds1ds2,d/ds3,d2/ds1ds3,d2/ds2ds3,d3/ds1ds2ds3)
y. #Values=8 (value,d/ds1,d/ds2,d2/ds1ds2,d/ds3,d2/ds1ds3,d2/ds2ds3,d3/ds1ds2ds3)
z. #Values=8 (value,d/ds1,d/ds2,d2/ds1ds2,d/ds3,d2/ds1ds3,d2/ds2ds3,d3/ds1ds2ds3)
2) fibres, anatomical, fibre, real, #Components=3
fibre angle. #Values=1 (value)
imbrication angle. #Values=1 (value)
sheet angle. #Values=1 (value)
Node: 289
-1.343825484149234e-01 5.669291159702738e-02 1.883660306419888e-02 0.000000000000000e+00 4.654344990526707e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
4.298391852279835e-01 -1.315387395513019e-01 6.697345639299829e-03 0.000000000000000e+00 1.730574158234077e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
2.928339535277109e-02 -3.920048594580861e-02 -2.133510214207279e-02 0.000000000000000e+00 8.522580732968656e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 290
-1.114317448808501e-01 4.727548089941411e-02 2.298060121651278e-02 0.000000000000000e+00 -3.640087916456855e-04 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
4.377997348193415e-01 -1.166076078136914e-01 7.970694888798896e-03 0.000000000000000e+00 -8.634944889662766e-05 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
1.469426881436097e-02 -4.377744439467479e-02 -5.808693018624855e-03 0.000000000000000e+00 1.012402438833155e-02 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 291
-8.842134598188778e-02 3.856039710038117e-02 1.985983351917241e-02 0.000000000000000e+00 -2.801815121851056e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
4.457805750055819e-01 -1.022044892255592e-01 6.888504401608930e-03 0.000000000000000e+00 -9.719652631124676e-04 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
1.766600931552523e-02 -3.306931968152238e-02 1.167102673674347e-02 0.000000000000000e+00 8.333637373544882e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 292
-7.171207784250125e-02 3.321468529741678e-02 6.196176279594789e-04 0.000000000000000e+00 -6.334828265772710e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
4.515767436225612e-01 -8.909989242937710e-02 2.151489581397326e-04 0.000000000000000e+00 -2.196952718794692e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
3.803632228784788e-02 -1.374277008578856e-02 3.425907954618451e-02 0.000000000000000e+00 4.305781266494928e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 293
-8.718211072596654e-02 3.732366076078319e-02 -1.849826495705909e-02 0.000000000000000e+00 -2.763044058543031e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
4.462108729218598e-01 -1.031875151512366e-01 -6.416214107576951e-03 0.000000000000000e+00 -7.502943280453811e-04 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
8.618416840789257e-02 -1.616312079530124e-02 3.009203211442518e-02 0.000000000000000e+00 -6.331546873107642e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 294
-1.087086077566105e-01 4.444481465425791e-02 -2.404763842955035e-02 0.000000000000000e+00 -2.097575104779634e-04 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
4.387443154074057e-01 -1.177262603472421e-01 -8.341188946476924e-03 0.000000000000000e+00 -7.261897115748428e-05 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
9.822038651669536e-02 -7.448279900618360e-03 -9.016555532798121e-04 0.000000000000000e+00 -1.058368744010352e-02 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 295
-1.352773875850561e-01 5.682527843035801e-02 -2.019817162632384e-02 0.000000000000000e+00 4.854561184636827e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
4.295284950289053e-01 -1.313822883854394e-01 -7.169635933330337e-03 0.000000000000000e+00 1.723785199796629e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
8.438085730132841e-02 -2.410972165041381e-03 -2.042795670909403e-02 0.000000000000000e+00 -9.835462586983285e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 296
-1.491049510092528e-01 6.276028010578705e-02 4.474195850664442e-04 0.000000000000000e+00 6.855890153700403e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
4.244050435407427e-01 -1.389823366557616e-01 1.553450995397665e-04 0.000000000000000e+00 2.268885166065354e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
5.736447309850297e-02 -2.265684786430158e-02 -2.754873097427801e-02 0.000000000000000e+00 1.554322188001427e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 297
-7.768963681786989e-02 6.792092066125902e-02 1.109420346099724e-02 0.000000000000000e+00 2.554952492182676e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
2.983004456766863e-01 -7.543882988258270e-02 1.788471006034381e-02 0.000000000000000e+00 4.052321663581215e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
-9.917090593079717e-03 -1.324679376730873e-01 -3.189540040722365e-02 0.000000000000000e+00 1.054914694706136e-02 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 298
-6.415626398146751e-02 7.611498043456449e-02 1.391434396819709e-02 0.000000000000000e+00 -1.992317725711679e-04 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
3.211921270057233e-01 -4.771013008715688e-02 2.263782005164663e-02 0.000000000000000e+00 -3.211406182901111e-04 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
-2.908317558030603e-02 -1.855487838144489e-01 -2.743109886471889e-03 0.000000000000000e+00 1.149272001921705e-02 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 299
-4.986094888138781e-02 9.364601337682674e-02 1.282943571813840e-02 0.000000000000000e+00 -2.517241575209552e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
3.435760857801165e-01 -4.891558975260418e-03 2.064236209369080e-02 0.000000000000000e+00 -4.155147685826296e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
-1.540331036600228e-02 -1.560355337038396e-01 2.668836389117971e-02 0.000000000000000e+00 1.420757989976769e-02 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 300
-3.849739254502609e-02 1.010446984167148e-01 1.249458072644094e-06 0.000000000000000e+00 -4.010836209323963e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
3.624768511932261e-01 1.760567624048809e-02 -2.763640047691585e-04 0.000000000000000e+00 -6.492227557972935e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
2.429355220206508e-02 -5.581257596478031e-02 4.271217898929230e-02 0.000000000000000e+00 2.120466031307914e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 301
-4.985844996519802e-02 9.357070512972590e-02 -1.288320027866632e-02 0.000000000000000e+00 -2.524814048447756e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
3.430233577706589e-01 -4.229749948171130e-03 -2.072939806656909e-02 0.000000000000000e+00 -4.476212023617393e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.002104761258285e-02 1.091954226754066e-02 3.323927720701170e-02 0.000000000000000e+00 -8.741832803193489e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 302
-6.426379310236011e-02 7.427237050599592e-02 -1.429682959476234e-02 0.000000000000000e+00 -3.911182460609730e-04 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
3.210180550601558e-01 -4.895807795285187e-02 -2.243857556361971e-02 0.000000000000000e+00 -6.308391717000650e-04 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
9.077210661609421e-02 3.723590962329004e-02 5.974418761846179e-03 0.000000000000000e+00 -9.912664020169416e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 303
-7.845210915467836e-02 6.913936947797630e-02 -1.104043890056656e-02 0.000000000000000e+00 2.317555454151209e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
2.981462066434096e-01 -7.404045700518969e-02 -1.779767408757048e-02 0.000000000000000e+00 3.683200653716703e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
8.196988513627654e-02 3.846312647962030e-02 -2.803224069093557e-02 0.000000000000000e+00 -8.327232513899208e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 304
-8.634467090346530e-02 6.099926357695706e-02 3.812361683953602e-04 0.000000000000000e+00 3.650159305906217e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
2.854227068849897e-01 -9.574666414229983e-02 7.711951663727512e-05 0.000000000000000e+00 5.884348796243541e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
3.470762523416338e-02 -1.818699925580158e-02 -4.594348786463441e-02 0.000000000000000e+00 5.073563816254956e-04 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 305
1.459292907684753e-03 7.122002010489728e-02 3.395231992175679e-02 0.000000000000000e+00 4.862133657912646e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
2.789615254628143e-01 -5.311322563859283e-02 5.473387969448007e-02 0.000000000000000e+00 7.838195778616386e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
-2.356524799931057e-01 -2.015613332219605e-01 -1.886968867008831e-01 0.000000000000000e+00 1.194883752353507e-02 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 306
4.079821598839407e-02 1.150465044516200e-01 4.870569393204073e-02 0.000000000000000e+00 4.573773867938384e-05 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
3.423794746450957e-01 -1.502735950251806e-02 7.851796579615701e-02 0.000000000000000e+00 7.368689720033128e-05 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
-3.564032988143805e-01 -2.387285049765597e-01 -2.937628904959994e-02 0.000000000000000e+00 1.884504139763368e-02 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
7.853981633974483e-01
0.000000000000000e+00
0.000000000000000e+00
Node: 307
9.887068077166040e-02 1.630939232796338e-01 4.478955150142662e-02 0.000000000000000e+00 -4.978219673554770e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
4.359974570551333e-01 2.683404475005313e-02 7.220431072924184e-02 0.000000000000000e+00 -8.025235397603803e-03 0.000000000000000e+00 0.000000000000000e+00 0.000000000000000e+00
-2.944050580920770e-01 -1.984528032183988e-01 | |
<filename>Projects/superhero-dueler/superheroes.py<gh_stars>0
import random
import math
from functools import reduce
class Ability():
def __init__(self, name, attack_strength):
'''
Initiate the abilities class with its name and attack strength
Args:
name (string): a single word discriptor of the ability
attack_strength (int): the value of the abilities strength
Returns:
ability object: a new object
'''
self.name = name
self.max_damage = attack_strength
def attack(self):
''' A method that returns random int between 0 and the initilized max_damage property'''
return random.randint(0, self.max_damage)
class Weapon(Ability):
def __init__(self, name, attack_strength):
'''
Initiate the weapons subclass with name and attack_strength
Args:
name (string): a single word descriptor of the weapon
attack_strength (int): value for the weapons may power
Returns:
weapon (object): new weapon object
'''
super().__init__(name, attack_strength)
def attack(self):
'''A method that returns a randome int between 0 and half the iniitlaized max_damage property'''
return random.randint(math.floor(self.max_damage/2), self.max_damage)
class Armor():
def __init__(self, name, blocking_strength):
'''
Initiate the armor class with name and blocking strength
Args:
name (string): a detailed one word discriptor of the armor
blocking_strength (int): the max value that the armor can block
Returns:
armor (object): a new armor object
'''
self.name = name
self.max_block = blocking_strength
def block(self):
'''A method that returns a random int between 0 and the initalized max_block property'''
return random.randint(0, self.max_block)
class Hero():
# TODO: Make a way for hero abilities to run out or be lost, and watch for heroes still having abilities
def __init__(self, name, starting_health=100):
'''
Initiate the hero class with name, starting health, kills, and deaths
Args:
name (string): a one word discription of the hero
starting_health (int): a value for the heroes inital health with a default of 100
Returns:
hero (object): a new hero object
'''
self.name = name
self.abilities = []
self.armors = []
self.starting_health = starting_health
self.current_health = starting_health
self.kills = 0
self.deaths = 0
def add_kill(self, num_kills):
'''A method for adding a kill to the heroes kill count'''
self.kills += num_kills
def add_death(self, num_deaths):
'''A method for adding a death the the heroes death count'''
self.deaths += num_deaths
def add_ability(self, new_ability):
'''A setter method that adds a new ability to the hero'''
self.abilities.append(new_ability)
def add_armor(self, new_armor):
'''A setter method that adds a new armor object to the hero'''
self.armors.append(new_armor)
def add_weapon(self, weapon):
'''A method for adding a new weapon object to the hero'''
self.abilities.append(weapon)
def attack(self):
'''A getter method that creates a list of attack values by looping through the heroes abilities and then returns the sum of the list'''
return sum(ability.attack() for ability in self.abilities)
def defend(self, damage_amount=0):
'''
A getter method that creates a list of block values by looping through the heroes armors and then returns the sum of the list
Args:
damage_amount (int): the amount of damage given to the hero
Returns:
damage_taken (int): the damage_taken subtracted by the heroes total block
'''
return sum(armor.block() for armor in self.armors)
def take_damage(self, damage):
'''
A setter method that updates the users current_health to reflect the damage minus the defence
Args:
damage (value): the value of the damage given to the hero
Updates:
current_health (int): sets the curret health equal to itself and the damage taken from defending
'''
damage_taken = damage - self.defend(damage)
if damage_taken > 0:
self.current_health -= damage_taken
def is_alive(self):
'''A getter method that returns true of false depending on whether or not the hero is alive'''
if self.current_health <= 0:
return False
else:
return True
def fight(self, opponent):
'''
A method that takes in a hero to fight and pits them agians the current hero untill one dies or no ailities are left
Args:
opponent (Hero): a hero object
Returns:
outcome (string): either which hero won or that the fight endded in a draw
'''
print(f'{self.name} and {opponent.name} are fighting!')
while self.is_alive() and opponent.is_alive():
hero_attack = self.attack()
opponent_attack = opponent.attack()
self.take_damage(opponent_attack)
opponent.take_damage(hero_attack)
if self.is_alive() == False and opponent.is_alive() == False:
print('Draw! Both heroes died from their injuries!')
self.add_kill(1)
self.add_death(1)
elif self.is_alive() == False:
print(f'{opponent.name} won!')
self.add_death(1)
opponent.add_kill(1)
elif opponent.is_alive() == False:
print(f'{self.name} won!')
self.add_kill(1)
opponent.add_death(1)
class Team():
def __init__(self, name):
'''
Initialize the team class with name and heroes properties
Args:
name (string): a single word descriptor of the team
heroes (list): a list for hero objects
Returns:
team (object): a new team object
'''
self.name = name
self.heroes = []
def add_hero(self, hero):
'''A method for adding a new hero to the team'''
self.heroes.append(hero)
def remove_hero(self, hero_name):
'''A method for removing a hero from the team'''
for index, hero in enumerate(self.heroes):
if hero.name == hero_name:
del self.heroes[index]
return 0
def view_all_heroes(self):
'''A method for seeing all the heroes on the team'''
for hero in self.heroes:
print(hero.name)
def heroes_alive(self):
return [hero for hero in self.heroes if hero.is_alive()]
def fight_should_continue(self, opponent, team_alive, opponents_alive):
'''A helper function for checking if a fight should coninue or not'''
team_abilities = sum(len(hero.abilities) for hero in self.heroes)
opponent_abilities = sum(len(hero.abilities) for hero in opponent.heroes)
if len(team_alive) > 0 and len(opponents_alive) > 0:
if team_abilities > 0 and opponent_abilities > 0:
return True
elif team_abilities <= 0 and opponent_abilities > 0:
return True
elif team_abilities > 0 and opponent_abilities <= 0:
return True
else:
return False
else:
return False
def attack(self, opponent):
'''A method for battling the team against another'''
team_alive = self.heroes_alive()
opponents_alive = opponent.heroes_alive()
while self.fight_should_continue(opponent, team_alive, opponents_alive):
team_hero = random.choice(team_alive)
opponent_hero = random.choice(opponents_alive)
team_hero.fight(opponent_hero)
team_alive = self.heroes_alive()
opponents_alive = opponent.heroes_alive()
def revive_heroes(self, health=100):
'''A method for resetting each heroes health to its starting_health'''
for hero in self.heroes:
hero.current_health = hero.starting_health
def stats(self):
'''A method for printing the teams stats'''
for hero in self.heroes:
if hero.deaths == 0:
kill_death_ratio = hero.kills / 1
else:
kill_death_ratio = hero.kills / hero.deaths
print(f'{hero.name}: {kill_death_ratio}')
class Arena():
def __init__(self, team_one=None, team_two=None):
'''Initialate the arena class with a team one and team two properties'''
self.team_one = team_one
self.team_two = team_two
def create(self, type_prompt, type_reference):
'''
A geneator method for prompting the user for values to create a specific object
Args:
type_prompt (sting): type to enter into the input promts
type_reference (class): class refrence for the type to create
Returns:
object: a new type_reference object
'''
print(f'To create an {type_prompt} enter the following:')
name = valid_str_input('Name: ')
strength = valid_int_input('Strength: ')
return type_reference(name, strength)
def create_hero(self):
'''A gernator method for prompting the suer for values to create a Hero instance'''
print('To create a hero follow the steps below:')
name = valid_str_input('Name: ')
health = greater_than_zero_input(f'How much health do you want {name} to have? ')
numb_armors = valid_int_input(f'How much armor do you want {name} to have? ')
armors = [self.create('Armor', Armor) for index in range(numb_armors)]
numb_abilities = valid_int_input(f'How may abilities do you want {name} to have? ')
abilities = [self.create('Ability', Ability) for index in range(numb_abilities)]
numb_weapons = valid_int_input(f'How may weapons do you want {name} to have? ')
abilities += [self.create('Weapon', Weapon) for index in range(numb_weapons)]
hero = Hero(name, health)
for armor in armors:
hero.add_armor(armor)
for ability in abilities:
hero.add_ability(ability)
return hero
def build_team_one(self):
'''A gernator method for prompting the user for values to create team one for the arena'''
print('Create the first team by following the steps below: ')
name = valid_str_input('Team Name: ')
numb_heroes = greater_than_zero_input('How many heroes are on this team? ')
self.team_one = Team(name)
for _ in range(numb_heroes):
self.team_one.add_hero(self.create_hero())
def build_team_two(self):
'''A gernator method for prompting the user for values to create team two for the arena'''
print('Create the second team by following the steps below: ')
name = valid_str_input('Team Name: ')
numb_heroes = greater_than_zero_input('How many heroes are on this team? ')
self.team_two = Team(name)
for _ in range(numb_heroes):
self.team_two.add_hero(self.create_hero())
def team_battle(self):
'''A method for making the two teams in the arena fight agianst each other'''
self.team_one.attack(self.team_two)
def show_stats(self):
'''A method for printing out the teams statistics'''
alive_team_one = self.team_one.heroes_alive()
alive_team_two = self.team_two.heroes_alive()
if len(alive_team_one) <= 0 and len(alive_team_two) <= 0:
print('Draw! No heroes survied the battle.')
elif len(alive_team_one) <= 0:
print(f'{self.team_two.name} Won!')
for | |
<filename>Source/Source Code/gens.py
# NS2 Script Generator
import os
import math
import datetime
activate_mal=False # do we want malware node?
CNUMER = 10 # Total number of nodes in a cluster
run_time = 10.0 # Runtime in seconds
#Initialisation
if activate_mal:
ns_file_name = "attack.tcl"
else:
ns_file_name = "normal.tcl"
os.system("rm " + ns_file_name) # to prevent overwriting
if activate_mal:
trace_and_nam_file_name="attack_out"
else:
trace_and_nam_file_name="normal_out"
tracefile_name = trace_and_nam_file_name+".tr"
namfile_name = trace_and_nam_file_name+".nam"
CLUSTER_ONE_NODE_POPULATION = CNUMER
CLUSTER_TWO_NODE_POPULATION = CNUMER
CLUSTER_THREE_NODE_POPULATION = CNUMER
CLUSTER_FOUR_NODE_POPULATION = CNUMER
CLUSTER_FIVE_NODE_POPULATION = CNUMER
cluster_one_node_list = []
cluster_two_node_list = []
cluster_three_node_list = []
cluster_four_node_list = []
wireless_cluster_five_node_list = []
malicious_node_list = []
cluster_one_name_suffix = "clusterone_node_"
cluster_two_name_suffix = "clustertwo_node_"
cluster_three_name_suffix = "clusterthree_node_"
cluster_four_name_suffix = "clusterfour_node_"
cluster_five_name_suffix = "clusterfive_node_"
malicious_node_name_suffix = "malicious_node_"
cluster_one_switch_node = "c1switch"
cluster_two_switch_node = "c2switch"
cluster_three_switch_node = "c3switch"
cluster_four_switch_node = "c4switch"
cluster_five_switch_node = "c5switch"
router1_node = "r1node"
router2_node = "r2node"
router3_node = "r3node"
# creating base setup
with open(ns_file_name, 'a') as ns_file:
ns_file.write("""
#===================================
# Simulation Script Generated by XSFM
#===================================
# Simulation parameters setup
#===================================
set val(stop) """ + str(run_time) + """ ;# time of simulation end
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator -multicast on]
#Open the NS trace file
set tracefile [open """ + tracefile_name + """ w]
$ns trace-all $tracefile
#Open the NAM trace file
set namfile [open """ + namfile_name + """ w]
$ns namtrace-all $namfile
""")
## setting up nodes
# Cluster 1
for i in range(0, CLUSTER_ONE_NODE_POPULATION):
cluster_one_node_list.append(str(cluster_one_name_suffix) + str(i))
# Cluster 2
for i in range(0, CLUSTER_TWO_NODE_POPULATION):
cluster_two_node_list.append(str(cluster_two_name_suffix) + str(i))
# Cluster 3
for i in range(0, CLUSTER_THREE_NODE_POPULATION):
cluster_three_node_list.append(str(cluster_three_name_suffix) + str(i))
# Cluster 4
for i in range(0, CLUSTER_FOUR_NODE_POPULATION):
cluster_four_node_list.append(str(cluster_four_name_suffix) + str(i))
# Cluster 5
for i in range(0, CLUSTER_FIVE_NODE_POPULATION):
wireless_cluster_five_node_list.append(str(cluster_five_name_suffix) + str(i))
# Malicious Node Def.
malicious_node_list.append(str(malicious_node_name_suffix) + str("1"))
# saving the node info in file
with open(ns_file_name, 'a') as nf:
nf.write("""
#===================================
# Nodes Definition
#===================================\n""")
# router nodes
with open(ns_file_name, 'a') as nf:
nf.write("set " + router1_node + " [$ns node]\n")
nf.write("set " + router2_node + " [$ns node]\n")
nf.write("set " + router3_node + " [$ns node]\n")
nf.write("$" + router1_node + " label \"Router1\"\n")
nf.write("$" + router2_node + " label \"Router2\"\n")
nf.write("$" + router3_node + " label \"Router3\"\n")
# switch nodes
with open(ns_file_name, 'a') as nf:
nf.write("set " + cluster_one_switch_node + " [$ns node]\n")
nf.write("set " + cluster_two_switch_node + " [$ns node]\n")
nf.write("set " + cluster_three_switch_node + " [$ns node]\n")
nf.write("set " + cluster_four_switch_node + " [$ns node]\n")
nf.write("set " + cluster_five_switch_node + " [$ns node]\n")
nf.write("$" + cluster_one_switch_node + " label \"C1SW\"\n")
nf.write("$" + cluster_two_switch_node + " label \"C2SW\"\n")
nf.write("$" + cluster_three_switch_node + " label \"C3SW\"\n")
nf.write("$" + cluster_four_switch_node + " label \"C4SW\"\n")
nf.write("$" + cluster_five_switch_node + " label \"C5SW\"\n")
# cluster 1
c1i = 0
for node in cluster_one_node_list:
with open(ns_file_name, 'a') as nf:
nf.write("set " + node + " [$ns node]\n")
nf.write("$" + node + " label \"C1N" + str(c1i) + "\" \n")
c1i += 1
# cluster 2
c2i = 0
for node in cluster_two_node_list:
with open(ns_file_name, 'a') as nf:
nf.write("set " + node + " [$ns node]\n")
nf.write("$" + node + " label \"C2N" + str(c2i) + "\" \n")
c2i += 1
# cluster 3
c3i = 0
for node in cluster_three_node_list:
with open(ns_file_name, 'a') as nf:
nf.write("set " + node + " [$ns node]\n")
nf.write("$" + node + " label \"C3N" + str(c3i) + "\" \n")
c3i += 1
# cluster 4
c4i = 0
for node in cluster_four_node_list:
with open(ns_file_name, 'a') as nf:
nf.write("set " + node + " [$ns node]\n")
nf.write("$" + node + " label \"C4N" + str(c4i) + "\" \n")
c4i += 1
# cluster 5
c5i = 0
for node in wireless_cluster_five_node_list:
with open(ns_file_name, 'a') as nf:
nf.write("set " + node + " [$ns node]\n")
nf.write("$" + node + " label \"C5N" + str(c5i) + "\" \n")
c5i += 1
# malicious node write
if activate_mal:
with open(ns_file_name, 'a') as nf:
nf.write("set " + malicious_node_list[0] + " [$ns node]\n")
nf.write("$" + malicious_node_list[0] + " label \"MALN1\" \n")
##Link Definition
with open(ns_file_name, 'a') as nf:
nf.write("""
#===================================
# Links Definition
#===================================\n""")
# router_nodes interconnection
with open(ns_file_name, 'a') as nf:
nf.write("$ns duplex-link $" + router1_node + " $" + router2_node + " 1000.0Mb 5ms DropTail\n")
nf.write("$ns queue-limit $" + router1_node + " $" + router2_node + " 50\n")
nf.write("$ns duplex-link $" + router1_node + " $" + router3_node + " 1000.0Mb 5ms DropTail\n")
nf.write("$ns queue-limit $" + router1_node + " $" + router3_node + " 50\n")
nf.write("$ns duplex-link $" + router2_node + " $" + router3_node + " 1000.0Mb 5ms DropTail\n")
nf.write("$ns queue-limit $" + router2_node + " $" + router3_node + " 50\n")
# connecting switches
with open(ns_file_name, 'a') as nf:
nf.write("$ns duplex-link $" + router1_node + " $" + cluster_one_switch_node + " 100.0Mb 10ms DropTail\n")
nf.write("$ns queue-limit $" + router1_node + " $" + cluster_one_switch_node + " 50\n")
nf.write("$ns duplex-link $" + router1_node + " $" + cluster_two_switch_node + " 100.0Mb 10ms DropTail\n")
nf.write("$ns queue-limit $" + router1_node + " $" + cluster_two_switch_node + " 50\n")
nf.write("$ns duplex-link $" + router2_node + " $" + cluster_three_switch_node + " 100.0Mb 10ms DropTail\n")
nf.write("$ns queue-limit $" + router2_node + " $" + cluster_three_switch_node + " 50\n")
nf.write("$ns duplex-link $" + router3_node + " $" + cluster_four_switch_node + " 100.0Mb 10ms DropTail\n")
nf.write("$ns queue-limit $" + router3_node + " $" + cluster_four_switch_node + " 50\n")
nf.write("$ns duplex-link $" + router3_node + " $" + cluster_five_switch_node + " 100.0Mb 10ms DropTail\n")
nf.write("$ns queue-limit $" + router3_node + " $" + cluster_five_switch_node + " 50\n")
## Connecting Clusters
print("Connecting Clusters.")
## Cluster 1 connection
with open(ns_file_name, 'a') as nf:
nf.write(
"$ns duplex-link $" + cluster_one_switch_node + " $" + cluster_one_node_list[0] + " 200.0Mb 10ms DropTail\n")
nf.write("$ns queue-limit $" + cluster_one_switch_node + " $" + cluster_one_node_list[0] + " 50\n")
with open(ns_file_name, 'a') as nf:
for i in range(0, len(cluster_one_node_list)):
nf.write("$ns duplex-link $" + cluster_one_node_list[0] + " $" + cluster_one_node_list[
i] + " 100.0Mb 10ms DropTail\n")
nf.write("$ns queue-limit $" + cluster_one_node_list[0] + " $" + cluster_one_node_list[i] + " 50\n")
## Cluster 2 connection
with open(ns_file_name, 'a') as nf:
nf.write(
"$ns duplex-link $" + cluster_two_switch_node + " $" + cluster_two_node_list[0] + " 200.0Mb 10ms DropTail\n")
nf.write("$ns queue-limit $" + cluster_two_switch_node + " $" + cluster_two_node_list[0] + " 50\n")
with open(ns_file_name, 'a') as nf:
for i in range(1, len(cluster_two_node_list)):
nf.write("$ns duplex-link $" + cluster_two_node_list[i - 1] + " $" + cluster_two_node_list[
i] + " 100.0Mb 10ms DropTail\n")
nf.write("$ns queue-limit $" + cluster_two_node_list[i - 1] + " $" + cluster_two_node_list[i] + " 50\n")
with open(ns_file_name, 'a') as nf:
nf.write(
"$ns duplex-link $" + cluster_two_node_list[(len(cluster_two_node_list) - 1)] + " $" + cluster_two_node_list[
0] + " 200.0Mb 10ms DropTail\n")
nf.write(
"$ns queue-limit $" + cluster_two_node_list[(len(cluster_two_node_list) - 1)] + " $" + cluster_two_node_list[
0] + " 50\n")
## Cluster 3 connection (all directly to switch)
with open(ns_file_name, 'a') as nf:
for i in range(0, len(cluster_three_node_list)):
nf.write("$ns duplex-link $" + cluster_three_switch_node + " $" + cluster_three_node_list[
i] + " 100.0Mb 10ms DropTail\n")
nf.write("$ns queue-limit $" + cluster_three_switch_node + " $" + cluster_three_node_list[i] + " 50\n")
##Cluster 4 connection (two-part)
with open(ns_file_name, 'a') as nf:
nf.write(
"$ns duplex-link $" + cluster_four_switch_node + " $" + cluster_four_node_list[0] + " 200.0Mb 10ms DropTail\n")
nf.write("$ns queue-limit $" + cluster_four_switch_node + " $" + cluster_four_node_list[0] + " 50\n")
# determine separation
with open(ns_file_name, 'a') as nf:
for i in range(1, int(CLUSTER_FOUR_NODE_POPULATION // 2) + 1):
nf.write("$ns duplex-link $" + cluster_four_node_list[0] + " $" + cluster_four_node_list[
i] + " 200.0Mb 10ms DropTail\n")
nf.write("$ns queue-limit $" + cluster_four_node_list[0] + " $" + cluster_four_node_list[i] + " 50\n")
for i in range(int(CLUSTER_FOUR_NODE_POPULATION // 2) + 1, CLUSTER_FOUR_NODE_POPULATION):
nf.write("$ns duplex-link $" + cluster_four_node_list[int(CLUSTER_FOUR_NODE_POPULATION // 2)] + " $" +
cluster_four_node_list[i] + " 200.0Mb 10ms DropTail\n")
nf.write("$ns queue-limit $" + cluster_four_node_list[int(CLUSTER_FOUR_NODE_POPULATION // 2)] + " $" +
cluster_four_node_list[i] + " 50\n")
# # Cluster 5 connection (wireless) [Wired for now as we were having problems in connecting wireless with the asset.]
with open(ns_file_name, 'a') as nf:
nf.write("$ns duplex-link $" + cluster_five_switch_node + " $" + wireless_cluster_five_node_list[
0] + " 200.0Mb 10ms DropTail\n")
nf.write("$ns queue-limit $" + cluster_five_switch_node + " $" + wireless_cluster_five_node_list[0] + " 50\n")
with open(ns_file_name, 'a') as nf:
for i in range(0, len(wireless_cluster_five_node_list)):
for j in range(i + 1, len(wireless_cluster_five_node_list)):
if j == len(wireless_cluster_five_node_list):
break
else:
nf.write(
"$ns duplex-link $" + wireless_cluster_five_node_list[i] + " $" + wireless_cluster_five_node_list[
j] + " 200.0Mb 10ms DropTail\n")
nf.write(
"$ns queue-limit $" + wireless_cluster_five_node_list[i] + " $" + wireless_cluster_five_node_list[
j] + " 50\n")
## | |
#!/usr/bin/env python
"""Provides class Actor with the function approximator (NN) of the Actor
Actor creates the Neural Network model with Tensorflow and it can train the network online.
The user can decide the number of layers, the number of neurons, the batch size and the number
of epochs and activation functions.
"""
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten
"----------------------------------------------------------------------------------------------------------------------"
__author__ = "<NAME>"
__copyright__ = "Copyright (C) 2020 <NAME>"
__credits__ = []
__license__ = "MIT"
__version__ = "2.0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Production"
"----------------------------------------------------------------------------------------------------------------------"
class Actor:
# Class attributes
# Attributes related to RMSprop
beta_rmsprop = 0.999
epsilon = 1e-8
# Attributes related to the momentum
beta_momentum = 0.9
def __init__(self, selected_inputs, selected_states, tracking_states, indices_tracking_states,
number_time_steps, start_training, layers=(6, 1), activations=('sigmoid', 'sigmoid'),
learning_rate=0.9, learning_rate_cascaded=0.9, learning_rate_exponent_limit=10,
type_PE='3211', amplitude_3211=1, pulse_length_3211=15, WB_limits=30,
maximum_input=25, maximum_q_rate=20, cascaded_actor=False, NN_initial=None):
self.number_inputs = len(selected_inputs)
self.selected_states = selected_states
self.number_states = len(selected_states)
self.number_tracking_states = len(tracking_states)
self.indices_tracking_states = indices_tracking_states
self.xt = None
self.xt_ref = None
self.ut = 0
self.maximum_input = maximum_input
self.maximum_q_rate = maximum_q_rate
# Attributes related to time
self.number_time_steps = number_time_steps
self.time_step = 0
self.start_training = start_training
# Attributes related to the NN
self.model = None
self.model_q = None
if layers[-1] != 1:
raise Exception("The last layer should have a single neuron.")
elif len(layers) != len(activations):
raise Exception("The number of layers needs to be equal to the number of activations.")
self.layers = layers
self.activations = activations
self.learning_rate = learning_rate
self.learning_rate_cascaded = learning_rate_cascaded
self.learning_rate_0 = learning_rate
self.learning_rate_exponent_limit = learning_rate_exponent_limit
self.WB_limits = WB_limits
self.NN_initial = NN_initial
# Attributes related to the persistent excitation
self.type_PE = type_PE
self.amplitude_3211 = amplitude_3211
self.pulse_length_3211 = pulse_length_3211
# Attributes related to the training of the NN
self.dut_dWb = None
self.dut_dWb_1 = None
# Attributes related to the Adam optimizer
self.Adam_opt = None
# Attributes related to the momentum
self.momentum_dict = {}
# Attributes related to RMSprop
self.rmsprop_dict = {}
# Declaration of the storage arrays for the weights
self.store_weights = {}
self.store_weights_q = {}
# Attributes for the cascaded actor
self.cascaded_actor = cascaded_actor
self.dut_dq_ref = None
self.dq_ref_dWb = None
self.store_q = np.zeros((1, self.number_time_steps))
def build_actor_model(self):
"""
Function that creates the actor ANN architecture. It is a densely connected neural network. The user
can decide the number of layers, the number of neurons, as well as the activation function.
:return:
"""
# First Neural Network
self.model, self.store_weights = self.create_NN(self.store_weights)
# Second Neural Network for the cascaded actor
if self.cascaded_actor:
print("It is assumed that the input to the NNs is the tracking error.")
tracking_states = ['alpha', 'q']
self.indices_tracking_states = [self.selected_states.index(tracking_states[i]) for i in
range(len(tracking_states))]
self.number_tracking_states = len(tracking_states)
self.model_q, self.store_weights_q = self.create_NN(self.store_weights_q)
for count in range(len(self.model.trainable_variables) * 2):
self.momentum_dict[count] = 0
self.rmsprop_dict[count] = 0
def create_NN(self, store_weights):
"""
Creates a NN given the user input
:param store_weights: dictionary containing weights and biases
:return: model --> the created NN model
store_weights --> the dictionary that contains the updated weights and biases.
"""
# initializer = tf.keras.initializers.GlorotNormal()
initializer = tf.keras.initializers.VarianceScaling(
scale=0.01, mode='fan_in', distribution='truncated_normal', seed=self.NN_initial)
model = tf.keras.Sequential()
model.add(Flatten(input_shape=(self.number_tracking_states, 1), name='Flatten_1'))
model.add(Dense(self.layers[0], activation=self.activations[0], kernel_initializer=initializer,
name='dense_1'))
store_weights['W1'] = np.zeros((self.number_tracking_states * self.layers[0], self.number_time_steps + 1))
store_weights['W1'][:, self.time_step] = model.trainable_variables[0].numpy().flatten()
for counter, layer in enumerate(self.layers[1:]):
model.add(Dense(self.layers[counter + 1], activation=self.activations[counter + 1],
kernel_initializer=initializer, name='dense_' + str(counter + 2)))
store_weights['W' + str(counter + 2)] = np.zeros(
(self.layers[counter] * self.layers[counter + 1], self.number_time_steps + 1))
store_weights['W' + str(counter + 2)][:, self.time_step] = model.trainable_variables[
(counter + 1) * 2].numpy().flatten()
return model, store_weights
def run_actor_online(self, xt, xt_ref):
"""
Generate input to the system with the reference and real states.
:param xt: current time_step states
:param xt_ref: current time step reference states
:return: ut --> input to the system and the incremental model
"""
if self.cascaded_actor:
self.xt = xt
self.xt_ref = xt_ref
tracked_states = np.reshape(xt[self.indices_tracking_states[0], :], [-1, 1])
alphat_error = np.reshape(tracked_states - xt_ref, [-1, 1])
nn_input_alpha = tf.constant(np.array([(alphat_error)]).astype('float32'))
with tf.GradientTape() as tape:
tape.watch(self.model.trainable_variables)
q_ref = self.model(nn_input_alpha)
self.dq_ref_dWb = tape.gradient(q_ref, self.model.trainable_variables)
if self.activations[-1] == 'sigmoid':
q_ref = max(min((2 * self.maximum_q_rate * q_ref.numpy()) - self.maximum_q_rate,
np.reshape(self.maximum_q_rate, q_ref.numpy().shape)),
np.reshape(-self.maximum_q_rate, q_ref.numpy().shape))
elif self.activations[-1] == 'tanh':
q_ref = max(min((self.maximum_q_rate * q_ref.numpy()),
np.reshape(self.maximum_q_rate, q_ref.numpy().shape)),
np.reshape(-self.maximum_q_rate, q_ref.numpy().shape))
self.store_q[:, self.time_step] = q_ref
tracked_states_q = np.reshape(xt[self.indices_tracking_states[1], :], [-1, 1])
qt_error = np.reshape(tracked_states_q - np.reshape(q_ref, tracked_states_q.shape), [-1, 1])
nn_input_q = tf.constant(np.array([(qt_error)]).astype('float32'))
with tf.GradientTape() as tape:
tape.watch(nn_input_q)
ut = self.model_q(nn_input_q)
self.dut_dq_ref = tape.gradient(ut, nn_input_q)
with tf.GradientTape() as tape:
tape.watch(self.model_q.trainable_variables)
ut = self.model_q(nn_input_q)
self.dut_dWb = tape.gradient(ut, self.model_q.trainable_variables)
else:
self.xt = xt
self.xt_ref = xt_ref
tracked_states = np.reshape(xt[self.indices_tracking_states, :], [-1, 1])
xt_error = np.reshape(tracked_states - xt_ref, [-1, 1])
nn_input = tf.constant(np.array([(xt_error)]).astype('float32'))
with tf.GradientTape() as tape:
tape.watch(self.model.trainable_variables)
ut = self.model(nn_input)
self.dut_dWb = tape.gradient(ut, self.model.trainable_variables)
e0 = self.compute_persistent_excitation()
if self.activations[-1] == 'sigmoid':
self.ut = max(min((2 * self.maximum_input * ut.numpy()) - self.maximum_input + e0,
np.reshape(self.maximum_input, ut.numpy().shape)),
np.reshape(-self.maximum_input, ut.numpy().shape))
elif self.activations[-1] == 'tanh':
ut = max(min((self.maximum_input * ut.numpy()),
np.reshape(self.maximum_input, ut.numpy().shape)),
np.reshape(-self.maximum_input, ut.numpy().shape))
self.ut = max(min(ut + e0,
np.reshape(self.maximum_input, ut.shape)),
np.reshape(-self.maximum_input, ut.shape))
return self.ut
def train_actor_online(self, Jt1, dJt1_dxt1, G):
"""
Obtains the elements of the chain rule, computes the gradient and applies it to the corresponding weights and
biases.
:param Jt1: dEa/dJ
:param dJt1_dxt1: dJ/dx
:param G: dx/du, obtained from the incremental model
:return:
"""
Jt1 = Jt1.flatten()[0]
chain_rule = Jt1 * np.matmul(np.reshape(G[self.indices_tracking_states, :], [-1, 1]).T, dJt1_dxt1)
chain_rule = chain_rule.flatten()[0]
for count in range(len(self.dut_dWb)):
update = chain_rule * self.dut_dWb[count]
self.model.trainable_variables[count].assign_sub(np.reshape(self.learning_rate * update,
self.model.trainable_variables[count].shape))
# Implement WB_limits: the weights and biases can not have values whose absolute value exceeds WB_limits
self.model = self.check_WB_limits(count, self.model)
def train_actor_online_adaptive_alpha(self, Jt1, dJt1_dxt1, G, incremental_model, critic, xt_ref1):
"""
Train the actor with an adaptive alpha depending on the sign and magnitude of the network errors
:param Jt1: the evaluation of the critic with the next time step prediction of the incremental model
:param dJt1_dxt1: the gradient of the critic network with respect to the next time prediction of the incremental model
:param G: the input distribution matrix
:param incremental_model: the incremental model
:param critic: the critic
:param xt_ref1: reference states at the next time step
:return:
"""
Ec_actor_before = 0.5 * np.square(Jt1)
weight_cache = [tf.Variable(self.model.trainable_variables[i].numpy()) for i in
range(len(self.model.trainable_variables))]
network_improvement = False
n_reductions = 0
while not network_improvement and self.time_step > self.start_training:
# Train the actor
self.train_actor_online(Jt1, dJt1_dxt1, G)
# Code for checking if the actor NN error with the new weights has changed sign
ut_after = self.evaluate_actor()
xt1_est_after = incremental_model.evaluate_incremental_model(ut_after)
Jt1_after, _ = critic.evaluate_critic(xt1_est_after, xt_ref1)
Ec_actor_after = 0.5 * np.square(Jt1_after)
# Code for checking whether the learning rate of the actor should be halved
if Ec_actor_after <= Ec_actor_before or n_reductions > 10:
network_improvement = True
if np.sign(Jt1) == np.sign(Jt1_after):
self.learning_rate = min(2 * self.learning_rate,
self.learning_rate_0 * 2**self.learning_rate_exponent_limit)
else:
n_reductions += 1
self.learning_rate = max(self.learning_rate / 2,
self.learning_rate_0/2**self.learning_rate_exponent_limit)
for WB_count in range(len(self.model.trainable_variables)):
self.model.trainable_variables[WB_count].assign(weight_cache[WB_count].numpy())
def train_actor_online_adam(self, Jt1, dJt1_dxt1, G, incremental_model, critic, xt_ref1):
"""
Train the actor with the Adam optimizer .
:param Jt1: the evaluation of the critic with the next time step prediction of the incremental model
:param dJt1_dxt1: the gradient of the critic network with respect to the next time prediction of the incremental model
:param G: the input distribution matrix
:param incremental_model: the incremental model
:param critic: the critic
:param xt_ref1: reference states at the next time step
:return:
"""
if self.cascaded_actor:
# Train the actor
Jt1 = Jt1.flatten()[0]
chain_rule = Jt1 * np.matmul(np.reshape(G[self.indices_tracking_states[0], :], [-1, 1]).T, dJt1_dxt1)
chain_rule = chain_rule.flatten()[0]
if self.time_step > self.start_training and np.abs(self.ut) < 25:
for count in range(len(self.dut_dWb)):
if self.activations[-1] == 'sigmoid':
gradient = 2 * self.maximum_input * chain_rule * self.dut_dWb[count]
elif self.activations[-1] == 'tanh':
gradient = self.maximum_input * chain_rule * self.dut_dWb[count]
else:
raise Exception("There is no code for the defined output activation function.")
self.model_q, self.learning_rate_cascaded = self.compute_Adam_update(count, gradient,
self.model_q,
self.learning_rate_cascaded)
for count in range(len(self.dq_ref_dWb)):
if self.activations[-1] == 'sigmoid':
gradient = -2 * self.maximum_q_rate * chain_rule * self.dut_dq_ref * self.dq_ref_dWb[count]
elif self.activations[-1] == 'tanh':
gradient = -self.maximum_q_rate * chain_rule * self.dut_dq_ref * self.dq_ref_dWb[count]
else:
raise Exception("There is no code for the defined output activation function.")
self.model, self.learning_rate = self.compute_Adam_update(count, gradient,
self.model, self.learning_rate)
# Code for checking if the actor | |
import sys
sys.path.insert(0, "/home/hardik/dl_exp/nglod/sdf-net/lib/submodules/libigl/python/")
import pyigl as igl
from decimal import *
import iglhelpers
# import miniball
import math
import numpy as np
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
from scipy.stats import gaussian_kde
import matplotlib.cm as cm
#constants used for sampling box AND miniball normalization
BOUNDING_SPHERE_RADIUS = 0.9
SAMPLE_SPHERE_RADIUS = 1.0
class CubeMarcher():
def __init__(self):
self._rV = igl.eigen.MatrixXd()
self._rF = igl.eigen.MatrixXi()
self.hasMarched = False
def march(self, pts, sdf):
res = round(pts.shape[0]**(1/3))
v = iglhelpers.p2e(pts)
s = iglhelpers.p2e(sdf)
igl.copyleft.marching_cubes(s, v, res, res, res, self._rV, self._rF)
self.hasMarched = True
def createGrid(self, res):
K = np.linspace(
-SAMPLE_SPHERE_RADIUS,
SAMPLE_SPHERE_RADIUS,
res
)
grid = [[x,y,z] for x in K for y in K for z in K]
return np.array(grid)
def getMesh(self, viewer = None):
if self.hasMarched:
V = self._rV
F = self._rF
else:
raise("Mesh has not been marched!")
if viewer is None:
return Mesh(V=V.copy(), F=F.copy(), doNormalize=False)
return Mesh(V=V.copy(), F=F.copy(), doNormalize=False, viewer=viewer)
# class PointSampler():
# def __init__(self, mesh, ratio = 0.0, std=0.0, verticeSampling=False, importanceSampling=False):
# self._V = iglhelpers.e2p(mesh.V())
# self._F = iglhelpers.e2p(mesh.F())
# self._sampleVertices = verticeSampling
# if ratio < 0 or ratio > 1:
# raise(ValueError("Ratio must be [0,1]"))
# self._ratio = ratio
# if std < 0 or std > 1:
# raise(ValueError("Normal deviation must be [0,1]"))
# self._std = std
# self._calculateFaceBins()
# def _calculateFaceBins(self):
# """Calculates and saves face area bins for sampling against"""
# vc = np.cross(
# self._V[self._F[:, 0], :] - self._V[self._F[:, 2], :],
# self._V[self._F[:, 1], :] - self._V[self._F[:, 2], :])
# A = np.sqrt(np.sum(vc ** 2, 1))
# FA = A / np.sum(A)
# self._faceBins = np.concatenate(([0],np.cumsum(FA)))
# def _surfaceSamples(self,n):
# """Returns n points uniformly sampled from surface of mesh"""
# R = np.random.rand(n) #generate number between [0,1]
# sampleFaceIdxs = np.array(np.digitize(R,self._faceBins)) -1
# #barycentric coordinates for each face for each sample :)
# #random point within face for each sample
# r = np.random.rand(n, 2)
# A = self._V[self._F[sampleFaceIdxs, 0], :]
# B = self._V[self._F[sampleFaceIdxs, 1], :]
# C = self._V[self._F[sampleFaceIdxs, 2], :]
# P = (1 - np.sqrt(r[:,0:1])) * A \
# + np.sqrt(r[:,0:1]) * (1 - r[:,1:]) * B \
# + np.sqrt(r[:,0:1]) * r[:,1:] * C
# return P
# def _verticeSamples(self, n):
# """Returns n random vertices of mesh"""
# verts = np.random.choice(len(self._V), n)
# return self._V[verts]
# def _normalDist(self, V):
# """Returns normal distribution about each point V"""
# if self._std > 0.0:
# return np.random.normal(loc = V,scale = self._std)
# return V
# def _randomSamples(self, n):
# """Returns n random points in unit sphere"""
# # we want to return points in unit sphere, could do using spherical coords
# # but rejection method is easier and arguably faster :)
# points = np.array([])
# while points.shape[0] < n:
# remainingPoints = n - points.shape[0]
# p = (np.random.rand(remainingPoints,3) - 0.5)*2
# #p = p[np.linalg.norm(p, axis=1) <= SAMPLE_SPHERE_RADIUS]
# if points.size == 0:
# points = p
# else:
# points = np.concatenate((points, p))
# return points
# def sample(self,n):
# """Returns n points according to point sampler settings"""
# nRandom = round(Decimal(n)*Decimal(self._ratio))
# nSurface = n - nRandom
# xRandom = self._randomSamples(nRandom)
# if nSurface > 0:
# if self._sampleVertices:
# # for comparison later :)
# xSurface = self._verticeSamples(nSurface)
# else:
# xSurface = self._surfaceSamples(nSurface)
# xSurface = self._normalDist(xSurface)
# if nRandom > 0:
# x = np.concatenate((xSurface,xRandom))
# else:
# x = xSurface
# else:
# x = xRandom
# np.random.shuffle(x) #remove bias on order
# return x
# class ImportanceSampler():
# # M, initital uniform set size, N subset size.
# def __init__(self, mesh, M, W):
# self.M = M # uniform sample set size
# self.W = W # sample weight...
# if (not mesh is None):
# #if mesh given, we can create our own uniform sampler
# self.uniformSampler = PointSampler(mesh, ratio=1.0) # uniform sampling
# self.sdf = SDF(mesh)
# else:
# # otherwise we assume uniform samples (and the sdf val) will be passed in.
# self.uniformSampler = None
# self.sdf = None
# def _subsample(self, s, N):
# # weighted by exp distance to surface
# w = np.exp(-self.W*np.abs(s))
# # probabilities to choose each
# pU = w / np.sum(w)
# # exclusive sum
# C = np.concatenate(([0],np.cumsum(pU)))
# C = C[0:-1]
# # choose N random buckets
# R = np.random.rand(N)
# # histc
# I = np.array(np.digitize(R,C)) - 1
# return I
# ''' importance sample a given mesh, M uniform samples, N subset based on importance'''
# def sample(self, N):
# if (self.uniformSampler is None):
# raise("No mesh supplied, cannot run importance sampling...")
# #uniform samples
# U = self.uniformSampler.sample(self.M)
# s = self.sdf.query(U)
# I = self._subsample(s, N)
# R = np.random.choice(len(U), int(N*0.1))
# S = U[I,:]#np.concatenate((U[I,:],U[R, :]), axis=0)
# return S
# ''' sampling against a supplied U set, where s is sdf at each U'''
# def sampleU(self, N, U, s):
# I = self._subsample(s, N)
# q = U[I,:]
# d = s[I]
# return U[I,:], s[I]
# class SDF():
# _V = igl.eigen.MatrixXd()
# _F = igl.eigen.MatrixXi()
# def __init__(self, mesh, signType = 'fast_winding_number', doPrecompute=True):
# self._V = mesh.V()
# self._F = mesh.F()
# self._precomputed = False
# if signType == 'fast_winding_number':
# self._signType = igl.SIGNED_DISTANCE_TYPE_FAST_WINDING_NUMBER
# if doPrecompute:
# self._tree = igl.AABB()
# self._fwn_bvh = igl.FastWindingNumberBVH()
# print("[INFO] Precomuting bvh trees...")
# self._tree.init(self._V,self._F)
# igl.fast_winding_number(self._V,self._F,2,self._fwn_bvh)
# print("[INFO] Done precomputing")
# self._precomputed = True
# elif signType == 'pseudonormal':
# self._signType = igl.SIGNED_DISTANCE_TYPE_PSEUDONORMAL
# else:
# raise("Invalid signing type given")
# def query(self, queries):
# """Returns numpy array of SDF values for each point in queries"""
# queryV = iglhelpers.p2e(queries)
# S = igl.eigen.MatrixXd()
# B = igl.eigen.MatrixXd()
# I = igl.eigen.MatrixXi()
# C = igl.eigen.MatrixXd()
# N = igl.eigen.MatrixXd()
# if self._precomputed and self._signType == igl.SIGNED_DISTANCE_TYPE_FAST_WINDING_NUMBER:
# # generate samples from precomputed bvh's
# print("[INFO] Generating SDFs")
# igl.signed_distance_fast_winding_number(
# queryV,
# self._V,
# self._F,
# self._tree,
# self._fwn_bvh,
# S
# )
# print("[INFO] SDFs done")
# else:
# igl.signed_distance(
# queryV,
# self._V,
# self._F,
# self._signType,
# S,
# I,
# C,
# N
# )
# return iglhelpers.e2p(S)
class Mesh():
_V = igl.eigen.MatrixXd()
_F = igl.eigen.MatrixXi()
_normalized = False
def __init__(
self,
meshPath=None,
V=None,
F=None,
viewer = None,
doNormalize = True):
if meshPath == None:
if V == None or F == None:
raise("Mesh path or Mesh data must be given")
else:
self._V = V
self._F = F
# self._normalizeMesh()
else:
self._loadMesh(meshPath,doNormalize)
self._viewer = viewer
def _loadMesh(self, fp, doNormalize):
#load mesh
igl.read_triangle_mesh(fp, self._V, self._F)
if doNormalize:
self._normalizeMesh()
def V(self):
return self._V.copy()
def F(self):
return self._F.copy()
# def _normalizeMesh(self):
# mb = miniball.Miniball(iglhelpers.e2p(self._V))
# scale = BOUNDING_SPHERE_RADIUS / math.sqrt(mb.squared_radius())
# T = igl.eigen.Affine3d()
# T.setIdentity()
# T.translate(
# igl.eigen.MatrixXd(
# [
# -mb.center()[0] * scale,
# -mb.center()[1] * scale,
# -mb.center()[2] * scale
# ]
# )
# )
# print("[INFO] scaled down by", scale)
# Vscale = T.matrix().block(0,0,3,3).transpose()
# Vtrans = igl.eigen.MatrixXd(self._V.rows(), self._V.cols())
# Vtrans.rowwiseSet(T.matrix().block(0,3,3,1).transpose())
# self._V = (self._V*Vscale)*scale + Vtrans
def show(self, doLaunch = False):
if self._viewer == None:
self._viewer = igl.glfw.Viewer()
self._viewer.data(0).set_mesh(self._V,self._F)
if doLaunch:
self._viewer.launch()
def save(self, fp):
igl.writeOBJ(fp,self._V,self._F)
# def normSDF(S, minVal=None,maxVal=None):
# if minVal is None:
# minVal = np.min(S)
# maxVal = np.max(S)
# # we don't shift. Keep 0 at 0.
# S = np.array([item for sublist in S for item in sublist])
# #S[S<0] = -(S[S<0] / minVal)
# #S[S>0] = (S[S>0] / maxVal)
# #S = (S + 1)/2
# S[S<0] = -0.8
# S[S>0] = 0.8
# return S
# def createAx(idx):
# subplot = pyplot.subplot(idx, projection='3d')
# subplot.set_xlim((-1,1))
# subplot.set_ylim((-1,1))
# subplot.set_zlim((-1,1))
# subplot.view_init(elev=10, azim=100)
# subplot.axis('off')
# subplot.dist = 8
# return subplot
# def createAx2d(idx):
# subplot = pyplot.subplot(idx)
# subplot.set_xlim((-1,1))
# subplot.set_ylim((-1,1))
# subplot.axis('off')
# return subplot
# def plotCube(ax):
# # draw cube
# r = [-1, 1]
# from itertools import product, combinations
# for s, e in combinations(np.array(list(product(r, r, r))), 2):
# if np.sum(np.abs(s-e)) == r[1]-r[0]:
# ax.plot3D(*zip(s, e), color="black")
# def density(U):
# c = gaussian_kde(np.transpose(U))(np.transpose(U))
# return c
# def plotMesh(ax, mesh, N=10000):
# surfaceSampler = PointSampler(mesh, ratio=0.0, std=0.0)
# surfaceSamples = surfaceSampler.sample(N)
# x,y,z = np.hsplit(surfaceSamples,3)
# ax.scatter(x,z,y, c='black', marker='.')
# def plotSamples(ax, U, c, vmin = -1, is2d = False):
# x,y,z = np.hsplit(U,3)
# ax.scatter(x,y,z,c=c, marker='.',cmap='coolwarm', norm=None, vmin=vmin, vmax=1)
# def importanceSamplingComparisonPlot(mesh,sdf):
# fig = pyplot.figure(figsize=(30,10))
# axUniform = createAx(131)
# axSurface = createAx(132)
# axImportance = createAx(133)
# plotCube(axUniform)
# plotCube(axSurface)
# plotCube(axImportance)
# #plotMesh(axUniform,mesh)
# #plotMesh(axImportance,mesh)
# #plotMesh(axSurface,mesh)
# # plot uniform sampled
# uniformSampler = PointSampler(mesh, ratio = 1.0)
# U = uniformSampler.sample(10000)
# SU = sdf.query(U)
# c = normSDF(SU)
# plotSamples(axUniform, U,c)
# # plot surface + noise sampling
# sampler = PointSampler(mesh, ratio = 0.1, std = 0.01, verticeSampling=False)
# p = sampler.sample(10000)
# S = sdf.query(p)
# c = normSDF(S, np.min(SU), np.max(SU))
# plotSamples(axSurface, p,c)
# # plot importance
# importanceSampler = ImportanceSampler(mesh, 100000, 20)
# p = importanceSampler.sample(10000)
# S = sdf.query(p)
# c = normSDF(S, np.min(SU), np.max(SU))
# plotSamples(axImportance, p,c)
# fig.patch.set_visible(False)
# pyplot.axis('off')
# pyplot.show()
# def beforeAndAfterPlot(mesh,sdf):
# fig = pyplot.figure(figsize=(10,10))
# fig.patch.set_visible(False)
# | |
# copytrue (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .. import workspace_pb2 as w
import os
import os.path as osp
import shutil
import time
import pickle
import json
import multiprocessing as mp
import xlwt
import numpy as np
from ..utils import set_folder_status, TaskStatus, get_folder_status, is_available, get_ip, trans_name
from .train.params import ClsParams, DetParams, SegParams
from paddlex_restful.restful.dataset.utils import get_encoding
def create_task(data, workspace):
"""根据request创建task。
Args:
data为dict,key包括
'pid'所属项目id, 'train'训练参数。训练参数和数据增强参数以pickle的形式保存
在任务目录下的params.pkl文件中。 'parent_id'(可选)该裁剪训练任务的父任务,
'desc'(可选)任务描述。
"""
create_time = time.time()
time_array = time.localtime(create_time)
create_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
id = workspace.max_task_id + 1
workspace.max_task_id = id
if id < 10000:
id = 'T%04d' % id
else:
id = 'T{}'.format(id)
pid = data['pid']
assert pid in workspace.projects, "【任务创建】项目ID'{}'不存在.".format(pid)
assert not id in workspace.tasks, "【任务创建】任务ID'{}'已经被占用.".format(id)
did = workspace.projects[pid].did
assert did in workspace.datasets, "【任务创建】数据集ID'{}'不存在".format(did)
path = osp.join(workspace.projects[pid].path, id)
if not osp.exists(path):
os.makedirs(path)
set_folder_status(path, TaskStatus.XINIT)
data['task_type'] = workspace.projects[pid].type
data['dataset_path'] = workspace.datasets[did].path
data['pretrain_weights_download_save_dir'] = osp.join(workspace.path,
'pretrain')
#获取参数
if 'train' in data:
params_json = json.loads(data['train'])
if (data['task_type'] == 'classification'):
params_init = ClsParams()
if (data['task_type'] == 'detection' or
data['task_type'] == 'instance_segmentation'):
params_init = DetParams()
if (data['task_type'] == 'segmentation' or
data['task_type'] == 'remote_segmentation'):
params_init = SegParams()
params_init.load_from_dict(params_json)
data['train'] = params_init
parent_id = ''
if 'parent_id' in data:
data['tid'] = data['parent_id']
parent_id = data['parent_id']
assert data['parent_id'] in workspace.tasks, "【任务创建】裁剪任务创建失败".format(
data['parent_id'])
r = get_task_params(data, workspace)
train_params = r['train']
data['train'] = train_params
desc = ""
if 'desc' in data:
desc = data['desc']
with open(osp.join(path, 'params.pkl'), 'wb') as f:
pickle.dump(data, f)
task = w.Task(
id=id,
pid=pid,
path=path,
create_time=create_time,
parent_id=parent_id,
desc=desc)
workspace.tasks[id].CopyFrom(task)
with open(os.path.join(path, 'info.pb'), 'wb') as f:
f.write(task.SerializeToString())
return {'status': 1, 'tid': id}
def delete_task(data, workspace):
"""删除task。
Args:
data为dict,key包括
'tid'任务id
"""
task_id = data['tid']
assert task_id in workspace.tasks, "任务ID'{}'不存在.".format(task_id)
if osp.exists(workspace.tasks[task_id].path):
shutil.rmtree(workspace.tasks[task_id].path)
del workspace.tasks[task_id]
return {'status': 1}
def get_task_params(data, workspace):
"""根据request获取task的参数。
Args:
data为dict,key包括
'tid'任务id
"""
tid = data['tid']
assert tid in workspace.tasks, "【任务创建】任务ID'{}'不存在.".format(tid)
path = workspace.tasks[tid].path
with open(osp.join(path, 'params.pkl'), 'rb') as f:
task_params = pickle.load(f)
return {'status': 1, 'train': task_params['train']}
def list_tasks(data, workspace):
'''列出任务列表,可request的参数进行筛选
Args:
data为dict, 包括
'pid'(可选)所属项目id
'''
task_list = list()
for key in workspace.tasks:
task_id = workspace.tasks[key].id
task_name = workspace.tasks[key].name
task_desc = workspace.tasks[key].desc
task_pid = workspace.tasks[key].pid
task_path = workspace.tasks[key].path
task_create_time = workspace.tasks[key].create_time
task_type = workspace.projects[task_pid].type
from .operate import get_task_status
path = workspace.tasks[task_id].path
status, message = get_task_status(path)
if data is not None:
if "pid" in data:
if data["pid"] != task_pid:
continue
attr = {
"id": task_id,
"name": task_name,
"desc": task_desc,
"pid": task_pid,
"path": task_path,
"create_time": task_create_time,
"status": status.value,
'type': task_type
}
task_list.append(attr)
return {'status': 1, 'tasks': task_list}
def set_task_params(data, workspace):
"""根据request设置task的参数。只有在task是TaskStatus.XINIT状态时才有效
Args:
data为dict,key包括
'tid'任务id, 'train'训练参数. 训练
参数和数据增强参数以pickle的形式保存在任务目录下的params.pkl文件
中。
"""
tid = data['tid']
train = data['train']
assert tid in workspace.tasks, "【任务创建】任务ID'{}'不存在.".format(tid)
path = workspace.tasks[tid].path
status = get_folder_status(path)
assert status == TaskStatus.XINIT, "该任务不在初始化阶段,设置参数失败"
with open(osp.join(path, 'params.pkl'), 'rb') as f:
task_params = pickle.load(f)
train_json = json.loads(train)
task_params['train'].load_from_dict(train_json)
with open(osp.join(path, 'params.pkl'), 'wb') as f:
pickle.dump(task_params, f)
return {'status': 1}
def get_default_params(data, workspace, machine_info):
from .train.params_v2 import get_params
from ..dataset.dataset import get_dataset_details
pid = data['pid']
assert pid in workspace.projects, "项目ID{}不存在.".format(pid)
project_type = workspace.projects[pid].type
did = workspace.projects[pid].did
result = get_dataset_details({'did': did}, workspace)
if result['status'] == 1:
details = result['details']
else:
raise Exception("Fail to get dataset details!")
train_num = len(details['train_files'])
class_num = len(details['labels'])
if machine_info['gpu_num'] == 0:
gpu_num = 0
per_gpu_memory = 0
gpu_list = None
else:
if 'gpu_list' in data:
gpu_list = data['gpu_list']
gpu_num = len(gpu_list)
per_gpu_memory = None
for gpu_id in gpu_list:
if per_gpu_memory is None:
per_gpu_memory = machine_info['gpu_free_mem'][gpu_id]
elif machine_info['gpu_free_mem'][gpu_id] < per_gpu_memory:
per_gpu_memory = machine_info['gpu_free_mem'][gpu_id]
else:
gpu_num = 1
per_gpu_memory = machine_info['gpu_free_mem'][0]
gpu_list = [0]
params = get_params(data, project_type, train_num, class_num, gpu_num,
per_gpu_memory, gpu_list)
return {"status": 1, "train": params}
def get_task_params(data, workspace):
"""根据request获取task的参数。
Args:
data为dict,key包括
'tid'任务id
"""
tid = data['tid']
assert tid in workspace.tasks, "【任务创建】任务ID'{}'不存在.".format(tid)
path = workspace.tasks[tid].path
with open(osp.join(path, 'params.pkl'), 'rb') as f:
task_params = pickle.load(f)
return {'status': 1, 'train': task_params['train']}
def get_task_status(data, workspace):
""" 获取任务状态
Args:
data为dict, key包括
'tid'任务id, 'resume'(可选):获取是否可以恢复训练的状态
"""
from .operate import get_task_status, get_task_max_saved_epochs
tid = data['tid']
assert tid in workspace.tasks, "任务ID'{}'不存在".format(tid)
path = workspace.tasks[tid].path
status, message = get_task_status(path)
task_pid = workspace.tasks[tid].pid
task_type = workspace.projects[task_pid].type
if 'resume' in data:
max_saved_epochs = get_task_max_saved_epochs(path)
params = {'tid': tid}
results = get_task_params(params, workspace)
total_epochs = results['train'].num_epochs
resumable = max_saved_epochs > 0 and max_saved_epochs < total_epochs
return {
'status': 1,
'task_status': status.value,
'message': message,
'resumable': resumable,
'max_saved_epochs': max_saved_epochs,
'type': task_type
}
return {
'status': 1,
'task_status': status.value,
'message': message,
'type': task_type
}
def get_train_metrics(data, workspace):
""" 获取任务日志
Args:
data为dict, key包括
'tid'任务id
Return:
train_log(dict): 'eta':剩余时间,'train_metrics': 训练指标,'eval_metircs': 评估指标,
'download_status': 下载模型状态,'eval_done': 是否已保存模型,'train_error': 训练错误原因
"""
tid = data['tid']
assert tid in workspace.tasks, "任务ID'{}'不存在".format(tid)
from ..utils import TrainLogReader
task_path = workspace.tasks[tid].path
log_file = osp.join(task_path, 'out.log')
train_log = TrainLogReader(log_file)
train_log.update()
train_log = train_log.__dict__
return {'status': 1, 'train_log': train_log}
def get_eval_metrics(data, workspace):
""" 获取任务日志
Args:
data为dict, key包括
'tid'父任务id
"""
tid = data['tid']
assert tid in workspace.tasks, "任务ID'{}'不存在".format(tid)
best_model_path = osp.join(workspace.tasks[tid].path, "output",
"best_model", "model.yml")
import yaml
f = open(best_model_path, "r", encoding="utf-8")
eval_metrics = yaml.load(f)['_Attributes']['eval_metrics']
f.close()
return {'status': 1, 'eval_metric': eval_metrics}
def get_eval_all_metrics(data, workspace):
tid = data['tid']
assert tid in workspace.tasks, "任务ID'{}'不存在".format(tid)
output_dir = osp.join(workspace.tasks[tid].path, "output")
epoch_result_dict = dict()
best_epoch = -1
best_result = -1
import yaml
for file_dir in os.listdir(output_dir):
if file_dir.startswith("epoch"):
epoch_dir = osp.join(output_dir, file_dir)
if osp.exists(osp.join(epoch_dir, ".success")):
epoch_index = int(file_dir.split('_')[-1])
yml_file_path = osp.join(epoch_dir, "model.yml")
f = open(yml_file_path, 'r', encoding='utf-8')
yml_file = yaml.load(f.read())
result = yml_file["_Attributes"]["eval_metrics"]
key = list(result.keys())[0]
value = result[key]
if value > best_result:
best_result = value
best_epoch = epoch_index
elif value == best_result:
if epoch_index < best_epoch:
best_epoch = epoch_index
epoch_result_dict[epoch_index] = value
return {
'status': 1,
'key': key,
'epoch_result_dict': epoch_result_dict,
'best_epoch': best_epoch,
'best_result': best_result
}
def get_sensitivities_loss_img(data, workspace):
""" 获取敏感度与模型裁剪率关系图
Args:
data为dict, key包括
'tid'任务id
"""
tid = data['tid']
assert tid in workspace.tasks, "任务ID'{}'不存在".format(tid)
task_path = workspace.tasks[tid].path
pkl_path = osp.join(task_path, 'prune', 'sensitivities_xy.pkl')
import pickle
f = open(pkl_path, 'rb')
sensitivities_xy = pickle.load(f)
return {'status': 1, 'sensitivities_loss_img': sensitivities_xy}
def start_train_task(data, workspace, monitored_processes):
"""启动训练任务。
Args:
data为dict,key包括
'tid'任务id, 'eval_metric_loss'(可选)裁剪任务所需的评估loss
"""
from .operate import train_model
tid = data['tid']
assert tid in workspace.tasks, "任务ID'{}'不存在".format(tid)
path = workspace.tasks[tid].path
if 'eval_metric_loss' in data and \
data['eval_metric_loss'] is not None:
# 裁剪任务
parent_id = workspace.tasks[tid].parent_id
assert parent_id != "", "任务{}不是裁剪训练任务".format(tid)
parent_path = workspace.tasks[parent_id].path
sensitivities_path = osp.join(parent_path, 'prune',
'sensitivities.data')
eval_metric_loss = data['eval_metric_loss']
parent_best_model_path = osp.join(parent_path, 'output', 'best_model')
params_conf_file = osp.join(path, 'params.pkl')
with open(params_conf_file, 'rb') as f:
params = pickle.load(f)
params['train'].sensitivities_path = sensitivities_path
params['train'].eval_metric_loss = eval_metric_loss
params['train'].pretrain_weights = parent_best_model_path
with open(params_conf_file, 'wb') as f:
pickle.dump(params, f)
p = train_model(path)
monitored_processes.put(p.pid)
return {'status': 1}
def resume_train_task(data, workspace, monitored_processes):
"""恢复训练任务
Args:
data为dict, key包括
'tid'任务id,'epoch'恢复训练的起始轮数
"""
from .operate import train_model
tid = data['tid']
assert tid in workspace.tasks, "任务ID'{}'不存在".format(tid)
path = workspace.tasks[tid].path
epoch_path = "epoch_" + str(data['epoch'])
resume_checkpoint_path = osp.join(path, "output", epoch_path)
params_conf_file = osp.join(path, 'params.pkl')
with open(params_conf_file, 'rb') as f:
params = pickle.load(f)
params['train'].resume_checkpoint = resume_checkpoint_path
with open(params_conf_file, 'wb') as f:
pickle.dump(params, f)
p = train_model(path)
monitored_processes.put(p.pid)
return {'status': 1}
def stop_train_task(data, workspace):
"""停止训练任务
Args:
data为dict, key包括
'tid'任务id
"""
from .operate import stop_train_model
tid = data['tid']
assert tid in workspace.tasks, "任务ID'{}'不存在".format(tid)
path = workspace.tasks[tid].path
stop_train_model(path)
return {'status': 1}
def start_prune_analysis(data, workspace, monitored_processes):
"""开始模型裁剪分析
Args:
data为dict, key包括
'tid'任务id
"""
tid = data['tid']
assert tid in workspace.tasks, "任务ID'{}'不存在".format(tid)
task_path = workspace.tasks[tid].path
from .operate import prune_analysis_model
p = prune_analysis_model(task_path)
monitored_processes.put(p.pid)
return {'status': 1}
def get_prune_metrics(data, workspace):
""" 获取模型裁剪分析日志
Args:
data为dict, key包括
'tid'任务id
Return:
prune_log(dict): 'eta':剩余时间,'iters': 模型裁剪总轮数,'current': 当前轮数,
'progress': 模型裁剪进度
"""
tid = data['tid']
assert tid in workspace.tasks, "任务ID'{}'不存在".format(tid)
from ..utils import PruneLogReader
task_path = workspace.tasks[tid].path
log_file = osp.join(task_path, 'prune', 'out.log')
# assert osp.exists(log_file), "模型裁剪分析任务还未开始,请稍等"
if not osp.exists(log_file):
return {'status': 1, 'prune_log': None}
prune_log = PruneLogReader(log_file)
prune_log.update()
prune_log = prune_log.__dict__
return {'status': 1, 'prune_log': prune_log}
def get_prune_status(data, workspace):
""" 获取模型裁剪状态
Args:
data为dict, key包括
'tid'任务id
"""
from .operate import get_prune_status
tid = data['tid']
assert tid in workspace.tasks, "任务ID'{}'不存在".format(tid)
| |
<gh_stars>0
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from skimage.transform import pyramid_gaussian
from PIL import Image
import numpy as np
from struct import unpack
import os
import sys
import re
import gc
import fs_utility
from logger import Logger
log = Logger(__name__)
log.logger.propagate = False
def fill_ico_subimage(depth_data_list_, subimage_idx_list):
""" replace missed subimage with zero matrix.
"""
depth_data_list = [np.zeros_like(depth_data_list_[0])] * 20
for subimage_index in range(len(subimage_idx_list)):
subimage_face_idx = subimage_idx_list[subimage_index]
depth_data_list[subimage_face_idx] = depth_data_list_[subimage_index]
return depth_data_list
def depth_ico_visual_save(depth_data_list_, output_path, subimage_idx_list=None):
"""save the visualized depth map array to image file with value-bar.
:param dapthe_data: The depth data.
:type dapthe_data: numpy
:param output_path: the absolute path of output image.
:type output_path: str
:param subimage_idx_list: available subimages index list.
:type subimage_idx_list: list
"""
# get vmin and vmax
# for dispmap in depth_data_list:
# if vmin_ > np.amin(dispmap):
# vmin_ = np.amin(dispmap)
# if vmax_ < np.amax(dispmap):
# vmax_ = np.amax(dispmap)
vmin_ = 0
vmax_ = 0
dispmap_array = np.concatenate(depth_data_list_).flatten()
vmin_idx = int(dispmap_array.size * 0.05)
vmax_idx = int(dispmap_array.size * 0.95)
vmin_ = np.partition(dispmap_array, vmin_idx)[vmin_idx]
vmax_ = np.partition(dispmap_array, vmax_idx)[vmax_idx]
# add blank image to miss subimage to fill the sub-image array
depth_data_list = None
if len(depth_data_list_) != 20 \
and subimage_idx_list is not None \
and len(depth_data_list_) == len(subimage_idx_list):
log.debug("The ico's sub-image size is {}, fill blank sub-images.".format(len(depth_data_list_)))
# depth_data_list = [np.zeros_like(depth_data_list_[0])] * 20
# for subimage_index in range(len(subimage_idx_list)):
# subimage_face_idx = subimage_idx_list[subimage_index]
# depth_data_list[subimage_face_idx] = depth_data_list_[subimage_index]
depth_data_list = fill_ico_subimage(depth_data_list_, subimage_idx_list)
elif len(depth_data_list_) == 20:
depth_data_list = depth_data_list_
else:
raise log.error("The sub-image is not completed.")
# draw image
figure, axes = plt.subplots(4, 5)
counter = 0
for row_index in range(0, 4):
for col_index in range(0, 5):
axes[row_index, col_index].get_xaxis().set_visible(False)
axes[row_index, col_index].get_yaxis().set_visible(False)
# add sub caption
axes[row_index, col_index].set_title(str(counter))
counter = counter + 1
#
dispmap_index = row_index * 5 + col_index
im = axes[row_index, col_index].imshow(depth_data_list[dispmap_index],
cmap=cm.jet, vmin=vmin_, vmax=vmax_)
figure.tight_layout()
plt.colorbar(im, ax=axes.ravel().tolist())
plt.savefig(output_path, dpi=150)
# plt.show()
plt.close(figure)
def depth_visual_save(depth_data, output_path, overwrite=True):
"""save the visualized depth map to image file with value-bar.
:param dapthe_data: The depth data.
:type dapthe_data: numpy
:param output_path: the absolute path of output image.
:type output_path: str
"""
depth_data_temp = depth_data.astype(np.float64)
if fs_utility.exist(output_path, 1) and overwrite:
log.warn("{} exist.".format(output_path))
fs_utility.file_rm(output_path)
# draw image
fig = plt.figure()
plt.subplots_adjust(left=0, bottom=0, right=0.1, top=0.1, wspace=None, hspace=None)
ax = fig.add_subplot(111)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
fig.tight_layout()
im = ax.imshow(depth_data_temp, cmap="turbo")
cbar = ax.figure.colorbar(im, ax=ax)
plt.savefig(output_path, dpi=150)
# plt.imsave(output_path, dapthe_data_temp, cmap="turbo")
plt.close(fig)
def depth_visual(depth_data):
"""
visualize the depth map
"""
min = np.min(depth_data)
max = np.max(depth_data)
norm = mpl.colors.Normalize(vmin=min, vmax=max)
cmap = plt.get_cmap('jet')
m = cm.ScalarMappable(norm=norm, cmap=cmap)
return (m.to_rgba(depth_data)[:, :, :3] * 255).astype(np.uint8)
def rgb2dispmap(image_filepath, pytorch_hub=True):
"""
Estimate dispmap from rgb image.
:param image_filepath: the rgb image filepath
:type image_filepath: str
:param pytorch_hub: which module should use, defaults to True
:type pytorch_hub: bool, optional
:return: MiDaS estimated dispmap
:rtype: numpy
"""
depthmap_data = None
if pytorch_hub:
log.debug("use PyTorch Hub MiDaS.")
depthmap_data = MiDaS_torch_hub_file(image_filepath)
else:
log.debug("use local MiDaS.")
# add local MiDas to python path
dir_scripts = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.join(dir_scripts, "../../MiDaS/"))
from MiDaS import MiDaS_utils
from MiDaS.monodepth_net import MonoDepthNet
from MiDaS.run import run_depth
image_data = np.asarray(Image.open(image_filepath)[..., :3])
image_data = image_data[np.newaxis, :, :, [2, 0, 1]]
MiDaS_module_filepath = dir_scripts + '../../MiDas/model.pt'
if os.path.exists(MiDaS_module_filepath):
log.error("MiDaS local module {} does not exist.".format(MiDaS_module_filepath))
depthmap_data = run_depth(image_data, MiDaS_module_filepath, MonoDepthNet, MiDaS_utils)[0]
return depthmap_data
def MiDaS_torch_hub_data(rgb_image_data_list, persp_monodepth, use_large_model=True):
"""Estimation the single RGB image's depth with MiDaS downloading from Torch Hub.
reference: https://pytorch.org/hub/intelisl_midas_v2/
:param rgb_image_path: the RGB image file path.
:type rgb_image_path: str
:param use_large_model: the MiDaS model type.
:type use_large_model: bool, optional
"""
import torch
# 1)initial PyTorch run-time environment
if use_large_model:
if persp_monodepth == "midas2":
midas = torch.hub.load("intel-isl/MiDaS", "MiDaS")
if persp_monodepth == "midas3":
midas = torch.hub.load("intel-isl/MiDaS", "DPT_Large")
else:
if persp_monodepth == "midas2":
midas = torch.hub.load("intel-isl/MiDaS", "MiDaS_small")
if persp_monodepth == "midas3":
midas = torch.hub.load("intel-isl/MiDaS", "DPT_Hybrid")
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
midas.to(device)
midas.eval()
midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms")
if use_large_model:
transform = midas_transforms.default_transform
else:
transform = midas_transforms.small_transform
disparity_map_list = []
for index in range(0, len(rgb_image_data_list)):
img = rgb_image_data_list[index]
input_batch = transform(img).to(device)
with torch.no_grad():
prediction = midas(input_batch)
prediction = torch.nn.functional.interpolate(
prediction.unsqueeze(1),
size=img.shape[:2],
mode="bicubic",
align_corners=False,
).squeeze()
output = prediction.cpu().numpy()
disparity_map_list.append(output)
del output
del input_batch
del prediction
torch.cuda.empty_cache()
if index % 10 ==0:
log.debug("MiDaS estimate {} rgb image's disparity map.".format(index))
del midas
gc.collect()
torch.cuda.empty_cache()
return disparity_map_list
def MiDaS_torch_hub_file(rgb_image_path, use_large_model=True):
"""Estimation the single RGB image's depth with MiDaS downloading from Torch Hub.
reference: https://pytorch.org/hub/intelisl_midas_v2/
:param rgb_image_path: the RGB image file path.
:type rgb_image_path: str
:param use_large_model: the MiDaS model type.
:type use_large_model: bool, optional
"""
import cv2
import torch
# import urllib.request
# import matplotlib.pyplot as plt
# url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")
# urllib.request.urlretrieve(url, filename)
# use_large_model = True
if use_large_model:
midas = torch.hub.load("intel-isl/MiDaS", "MiDaS")
else:
midas = torch.hub.load("intel-isl/MiDaS", "MiDaS_small")
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
midas.to(device)
midas.eval()
midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms")
if use_large_model:
transform = midas_transforms.default_transform
else:
transform = midas_transforms.small_transform
img = cv2.imread(rgb_image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
input_batch = transform(img).to(device)
with torch.no_grad():
prediction = midas(input_batch)
prediction = torch.nn.functional.interpolate(
prediction.unsqueeze(1),
size=img.shape[:2],
mode="bicubic",
align_corners=False,
).squeeze()
output = prediction.cpu().numpy()
# plt.imshow(output)
# plt.show()
return output
def read_dpt(dpt_file_path):
"""read depth map from *.dpt file.
:param dpt_file_path: the dpt file path
:type dpt_file_path: str
:return: depth map data
:rtype: numpy
"""
TAG_FLOAT = 202021.25 # check for this when READING the file
ext = os.path.splitext(dpt_file_path)[1]
assert len(ext) > 0, ('readFlowFile: extension required in fname %s' % dpt_file_path)
assert ext == '.dpt', exit('readFlowFile: fname %s should have extension ''.flo''' % dpt_file_path)
fid = None
try:
fid = open(dpt_file_path, 'rb')
except IOError:
print('readFlowFile: could not open %s', dpt_file_path)
tag = unpack('f', fid.read(4))[0]
width = unpack('i', fid.read(4))[0]
height = unpack('i', fid.read(4))[0]
assert tag == TAG_FLOAT, ('readFlowFile(%s): wrong tag (possibly due to big-endian machine?)' % dpt_file_path)
assert 0 < width and width < 100000, ('readFlowFile(%s): illegal width %d' % (dpt_file_path, width))
assert 0 < height and height < 100000, ('readFlowFile(%s): illegal height %d' % (dpt_file_path, height))
# arrange into matrix form
depth_data = np.fromfile(fid, np.float32)
depth_data = depth_data.reshape(height, width)
fid.close()
return depth_data
def read_exr(exp_file_path):
"""Read depth map from EXR file
:param exp_file_path: file path
:type exp_file_path: str
:return: depth map data
:rtype: numpy
"""
import array
import OpenEXR
import Imath
# Open the input file
file = OpenEXR.InputFile(exp_file_path)
# Compute the size
dw = file.header()['dataWindow']
sz = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)
# Read the three color channels as 32-bit floats
FLOAT = Imath.PixelType(Imath.PixelType.FLOAT)
(R, G, B) = [array.array('f', file.channel(Chan, FLOAT)).tolist() for Chan in ("R", "G", "B")]
# R,G,B channel is same
R_np = np.array(R).reshape((sz[1], sz[0]))
return R_np
def read_pfm(path):
"""Read pfm file.
:param path: the PFM file's path.
:type path: str
:return: the depth map array and scaler of depth
:rtype: tuple: (data, scale)
"""
with open(path, "rb") as file:
color = None
width = None
height = None
scale = None
endian = None
header = file.readline().rstrip()
if header.decode("ascii") == "PF":
color = True
elif header.decode("ascii") == "Pf":
color = False
else:
log.error("Not a PFM file: " + path)
dim_match = re.match(r"^(\d+)\s(\d+)\s$", file.readline().decode("ascii"))
if dim_match:
width, height = list(map(int, dim_match.groups()))
else:
log.error("Malformed PFM header.")
scale = float(file.readline().decode("ascii").rstrip())
if scale < 0:
# little-endian
endian = "<"
scale = -scale
else:
# big-endian
endian = ">"
data = np.fromfile(file, endian + "f")
shape = (height, width, 3) if color else (height, width)
data = np.reshape(data, shape)
data = np.flipud(data)
return data, scale
def write_pfm(path, image, scale=1):
"""Write depth data to pfm file.
:param path: pfm file path
:type path: str
:param image: depth data
:type image: numpy
:param scale: Scale, defaults to 1
:type scale: int, optional
"""
if image.dtype.name != "float32":
#raise Exception("Image dtype must be float32.")
log.warn("The depth map data is {}, convert to float32 and save to pfm format.".format(image.dtype.name))
image_ = image.astype(np.float32)
else :
image_ = image
image_ = np.flipud(image_)
color = None
if len(image_.shape) == 3 and image_.shape[2] == 3: # color image
color = True
elif len(image_.shape) == 2 or len(image_.shape) == 3 and image_.shape[2] == 1: # greyscale
color = False
else:
log.error("Image | |
NonCommutativeSymmetricFunctions(QQ).S()
sage: SGA4 = SymmetricGroupAlgebra(QQ, 4)
sage: D4 = DescentAlgebra(QQ, 4).D()
sage: all( S[C].to_symmetric_group_algebra()
....: == SGA4(D4(S[C].to_descent_algebra(4)))
....: for C in Compositions(4) )
True
"""
S = NonCommutativeSymmetricFunctions(self.base_ring()).S()
S_expansion = S(self)
return sum(S_expansion.coefficient(I)*S._to_symmetric_group_algebra_on_basis(I) for I in S_expansion.support())
# TODO:
# This is ugly (uses global sum function) and undefined if self
# is not homogeneous. Improve?
def to_symmetric_function(self):
r"""
Return the commutative image of a non-commutative symmetric function.
OUTPUT:
- The commutative image of ``self``. This will be a symmetric function.
EXAMPLES::
sage: N = NonCommutativeSymmetricFunctions(QQ)
sage: R = N.ribbon()
sage: x = R.an_element(); x
2*R[] + 2*R[1] + 3*R[1, 1]
sage: x.to_symmetric_function()
2*s[] + 2*s[1] + 3*s[1, 1]
sage: y = N.Phi()[1,3]
sage: y.to_symmetric_function()
h[1, 1, 1, 1] - 3*h[2, 1, 1] + 3*h[3, 1]
"""
return self.parent().to_symmetric_function(self)
chi = to_symmetric_function
def to_ncsym(self):
r"""
Return the image of ``self`` in the symmetric functions in
non-commuting variables under the map that fixes the usual
symmetric functions.
EXAMPLES::
sage: N = NonCommutativeSymmetricFunctions(QQ)
sage: R = N.ribbon()
sage: x = R.an_element(); x
2*R[] + 2*R[1] + 3*R[1, 1]
sage: x.to_ncsym()
2*m{} + 2*m{{1}} + 3/2*m{{1}, {2}}
sage: y = N.Phi()[1,2]
sage: y.to_ncsym()
m{{1}, {2, 3}} + m{{1, 2, 3}}
"""
return self.parent().to_ncsym(self)
class MultiplicativeBases(Category_realization_of_parent):
"""
Category of multiplicative bases of non-commutative symmetric functions.
EXAMPLES::
sage: N = NonCommutativeSymmetricFunctions(QQ)
sage: N.MultiplicativeBases()
Category of multiplicative bases of Non-Commutative Symmetric Functions over the Rational Field
The complete basis is a multiplicative basis, but the ribbon basis is not::
sage: N.Complete() in N.MultiplicativeBases()
True
sage: N.Ribbon() in N.MultiplicativeBases()
False
"""
def super_categories(self):
r"""
Return the super categories of the category of multiplicative
bases of the non-commutative symmetric functions.
OUTPUT:
- list
TESTS::
sage: N = NonCommutativeSymmetricFunctions(QQ)
sage: N.MultiplicativeBases().super_categories()
[Category of bases of Non-Commutative Symmetric Functions over the Rational Field]
"""
return [self.base().Bases()]
class ParentMethods:
@cached_method
def algebra_generators(self):
"""
Return the algebra generators of a given multiplicative basis of
non-commutative symmetric functions.
OUTPUT:
- The family of generators of the multiplicative basis ``self``.
EXAMPLES::
sage: Psi = NonCommutativeSymmetricFunctions(QQ).Psi()
sage: f = Psi.algebra_generators()
sage: f
Lazy family (<lambda>(i))_{i in Positive integers}
sage: f[1], f[2], f[3]
(Psi[1], Psi[2], Psi[3])
"""
from sage.sets.family import Family
from sage.sets.positive_integers import PositiveIntegers
return Family(PositiveIntegers(), lambda i: self.monomial(self._basis_keys([i])))
def product_on_basis(self, composition1, composition2):
"""
Return the product of two basis elements from the multiplicative basis.
Multiplication is just concatenation on compositions.
INPUT:
- ``composition1``, ``composition2`` -- integer compositions
OUTPUT:
- The product of the two non-commutative symmetric functions
indexed by ``composition1`` and ``composition2`` in the
multiplicative basis ``self``. This will be again
a non-commutative symmetric function.
EXAMPLES::
sage: Psi = NonCommutativeSymmetricFunctions(QQ).Psi()
sage: Psi[3,1,2] * Psi[4,2] == Psi[3,1,2,4,2]
True
sage: S = NonCommutativeSymmetricFunctions(QQ).S()
sage: S.product_on_basis(Composition([2,1]), Composition([1,2]))
S[2, 1, 1, 2]
"""
return self.monomial(composition1 + composition2)
def algebra_morphism(self, on_generators, **keywords):
"""
Given a map defined on the generators of the multiplicative
basis ``self``, return the algebra morphism that extends
this map to the whole algebra of non-commutative symmetric
functions.
INPUT:
- ``on_generators`` -- a function defined on the index set of
the generators (that is, on the positive integers)
- ``anti`` -- a boolean; defaults to ``False``
- ``category`` -- a category; defaults to ``None``
OUTPUT:
- The algebra morphism of ``self`` which is defined by
``on_generators`` in the basis ``self``. When ``anti``
is set to ``True``, an algebra anti-morphism is
computed instead of an algebra morphism.
EXAMPLES::
sage: NCSF = NonCommutativeSymmetricFunctions(QQ)
sage: Psi = NCSF.Psi()
sage: def double(i) : return Psi[i,i]
...
sage: f = Psi.algebra_morphism(double, codomain = Psi)
sage: f
Generic endomorphism of Non-Commutative Symmetric Functions over the Rational Field in the Psi basis
sage: f(2*Psi[[]] + 3 * Psi[1,3,2] + Psi[2,4] )
2*Psi[] + 3*Psi[1, 1, 3, 3, 2, 2] + Psi[2, 2, 4, 4]
sage: f.category()
Join of Category of hom sets in Category of modules with basis over Rational Field and Category of hom sets in Category of rings
When extra properties about the morphism are known, one
can specify the category of which it is a morphism::
sage: def negate(i): return -Psi[i]
sage: f = Psi.algebra_morphism(negate, codomain = Psi, category = GradedHopfAlgebrasWithBasis(QQ))
sage: f
Generic endomorphism of Non-Commutative Symmetric Functions over the Rational Field in the Psi basis
sage: f(2*Psi[[]] + 3 * Psi[1,3,2] + Psi[2,4] )
2*Psi[] - 3*Psi[1, 3, 2] + Psi[2, 4]
sage: f.category()
Join of Category of hom sets in Category of modules with basis over Rational Field and Category of hom sets in Category of rings
If ``anti`` is true, this returns an anti-algebra morphism::
sage: f = Psi.algebra_morphism(double, codomain = Psi, anti=True)
sage: f
Generic endomorphism of Non-Commutative Symmetric Functions over the Rational Field in the Psi basis
sage: f(2*Psi[[]] + 3 * Psi[1,3,2] + Psi[2,4] )
2*Psi[] + 3*Psi[2, 2, 3, 3, 1, 1] + Psi[4, 4, 2, 2]
sage: f.category()
Category of hom sets in Category of modules with basis over Rational Field
"""
from sage.combinat.ncsf_qsym.generic_basis_code import AlgebraMorphism
return AlgebraMorphism(self, on_generators, **keywords)
@lazy_attribute
def antipode(self):
r"""
Return the antipode morphism on the basis ``self``.
The antipode of `NSym` is closely related to the omega
involution; see
:meth:`~sage.combinat.ncsf_qsym.ncsf.NonCommutativeSymmetricFunctions.Bases.ElementMethods.omega_involution`
for the latter.
OUTPUT:
- The antipode module map from non-commutative symmetric
functions on basis ``self``.
EXAMPLES::
sage: S=NonCommutativeSymmetricFunctions(QQ).S()
sage: S.antipode
Generic endomorphism of Non-Commutative Symmetric Functions over the Rational Field in the Complete basis
"""
if hasattr(self, "antipode_on_generators"):
return self.algebra_morphism(self.antipode_on_generators, codomain = self, anti = True)
else:
return NotImplemented
@lazy_attribute
def coproduct(self):
r"""
Return the coproduct morphism in the basis ``self``.
OUTPUT:
- The coproduct module map from non-commutative symmetric
functions on basis ``self``.
EXAMPLES::
sage: S=NonCommutativeSymmetricFunctions(QQ).S()
sage: S.coproduct
Generic morphism:
From: Non-Commutative Symmetric Functions over the Rational Field in the Complete basis
To: Non-Commutative Symmetric Functions over the Rational Field in the Complete basis # Non-Commutative Symmetric Functions over the Rational Field in the Complete basis
"""
from sage.categories.all import tensor
if hasattr(self, "coproduct_on_generators"):
return self.algebra_morphism(self.coproduct_on_generators, codomain = tensor([self, self]))
else:
return NotImplemented
class MultiplicativeBasesOnGroupLikeElements(Category_realization_of_parent):
r"""
Category of multiplicative bases on grouplike elements of
non-commutative symmetric functions.
Here, a "multiplicative basis on grouplike elements" means
a multiplicative basis whose generators `(f_1, f_2, f_3, \ldots )`
satisfy
.. MATH::
\Delta(f_i) = \sum_{j=0}^{i} f_j \otimes f_{i-j}
with `f_0 = 1`. (In other words, the generators are to form a
divided power sequence in the sense of a coalgebra.) This
does not mean that the generators are grouplike, but means that
the element `1 + f_1 + f_2 + f_3 + \cdots` in the completion of
the ring of non-commutative symmetric functions with respect
to the grading is grouplike.
EXAMPLES::
sage: N = NonCommutativeSymmetricFunctions(QQ)
sage: N.MultiplicativeBasesOnGroupLikeElements()
Category of multiplicative bases on group like elements of Non-Commutative Symmetric Functions over the Rational Field
The complete basis is a multiplicative basis, but the ribbon basis is not::
sage: N.Complete() in N.MultiplicativeBasesOnGroupLikeElements()
True
sage: N.Ribbon() in N.MultiplicativeBasesOnGroupLikeElements()
False
"""
def super_categories(self):
r"""
Return the super categories of the category of multiplicative
bases of group-like elements of the non-commutative symmetric
functions.
OUTPUT:
- list
TESTS::
sage: N = NonCommutativeSymmetricFunctions(QQ)
sage: N.MultiplicativeBasesOnGroupLikeElements().super_categories()
[Category of multiplicative bases of Non-Commutative Symmetric Functions over the Rational Field]
"""
return [self.base().MultiplicativeBases()]
class ParentMethods:
def antipode_on_basis(self, composition):
"""
Return the application of the antipode to a basis element.
INPUT:
- ``composition`` -- a composition
OUTPUT:
- The image of the basis element indexed by ``composition``
under the antipode map.
EXAMPLES::
sage: S = NonCommutativeSymmetricFunctions(QQ).complete()
sage: S.antipode_on_basis(Composition([2,1]))
-S[1, 1, 1] + S[1, 2]
sage: S[1].antipode() # indirect doctest
-S[1]
sage: S[2].antipode() # indirect doctest
S[1, 1] - S[2]
sage: S[3].antipode() # indirect docttest
-S[1, 1, 1] + S[1, 2] + S[2, 1] - S[3]
sage: S[2,3].coproduct().apply_multilinear_morphism(lambda be,ga: S(be)*S(ga).antipode())
0
sage: S[2,3].coproduct().apply_multilinear_morphism(lambda be,ga: S(be).antipode()*S(ga))
0
"""
# TODO: avoid this -1^... by using properly
return (-1)**len(composition) * self.alternating_sum_of_finer_compositions(composition.reversed())
# @cached_method?
def coproduct_on_generators(self, i):
r"""
Return the image of the | |
<filename>imutils/ml/run_main.py
# import logging
# import os
# import shutil
# from pathlib import Path
# from typing import List
import hydra
from hydra.core.hydra_config import HydraConfig
from icecream import ic
# import omegaconf
import os
from omegaconf import DictConfig, OmegaConf
from rich import print as pp
import pytorch_lightning as pl
from pytorch_lightning.utilities import rank_zero_only
from imutils.ml.utils.common import load_envs
from imutils.ml.utils import template_utils
logging = template_utils.get_logger(__file__)
# Set the cwd to the project root
# os.chdir(Path(__file__).parent.parent)
# Load environment variables
load_envs()
@rank_zero_only
def ddp_print(*args, rich: bool=True):
if rich:
pp(*args)
return
print(*args)
def init_cfg(cfg: DictConfig):
if cfg.train.deterministic:
pl.seed_everything(cfg.train.random_seed)
if cfg.train.pl_trainer.devices==1:
cfg.train.pl_trainer.strategy=None
if cfg.train.pl_trainer.fast_dev_run:
hydra.utils.log.info(
f"Debug mode <{cfg.train.pl_trainer.fast_dev_run}>. "
f"Forcing debugger friendly configuration!"
)
# Debuggers don't like GPUs nor multiprocessing
if cfg.train.callbacks.get('watch_model_with_wandb') is not None:
del cfg.train.callbacks.watch_model_with_wandb
if cfg.train.callbacks.get('uploadcheckpointsasartifact') is not None:
del cfg.train.callbacks.uploadcheckpointsasartifact
if cfg.train.callbacks.get('model_checkpoint') is not None:
del cfg.train.callbacks.model_checkpoint
# cfg.train.pl_trainer.gpus = 0
cfg.data.datamodule.num_workers = 0
cfg.run_output_dir = os.path.abspath(cfg.run_output_dir)
return cfg
def run_pretrain(cfg: DictConfig) -> None:
"""
Generic pretrain loop
:param cfg: run configuration, defined by Hydra in /conf
"""
import os
cfg = init_cfg(cfg)
hydra_dir = os.path.abspath(os.getcwd())
ddp_print(f"Using hydra_dir: {hydra_dir}")
# hydra.utils.log.info(f"Before pretrain.lr_tuner value of lr: {cfg.optim.optimizer.lr}")
if cfg.execution_list.auto_lr_tune:
ddp_print(f"Executing pretrain stage: auto_lr_tune")
from imutils.ml import pretrain
cfg = pretrain.lr_tuner.run(cfg=cfg)
# datamodule=datamodule)
# model=model)
else:
ddp_print(f"[SKIPPING PRETRAIN STAGE]: auto_lr_tune")
# hydra.utils.log.info(f"Skipping pretrain stage: auto_lr_tune")
ddp_print(f"[PROCEEDING] with value cfg.optim.lr_scheduler.warmup_start_lr={cfg.optim.lr_scheduler.warmup_start_lr}")
# hydra.utils.log.info(f"Proceeding with cfg.optim.lr_scheduler.warmup_start_lr={cfg.optim.lr_scheduler.warmup_start_lr}")
return cfg
def train(cfg: DictConfig) -> None:
"""
Generic train loop
:param cfg: run configuration, defined by Hydra in /conf
"""
from imutils.ml.utils.experiment_utils import (configure_model,
configure_callbacks,
configure_loggers,
configure_trainer,
configure_loss_func)
import imutils.ml.models.pl.classifier
cfg = init_cfg(cfg)
hydra_dir = os.path.abspath(os.getcwd())
ddp_print(f"Using hydra_dir: {hydra_dir}")
if cfg.execution_list.model_fit:
# hydra.utils.log.info(f"Executing train stage: model_fit")
# hydra.utils.log.info(f"Instantiating <{cfg.data.datamodule._target_}>")
ddp_print(f"Executing train stage: model_fit")
ddp_print(f"Instantiating {cfg.data.datamodule._target_}")
datamodule: pl.LightningDataModule = hydra.utils.instantiate(
cfg.data.datamodule, _recursive_=False)
datamodule.setup()
loss_func = configure_loss_func(cfg, targets=datamodule.train_dataset.df.y)
model = configure_model(cfg=cfg,
loss_func=loss_func)
ddp_print(f"{cfg.optim.lr_scheduler.warmup_start_lr=}")
ddp_print(f"{model.lr=}, {cfg.hp.lr=}, {cfg.optim.optimizer.lr}")
loggers = configure_loggers(cfg=cfg, model=model)
callbacks: List[pl.Callback] = configure_callbacks(cfg=cfg.train)
ddp_print(f"Instantiating the Trainer")
ddp_print(OmegaConf.to_container(cfg.train.pl_trainer, resolve=True))
trainer = configure_trainer(cfg,
callbacks=callbacks,
logger=loggers)
num_samples_train = len(datamodule.train_dataset)
num_samples_val = len(datamodule.val_dataset)
# num_classes = cfg.model_cfg.head.num_classes
num_classes = cfg.hp.num_classes
batch_size = datamodule.batch_size #["train"]
ddp_print(
"Starting training: \n" \
+ f"train_size: {num_samples_train} images" + "\n" \
+ f"val_size: {num_samples_val} images" + "\n" \
+ f"num_classes: {num_classes}" + "\n" \
+ f"batch_size: {batch_size}" + "\n"
)
trainer.fit(model=model, datamodule=datamodule)
template_utils.finish(
config=cfg,
logger=loggers,
callbacks=callbacks)
# if args.train:
# trainer.fit(model, dm)
# if args.test:
# ckpt_path = (
# checkpoint_callback.best_model_path if args.train else cfg.model.checkpoint
# )
# trainer.test(model=model, datamodule=dm)
# print(f"Skipping testing for now, must run predict on unlabeled test set")
# hydra.utils.log.info(f"Starting testing!")
# trainer.test(model=model, datamodule=datamodule)
# print(f"SUCCESS: Made it to the other side of experiment finished.", f"device:{torch.cuda.current_device()}")
# @hydra.main(config_path="configs/", config_name="multi-gpu")
@hydra.main(config_path="conf", config_name="base_conf")
def main(cfg: DictConfig):
# Imports should be nested inside @hydra.main to optimize tab completion
# Read more here: https://github.com/facebookresearch/hydra/issues/934
# template_utils.extras(cfg)
template_utils.initialize_config(cfg)
ddp_print(f"CUBLAS_WORKSPACE_CONFIG = {os.environ.get('CUBLAS_WORKSPACE_CONFIG')}")
# Pretty print config using Rich library
if cfg.get("print_config_only"):
template_utils.print_config(cfg, resolve=True)
return
if cfg.execution_list.get("print_cfg"):
template_utils.print_config(cfg, resolve=True)
cfg = run_pretrain(cfg=cfg)
return train(cfg)
# def initialize_config(cfg: DictConfig):
# OmegaConf.set_struct(cfg, False)
# OmegaConf.register_new_resolver("int", int)
# return cfg
# @hydra.main(config_path="conf", config_name="base_conf")
# def main(cfg: omegaconf.DictConfig):
# run(cfg)
if __name__ == "__main__":
main()
########################################################
########################################################
"""
Sunday April 10th, 2022
Experiment #22 (Previous efforts for class balanced cross entropy on hold)
- Introducing our in house datasets with Extant_Leaves
- Implemented actual custom dataset-specific means & stds, instead of using imagenet stats for everything
- Refactored image augmentations to use albumentations instead of torchvision.transforms
- Reimplemented render_image_predictions model hook for sanity checking the augmentations.
Observations:
* Initial run went fast but wasnt learning much, when I realized I hadnt adapted the config to use different values for num_classes when switching datasets yet. This resulted in accidentally building a model with output size 15,501 for an extant leaves dataset with 94 families as unique classes.
* (~4:30 AM Monday April 11th, 2022) -- Now Im rerunning after fixing the model output size.
-- 2-gpus
export CUDA_VISIBLE_DEVICES=6,7; python run_main.py \
'core.name="[DEV] - extant_leaves_family_10_512 - Experiment #22 (2022-04-10)"' \
+train.pl_trainer.limit_train_batches=8 \
+train.pl_trainer.limit_val_batches=8 \
train.pl_trainer.log_every_n_steps=2 \
execution_list.auto_lr_tune=false \
hp.warmup_epochs=5 \
hp.batch_size=24 \
hp.lr=1e-2 \
<EMAIL>.transform_cfg=medium_image_aug_conf \
hp.preprocess_size=512 \
hp.resolution=448 \
data/datamodule@data=extant_leaves_family_10_512_datamodule \
optim.optimizer.weight_decay=5e-6 \
model_cfg.backbone.name=resnext50_32x4d \
model_cfg.backbone.pretrained=false \
hp.freeze_backbone_up_to=0 \
hp.freeze_backbone=false \
train.pl_trainer.devices=2 \
train.pl_trainer.accelerator="gpu" \
data.datamodule.num_workers=4 \
train.pl_trainer.max_epochs=50 \
+train.pl_trainer.profiler="simple" \
train.pl_trainer.accumulate_grad_batches=1
######################
-- 4-gpus
* (Launched ~4:30 AM Monday April 11th, 2022)
export CUDA_VISIBLE_DEVICES=4,5,6,7; python run_main.py \
'core.name="[EXP] - extant_leaves_family_10_512 - Experiment #22 (2022-04-10)"' \
train.pl_trainer.log_every_n_steps=10 \
execution_list.auto_lr_tune=true \
hp.warmup_epochs=5 \
hp.batch_size=24 \
hp.lr=1e-2 \
aug<EMAIL>.transform_cfg=medium_image_aug_conf \
hp.preprocess_size=512 \
hp.resolution=448 \
data/datamodule@data=extant_leaves_family_10_512_datamodule \
optim.optimizer.weight_decay=5e-6 \
model_cfg.backbone.name=resnext50_32x4d \
model_cfg.backbone.pretrained=true \
hp.freeze_backbone_up_to=0 \
hp.freeze_backbone=false \
train.pl_trainer.devices=4 \
train.pl_trainer.accelerator="gpu" \
data.datamodule.num_workers=4 \
train.pl_trainer.max_epochs=50 \
+train.pl_trainer.profiler="simple" \
train.pl_trainer.accumulate_grad_batches=2
######################
-- 4-gpus
* (Launched ~4:30 AM Monday April 11th, 2022)
export CUDA_VISIBLE_DEVICES=4,5,6,7; python run_main.py \
'core.name="[EXP] - extant_leaves_family_10_512 - Experiment #22 (2022-04-11)"' \
train.pl_trainer.log_every_n_steps=10 \
execution_list.auto_lr_tune=false \
hp.warmup_epochs=7 \
hp.batch_size=24 \
hp.lr=2e-2 \
aug@data.datamodule.transform_cfg=medium_image_aug_conf \
hp.preprocess_size=512 \
hp.resolution=448 \
data/datamodule@data=extant_leaves_family_10_512_datamodule \
optim.optimizer.weight_decay=5e-6 \
optim.lr_scheduler.warmup_start_lr=1e-4 \
model_cfg.backbone.name=resnext50_32x4d \
model_cfg.backbone.pretrained=true \
hp.freeze_backbone_up_to=0 \
hp.freeze_backbone=false \
train.pl_trainer.devices=4 \
train.pl_trainer.accelerator="gpu" \
data.datamodule.num_workers=4 \
train.pl_trainer.max_epochs=75 \
+train.pl_trainer.profiler="simple" \
train.pl_trainer.accumulate_grad_batches=4
######################
## Experiment #23
-- RGB Extant_Leaves_family_10_512
* (Launched ~4:55 PM Friday April 15th, 2022)
* (Finished ~8:35 PM Friday April 15th, 2022)
export CUDA_VISIBLE_DEVICES=4,5,6,7; python run_main.py \
'core.name="[EXP] - extant_leaves_family_10_512 - Experiment #23 (2022-04-15)"' \
train.pl_trainer.log_every_n_steps=5 \
execution_list.auto_lr_tune=true \
hp.warmup_epochs=7 \
hp.batch_size=24 \
hp.lr=1e-2 \
hp.preprocess_size=512 \
hp.resolution=448 \
data/datamodule@data=extant_leaves_family_10_512_datamodule \
optim.optimizer.weight_decay=5e-6 \
optim.lr_scheduler.warmup_start_lr=1e-4 \
model_cfg.backbone.name=hrnet_w32 \
model_cfg.backbone.pretrained=true \
hp.freeze_backbone_up_to=0 \
hp.freeze_backbone=false \
train.pl_trainer.devices=4 \
train.pl_trainer.accelerator="gpu" \
data.datamodule.num_workers=4 \
train.pl_trainer.max_epochs=75 \
+train.pl_trainer.profiler="simple" \
train.pl_trainer.accumulate_grad_batches=4
######################
## Experiment #24
-- Grayscale Extant_Leaves_family_10_512
* (Launched 8:40 PM Friday April 15th, 2022)
* (Finished ~12:15 AM Saturday April 16th, 2022)
export CUDA_VISIBLE_DEVICES=4,5,6,7; python run_main.py \
'core.name="[EXP] - extant_leaves_family_10_512 - Experiment #24 (2022-04-15)"' \
execution_list.auto_lr_tune=true \
experiments=grayscale_3-channel \
hp.warmup_epochs=7 \
hp.batch_size=24 \
hp.lr=1e-2 \
hp.preprocess_size=512 \
hp.resolution=448 \
data/datamodule@data=extant_leaves_family_10_512_datamodule \
optim.optimizer.weight_decay=5e-6 \
optim.lr_scheduler.warmup_start_lr=1e-4 \
model_cfg.backbone.name=hrnet_w32 \
model_cfg.backbone.pretrained=true \
hp.freeze_backbone_up_to=0 \
hp.freeze_backbone=false \
train.pl_trainer.devices=4 \
train.pl_trainer.accelerator="gpu" \
data.datamodule.num_workers=4 \
train.pl_trainer.max_epochs=75 \
+train.pl_trainer.profiler="simple" \
train.pl_trainer.accumulate_grad_batches=4
#############################
######################
## Experiment #25
-- Grayscale herbarium2022-res_512_datamodule
-- Using AdamW instead of Adam
- Changing weight_decay from 5e-6 -> 1e-2
-- Created new transform_cfg: medium_image_aug & renamed previous one from auto_image_aug->light_image_aug
- Increased shift & scale limits of shift_scale_rotate from 0.05->0.15
- Increased the probability p of shift_scale_rotate from 0.5->0.6
- Increased probability p of random_brightness_contrast from 0.5->0.6
- Added horizontal flip w/ p=0.5
- Added vertical flip w/ p=0.5
### Attempt #1:
* (Launched 4:27 AM Saturday April 16th, 2022)
* I'm seeing NaN train Loss within epoch 0, trying to lower weight_decay from 1e-2 -> 1e-4
### Attempt #2
* (Launched 4:48 AM Saturday April 16th, 2022)
* (Launched 4:27 AM Saturday April 16th, 2022)
* (Finished xx:xx AM Saturday April 16th, 2022)
export CUDA_VISIBLE_DEVICES=3,4,5,7; python run_main.py \
'core.name="[EXP] - Grayscale herbarium2022-res_512_datamodule - Experiment #25 (2022-04-16)"' \
execution_list.auto_lr_tune=true \
+data/datamodule@data=herbarium2022-res_512_datamodule \
<EMAIL>.transform_cfg=medium_image_aug \
experiments=grayscale_3-channel \
hp.warmup_epochs=7 \
hp.batch_size=24 \
hp.lr=1e-2 \
hp.preprocess_size=512 \
hp.resolution=448 \
optim/optimizer=AdamW \
optim.optimizer.weight_decay=1e-4 \
optim.lr_scheduler.warmup_start_lr=1e-4 \
model_cfg.backbone.name=hrnet_w32 \
model_cfg.backbone.pretrained=true \
hp.freeze_backbone_up_to=0 \
hp.freeze_backbone=false \
train.pl_trainer.devices=4 \
train.pl_trainer.accelerator="gpu" \
data.datamodule.num_workers=4 \
train.pl_trainer.max_epochs=75 \
+train.pl_trainer.profiler="simple" \
train.pl_trainer.accumulate_grad_batches=4
##################
#################
######################
## Experiment #26
-- Loading from best pretrained weights -- Experiment #21 -- RGB Herbarium2022 512
-- Finetuning on Grayscale Extant_Leaves_family_10_512
* (Launched 9:54 AM Monday April 18th, 2022)
* (Finished 1:11 PM Monday April 18th, 2022)
export CUDA_VISIBLE_DEVICES=0,1,2,6; python run_main.py \
'core.name="[EXP] - Herbarium2022-pretrained-weights -> Finetuning on Extant_Leaves_family_10_512 - Experiment #26 (2022-04-18)"' \
execution_list.auto_lr_tune=true \
data/datamodule@data=extant_leaves_family_10_512_datamodule \
aug@<EMAIL>.<EMAIL>.transform_cfg=medium_image_aug \
experiments=grayscale_3-channel \
hp.warmup_epochs=7 \
hp.batch_size=32 \
hp.lr=5e-3 \
hp.preprocess_size=512 \
hp.resolution=448 \
optim/optimizer=AdamW \
optim.optimizer.weight_decay=1e-5 \
optim.lr_scheduler.warmup_start_lr=1e-5 \
model_cfg.backbone.name=resnext50_32x4d \
hp.freeze_backbone_up_to=0 \
hp.freeze_backbone=false \
train.pl_trainer.devices=4 \
train.pl_trainer.accelerator="gpu" \
data.datamodule.num_workers=4 \
train.pl_trainer.max_epochs=75 \
+train.pl_trainer.profiler="simple" \
train.pl_trainer.accumulate_grad_batches=4 \
hp.load_from_checkpoint=true \
'ckpt_path="/media/data_cifs/projects/prj_fossils/users/jacob/experiments/2022/herbarium2022/hydra_experiments/2022-04-01/21-13-25/ckpts/epoch=22-val_loss=1.316-val_macro_F1=0.720/model_weights.ckpt"'
######################
## Experiment #27
-- Loading from best pretrained weights -- Experiment #21 -- RGB Herbarium2022 512
-- Finetuning on Grayscale Extant_Leaves_family_10_512
Goal: Manually adjusting some hyperparameters from Experiment #26 in order to reduce overfitting
Compared to Experiment #26
-- Increasing weight decay from 1e-5 to 1e-4
-- Increasing max_epochs from 75 to 100
-- Increasing warmup_epochs from 7 to 10
-- Increasing early_stopping.patience from 15 to 20
-- Decreasing early_stopping.min_delta from 0.05 to 0.02
* (Launched 1:25 PM Monday April 18th, 2022)
* (Finished 5:20 PM Monday April 18th, 2022) -- Crashed in the 43rd epoch due to a mysterious CUDA OOM error
export CUDA_VISIBLE_DEVICES=0,1,2,6; python run_main.py \
'core.name="[EXP] - Herbarium2022-pretrained-weights -> Finetuning on Extant_Leaves_family_10_512 - Experiment #27 (2022-04-18)"' \
execution_list.auto_lr_tune=false \
data/datamodule@data=extant_leaves_family_10_512_datamodule \
<EMAIL>.transform_cfg=medium_image_aug \
experiments=grayscale_3-channel \
hp.warmup_epochs=10 \
hp.batch_size=32 \
hp.lr=5e-3 \
hp.preprocess_size=512 \
hp.resolution=448 \
optim/optimizer=AdamW \
optim.optimizer.weight_decay=1e-4 \
optim.lr_scheduler.warmup_start_lr=2.7673e-6 \
model_cfg.backbone.name=resnext50_32x4d \
hp.freeze_backbone_up_to=0 \
hp.freeze_backbone=false \
train.pl_trainer.devices=4 \
train.pl_trainer.accelerator="gpu" \
data.datamodule.num_workers=4 \
train.pl_trainer.max_epochs=100 \
train.callbacks.early_stopping.patience=20 \
train.callbacks.early_stopping.min_delta=0.02 \
+train.pl_trainer.profiler="simple" \
train.pl_trainer.accumulate_grad_batches=4 \
hp.load_from_checkpoint=true \
'ckpt_path="/media/data_cifs/projects/prj_fossils/users/jacob/experiments/2022/herbarium2022/hydra_experiments/2022-04-01/21-13-25/ckpts/epoch=22-val_loss=1.316-val_macro_F1=0.720/model_weights.ckpt"'
##################################################
##################################################
######################
## Experiment #28
-- Loading from best pretrained weights -- Experiment #21 -- RGB Herbarium2022 512
-- Finetuning on Grayscale Extant_Leaves_family_10_512
Goal: Adding label smoothing CE Loss in order to reduce overfitting observed in Experiments #26 & #27
Compared to Experiment #27
-- Added Label Smoothing = 0.1
-- Decreasing weight decay from 1e-4 to 5e-5
* (Launched 5:40 PM Monday April 18th, 2022)
* (Finished x:xx PM Monday April 18th, 2022) -- Crashed in the 43rd epoch due to a mysterious CUDA OOM error
export CUDA_VISIBLE_DEVICES=0,1,2,6; python run_main.py \
'core.name="[EXP] - Herbarium2022-pretrained-weights -> Finetuning on Extant_Leaves_family_10_512 w ls-ce loss - Experiment #28 (2022-04-18)"' \
execution_list.auto_lr_tune=false \
data/datamodule@data=extant_leaves_family_10_512_datamodule \
<EMAIL>.transform_cfg=medium_image_aug \
experiments=grayscale_3-channel \
hp.warmup_epochs=10 \
hp.batch_size=32 \
hp.lr=5e-3 \
hp.preprocess_size=512 \
hp.resolution=448 \
optim/optimizer=AdamW \
optim.optimizer.weight_decay=5e-5 \
optim.lr_scheduler.warmup_start_lr=2.7673e-6 \
model_cfg.backbone.name=resnext50_32x4d \
model_cfg/loss=label-smoothing_ce-loss \
hp.freeze_backbone_up_to=0 \
hp.freeze_backbone=false \
train.pl_trainer.devices=4 \
train.pl_trainer.accelerator="gpu" \
data.datamodule.num_workers=4 \
train.pl_trainer.max_epochs=100 \
train.callbacks.early_stopping.patience=20 \
train.callbacks.early_stopping.min_delta=0.02 \
+train.pl_trainer.profiler="simple" \
train.pl_trainer.accumulate_grad_batches=4 \
hp.load_from_checkpoint=true \
'ckpt_path="/media/data_cifs/projects/prj_fossils/users/jacob/experiments/2022/herbarium2022/hydra_experiments/2022-04-01/21-13-25/ckpts/epoch=22-val_loss=1.316-val_macro_F1=0.720/model_weights.ckpt"'
########################################################
########################################################
######################
## Experiment #29
-- Grayscale Herbarium2022 512 -- Using m=272 **family** labels
Goal: Train model until saturation on family labels, the lowest cardinality level in the hierarchy. Then, downstream, finetune it on more fine-grained labels.
-- Changed primary class label level from scientificName (M=15501) to family (M=272)
-- Increased Label Smoothing from 0.1 to 0.2
-- Increasing hp.lr from 5e-3 to 7e-3
* (Launched 6:30 AM Tuesday April 19th, 2022)
(Stalled overnight for some reason, we have a zoom seder in 15 mins so I couldnt really diagnose)
* (Relaunched 5:45 PM Tuesday April 19th, 2022)
* (Relaunched 12:05 PM Tuesday April 21st, 2022)
* (Finished x:xx PM Monday April 19th, 2022) -- Crashed in the 43rd epoch due to a mysterious CUDA OOM error
export CUDA_VISIBLE_DEVICES=0,1,2,6; python run_main.py \
'core.name="[EXP] - Grayscale Herbarium2022 pretrain on family - Experiment #29 (2022-04-21)"' \
execution_list.auto_lr_tune=false \
optim.lr_scheduler.warmup_start_lr=1.746e-3 \
data/datamodule@data=herbarium2022-res_512_datamodule \
<EMAIL>_cfg=medium_image_aug \
'data.datamodule.label_col="family"' \
experiments=grayscale_3-channel \
hp.warmup_epochs=10 \
hp.batch_size=32 \
hp.lr=7e-3 \
hp.preprocess_size=512 | |
import argparse
import ConfigParser
import cPickle
import csv
import mysql.connector
import time
import sys, os, re
from context import diana
import diana.classes.drug as diana_drug
def main():
options = parse_user_arguments()
design_experiment_dcdb(options)
def parse_user_arguments(*args, **kwds):
"""
Parses the arguments of the program
"""
parser = argparse.ArgumentParser(
description = "Generate the profiles of the input drug",
epilog = "@oliva's lab 2017")
parser.add_argument('-cr','--crossings_file',dest='crossings_file',action = 'store',default=os.path.join(os.path.join(os.path.dirname(__file__), '..'), 'workspace/crossings_file.txt'),
help = """Define the file where the drug crossings to be explored will be written""")
parser.add_argument('-min','--minimum_targets',dest='minimum_targets',action = 'store',default=1,
help = """Define the minimum number of targets that the drugs need to have to be considered in the experiment""")
parser.add_argument('-sif','--sif_file',dest='sif',action = 'store',
help = """" Input file with the protein-protein interaction network in SIF format that will be used in the experiment. """)
parser.add_argument('-se','--restrict_se',dest='restrict_se',action = 'store_true',
help = """" Restrict to drugs that have Side Effects / ATCs. """)
options=parser.parse_args()
return options
#################
#################
# MAIN FUNCTION #
#################
#################
def design_experiment_dcdb(options):
"""
Designs the drug crossings to be explored in the experiment of DCDB.
"""
# Start marker for time measure
start = time.time()
# Get the script path
main_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
toolbox_dir = os.path.join(main_path, 'diana/toolbox')
#--------------------------------------#
# GET INFORMATION FROM CONFIG FILE #
#--------------------------------------#
# Read the config file
config_file = os.path.join(main_path, 'config.ini')
config = ConfigParser.ConfigParser()
config.read(config_file)
#-------------------------#
# CREATE PICKLE FILES #
#-------------------------#
drugbank2targets_file = os.path.join(toolbox_dir, 'drugbank_to_targets.pcl')
pfam_drugbank_pickle_file = os.path.join(toolbox_dir, 'drugbank_target_to_pfams.pcl')
smiles_drugbank_pickle_file = os.path.join(toolbox_dir, 'drugbank_to_smiles.pcl')
atc_drugbank_pickle_file = os.path.join(toolbox_dir, 'drugbank_to_atcs.pcl')
sider_drugbank_pickle_file = os.path.join(toolbox_dir, 'drugbank_to_side_effects.pcl')
int_to_drugs_file = os.path.join(toolbox_dir, 'drug_int_2_drugs.pcl')
int_to_info_file = os.path.join(toolbox_dir, 'drug_int_2_info.pcl')
dump_file = os.path.join(toolbox_dir, 'pair2comb.pcl')
pubchem2drugbank_file = os.path.join(toolbox_dir, 'pubchem_to_drugbank.pcl')
# Obtain the targets for all the DrugBank drugs
if not fileExist(drugbank2targets_file):
print( " DIANA INFO:\tCreating pickle file {}.\n".format( drugbank2targets_file ))
biana_cnx = mysql.connector.connect(user=config.get('BIANA', 'user'),
password=config.get('BIANA', 'password'),
host=config.get('BIANA', 'host'),
database=config.get('BIANA', 'database'))
diana_drug.obtain_drugbank_to_targets(biana_cnx, config.get('BIANA', 'unification_protocol'), options.sif, drugbank2targets_file)
biana_cnx.close()
# Obtain all the PFAMs of the targets
if not fileExist(pfam_drugbank_pickle_file):
print( " DIANA INFO:\tCreating pickle file {}.\n".format( pfam_drugbank_pickle_file ))
biana_cnx = mysql.connector.connect(user=config.get('BIANA', 'user'),
password=config.get('BIANA', 'password'),
host=config.get('BIANA', 'host'),
database=config.get('BIANA', 'database'))
drugbank2targets = cPickle.load(open(drugbank2targets_file))
all_targets = set()
for drug in drugbank2targets:
for target in drugbank2targets[drug]:
all_targets.add(target)
diana_drug.obtain_target_to_pfam(biana_cnx, config.get('BIANA', 'unification_protocol'), all_targets, pfam_drugbank_pickle_file)
biana_cnx.close()
# Obtain the SMILES of all the DrugBank drugs
if not fileExist(smiles_drugbank_pickle_file):
print( " DIANA INFO:\tCreating pickle file {}.\n".format( smiles_drugbank_pickle_file ))
biana_cnx = mysql.connector.connect(user=config.get('BIANA', 'user'),
password=config.get('BIANA', 'password'),
host=config.get('BIANA', 'host'),
database=config.get('BIANA', 'database'))
drug2targets = cPickle.load(open(drugbank2targets_file))
all_drugs = set(drug2targets.keys())
diana_drug.obtain_drug_to_smiles(biana_cnx, config.get('BIANA', 'unification_protocol'), all_drugs, 'drugbank', smiles_drugbank_pickle_file)
biana_cnx.close()
# Obtain the ATCs of all the DrugBank drugs
if not fileExist(atc_drugbank_pickle_file):
print( " DIANA INFO:\tCreating pickle file {}.\n".format( atc_drugbank_pickle_file ))
biana_cnx = mysql.connector.connect(user=config.get('BIANA', 'user'),
password=config.get('BIANA', 'password'),
host=config.get('BIANA', 'host'),
database=config.get('BIANA', 'database'))
drug2targets = cPickle.load(open(drugbank2targets_file))
all_drugs = set(drug2targets.keys())
diana_drug.obtain_drug_to_atcs(biana_cnx, config.get('BIANA', 'unification_protocol'), all_drugs, 'drugbank', atc_drugbank_pickle_file)
biana_cnx.close()
# Obtain the side effects of all the DrugBank drugs
if not fileExist(sider_drugbank_pickle_file):
print( " DIANA INFO:\tCreating pickle file {}.\n".format( sider_drugbank_pickle_file ))
biana_cnx = mysql.connector.connect(user=config.get('BIANA', 'user'),
password=config.get('BIANA', 'password'),
host=config.get('BIANA', 'host'),
database=config.get('BIANA', 'database'))
drug2targets = cPickle.load(open(drugbank2targets_file))
all_drugs = set(drug2targets.keys())
diana_drug.obtain_drug_to_side_effects(biana_cnx, config.get('BIANA', 'unification_protocol'), all_drugs, 'drugbank', sider_drugbank_pickle_file)
biana_cnx.close()
# Obtain the component drugs of the drug interactions in DCDB
if not fileExist(int_to_drugs_file):
print( " DIANA INFO:\tCreating pickle file {}.\n".format( int_to_drugs_file ))
biana_cnx = mysql.connector.connect(user=config.get('BIANA', 'user'),
password=config.get('BIANA', 'password'),
host=config.get('BIANA', 'host'),
database=config.get('BIANA', 'database'))
diana_drug.obtain_drug_interaction_to_drugs(biana_cnx, int_to_drugs_file)
biana_cnx.close()
# Obtain the information of the drug interactions in DCDB
if not fileExist(int_to_info_file):
print( " DIANA INFO:\tCreating pickle file {}.\n".format( int_to_info_file ))
biana_cnx = mysql.connector.connect(user=config.get('BIANA', 'user'),
password=config.get('BIANA', 'password'),
host=config.get('BIANA', 'host'),
database=config.get('BIANA', 'database'))
diana_drug.obtain_drug_interaction_to_info(biana_cnx, int_to_info_file)
biana_cnx.close()
#-------------------------------------------------------#
# OBTAIN THE NAMES OF THE DCDB DRUGS IN DRUGBANK ID #
#-------------------------------------------------------#
dcdb_to_drugbank_file = os.path.join(toolbox_dir, 'dcdb_to_drugbank.pcl')
check_file(dcdb_to_drugbank_file)
dcdb_to_drugbank = cPickle.load(open(dcdb_to_drugbank_file))
print('The number of DCDB IDs with DrugBank ID is: {}\n'.format(len(dcdb_to_drugbank.keys())))
#------------------------------#
# GET THE DRUGS CONSIDERED #
#------------------------------#
# Get the drugs with at least the minimum number of targets
drugs_with_targets = set()
drugbankIDs_with_targets = set()
drugbank2targets = cPickle.load(open(drugbank2targets_file))
for dcdbID in dcdb_to_drugbank:
for drugbankID in dcdb_to_drugbank[dcdbID]:
if drugbankID in drugbank2targets:
if len(drugbank2targets[drugbankID]) >= int(options.minimum_targets):
drugs_with_targets.add(dcdbID)
drugbankIDs_with_targets.add(drugbankID)
print('\nThe number of DCDB IDs with targets is: {}\n'.format(len(drugs_with_targets)))
# Get the drugs that have at least one PFAM
drugs_with_pfams = set()
drugbankIDs_with_pfams = set()
geneid2pfams = cPickle.load(open(pfam_drugbank_pickle_file))
for dcdbID in drugs_with_targets:
for drugbankID in dcdb_to_drugbank[dcdbID]:
if drugbankID in drugbank2targets:
for target in drugbank2targets[drugbankID]:
if target in geneid2pfams:
drugs_with_pfams.add(dcdbID)
drugbankIDs_with_pfams.add(drugbankID)
print('The number of DCDB IDs with at least one PFAM is: {}\n'.format(len(drugs_with_pfams)))
# Check how many drugs have side effects
drugs_with_side_effects = set()
drugbankIDs_with_side_effects = set()
drug2side_effects = cPickle.load(open(sider_drugbank_pickle_file))
for dcdbID in dcdb_to_drugbank:
for drugbankID in dcdb_to_drugbank[dcdbID]:
if drugbankID in drug2side_effects:
drugs_with_side_effects.add(dcdbID)
drugbankIDs_with_side_effects.add(drugbankID)
print('The number of DCDB IDs with at least one SIDE EFFECT is: {}\n'.format(len(drugs_with_side_effects)))
# Get the drugs that have at least one ATC
drugs_with_atcs = set()
drugbankIDs_with_atcs = set()
drug2atcs = cPickle.load(open(atc_drugbank_pickle_file))
for dcdbID in dcdb_to_drugbank:
for drugbankID in dcdb_to_drugbank[dcdbID]:
if drugbankID in drug2atcs:
drugs_with_atcs.add(dcdbID)
drugbankIDs_with_atcs.add(drugbankID)
print('The number of DCDB IDs with at least one ATC is: {}\n'.format(len(drugs_with_atcs)))
# Check how many drugs have SMILES
drugs_with_smiles = set()
drugbankIDs_with_smiles = set()
drug2smiles = cPickle.load(open(smiles_drugbank_pickle_file))
for dcdbID in dcdb_to_drugbank:
for drugbankID in dcdb_to_drugbank[dcdbID]:
if drugbankID in drug2smiles:
drugs_with_smiles.add(dcdbID)
drugbankIDs_with_smiles.add(drugbankID)
print('The number of DCDB drugs with at least one SMILES is: {}\n'.format(len(drugs_with_smiles)))
if options.restrict_se:
# Get the drugs considered (with at least n targets, 1 PFAM, 1 SMILE, 1 ATC, 1 SE)
drugs_considered = drugs_with_targets & drugs_with_pfams & drugs_with_smiles & drugs_with_atcs & drugs_with_side_effects
print('\nThe number of DCDB IDs considered is: {}'.format(len(drugs_considered)))
drugs_considered_drugbank = drugbankIDs_with_targets & drugbankIDs_with_pfams & drugbankIDs_with_smiles & drugbankIDs_with_atcs & drugbankIDs_with_side_effects
print('\nThe number of DrugBank IDs considered is: {}\n'.format(len(drugs_considered_drugbank)))
else:
# Get the drugs considered (with at least n targets, 1 PFAM, 1 SMILE)
drugs_considered = drugs_with_targets & drugs_with_pfams & drugs_with_smiles
print('\nThe number of DCDB IDs considered is: {}'.format(len(drugs_considered)))
drugs_considered_drugbank = drugbankIDs_with_targets & drugbankIDs_with_pfams & drugbankIDs_with_smiles
print('\nThe number of DrugBank IDs considered is: {}\n'.format(len(drugs_considered_drugbank)))
#-------------------------------------------------#
# DEFINE ALL POSSIBLE CROSSINGS BETWEEN PAIRS #
#-------------------------------------------------#
# We need to copy the list using the list() method because if not, when you modify one of the lists, the other gets modified as well
# This can also be done with copy.copy() method or copy.deepcopy() if the list contains objects and you want to copy them as well
# More info: http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list
list_of_drugs = list(drugs_considered)
list_of_drugs2 = list(drugs_considered)
drug_int_2_drugs = cPickle.load(open(int_to_drugs_file))
drug_int_2_info = cPickle.load(open(int_to_info_file))
crossings = set()
pair2comb = {}
dc = 0
non_dc = 0
n = 0
while (n < len(list_of_drugs)):
i = 0
while (i < len(list_of_drugs2)):
drug1 = list_of_drugs[n]
drug2 = list_of_drugs2[i]
if drug1 == drug2:
i+=1
continue
ddi_name1 = "%s---%s"%(drug1, drug2)
ddi_name2 = "%s---%s"%(drug2, drug1)
#print("%s vs. %s" %(drug1, drug2))
# We check that none of the two possible names are in the crossings set, and we add it (this is not necessary, but it is added as security)
if ddi_name1 not in crossings and ddi_name2 not in crossings:
crossings.add(ddi_name1)
i+=1
# We remove the first drug from the second list, so that we do not have to repeat pairings
list_of_drugs2.remove(drug1)
n+=1
print('There are {} possible DCDB crossings\n'.format(len(crossings)))
checking = len(list_of_drugs) * (len(list_of_drugs) - 1) / 2
if len(crossings) != checking:
print("THERE IS AN ERROR IN THE ANALYSIS. The number of crossings does not correspond to the theoretical number")
sys.exit(10)
#print(crossings)
#--------------------------------#
# TRANSLATE DCDB TO DRUGBANK #
#--------------------------------#
db_crossings = set()
for crossing in crossings:
drug1, drug2 = crossing.split('---')
db_drugs1 = [ x for x in dcdb_to_drugbank[drug1] if x in drugbankIDs_with_targets ]
db_drugs2 = [ x for x in dcdb_to_drugbank[drug2] if x in drugbankIDs_with_targets ]
for db_drug1 in db_drugs1:
for db_drug2 in db_drugs2:
db_crossing1 = '{}---{}'.format(db_drug1, db_drug2)
db_crossing2 = '{}---{}'.format(db_drug1, db_drug2)
if db_crossing1 not in db_crossings and db_crossing2 not in db_crossings:
db_crossings.add(db_crossing1)
pair2comb[db_crossing1] = 0 # We will introduce 0 if it is not drug interaction
non_dc+=1
for drug_int in drug_int_2_drugs:
if drug1 in drug_int_2_drugs[drug_int] and drug2 in drug_int_2_drugs[drug_int]:
if drug_int_2_info[drug_int]['type'] == 'pharmacodynamical':
pair2comb[db_crossing1] = 1 # We will introduce 1 if it is a pharmacodynamical drug interaction
dc+=1
non_dc-=1
else:
pair2comb[db_crossing1] = 0 # We will introduce 0 if it is not a pharmacodynamical drug interaction
| |
<reponame>pschou/py-sdf<gh_stars>0
"""
Copyright 2010 <NAME> <<EMAIL>>
Copyright 2008 <NAME>
This file is part of PyCAM.
PyCAM is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PyCAM is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PyCAM. If not, see <http://www.gnu.org/licenses/>.
"""
import time
from pycam.Geometry import epsilon, INFINITE
from pycam.Geometry.PointUtils import pdist, pnormalized, points_in_line, psub
from pycam.Utils.events import get_event_handler
class Hit:
def __init__(self, cl, cp, t, d, direction):
self.cl = cl
self.cp = cp
self.t = t
self.d = d
self.dir = direction
self.z = -INFINITE
def __repr__(self):
return "%s - %s - %s - %s" % (self.d, self.cl, self.dir, self.cp)
def get_free_paths_triangles(models, cutter, p1, p2, return_triangles=False):
if (len(models) == 0) or ((len(models) == 1) and (models[0] is None)):
return (p1, p2)
elif len(models) == 1:
# only one model is left - just continue
model = models[0]
else:
# multiple models were given - process them in layers
result = get_free_paths_triangles(models[:1], cutter, p1, p2, return_triangles)
# group the result into pairs of two points (start/end)
point_pairs = []
while result:
pair1 = result.pop(0)
pair2 = result.pop(0)
point_pairs.append((pair1, pair2))
all_results = []
for pair in point_pairs:
one_result = get_free_paths_triangles(models[1:], cutter, pair[0], pair[1],
return_triangles)
all_results.extend(one_result)
return all_results
backward = pnormalized(psub(p1, p2))
forward = pnormalized(psub(p2, p1))
xyz_dist = pdist(p2, p1)
minx = min(p1[0], p2[0])
maxx = max(p1[0], p2[0])
miny = min(p1[1], p2[1])
maxy = max(p1[1], p2[1])
minz = min(p1[2], p2[2])
# find all hits along scan line
hits = []
triangles = model.triangles(minx - cutter.distance_radius, miny - cutter.distance_radius, minz,
maxx + cutter.distance_radius, maxy + cutter.distance_radius,
INFINITE)
for t in triangles:
(cl1, d1, cp1) = cutter.intersect(backward, t, start=p1)
if cl1:
hits.append(Hit(cl1, cp1, t, -d1, backward))
(cl2, d2, cp2) = cutter.intersect(forward, t, start=p1)
if cl2:
hits.append(Hit(cl2, cp2, t, d2, forward))
# sort along the scan direction
hits.sort(key=lambda h: h.d)
count = 0
points = []
for h in hits:
if h.dir == forward:
if count == 0:
if -epsilon <= h.d <= xyz_dist + epsilon:
if len(points) == 0:
points.append((p1, None, None))
points.append((h.cl, h.t, h.cp))
count += 1
else:
if count == 1:
if -epsilon <= h.d <= xyz_dist + epsilon:
points.append((h.cl, h.t, h.cp))
count -= 1
if len(points) % 2 == 1:
points.append((p2, None, None))
if len(points) == 0:
# check if the path is completely free or if we are inside of the model
inside_counter = 0
for h in hits:
if -epsilon <= h.d:
# we reached the outer limit of the model
break
if h.dir == forward:
inside_counter += 1
else:
inside_counter -= 1
if inside_counter <= 0:
# we are not inside of the model
points.append((p1, None, None))
points.append((p2, None, None))
if return_triangles:
return points
else:
# return only the cutter locations (without triangles)
return [cut_info[0] for cut_info in points]
def get_max_height_triangles(model, cutter, x, y, minz, maxz):
""" calculate the lowest position of a tool at a location without colliding with a model
@param model: a 3D model
@param cutter: the tool to be used
@param x: requested position along the x axis
@param y: requested position along the y axis
@param minz: the tool should never go lower
used as the resulting z level, if no collision was found or it was lower than minz
@param maxz: the highest allowed tool position
@result: a tuple (x/y/z) or None (if the height limit was exeeded)
"""
if model is None:
return (x, y, minz)
p = (x, y, maxz)
height_max = None
box_x_min = cutter.get_minx(p)
box_x_max = cutter.get_maxx(p)
box_y_min = cutter.get_miny(p)
box_y_max = cutter.get_maxy(p)
box_z_min = minz
box_z_max = maxz
# reduce the set of triangles to be checked for collisions
triangles = model.triangles(box_x_min, box_y_min, box_z_min, box_x_max, box_y_max, box_z_max)
for t in triangles:
cut = cutter.drop(t, start=p)
if cut and ((height_max is None) or (cut[2] > height_max)):
height_max = cut[2]
if (height_max is None) or (height_max < minz + epsilon):
# no collision occurred or the collision height is lower than the minimum
return (x, y, minz)
elif height_max > maxz + epsilon:
# there was a collision above the upper allowed z level -> no suitable tool location found
return None
else:
# a suitable tool location was found within the bounding box
return (x, y, height_max)
def _get_dynamic_fill_points(start, end, max_height_point_func, remaining_levels):
""" generator for adding points between two given points
Points are only added, if the point in their middle (especially its height) is not in line with
the outer points.
More points are added recursively (limited via "remaining_levels") between start/middle and
middle/end.
The start and end points are never emitted. This should be done by the caller.
"""
if remaining_levels <= 0:
return
middle = max_height_point_func((start[0] + end[0]) / 2, (start[1] + end[1]) / 2)
if middle is None:
return
if points_in_line(start, middle, end):
return
# the three points are not in line - thus we should add some interval points
for p in _get_dynamic_fill_points(start, middle, max_height_point_func, remaining_levels - 1):
yield p
yield middle
for p in _get_dynamic_fill_points(middle, end, max_height_point_func, remaining_levels - 1):
yield p
def _dynamic_point_fill_generator(positions, max_height_point_func, max_level_count):
""" add more points between the given positions in order to detect minor bumps in the model
If the calculated height between two given positions (points) is not in line with its
neighbours, then additional points are added until the recursion limit ("max_level_count") is
reached or until the interpolated points are in line with their neighbours.
The input positions are returned unchanged, if less than three points are given.
"""
# handle incoming lists/tuples as well as generators
positions = iter(positions)
if max_level_count <= 0:
# reached the maximum recursion limit - simply deliver the input values
for p in positions:
yield p
return
try:
p1 = next(positions)
except StopIteration:
# no items were provided - we do the same
return
try:
p2 = next(positions)
except StopIteration:
# only one item was provided - we just deliver it unchanged
yield p1
return
last_segment_wants_more_points = False
for p3 in positions:
yield p1
if (None not in (p1, p2, p3)) and not points_in_line(p1, p2, p3):
for p in _get_dynamic_fill_points(p1, p2, max_height_point_func, max_level_count - 1):
yield p
last_segment_wants_more_points = True
else:
last_segment_wants_more_points = False
p1, p2 = p2, p3
yield p1
if last_segment_wants_more_points:
for p in _get_dynamic_fill_points(p1, p2, max_height_point_func, max_level_count - 1):
yield p
yield p2
def _filter_linear_points(positions):
""" reduce the input positions by removing all points which are in line with their neighbours
The input can be either a list or a generator.
"""
# handle incoming lists/tuples as well as generators
positions = iter(positions)
try:
p1 = next(positions)
except StopIteration:
# no items were provided - we do the same
return
try:
p2 = next(positions)
except StopIteration:
# only one item was provided - we just deliver it unchanged
yield p1
return
for p3 in positions:
if (None not in (p1, p2, p3) and points_in_line(p1, p2, p3)):
# the three points are in line -> skip p2
p2 = p3
else:
# the three points are not in line -> emit them unchanged
yield p1
p1, p2 = p2, p3
# emit the backlog
yield p1
yield p2
def get_max_height_dynamic(model, cutter, positions, minz, maxz, max_depth=5):
""" calculate the tool positions based on a given set of x/y locations
The given input locations should be suitable for the tool size in order to find all relevant
major features of the model. Additional locations are recursively added, if the calculated
height between every set of two points is not in line with its neighbours.
The result is a list of points to be traveled by | |
<reponame>Forenzik-1989/Kyty
# Copyright (c) 2014-2020 The Khronos Group Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and/or associated documentation files (the "Materials"),
# to deal in the Materials without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Materials, and to permit persons to whom the
# Materials are furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Materials.
#
# MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS
# STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND
# HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/
#
# THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM,OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS
# IN THE MATERIALS.
# This header is automatically generated by the same tool that creates
# the Binary Section of the SPIR-V specification.
# Enumeration tokens for SPIR-V, in various styles:
# C, C++, C++11, JSON, Lua, Python, C#, D
#
# - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL
# - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL
# - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL
# - Lua will use tables, e.g.: spv.SourceLanguage.GLSL
# - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL']
# - C# will use enum classes in the Specification class located in the "Spv" namespace,
# e.g.: Spv.Specification.SourceLanguage.GLSL
# - D will have tokens under the "spv" module, e.g: spv.SourceLanguage.GLSL
#
# Some tokens act like mask values, which can be OR'd together,
# while others are mutually exclusive. The mask-like ones have
# "Mask" in their name, and a parallel enum that has the shift
# amount (1 << x) for each corresponding enumerant.
spv = {
'MagicNumber' : 0x07230203,
'Version' : 0x00010500,
'Revision' : 4,
'OpCodeMask' : 0xffff,
'WordCountShift' : 16,
'SourceLanguage' : {
'Unknown' : 0,
'ESSL' : 1,
'GLSL' : 2,
'OpenCL_C' : 3,
'OpenCL_CPP' : 4,
'HLSL' : 5,
'CPP_for_OpenCL' : 6,
},
'ExecutionModel' : {
'Vertex' : 0,
'TessellationControl' : 1,
'TessellationEvaluation' : 2,
'Geometry' : 3,
'Fragment' : 4,
'GLCompute' : 5,
'Kernel' : 6,
'TaskNV' : 5267,
'MeshNV' : 5268,
'RayGenerationKHR' : 5313,
'RayGenerationNV' : 5313,
'IntersectionKHR' : 5314,
'IntersectionNV' : 5314,
'AnyHitKHR' : 5315,
'AnyHitNV' : 5315,
'ClosestHitKHR' : 5316,
'ClosestHitNV' : 5316,
'MissKHR' : 5317,
'MissNV' : 5317,
'CallableKHR' : 5318,
'CallableNV' : 5318,
},
'AddressingModel' : {
'Logical' : 0,
'Physical32' : 1,
'Physical64' : 2,
'PhysicalStorageBuffer64' : 5348,
'PhysicalStorageBuffer64EXT' : 5348,
},
'MemoryModel' : {
'Simple' : 0,
'GLSL450' : 1,
'OpenCL' : 2,
'Vulkan' : 3,
'VulkanKHR' : 3,
},
'ExecutionMode' : {
'Invocations' : 0,
'SpacingEqual' : 1,
'SpacingFractionalEven' : 2,
'SpacingFractionalOdd' : 3,
'VertexOrderCw' : 4,
'VertexOrderCcw' : 5,
'PixelCenterInteger' : 6,
'OriginUpperLeft' : 7,
'OriginLowerLeft' : 8,
'EarlyFragmentTests' : 9,
'PointMode' : 10,
'Xfb' : 11,
'DepthReplacing' : 12,
'DepthGreater' : 14,
'DepthLess' : 15,
'DepthUnchanged' : 16,
'LocalSize' : 17,
'LocalSizeHint' : 18,
'InputPoints' : 19,
'InputLines' : 20,
'InputLinesAdjacency' : 21,
'Triangles' : 22,
'InputTrianglesAdjacency' : 23,
'Quads' : 24,
'Isolines' : 25,
'OutputVertices' : 26,
'OutputPoints' : 27,
'OutputLineStrip' : 28,
'OutputTriangleStrip' : 29,
'VecTypeHint' : 30,
'ContractionOff' : 31,
'Initializer' : 33,
'Finalizer' : 34,
'SubgroupSize' : 35,
'SubgroupsPerWorkgroup' : 36,
'SubgroupsPerWorkgroupId' : 37,
'LocalSizeId' : 38,
'LocalSizeHintId' : 39,
'SubgroupUniformControlFlowKHR' : 4421,
'PostDepthCoverage' : 4446,
'DenormPreserve' : 4459,
'DenormFlushToZero' : 4460,
'SignedZeroInfNanPreserve' : 4461,
'RoundingModeRTE' : 4462,
'RoundingModeRTZ' : 4463,
'StencilRefReplacingEXT' : 5027,
'OutputLinesNV' : 5269,
'OutputPrimitivesNV' : 5270,
'DerivativeGroupQuadsNV' : 5289,
'DerivativeGroupLinearNV' : 5290,
'OutputTrianglesNV' : 5298,
'PixelInterlockOrderedEXT' : 5366,
'PixelInterlockUnorderedEXT' : 5367,
'SampleInterlockOrderedEXT' : 5368,
'SampleInterlockUnorderedEXT' : 5369,
'ShadingRateInterlockOrderedEXT' : 5370,
'ShadingRateInterlockUnorderedEXT' : 5371,
'SharedLocalMemorySizeINTEL' : 5618,
'RoundingModeRTPINTEL' : 5620,
'RoundingModeRTNINTEL' : 5621,
'FloatingPointModeALTINTEL' : 5622,
'FloatingPointModeIEEEINTEL' : 5623,
'MaxWorkgroupSizeINTEL' : 5893,
'MaxWorkDimINTEL' : 5894,
'NoGlobalOffsetINTEL' : 5895,
'NumSIMDWorkitemsINTEL' : 5896,
'SchedulerTargetFmaxMhzINTEL' : 5903,
},
'StorageClass' : {
'UniformConstant' : 0,
'Input' : 1,
'Uniform' : 2,
'Output' : 3,
'Workgroup' : 4,
'CrossWorkgroup' : 5,
'Private' : 6,
'Function' : 7,
'Generic' : 8,
'PushConstant' : 9,
'AtomicCounter' : 10,
'Image' : 11,
'StorageBuffer' : 12,
'CallableDataKHR' : 5328,
'CallableDataNV' : 5328,
'IncomingCallableDataKHR' : 5329,
'IncomingCallableDataNV' : 5329,
'RayPayloadKHR' : 5338,
'RayPayloadNV' : 5338,
'HitAttributeKHR' : 5339,
'HitAttributeNV' : 5339,
'IncomingRayPayloadKHR' : 5342,
'IncomingRayPayloadNV' : 5342,
'ShaderRecordBufferKHR' : 5343,
'ShaderRecordBufferNV' : 5343,
'PhysicalStorageBuffer' : 5349,
'PhysicalStorageBufferEXT' : 5349,
'CodeSectionINTEL' : 5605,
'DeviceOnlyINTEL' : 5936,
'HostOnlyINTEL' : 5937,
},
'Dim' : {
'Dim1D' : 0,
'Dim2D' : 1,
'Dim3D' : 2,
'Cube' : 3,
'Rect' : 4,
'Buffer' : 5,
'SubpassData' : 6,
},
'SamplerAddressingMode' : {
'None' : 0,
'ClampToEdge' : 1,
'Clamp' : 2,
'Repeat' : 3,
'RepeatMirrored' : 4,
},
'SamplerFilterMode' : {
'Nearest' : 0,
'Linear' : 1,
},
'ImageFormat' : {
'Unknown' : 0,
'Rgba32f' : 1,
'Rgba16f' : 2,
'R32f' : 3,
'Rgba8' : 4,
'Rgba8Snorm' : 5,
'Rg32f' : 6,
'Rg16f' : 7,
'R11fG11fB10f' : 8,
'R16f' : 9,
'Rgba16' : 10,
'Rgb10A2' : 11,
'Rg16' : 12,
'Rg8' : 13,
'R16' : 14,
'R8' : 15,
'Rgba16Snorm' : 16,
'Rg16Snorm' : 17,
'Rg8Snorm' : 18,
'R16Snorm' : 19,
'R8Snorm' : 20,
'Rgba32i' : 21,
'Rgba16i' : 22,
'Rgba8i' : 23,
'R32i' : 24,
'Rg32i' : 25,
'Rg16i' : 26,
'Rg8i' : 27,
'R16i' : 28,
'R8i' : 29,
'Rgba32ui' : 30,
'Rgba16ui' : 31,
'Rgba8ui' : 32,
'R32ui' : 33,
'Rgb10a2ui' : 34,
'Rg32ui' : 35,
'Rg16ui' : 36,
'Rg8ui' : 37,
'R16ui' : 38,
'R8ui' : 39,
'R64ui' : 40,
'R64i' : 41,
},
'ImageChannelOrder' : {
'R' : 0,
'A' : 1,
'RG' : 2,
'RA' : 3,
'RGB' : 4,
'RGBA' : 5,
'BGRA' : 6,
'ARGB' : 7,
'Intensity' : 8,
'Luminance' : 9,
'Rx' : 10,
'RGx' : 11,
'RGBx' : 12,
'Depth' : 13,
'DepthStencil' : 14,
'sRGB' : 15,
'sRGBx' : 16,
'sRGBA' : 17,
'sBGRA' : 18,
'ABGR' : 19,
},
'ImageChannelDataType' : {
'SnormInt8' : 0,
'SnormInt16' : 1,
'UnormInt8' : 2,
'UnormInt16' : 3,
'UnormShort565' : 4,
'UnormShort555' : 5,
'UnormInt101010' : 6,
'SignedInt8' : 7,
'SignedInt16' : 8,
'SignedInt32' : 9,
'UnsignedInt8' : 10,
'UnsignedInt16' : 11,
'UnsignedInt32' : 12,
'HalfFloat' : 13,
'Float' : 14,
'UnormInt24' : 15,
'UnormInt101010_2' : 16,
},
'ImageOperandsShift' : {
'Bias' : 0,
'Lod' : 1,
'Grad' : 2,
'ConstOffset' : 3,
'Offset' : 4,
'ConstOffsets' : 5,
'Sample' : 6,
'MinLod' : 7,
'MakeTexelAvailable' : 8,
'MakeTexelAvailableKHR' : 8,
'MakeTexelVisible' : 9,
'MakeTexelVisibleKHR' : 9,
'NonPrivateTexel' : 10,
'NonPrivateTexelKHR' : 10,
'VolatileTexel' : 11,
'VolatileTexelKHR' : 11,
'SignExtend' : 12,
'ZeroExtend' : 13,
},
'ImageOperandsMask' : {
'MaskNone' : 0,
'Bias' : 0x00000001,
'Lod' : 0x00000002,
'Grad' : 0x00000004,
'ConstOffset' : 0x00000008,
'Offset' : 0x00000010,
'ConstOffsets' : 0x00000020,
'Sample' : 0x00000040,
'MinLod' : 0x00000080,
'MakeTexelAvailable' : 0x00000100,
'MakeTexelAvailableKHR' : 0x00000100,
'MakeTexelVisible' : 0x00000200,
'MakeTexelVisibleKHR' : 0x00000200,
'NonPrivateTexel' : 0x00000400,
'NonPrivateTexelKHR' : 0x00000400,
'VolatileTexel' : 0x00000800,
'VolatileTexelKHR' : 0x00000800,
'SignExtend' : 0x00001000,
'ZeroExtend' : 0x00002000,
},
'FPFastMathModeShift' : {
'NotNaN' : 0,
'NotInf' : 1,
'NSZ' : 2,
'AllowRecip' : 3,
'Fast' : 4,
'AllowContractFastINTEL' : 16,
'AllowReassocINTEL' : 17,
},
'FPFastMathModeMask' : {
'MaskNone' : 0,
'NotNaN' : 0x00000001,
'NotInf' : 0x00000002,
'NSZ' : 0x00000004,
'AllowRecip' : 0x00000008,
'Fast' : 0x00000010,
'AllowContractFastINTEL' : 0x00010000,
'AllowReassocINTEL' : 0x00020000,
},
'FPRoundingMode' : {
'RTE' : 0,
| |
ki.getGroup(op.param1)
ki.leaveGroup(op.param1)
else:
ki.acceptGroupInvitation(op.param1)
ginfo = ki.getGroup(op.param1)
if Bmid in op.param3:
if wait["autoJoin"] == True:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
kk.acceptGroupInvitation(op.param1)
ginfo = kk.getGroup(op.param1)
kk.leaveGroup(op.param1)
else:
kk.acceptGroupInvitation(op.param1)
ginfo = kk.getGroup(op.param1)
if Cmid in op.param3:
if wait["autoJoin"] == True:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
kc.acceptGroupInvitation(op.param1)
ginfo = kc.getGroup(op.param1)
kc.leaveGroup(op.param1)
else:
kc.acceptGroupInvitation(op.param1)
ginfo = kc.getGroup(op.param1)
if Dmid in op.param3:
if wait["autoJoin"] == True:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
ko.acceptGroupInvitation(op.param1)
ginfo = ko.getGroup(op.param1)
ko.leaveGroup(op.param1)
else:
ko.acceptGroupInvitation(op.param1)
ginfo = ko.getGroup(op.param1)
if Emid in op.param3:
if wait["autoJoin"] == True:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
jk.acceptGroupInvitation(op.param1)
ginfo = jk.getGroup(op.param1)
jk.leaveGroup(op.param1)
else:
jk.acceptGroupInvitation(op.param1)
ginfo = jk.getGroup(op.param1)
if op.type == 19:
if op.param1 in protectkick:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
wait["blacklist"][op.param2] = True
try:
jk.findAndAddContactsByMid(op.param3)
jk.kickoutFromGroup(op.param1,[op.param2])
jk.inviteIntoGroup(op.param1,[op.param3])
except:
try:
ki.findAndAddContactsByMid(op.param3)
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
except:
try:
kk.findAndAddContactsByMid(op.param3)
kk.kickoutFromGroup(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
except:
try:
kc.findAndAddContactsByMid(op.param3)
kc.kickoutFromGroup(op.param1,[op.param2])
kc.inviteIntoGroup(op.param1,[op.param3])
except:
try:
ko.findAndAddContactsByMid(op.param3)
ko.kickoutFromGroup(op.param1,[op.param2])
ko.inviteIntoGroup(op.param1,[op.param3])
except:
try:
random.choice(ABC).findAndAddContactsByMid(op.param3)
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
random.choice(ABC).inviteIntoGroup(op.param1,[op.param3])
except:
pass
if op.type == 17:
if op.param2 in wait["blacklist"]:
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
else:
pass
if op.type == 17:
if op.param1 in welcome:
ginfo = cl.getGroup(op.param1)
welcomeMembers(op.param1, [op.param2])
contact = cl.getContact(op.param2)
data = {
"type": "flex",
"altText": "wiro_212 bots",
"contents": {
"type": "bubble",
"body": {
"type": "box",
"layout": "horizontal",
"spacing": "md",
"contents": [
{
"type": "box",
"layout": "vertical",
"flex": 2,
"contents": [
{
"type": "text",
"flex": 2,
"text": "{}".format(cl.getContact(op.param2).displayName),
"size": "md",
"wrap": True,
"weight": "bold",
"gravity": "center",
"color": "#FF0000"
},
{
"type": "separator",
"color": "#6F4E37"
},
{
"type": "text",
"text": "ð WELCOME TO THE ROOM ð ",
"size": "md",
"weight": "bold",
"wrap": True,
"color": "#FFD700"
},
{
"type": "text",
"text": "⣠Jangan Lupa Cek Note\n⣠Ciptakan Keamanan Room,\n⣠Dan Harmoni Persahabatan\n⣠Karena Kita Semua\n⣠Sahabat Disini\n⣠Terimakasih",
"size": "md",
"weight": "bold",
"color": "#ADFF2F",
"wrap": True
}
]
}
]
},
"styles": {
"body": {
"backgroundColor": "#0000FF"
},
"footer": {
"backgroundColor": "#DC143C"
}
},
"hero": {
"type": "image",
"aspectRatio": "20:13",
"url": "https://obs.line-scdn.net/{}".format(cl.getContact(op.param2).pictureStatus),
"size": "full",
"margin": "xxl"
},
"footer": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "BOSS",
"size": "xxl",
"wrap": True,
"weight": "bold",
"color": "#7CFC00",
"action": {
"type": "uri",
"uri": "http://line.me/ti/p/keyla_77"
},
"align": "center"
},
{
"type": "separator",
"color": "#E5E4E2"
},
{
"type": "text",
"text": "ORDER",
"size": "xxl",
"wrap": True,
"weight": "bold",
"color": "#FFD700",
"action": {
"type": "uri",
"uri": "line://app/1603968955-ORWb9RdY/?type=text&text=Order"
},
"align": "center"
}
]
}
}
}
cl.postTemplate(op.param1, data)
sendStickerTemplate(op.param1, "https://i.ibb.co/rGSVfNg/89933.gif")
if op.type == 5:
print ("[ 5 ] NOTIFIED AUTO BLOCK CONTACT")
if wait["autoBlock"] == True:
cl.blockContact(op.param1)
cl.sendMessage(op.param1, wait["Sory aim bclock u"])
if op.type == 0:
return
if op.type == 5:
if wait["autoAdd"] == True:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
if (wait["message"] in [" "," ","\n",None]):
pass
else:
cl.sendMessage(op.param1, wait["message"])
if op.type == 65:
if wait["unsend"] == True:
try:
at = op.param1
msg_id = op.param2
if msg_id in msg_dict:
if msg_dict[msg_id]["from"]:
if msg_dict[msg_id]["text"] == 'Gambarnya dibawah':
ginfo = cl.getGroup(at)
ryan = cl.getContact(msg_dict[msg_id]["from"])
zx = ""
zxc = ""
zx2 = []
xpesan = "「 Gambar Dihapus 」\n°❂° Pengirim : "
ret_ = "°❂° Nama Grup : {}".format(str(ginfo.name))
ret_ += "\n°❂° Waktu Ngirim : {}".format(dt_to_str(cTime_to_datetime(msg_dict[msg_id]["createdTime"])))
ry = str(ryan.displayName)
pesan = ''
pesan2 = pesan+"@x \n"
xlen = str(len(zxc)+len(xpesan))
xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1)
zx = {'S':xlen, 'E':xlen2, 'M':ryan.mid}
zx2.append(zx)
zxc += pesan2
text = xpesan + zxc + ret_ + ""
cl.sendMessage(at, text, contentMetadata={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0)
cl.sendImage(at, msg_dict[msg_id]["data"])
else:
ginfo = cl.getGroup(at)
ryan = cl.getContact(msg_dict[msg_id]["from"])
ret_ = "°❂°Pesan Dihapus°❂°\n"
ret_ += "°❂° Pengirim : {}".format(str(ryan.displayName))
ret_ += "\n°❂° Nama Grup : {}".format(str(ginfo.name))
ret_ += "\n°❂° Waktu Ngirim : {}".format(dt_to_str(cTime_to_datetime(msg_dict[msg_id]["createdTime"])))
ret_ += "\n°❂° Pesannya : {}".format(str(msg_dict[msg_id]["text"]))
cl.sendMessage(at, str(ret_))
del msg_dict[msg_id]
except Exception as e:
print(e)
if op.type == 65:
if wait["unsend"] == True:
try:
at = op.param1
msg_id = op.param2
if msg_id in msg_dict1:
if msg_dict1[msg_id]["from"]:
ginfo = cl.getGroup(at)
ryan = cl.getContact(msg_dict1[msg_id]["from"])
ret_ = "°❂° Sticker Dihapus °❂°\n"
ret_ += "°❂° Pengirim : {}".format(str(ryan.displayName))
ret_ += "\n°❂° Nama Grup : {}".format(str(ginfo.name))
ret_ += "\n°❂° Waktu Ngirim : {}".format(dt_to_str(cTime_to_datetime(msg_dict1[msg_id]["createdTime"])))
ret_ += "{}".format(str(msg_dict1[msg_id]["text"]))
cl.sendMessage(at, str(ret_))
cl.sendImage(at, msg_dict1[msg_id]["data"])
del msg_dict1[msg_id]
except Exception as e:
print(e)
if op.type == 19:
if mid in op.param3:
if op.param2 in Bots:
pass
if op.param2 in owner:
pass
if op.param2 in admin:
pass
if op.param2 in staff:
pass
else:
wait["blacklist"][op.param2] = True
try:
sw.acceptGroupInvitation(op.param1)
sw.findAndAddContactsByMid(op.param3)
sw.kickoutFromGroup(op.param1,[op.param2])
sw.inviteIntoGroup(op.param1,[op.param3])
cl.acceptGroupInvitation(op.param1)
x = sw.getGroup(op.param1)
x.preventedJoinByTicket = False
sw.updateGroup(x)
invsend = 0
Ti = sw.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
ko.acceptGroupInvitationByTicket(op.param1,Ti)
jk.acceptGroupInvitationByTicket(op.param1,Ti)
Ticket = sw.reissueGroupTicket(op.param1)
sw.leaveGroup(op.param1)
random.choice(ABC).inviteIntoGroup(op.param1,[Zmid])
except:
random.choice(ABC).findAndAddContactsByMid(op.param3)
random.choice(ABC).inviteIntoGroup(op.param1,[Zmid])
if op.type == 19:
if mid in op.param3:
if op.param2 in Bots:
pass
if op.param2 in owner:
pass
if op.param2 in admin:
pass
if op.param2 in staff:
pass
else:
wait["blacklist"][op.param2] = True
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
cl.acceptGroupInvitation(op.param1)
except:
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
cl.acceptGroupInvitation(op.param1)
except:
try:
kc.kickoutFromGroup(op.param1,[op.param2])
kc.inviteIntoGroup(op.param1,[op.param3])
cl.acceptGroupInvitation(op.param1)
except:
try:
x = ki.getGroup(op.param1)
x.preventedJoinByTicket = False
ki.updateGroup(x)
invsend = 0
Ti = ki.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
sw.acceptGroupInvitationByTicket(op.param1,Ti)
sw.kickoutFromGroup(op.param1,[op.param2])
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kk.kickoutFromGroup(op.param1,[op.param2])
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kc.kickoutFromGroup(op.param1,[op.param2])
ko.acceptGroupInvitationByTicket(op.param1,Ti)
ko.kickoutFromGroup(op.param1,[op.param2])
jk.acceptGroupInvitationByTicket(op.param1,Ti)
jk.kickoutFromGroup(op.param1,[op.param2])
G = sw.getGroup(op.param1)
G.preventedJoinByTicket = True
sw.updateGroup(G)
sw.leaveGroup(op.param1)
random.choice(KAC).inviteIntoGroup(op.param1,[Zmid])
except:
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
cl.acceptGroupInvitation(op.param1)
except:
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
cl.acceptGroupInvitation(op.param1)
except:
try:
random.choice(ABC).findAndAddContactsByMid(op.param3)
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
random.choice(ABC).inviteIntoGroup(op.param1,[op.param3])
cl.acceptGroupInvitation(op.param1)
except:
pass
return
if Amid in op.param3:
if op.param2 in Bots:
pass
if op.param2 in owner:
pass
if op.param2 in admin:
pass
if op.param2 in staff:
pass
else:
wait["blacklist"][op.param2] = True
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
ki.acceptGroupInvitation(op.param1)
except:
try:
kc.kickoutFromGroup(op.param1,[op.param2])
kc.inviteIntoGroup(op.param1,[op.param3])
ki.acceptGroupInvitation(op.param1)
except:
try:
jk.kickoutFromGroup(op.param1,[op.param2])
jk.inviteIntoGroup(op.param1,[op.param3])
ki.acceptGroupInvitation(op.param1)
except:
try:
x = kk.getGroup(op.param1)
x.preventedJoinByTicket = False
kk.updateGroup(x)
invsend = 0
Ti = kk.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
sw.acceptGroupInvitationByTicket(op.param1,Ti)
sw.kickoutFromGroup(op.param1,[op.param2])
ki.acceptGroupInvitationByTicket(op.param1,Ti)
ki.kickoutFromGroup(op.param1,[op.param2])
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kc.kickoutFromGroup(op.param1,[op.param2])
ko.acceptGroupInvitationByTicket(op.param1,Ti)
ko.kickoutFromGroup(op.param1,[op.param2])
jk.acceptGroupInvitationByTicket(op.param1,Ti)
jk.kickoutFromGroup(op.param1,[op.param2])
G = sw.getGroup(op.param1)
G.preventedJoinByTicket = True
sw.updateGroup(G)
sw.leaveGroup(op.param1)
random.choice(ABC).inviteIntoGroup(op.param1,[Zmid])
except:
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
ki.acceptGroupInvitation(op.param1)
except:
try:
kc.kickoutFromGroup(op.param1,[op.param2])
kc.inviteIntoGroup(op.param1,[op.param3])
ki.acceptGroupInvitation(op.param1)
except:
try:
random.choice(ABC).findAndAddContactsByMid(op.param3)
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
random.choice(ABC).inviteIntoGroup(op.param1,[op.param3])
ki.acceptGroupInvitation(op.param1)
except:
pass
return
if Bmid in op.param3:
if op.param2 in Bots:
pass
if op.param2 in owner:
pass
if op.param2 in admin:
pass
if op.param2 in staff:
pass
else:
wait["blacklist"][op.param2] = True
try:
kc.kickoutFromGroup(op.param1,[op.param2])
kc.inviteIntoGroup(op.param1,[op.param3])
kk.acceptGroupInvitation(op.param1)
except:
try:
jk.kickoutFromGroup(op.param1,[op.param2])
jk.inviteIntoGroup(op.param1,[op.param3])
kk.acceptGroupInvitation(op.param1)
except:
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
kk.acceptGroupInvitation(op.param1)
except:
try:
x = kc.getGroup(op.param1)
x.preventedJoinByTicket = False
kc.updateGroup(x)
invsend = 0
Ti = kc.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
sw.acceptGroupInvitationByTicket(op.param1,Ti)
sw.kickoutFromGroup(op.param1,[op.param2])
ki.acceptGroupInvitationByTicket(op.param1,Ti)
ki.kickoutFromGroup(op.param1,[op.param2])
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kk.kickoutFromGroup(op.param1,[op.param2])
ko.acceptGroupInvitationByTicket(op.param1,Ti)
ko.kickoutFromGroup(op.param1,[op.param2])
jk.acceptGroupInvitationByTicket(op.param1,Ti)
jk.kickoutFromGroup(op.param1,[op.param2])
G = sw.getGroup(op.param1)
G.preventedJoinByTicket = True
sw.updateGroup(G)
sw.leaveGroup(op.param1)
random.choice(ABC).inviteIntoGroup(op.param1,[Zmid])
except:
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
kk.acceptGroupInvitation(op.param1)
except:
try:
kc.kickoutFromGroup(op.param1,[op.param2])
kc.inviteIntoGroup(op.param1,[op.param3])
kk.acceptGroupInvitation(op.param1)
except:
try:
random.choice(ABC).findAndAddContactsByMid(op.param3)
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
random.choice(ABC).inviteIntoGroup(op.param1,[op.param3])
kk.acceptGroupInvitation(op.param1)
except:
pass
return
if Cmid in op.param3:
if op.param2 in Bots:
pass
if op.param2 in owner:
pass
if op.param2 in admin:
pass
if op.param2 in staff:
pass
else:
wait["blacklist"][op.param2] = True
try:
jk.kickoutFromGroup(op.param1,[op.param2])
jk.inviteIntoGroup(op.param1,[op.param3])
kc.acceptGroupInvitation(op.param1)
except:
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
kc.acceptGroupInvitation(op.param1)
except:
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
kc.acceptGroupInvitation(op.param1)
except:
try:
x = ko.getGroup(op.param1)
x.preventedJoinByTicket = False
ko.updateGroup(x)
invsend = 0
Ti = ko.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
sw.acceptGroupInvitationByTicket(op.param1,Ti)
sw.kickoutFromGroup(op.param1,[op.param2])
ki.acceptGroupInvitationByTicket(op.param1,Ti)
ki.kickoutFromGroup(op.param1,[op.param2])
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kk.kickoutFromGroup(op.param1,[op.param2])
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kc.kickoutFromGroup(op.param1,[op.param2])
jk.acceptGroupInvitationByTicket(op.param1,Ti)
jk.kickoutFromGroup(op.param1,[op.param2])
G = sw.getGroup(op.param1)
G.preventedJoinByTicket = True
sw.updateGroup(G)
sw.leaveGroup(op.param1)
random.choice(ABC).inviteIntoGroup(op.param1,[Zmid])
except:
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
kc.acceptGroupInvitation(op.param1)
except:
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
kc.acceptGroupInvitation(op.param1)
except:
try:
random.choice(ABC).findAndAddContactsByMid(op.param3)
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
random.choice(ABC).inviteIntoGroup(op.param1,[op.param3])
kc.acceptGroupInvitation(op.param1)
except:
pass
return
if Dmid in op.param3:
if op.param2 in Bots:
pass
if op.param2 in owner:
pass
if op.param2 in admin:
pass
if op.param2 in staff:
pass
else:
wait["blacklist"][op.param2] = True
try:
jk.kickoutFromGroup(op.param1,[op.param2])
jk.inviteIntoGroup(op.param1,[op.param3])
ko.acceptGroupInvitation(op.param1)
except:
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
ko.acceptGroupInvitation(op.param1)
except:
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
ko.acceptGroupInvitation(op.param1)
except:
try:
x = cl.getGroup(op.param1)
x.preventedJoinByTicket = False
cl.updateGroup(x)
invsend = 0
Ti = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
sw.acceptGroupInvitationByTicket(op.param1,Ti)
sw.kickoutFromGroup(op.param1,[op.param2])
ki.acceptGroupInvitationByTicket(op.param1,Ti)
ki.kickoutFromGroup(op.param1,[op.param2])
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kk.kickoutFromGroup(op.param1,[op.param2])
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kc.kickoutFromGroup(op.param1,[op.param2])
jk.acceptGroupInvitationByTicket(op.param1,Ti)
jk.kickoutFromGroup(op.param1,[op.param2])
G = sw.getGroup(op.param1)
G.preventedJoinByTicket = True
sw.updateGroup(G)
sw.leaveGroup(op.param1)
random.choice(ABC).inviteIntoGroup(op.param1,[Zmid])
except:
try:
| |
from __future__ import print_function
import glob
import sys
sys.path.append(glob.glob('C:\CARLA\CARLA_0.9.11\PythonAPI\carla\dist\carla-0.9.11-py3.7-win-amd64.egg')[0])
import carla
from carla import ColorConverter as cc
import pygame
import collections
import math
import re
import weakref
import numpy as np
def get_actor_display_name(actor, truncate=250):
name = ' '.join(actor.type_id.replace('_', '.').title().split('.')[1:])
return (name[:truncate - 1] + u'\u2026') if len(name) > truncate else name
def find_weather_presets():
rgx = re.compile('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)')
name = lambda x: ' '.join(m.group(0) for m in rgx.finditer(x))
presets = [x for x in dir(carla.WeatherParameters) if re.match('[A-Z].+', x)]
return [(getattr(carla.WeatherParameters, x), name(x)) for x in presets]
class World(object):
def __init__(self, carla_world, hud, args):
self.world = carla_world
self.actor_role_name = args.rolename
try:
self.map = self.world.get_map()
except RuntimeError as error:
print('RuntimeError: {}'.format(error))
print(' The server could not send the OpenDRIVE (.xodr) file:')
print(' Make sure it exists, has the same name of your town, and is correct.')
sys.exit(1)
self.hud = hud
self.player = None
self.collision_sensor = None
self.lane_invasion_sensor = None
self.gnss_sensor = None
self.imu_sensor = None
self.radar_sensor = None
self.camera_manager = None
self._weather_presets = find_weather_presets()
self._weather_index = 0
self._actor_filter = args.filter
self._gamma = args.gamma
self.restart()
self.world.on_tick(hud.on_world_tick)
self.recording_enabled = False
self.recording_start = 0
self.constant_velocity_enabled = False
self.current_map_layer = 0
self.map_layer_names = [
carla.MapLayer.NONE,
carla.MapLayer.Buildings,
carla.MapLayer.Decals,
carla.MapLayer.Foliage,
carla.MapLayer.Ground,
carla.MapLayer.ParkedVehicles,
carla.MapLayer.Particles,
carla.MapLayer.Props,
carla.MapLayer.StreetLights,
carla.MapLayer.Walls,
carla.MapLayer.All
]
CAR_MODEL_ID = "vehicle.tesla.model3"
def restart(self):
self.player_max_speed = 1.589
self.player_max_speed_fast = 3.713
# Keep same camera config if the camera manager exists.
# TODO:
cam_index = self.camera_manager.index if self.camera_manager is not None else 0
cam_pos_index = self.camera_manager.transform_index if self.camera_manager is not None else 0
blueprint = self.world.get_blueprint_library().find(self.CAR_MODEL_ID)
blueprint.set_attribute('role_name', self.actor_role_name)
if blueprint.has_attribute('color'):
blueprint.set_attribute('color', blueprint.get_attribute('color').recommended_values[0])
if blueprint.has_attribute('driver_id'):
blueprint.set_attribute('driver_id', blueprint.get_attribute('driver_id').recommended_values[0])
if blueprint.has_attribute('is_invincible'):
blueprint.set_attribute('is_invincible', 'true')
if self.player is not None:
spawn_point = self.player.get_transform()
spawn_point.location.z += 2.0
spawn_point.rotation.roll = 0.0
spawn_point.rotation.pitch = 0.0
self.destroy()
self.player = self.world.try_spawn_actor(blueprint, spawn_point)
self.modify_vehicle_physics(self.player)
while self.player is None:
if not self.map.get_spawn_points():
print('There are no spawn points available in your map/town.')
print('Please add some Vehicle Spawn Point to your UE4 scene.')
sys.exit(1)
spawn_points = self.map.get_spawn_points()
spawn_point = spawn_points[0] if spawn_points else carla.Transform()
self.player = self.world.try_spawn_actor(blueprint, spawn_point)
self.modify_vehicle_physics(self.player)
self.collision_sensor = CollisionSensor(self.player, self.hud)
self.lane_invasion_sensor = LaneInvasionSensor(self.player, self.hud)
self.gnss_sensor = GnssSensor(self.player)
self.imu_sensor = IMUSensor(self.player)
self.camera_manager = CameraManager(self.player, self.hud, self._gamma)
self.camera_manager.transform_index = cam_pos_index
self.camera_manager.set_sensor(cam_index, notify=False)
actor_type = get_actor_display_name(self.player)
self.hud.notification(actor_type)
def next_weather(self, reverse=False):
self._weather_index += -1 if reverse else 1
self._weather_index %= len(self._weather_presets)
preset = self._weather_presets[self._weather_index]
self.hud.notification('Weather: %s' % preset[1])
self.player.get_world().set_weather(preset[0])
def next_map_layer(self, reverse=False):
self.current_map_layer += -1 if reverse else 1
self.current_map_layer %= len(self.map_layer_names)
selected = self.map_layer_names[self.current_map_layer]
self.hud.notification('LayerMap selected: %s' % selected)
def load_map_layer(self, unload=False):
selected = self.map_layer_names[self.current_map_layer]
if unload:
self.hud.notification('Unloading map layer: %s' % selected)
self.world.unload_map_layer(selected)
else:
self.hud.notification('Loading map layer: %s' % selected)
self.world.load_map_layer(selected)
def toggle_radar(self):
if self.radar_sensor is None:
self.radar_sensor = RadarSensor(self.player)
elif self.radar_sensor.sensor is not None:
self.radar_sensor.sensor.destroy()
self.radar_sensor = None
def modify_vehicle_physics(self, vehicle):
physics_control = vehicle.get_physics_control()
physics_control.use_sweep_wheel_collision = True
vehicle.apply_physics_control(physics_control)
def tick(self, clock):
self.hud.tick(self, clock)
def render(self, display):
self.camera_manager.render(display)
self.hud.render(display)
def destroy_sensors(self):
self.camera_manager.sensor.destroy()
self.camera_manager.sensor = None
self.camera_manager.index = None
def destroy(self):
if self.radar_sensor is not None:
self.toggle_radar()
sensors = [
self.camera_manager.sensor,
self.collision_sensor.sensor,
self.lane_invasion_sensor.sensor,
self.gnss_sensor.sensor,
self.imu_sensor.sensor]
for sensor in sensors:
if sensor is not None:
sensor.stop()
sensor.destroy()
if self.player is not None:
self.player.destroy()
class CollisionSensor(object):
def __init__(self, parent_actor, hud):
self.sensor = None
self.history = []
self._parent = parent_actor
self.hud = hud
world = self._parent.get_world()
bp = world.get_blueprint_library().find('sensor.other.collision')
self.sensor = world.spawn_actor(bp, carla.Transform(), attach_to=self._parent)
# We need to pass the lambda a weak reference to self to avoid circular
# reference.
weak_self = weakref.ref(self)
self.sensor.listen(lambda event: CollisionSensor._on_collision(weak_self, event))
def get_collision_history(self):
history = collections.defaultdict(int)
for frame, intensity in self.history:
history[frame] += intensity
return history
@staticmethod
def _on_collision(weak_self, event):
self = weak_self()
if not self:
return
actor_type = get_actor_display_name(event.other_actor)
self.hud.notification('Collision with %r' % actor_type)
impulse = event.normal_impulse
intensity = math.sqrt(impulse.x**2 + impulse.y**2 + impulse.z**2)
self.history.append((event.frame, intensity))
if len(self.history) > 4000:
self.history.pop(0)
class LaneInvasionSensor(object):
def __init__(self, parent_actor, hud):
self.sensor = None
self._parent = parent_actor
self.hud = hud
world = self._parent.get_world()
bp = world.get_blueprint_library().find('sensor.other.lane_invasion')
self.sensor = world.spawn_actor(bp, carla.Transform(), attach_to=self._parent)
# We need to pass the lambda a weak reference to self to avoid circular
# reference.
weak_self = weakref.ref(self)
self.sensor.listen(lambda event: LaneInvasionSensor._on_invasion(weak_self, event))
@staticmethod
def _on_invasion(weak_self, event):
self = weak_self()
if not self:
return
lane_types = set(x.type for x in event.crossed_lane_markings)
text = ['%r' % str(x).split()[-1] for x in lane_types]
self.hud.notification('Crossed line %s' % ' and '.join(text))
class GnssSensor(object):
def __init__(self, parent_actor):
self.sensor = None
self._parent = parent_actor
self.lat = 0.0
self.lon = 0.0
world = self._parent.get_world()
bp = world.get_blueprint_library().find('sensor.other.gnss')
self.sensor = world.spawn_actor(bp, carla.Transform(carla.Location(x=1.0, z=2.8)), attach_to=self._parent)
# We need to pass the lambda a weak reference to self to avoid circular
# reference.
weak_self = weakref.ref(self)
self.sensor.listen(lambda event: GnssSensor._on_gnss_event(weak_self, event))
@staticmethod
def _on_gnss_event(weak_self, event):
self = weak_self()
if not self:
return
self.lat = event.latitude
self.lon = event.longitude
class IMUSensor(object):
def __init__(self, parent_actor):
self.sensor = None
self._parent = parent_actor
self.accelerometer = (0.0, 0.0, 0.0)
self.gyroscope = (0.0, 0.0, 0.0)
self.compass = 0.0
world = self._parent.get_world()
bp = world.get_blueprint_library().find('sensor.other.imu')
self.sensor = world.spawn_actor(
bp, carla.Transform(), attach_to=self._parent)
# We need to pass the lambda a weak reference to self to avoid circular
# reference.
weak_self = weakref.ref(self)
self.sensor.listen(
lambda sensor_data: IMUSensor._IMU_callback(weak_self, sensor_data))
@staticmethod
def _IMU_callback(weak_self, sensor_data):
self = weak_self()
if not self:
return
limits = (-99.9, 99.9)
self.accelerometer = (
max(limits[0], min(limits[1], sensor_data.accelerometer.x)),
max(limits[0], min(limits[1], sensor_data.accelerometer.y)),
max(limits[0], min(limits[1], sensor_data.accelerometer.z)))
self.gyroscope = (
max(limits[0], min(limits[1], math.degrees(sensor_data.gyroscope.x))),
max(limits[0], min(limits[1], math.degrees(sensor_data.gyroscope.y))),
max(limits[0], min(limits[1], math.degrees(sensor_data.gyroscope.z))))
self.compass = math.degrees(sensor_data.compass)
class RadarSensor(object):
def __init__(self, parent_actor):
self.sensor = None
self._parent = parent_actor
self.velocity_range = 7.5 # m/s
world = self._parent.get_world()
self.debug = world.debug
bp = world.get_blueprint_library().find('sensor.other.radar')
bp.set_attribute('horizontal_fov', str(35))
bp.set_attribute('vertical_fov', str(20))
self.sensor = world.spawn_actor(
bp,
carla.Transform(
carla.Location(x=2.8, z=1.0),
carla.Rotation(pitch=5)),
attach_to=self._parent)
# We need a weak reference to self to avoid circular reference.
weak_self = weakref.ref(self)
self.sensor.listen(
lambda radar_data: RadarSensor._Radar_callback(weak_self, radar_data))
@staticmethod
def _Radar_callback(weak_self, radar_data):
self = weak_self()
if not self:
return
# To get a numpy [[vel, altitude, azimuth, depth],...[,,,]]:
# points = np.frombuffer(radar_data.raw_data, dtype=np.dtype('f4'))
# points = np.reshape(points, (len(radar_data), 4))
current_rot = radar_data.transform.rotation
for detect in radar_data:
azi = math.degrees(detect.azimuth)
alt = math.degrees(detect.altitude)
# The 0.25 adjusts a bit the distance so the dots can
# be properly seen
fw_vec = carla.Vector3D(x=detect.depth - 0.25)
carla.Transform(
carla.Location(),
carla.Rotation(
pitch=current_rot.pitch + alt,
yaw=current_rot.yaw + azi,
roll=current_rot.roll)).transform(fw_vec)
def clamp(min_v, max_v, value):
return max(min_v, min(value, max_v))
norm_velocity = detect.velocity / self.velocity_range # range [-1, 1]
r = int(clamp(0.0, 1.0, 1.0 - norm_velocity) * 255.0)
g = int(clamp(0.0, 1.0, 1.0 - abs(norm_velocity)) * 255.0)
b = int(abs(clamp(- 1.0, 0.0, - 1.0 - norm_velocity)) * 255.0)
self.debug.draw_point(
radar_data.transform.location + fw_vec,
size=0.075,
life_time=0.06,
persistent_lines=False,
color=carla.Color(r, g, b))
class CameraManager(object):
def __init__(self, parent_actor, hud, gamma_correction):
self.sensor = None
self.surface = None
self._parent = parent_actor
self.hud = hud
self.recording = False
bound_y = 0.5 + self._parent.bounding_box.extent.y
Attachment = carla.AttachmentType
self._camera_transforms = [
(carla.Transform(carla.Location(x=-5.5, z=2.5), carla.Rotation(pitch=8.0)), Attachment.SpringArm),
(carla.Transform(carla.Location(x=1.6, z=1.7)), Attachment.Rigid),
(carla.Transform(carla.Location(x=5.5, y=1.5, z=1.5)), Attachment.SpringArm),
(carla.Transform(carla.Location(x=-8.0, z=6.0), carla.Rotation(pitch=6.0)), Attachment.SpringArm),
(carla.Transform(carla.Location(x=-1, y=-bound_y, z=0.5)), Attachment.Rigid)]
self.transform_index = 1
self.sensors = [
['sensor.camera.rgb', cc.Raw, 'Camera RGB', {}],
['sensor.camera.depth', cc.Raw, 'Camera Depth (Raw)', {}],
['sensor.camera.depth', cc.Depth, 'Camera Depth (Gray Scale)', {}],
['sensor.camera.depth', cc.LogarithmicDepth, 'Camera Depth (Logarithmic Gray Scale)', {}],
['sensor.camera.semantic_segmentation', cc.Raw, 'Camera Semantic Segmentation (Raw)', {}],
['sensor.camera.semantic_segmentation', cc.CityScapesPalette,
'Camera Semantic Segmentation (CityScapes Palette)', {}],
['sensor.lidar.ray_cast', None, 'Lidar (Ray-Cast)', {'range': '50'}],
['sensor.camera.dvs', cc.Raw, 'Dynamic Vision Sensor', {}],
['sensor.camera.rgb', cc.Raw, 'Camera RGB Distorted',
{'lens_circle_multiplier': '3.0',
'lens_circle_falloff': '3.0',
'chromatic_aberration_intensity': '0.5',
'chromatic_aberration_offset': '0'}]]
world = self._parent.get_world()
bp_library = world.get_blueprint_library()
for item in self.sensors:
bp = bp_library.find(item[0])
if item[0].startswith('sensor.camera'):
bp.set_attribute('image_size_x', str(hud.dim[0]))
bp.set_attribute('image_size_y', str(hud.dim[1]))
if bp.has_attribute('gamma'):
bp.set_attribute('gamma', str(gamma_correction))
for attr_name, attr_value in item[3].items():
bp.set_attribute(attr_name, attr_value)
elif item[0].startswith('sensor.lidar'):
self.lidar_range = 50
for attr_name, attr_value in item[3].items():
bp.set_attribute(attr_name, attr_value)
if attr_name == 'range':
self.lidar_range = float(attr_value)
item.append(bp)
self.index = None
def toggle_camera(self):
self.transform_index = (self.transform_index + 1) % len(self._camera_transforms)
self.set_sensor(self.index, notify=False, force_respawn=True)
def set_sensor(self, index, notify=True, force_respawn=False):
index = index % len(self.sensors)
needs_respawn = True if self.index is None else \
(force_respawn or (self.sensors[index][2] != self.sensors[self.index][2]))
if needs_respawn:
if self.sensor is not None:
self.sensor.destroy()
self.surface = None
self.sensor = self._parent.get_world().spawn_actor(
self.sensors[index][-1],
self._camera_transforms[self.transform_index][0],
attach_to=self._parent,
attachment_type=self._camera_transforms[self.transform_index][1])
# We need to pass the lambda a weak reference to self to avoid
# circular reference.
weak_self = weakref.ref(self)
self.sensor.listen(lambda image: CameraManager._parse_image(weak_self, | |
#!/usr/bin/python3
# <---------------------------------------------------------------------------- general imports --->
import os
import sys
import datetime
import configparser
from random import random
import math
# <---------------------------------------------------------------------------- numeric imports --->
import scipy as sci
import scipy.integrate
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
from matplotlib.widgets import TextBox, Button
# <--------------------------------------------------------------------------------- my imports --->
from .other import query_yes_no, timestamp, fprint
# <--------------------------------------------------------------------------- global variables --->
ANIMATION_LENGTH_SEC = 10
# <------------------------------------------------------------------------------------ classes --->
class OneBody:
def __init__(self, name: str, mass: float, position: list, velocity: list, color):
self.name = name
self.mass = mass
self.position = sci.array(position, dtype="float64")
self.velocity = sci.array(velocity, dtype="float64")
self.color = color
def __str__(self):
retval = '\t{0:<19}:'.format(self.name)
for i, d in enumerate(['x', 'y', 'z']):
retval += '\t{0:<2} = {1: 8.3f}'.format(d, self.position[i])
retval += '\n\t' + 20 * ' '
for i, d in enumerate(['vx', 'vy', 'vz']):
retval += '\t{0:<2} = {1: 8.3f}'.format(d, self.velocity[i])
retval += '\n\t' + 20 * ' '
retval += '\t{0:<2} = {1: 8.3f}'.format('m', self.mass)
return retval
class MultiBodyProblem:
def __init__(self, periods=8, points=500):
fprint('[+] initialising multibody problem solver\n periods: {0},integration points: {1}'.format(periods, points))
self.periods = periods
self.points = points
# define universal gravitation constant
self.g = 5.67408e-11 # n-m2/kg2
# reference quantities
self.m_nd = 0.989e+30 # kg #mass of the sun
self.r_nd = 4.326e+12 # m #distance between stars in alpha centauri
self.v_nd = 29999 # m/s #relative velocity of earth around the sun
self.t_nd = 78.91 * 365 * 24 * 3600 * 0.51 # s #orbital period of alpha centauri
# net constants
self.k0= self.g * self.t_nd * self.m_nd / (self.r_nd ** 2 * self.v_nd)
self.k1 = self.v_nd * self.t_nd / self.r_nd
self.bodies = []
self.com = None
self.init_params = None
self.time_span = None
# plotting
self.ani = None
self.fig = None
self.ax = None
self.ax_p = [0.05, 0.05, 0.65, 0.9] # [left, bottom, width, height]
self.ax_t = list() # texts
self.ax_wt = dict() # axes for widgets - textboxes
self.ax_wb = list() # axes for widgets - buttons
self.wt = dict() # widgets - textboxes
self.wb = list() # widgets - buttons
self.ax_c_p = [0.70, 0.05, 0.20, 0.9] # [left, bottom, width, height]
def add_body(self, mass, position, velocity, name=None, color=None):
if name is None:
name = 'star {0}'.format(len(self.bodies) + 1)
if color is None:
color = (random(), random(), random())
self.bodies.append(OneBody(name, mass, position, velocity, color))
fprint('[+] added celestial body:\n{0}'.format(str(self.bodies[-1])))
self.init_com()
def init_com(self):
r_numerator = 0
v_numerator = 0
denominator = 0
for body in self.bodies:
r_numerator += body.mass * body.position
v_numerator += body.mass * body.velocity
denominator += body.mass
self.com = OneBody('com', denominator, r_numerator / denominator, v_numerator / denominator, "tab:yellow")
#a function defining the equations of motion
def multibodyequations(self, w, t): # , g):
r = []
v = []
num = len(self.bodies)
for i in range(num):
r.append(w[i * 3: (i + 1) * 3])
v.append(w[(i + num) * 3: (i + num + 1) * 3])
dv_dt = []
dr_dt = []
for i in range(num):
dv_dt.append(0)
dr_dt.append(self.k1 * v[i])
for j in range(num):
if i != j:
dv_dt[i] += self.k0 * self.bodies[j].mass * (r[j] - r[i]) / (sci.linalg.norm(r[j] - r[i]) ** 3)
r_derivs = sci.concatenate((dr_dt[0], dr_dt[1]))
v_derivs = sci.concatenate((dv_dt[0], dv_dt[1]))
if num > 2:
for i in range(2, num):
r_derivs = sci.concatenate((r_derivs, dr_dt[i]))
v_derivs = sci.concatenate((v_derivs, dv_dt[i]))
derivs = sci.concatenate((r_derivs, v_derivs))
return derivs
def initialize(self):
self.init_params = []
for body in self.bodies:
self.init_params.append(body.position)
for body in self.bodies:
self.init_params.append(body.velocity)
self.init_params = sci.array(self.init_params).flatten()
self.time_span = sci.linspace(0, self.periods, self.points)
def solve(self, relative_to_com=False):
fprint('[+] running solver')
multi_body_solution = sci.integrate.odeint(self.multibodyequations,
self.init_params,
self.time_span)
r_sol = []
limits = [[multi_body_solution.max(), multi_body_solution.min()],
[multi_body_solution.max(), multi_body_solution.min()],
[multi_body_solution.max(), multi_body_solution.min()]]
for i, body in enumerate(self.bodies):
r_sol.append(sci.transpose(multi_body_solution[:, i*3:(i + 1) * 3]))
for j, tmp in enumerate(sci.transpose(multi_body_solution[:, i*3:(i + 1) * 3])):
limits[j] = [min(limits[j][0], tmp.min()), max(limits[j][1], tmp.max())]
if relative_to_com:
rcom_sol = self.bodies[0].mass * r_sol[0]
m = self.bodies[0].mass
for i, body in enumerate(self.bodies[1:]):
rcom_sol += body.mass * r_sol[i + 1]
m += body.mass
rcom_sol = rcom_sol / m
limits = [[rcom_sol.max(), rcom_sol.min()],
[rcom_sol.max(), rcom_sol.min()],
[rcom_sol.max(), rcom_sol.min()]]
for i, sol in enumerate(r_sol):
sol -= rcom_sol
for j in range(3):
limits[j] = [min(limits[j][0], sol[j].min()), max(limits[j][1], sol[j].max())]
fprint('[+] output data relative to COG of system: {0}'.format(str(relative_to_com)))
self.solution = r_sol
self.limits = limits
# return r_sol, limits
def load(self, filepath):
fprint('[+] loading saved sessions')
if os.path.isfile(filepath) and filepath.endswith('.ini'):
files = [filepath]
filepath = os.path.dirname(filepath)
elif os.path.isdir(filepath):
files = [f for f in os.listdir(filepath) if f.endswith('.ini')]
else:
fprint('[-] missing directory with saved files')
sys.exit(1)
files.sort()
for i, f in enumerate(files):
c = configparser.ConfigParser()
c.read_file(open(os.path.join(filepath, f)))
fprint('\t{0} - {1} ({2}), {3} bodies'.format(i, f, c['DEFAULT']['description'], c['DEFAULT']['bodies']))
for j in range(int(c['DEFAULT']['bodies'])):
fprint('\t\t{0:<20} m = {1: 6}\tx = [{2: 6}, {3: 6}, {4: 6}]\tv = [{5: 6}, {6: 6}, {7: 6}]\tcolor = {8:<20}'.format(c[str(j)]['name'],
float(c[str(j)]['mass']),
float(c[str(j)]['x']),
float(c[str(j)]['y']),
float(c[str(j)]['z']),
float(c[str(j)]['vx']),
float(c[str(j)]['vy']),
float(c[str(j)]['vz']),
c[str(j)]['color']))
select = fprint('[?] Select session number to load [0]: ', question=True)
if select == '':
select = '0'
if select in [str(i) for i in range(len(files))]:
select = int(select)
else:
sys.exit(fprint('[-] no session selected, exiting...', returnstr=True))
c = configparser.ConfigParser()
c.read_file(open(os.path.join(filepath, files[select])))
self.periods = int(c['DEFAULT']['periods to solve'])
self.points = int(c['DEFAULT']['integration points'])
for j in range(int(c['DEFAULT']['bodies'])):
color = c[str(j)]['color']
if color.startswith('('):
color = [float(col) for col in color[1:-1].split(',')]
self.add_body(float(c[str(j)]['mass']), [float(c[str(j)]['x']), float(c[str(j)]['y']), float(c[str(j)]['z'])], [float(c[str(j)]['vx']), float(c[str(j)]['vy']), float(c[str(j)]['vz'])], c[str(j)]['name'], color)
def save(self, filepath):
defname = '{0}'.format(timestamp('fullname'))
session = fprint('[?] session name [{0}]: '.format(defname), question=True)
if session == '':
session = defname
description = fprint('[?] description: ', question=True)
filename = os.path.join(filepath, session.replace(' ', '_').replace(':', '') + '.ini')
fprint('[+] saving session to: {0}'.format(filename))
config = configparser.ConfigParser(interpolation=None)
config['DEFAULT']['name'] = session
config['DEFAULT']['description'] = description
config['DEFAULT']['date'] = timestamp('datename')
config['DEFAULT']['time'] = timestamp('time')
config['DEFAULT']['bodies'] = str(len(self.bodies))
config['DEFAULT']['periods to solve'] = str(self.periods)
config['DEFAULT']['integration points'] = str(self.points)
for i, b in enumerate(self.bodies):
config.add_section(str(i))
config[str(i)]['name'] = b.name
config[str(i)]['mass'] = '{0:e}'.format(b.mass)
for j, x in enumerate(['x', 'y', 'z']):
config[str(i)][x] = '{0:e}'.format(b.position[j])
for j, x in enumerate(['vx', 'vy', 'vz']):
config[str(i)][x] = '{0:e}'.format(b.velocity[j])
config[str(i)]['color'] = str(b.color)
if not os.path.isdir(os.path.dirname(filename)):
os.mkdir(os.path.dirname(filename))
with open(filename, 'w') as configfile:
config.write(configfile)
fprint('[+] session saved')
def plot(self):
fprint('[+] plotting solution')
# Create figure
self.fig = plt.figure(figsize=(14, 9)) # (width, height)
# ax = p3.Axes3D(fig)
self.ax = self.fig.add_axes(self.ax_p, projection='3d')
ncol = 3 # x, y, z
nrow = 4 # name, mass, position, velocity
p = self.ax_c_p # [left, bottom, width, height]
w = p[2] / ncol # width
h = p[3] / (len(self.bodies) * nrow + 1) # height
w_pad = 0.1 * w # padding of one cell (horizontal)
h_pad = 0.1 * h # padding of one cell (vertical)
tb_w = w - 2* w_pad # TextBox width
tb_h = h - 2 * h_pad # TextBox height
for i, b in enumerate(self.bodies):
self.fig.text(p[0], p[1] + p[3] - h * (nrow * i + 1) + h_pad, b.name)
self.ax_wt[i] = dict()
self.wt[i] = dict()
self.ax_wt[i]['mass'] = plt.axes([p[0] + w_pad, p[1] + p[3] - h * (nrow * i + 2) + h_pad, tb_w, tb_h])
self.wt[i]['mass'] = TextBox(self.ax_wt[i]['mass'], 'm:', '{0:.4f}'.format(b.mass))
for j, x in enumerate(['x', 'y', 'z']):
self.ax_wt[i][x] = plt.axes([p[0] + j * w + w_pad, p[1] + p[3] - h * (nrow * i + 3) + h_pad, tb_w, tb_h])
self.wt[i][x] = TextBox(self.ax_wt[i][x], x + ':', '{0:.4f}'.format(b.position[j]))
for j, x in enumerate(['vx', 'vy', 'vz']):
self.ax_wt[i][x] = plt.axes([p[0] + j * w + w_pad, p[1] + p[3] - h * (nrow * i + 4) + h_pad, tb_w, tb_h])
self.wt[i][x] = TextBox(self.ax_wt[i][x], x + ':', '{0:.4f}'.format(b.position[j]))
# create the line objects for plots
# NOTE: Can't pass empy arrays into 3d plot
lines = [self.ax.plot(sol[0, 0:1], sol[1, 0:1], sol[2, 0:1],
color=self.bodies[i].color)[0] for i, sol in enumerate(self.solution)]
dots = [self.ax.plot([sol[0, 1]], [sol[1, 1]], sol[2, 1],
color=self.bodies[i].color, linestyle="", marker="o")[0] for i, sol in enumerate(self.solution)]
def update_lines(num, dataLines, lines, dots):
for line, data in zip(lines, dataLines):
line.set_data(data[0:2, :num])
line.set_3d_properties(data[2, :num])
for dot, data in zip(dots, dataLines):
# dot._offsets3d = [float(data[0, num]), float(data[1, num]), float(data[2, num])]
dot.set_data(data[0:2, num])
dot.set_3d_properties(data[2, num])
return lines, dots
self.ax.set_xlim3d([self.limits[0][0], self.limits[0][1]])
self.ax.set_xlabel("x-coordinate", | |
#!/usr/bin/env python
import os
import sys
import cookielib
import urllib
import urllib2
import json
import time
import argparse
import pandas as pd
import base64
from tqdm import tqdm
import re
# check that the python version is correct (need 2)
if sys.version_info[0] > 2:
raise "Must be using Python 2! Aborting."
#get a default directory with data files for this script
def getScriptsDataDir():
curr = os.getcwd()
sdata = re.sub("/stitcher.*$",
"/stitcher/scripts/data",
curr)
if not os.path.exists(sdata):
raise ValueError('Could not identify dir with script files!')
return sdata
sdata = getScriptsDataDir()
# check for arguments
args_p = argparse.ArgumentParser(description="Run Some Stitcher Tests")
args_p.add_argument('addr',
help="""a full Stitcher address OR
a shorthand: 'prod', 'dev', 'test', 'local' [on 8080] or a port number""")
args_p.add_argument('--unii',
nargs="?",
default=os.path.join(sdata,
"UNII Names 31Aug2018.txt"),
help="path to a file with unii names")
args_p.add_argument("--appyears",
nargs="?",
default=os.path.join(sdata,
"approvalYears.txt"),
help="path to a file with unii names")
args_p.add_argument("--fdanme",
nargs="?",
default=os.path.join(sdata,
"FDA-NMEs-2018-08-07.txt"),
help="path to a file with unii names")
args_p.add_argument('--maxsubs',
nargs="?",
type=int,
default=100000,
help="maximum number of substances to evaluate")
args_p.add_argument('--outdir',
nargs="?",
default="./test-results",
help="where to save the results")
site_arg = args_p.parse_args().addr
unii_path = args_p.parse_args().unii
appyears_path = args_p.parse_args().appyears
fdanme_path = args_p.parse_args().fdanme
max_subs = args_p.parse_args().maxsubs
outdir = args_p.parse_args().outdir
switcher = {
"prod": "https://stitcher.ncats.io/",
"dev": "https://stitcher-dev.ncats.io/",
"test": "https://stitcher-test.ncats.io/",
"local": "http://localhost:8080/"
}
#script can ingest a port number
ports_patt = "^[0-9]{4}$"
if site_arg in switcher:
site = switcher[site_arg]
elif re.search(ports_patt, str(site_arg)):
site = "http://localhost:%s/" % site_arg
else:
site = site_arg
print "Querying stitcher instance at %s..." % site
#create output directory if missing
if not os.path.exists(outdir):
os.mkdir(outdir)
date = time.strftime("%Y-%m-%d", time.gmtime())
cookies = cookielib.CookieJar()
opener = urllib2.build_opener(
urllib2.HTTPRedirectHandler(),
urllib2.HTTPHandler(debuglevel=0),
urllib2.HTTPSHandler(debuglevel=0),
urllib2.HTTPCookieProcessor(cookies))
opener.addheaders = [
('User-agent', ('Mozilla/4.0 (compatible; MSIE 6.0; '
'Windows NT 5.2; .NET CLR 1.1.4322)'))
]
def requestJson(uri):
try:
handle = opener.open(uri)
response = handle.read()
handle.close()
obj = json.loads(response)
return obj
except:
sys.stderr.write("failed: "+uri+"\n")
sys.stderr.flush()
time.sleep(5)
def uniiClashes(unii2stitch, stitch):
''' defined in main
header = ["UNII -- UNII PT"]
'''
for node in stitch['sgroup']['members']:
if "stitches" in node and "I_UNII" in node["stitches"]:
uniis = node['stitches']['I_UNII']
if not isinstance(uniis, list):
uniis = [uniis]
for unii in uniis:
unii2stitch.setdefault(unii,
[" -- ".join([unii,
all_uniis.get(unii, "")])
])
if stitch['id'] not in unii2stitch[unii]:
unii2stitch[unii].append(stitch['id'])
return unii2stitch
def approvedStitches(approved, stitch):
''' defined in main
header = ["UNII -- UNII PT",
"Approval Year",
"Stitch",
"Rank"]
'''
if stitch['USapproved']:
apprYear = "not given"
if 'approvedYear' in stitch:
apprYear = stitch['approvedYear']
parent = stitch['sgroup']['parent']
rank = stitch['rank']
unii = ''
for node in stitch['sgroup']['members']:
if node['node'] == parent:
if 'id' not in node:
unii = node['name']
else:
unii = node['id']
name = getName(stitch)
approved[unii] = [" -- ".join([unii,
all_uniis.get(unii, "")]),
apprYear,
parent,
rank]
return approved
def nmeStitches(stitch2nmes, stitch, nmelist):
''' defined in main
header = ["UNII -- UNII PT", # can repeat
"Stitch",
"Rank"]
'''
key = stitch['id']
entries = []
for node in stitch['sgroup']['members']:
if "g-srs" in node['source'].lower():
if node['id'] in nmelist:
# print node['id']
# add the UNII and its preferred name to the list
entries.append(" -- ".join([node['id'],
all_uniis.get(node['id'], "")]))
# print entries
if len(entries) > 1:
entries.sort()
entries.insert(1, key)
entries.insert(2, stitch['rank'])
stitch2nmes[entries[0]] = entries
return stitch2nmes
NMEs = []
NMEs2 = []
def nmeClashes(stitch2nmes, stitch):
return nmeStitches(stitch2nmes, stitch, NMEs)
def nmeClashes2(stitch2nmes, stitch):
return nmeStitches(stitch2nmes, stitch, NMEs2)
def PMEClashes(stitch2pmes, stitch):
''' defined in main
header = ["PME Entry",
"Stitch",
"Rank"]
'''
key = stitch['id']
entries = []
for node in stitch['sgroup']['members']:
if "manufacturing" in node['source'].lower():
entries.append(node['name'])
# if more than one PME entry found,
# sort and add stitch info and rank after the first one
if len(entries) > 1:
entries.sort()
entries.insert(1, key)
entries.insert(2, stitch['rank'])
stitch2pmes[entries[0]] = entries
return stitch2pmes
def activemoietyClashes(stitch2ams, stitch):
key = stitch['id']
entries = []
for node in stitch['sgroup']['members']:
if "g-srs" in node['source'].lower():
if 'T_ActiveMoiety' in node['stitches']:
item = node['stitches']['T_ActiveMoiety']
# check if item is a list -- if not, turn into a list
if not isinstance(item, list):
item = [item]
# if length of the t_activemoiety list is longer than 1, ignore
if len(item) > 1:
sys.stderr.write("ignoring multiple active moieties"
" for GSRS entry\n")
# get a preferred name for the active moiety unii
item = " -- ".join([item[0],
all_uniis.get(item[0], "")])
# if not already recoreded, record
if item not in entries:
entries.append(item)
if len(entries) > 1:
entries.sort()
entries.insert(1, key)
entries.insert(2, stitch['rank'])
stitch2ams[entries[0]] = entries
return stitch2ams
orphanList = ['Pharmaceutical Manufacturing Encyclopedia (Third Edition)',
'Broad Institute Drug List 2017-03-27',
'Rancho BioSciences, July 2020',
'DrugBank, July 2020',
'NCATS Pharmaceutical Collection, April 2012',
'Withdrawn and Shortage Drugs List Feb 2018']
def findOrphans(orphans, stitch):
''' defined in main
header = ["Name / UNII / ID",
"Blank / UNII PT",
"Source"]
'''
key = stitch['id']
rank = stitch['rank']
if rank == 1:
node = stitch['sgroup']['members'][0]
if node['source'] in orphanList:
name = ''
id = ''
status = ''
if 'id' in node:
id = node['id']
else:
id = node['name']
if 'name' in node:
name = node['name']
if "broad" in node['source'].lower():
if 'clinical_phase' in stitch['sgroup']['properties']:
status = '|' + stitch['sgroup']['properties']['clinical_phase']['value']
if "drugbank" in node['source'].lower():
if 'groups' in stitch['sgroup']['properties']:
status = ''
for group in stitch['sgroup']['properties']['groups']:
status = status + '|' + group['value']
if "collection" in node['source'].lower():
if 'DATASET' in stitch['sgroup']['properties']:
sets = []
for group in stitch['sgroup']['properties']['DATASET']:
sets.append(group['value'])
sets.sort()
status = '|'.join(sets)
if 'name' in stitch['sgroup']['properties']:
name = stitch['sgroup']['properties']['name']['value']
if "rancho" in node['source'].lower():
if 'Conditions' in stitch['sgroup']['properties']:
status = '|has_conditions'
item = node['source'] + status + "\t" + id
entry = [id, all_uniis.get(id, ""), node['source'], status, name]
orphans[item] = entry
return orphans
def iterateStitches(funcs):
dicts = [{} for d in range(len(funcs))]
top = 10
# max_subs = get_max_subs(100000, top)
# max_subs = 100000
for skip in tqdm(xrange(0, max_subs, top), ncols=100):
uri = site+'api/stitches/v1?top='+str(top)+'&skip='+str(skip)
obj = requestJson(uri)
if 'contents' not in obj:
obj = {'contents': obj}
skip = max_subs
if len(obj['contents']) == 0:
skip = max_subs
elif obj is not None:
for stitch in obj['contents']:
for i in range(len(funcs)):
funcs[i](dicts[i], stitch)
# sys.stderr.write(uri+"\n")
# sys.stderr.flush()
return dicts
def get_site_obj(top, skip):
uri = site + 'api/stitches/v1?top=' + str(top) + '&skip=' + str(skip)
sys.stderr.write("Getting " + uri + "\n")
sys.stderr.flush()
obj = requestJson(uri)
return obj
# TODO: possibly add a way to find the max number of pages
# helpful for a decent progress bar
def get_max_subs(startmax, top):
precision = 1000
# check the page using a start maximum
"Trying to guess the max number of pages to navigate..."
obj = get_site_obj(top, startmax)
# if not contents object present, reduce page number
# or the other way around
if 'contents' not in obj or len(obj['contents']) == 0:
newmax = startmax - precision
sys.stderr.write(str(startmax) + " - too high!\n")
sys.stderr.flush()
else:
newmax = startmax + precision
sys.stderr.write(str(startmax) + " - too low!\n")
sys.stderr.flush()
if abs(newnewmax - startmax) > precision:
# now if you call the same function
# and it returns the same number (startmax)
startmax = get_max_subs(newmax, top)
return newmax
def getName(obj):
name = ""
for member in obj["sgroup"]["members"]:
if name == "":
if "name" in member:
name = member["name"]
elif "N_Name" in member["stitches"]:
if len(member["stitches"]["N_Name"][0]) == 1:
name = str(member["stitches"]["N_Name"])
else:
name = str(member["stitches"]["N_Name"][0])
if name == "":
if "Synonyms" in obj["sgroup"]["properties"]:
if not isinstance(obj["sgroup"]["properties"]["Synonyms"],
(list, tuple)):
name = obj["sgroup"]["properties"]["Synonyms"]["value"]
else:
name = obj["sgroup"]["properties"]["Synonyms"][0]["value"]
if name == "":
if "unii" in obj["sgroup"]["properties"]:
name = obj["sgroup"]["properties"]["unii"][0]["value"]
return name
def getEdges(nodes, edges=[], nodesrc=dict()):
while len(nodes) > 0:
newnodes = []
for item in nodes:
uri = site + "api/node/" + str(item)
obj = requestJson(uri)
nodesrc[item] = obj["datasource"]["name"]
if "neighbors" in obj:
for entry in obj["neighbors"]:
edges.append([item, entry["id"],
entry["reltype"],
entry["value"]])
if entry["id"] not in nodes and entry["id"] not in nodesrc:
newnodes.append(entry["id"])
nodes = newnodes
return edges, nodesrc
def getPathsFromStitch(stitch):
paths = []
path = [stitch[0]]
paths.append(path)
for item in stitch[1:]:
npath = list(path)
npath.append(item)
paths.append(npath)
return paths
def extendPaths(paths, edges):
npaths = []
for path in paths:
for edge in edges:
if edge[0] == path[-1] and edge[1] not in path:
npath = list(path)
npath.append(edge[1])
npaths.append(npath)
return npaths
def get_uniis(unii_path):
uniis = pd.read_csv(unii_path,
sep="\t")
return (uniis[["UNII", "Display Name"]].drop_duplicates()
.set_index("UNII")
.to_dict()["Display Name"])
def output2df(output, test_name, header):
# turn the dict with results into
output_df = pd.DataFrame.from_dict(output,
orient="index")
if len(output_df.index) < 1:
return output_df
# add appropriate header
n_extra_cols = output_df.shape[1] - len(header)
if test_name == "uniiClashes":
header += ["Stitch"]*n_extra_cols
elif (test_name.startswith("nmeClashes")
or test_name == "activemoietyClashes"):
header += ["UNII -- | |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
import tvm
from tvm import tir, script
from tvm.script import tir as T
from tvm.tir import stmt_functor
from tvm.tir.usmp import utils as usmp_utils
from tvm.target import Target
def _replace_stmt_with_buf_var_names(buffer_info_map):
"""helper to replace tir.allocates with buffer names"""
new_buffer_info_map = dict()
for k, v in buffer_info_map.items():
new_buffer_info_map[v.buffer_var.name] = k
return new_buffer_info_map
def _verify_conflicts(main_buf_name, conflicting_buf_names, buffer_info_map):
"""helper to check expected liveness conflicts"""
buf_info = buffer_info_map[main_buf_name]
for conflict in buf_info.conflicts:
assert conflict.name_hint in conflicting_buf_names
def _get_allocates(primfunc):
"""helper to extract all allocate nodes by name"""
allocates = dict()
def get_allocate(stmt):
if isinstance(stmt, tvm.tir.Allocate):
allocates[str(stmt.buffer_var.name)] = stmt
stmt_functor.post_order_visit(primfunc.body, get_allocate)
return allocates
def _assign_poolinfos_to_allocates_in_primfunc(primfunc, pool_infos):
"""helper to assing poolinfos to allocate nodes in a tir.PrimFunc"""
def set_poolinfos(stmt):
if isinstance(stmt, tvm.tir.Allocate):
return tvm.tir.Allocate(
buffer_var=stmt.buffer_var,
dtype=stmt.dtype,
extents=stmt.extents,
condition=stmt.condition,
body=stmt.body,
annotations={tvm.tir.usmp.utils.CANDIDATE_MEMORY_POOL_ATTR: pool_infos},
)
return primfunc.with_body(stmt_functor.ir_transform(primfunc.body, None, set_poolinfos))
def _assign_poolinfos_to_allocates_in_irmodule(mod, pool_infos):
"""helper to assing poolinfos to allocate nodes in a IRModule"""
ret = tvm.IRModule()
for global_var, basefunc in mod.functions.items():
if isinstance(basefunc, tvm.tir.PrimFunc):
ret[global_var] = _assign_poolinfos_to_allocates_in_primfunc(basefunc, pool_infos)
return ret
def _assign_targets_to_primfuncs_irmodule(mod, target):
"""helper to assign target for PrimFunc in a IRModule"""
ret = tvm.IRModule()
for global_var, basefunc in mod.functions.items():
if isinstance(basefunc, tvm.tir.PrimFunc):
ret[global_var] = basefunc.with_attr("target", target)
return ret
def _check_max_workspace_size(buffer_pool_allocations, pool_info, size):
max_workspace_size = 0
for buffer_info, pool_allocation in buffer_pool_allocations.items():
if pool_allocation.pool_info == pool_info:
size_candidate = pool_allocation.byte_offset + buffer_info.size_bytes
if size_candidate > max_workspace_size:
max_workspace_size = size_candidate
assert max_workspace_size == size
def test_no_pool_error():
target = Target("c")
tiny_workspace_pool = usmp_utils.PoolInfo(
pool_name="tiny_workspace",
target_access={target: usmp_utils.PoolInfo.READ_WRITE_ACCESS},
size_hint_bytes=10,
)
bi_a = usmp_utils.BufferInfo(
name_hint="bi_a", size_bytes=10, pool_candidates=[tiny_workspace_pool]
)
bi_b = usmp_utils.BufferInfo(
name_hint="bi_b", size_bytes=10, pool_candidates=[tiny_workspace_pool]
)
bi_c = usmp_utils.BufferInfo(
name_hint="bi_c", size_bytes=10, pool_candidates=[tiny_workspace_pool]
)
bi_a.set_conflicts([bi_b])
bi_b.set_conflicts([bi_c])
bi_c.set_conflicts([bi_a])
buffer_info_arr = [bi_a, bi_b, bi_c]
fusmp_algo = tvm.get_global_func(f"tir.usmp.algo.greedy_by_size")
with pytest.raises(
tvm.TVMError, match="TVM USMP Error: the space available in the provided pools exceeded"
):
buffer_pool_allocations = fusmp_algo(buffer_info_arr)
@pytest.mark.parametrize("algorithm", ["greedy_by_size", "greedy_by_conflicts"])
def test_name_based_ordering(algorithm):
""" This checks when the size and conlicts are same a stable result is generated"""
def _test():
target = Target("c")
global_workspace_pool = usmp_utils.PoolInfo(
pool_name="global_workspace",
target_access={target: usmp_utils.PoolInfo.READ_WRITE_ACCESS},
)
bi_a = usmp_utils.BufferInfo(
name_hint="bi_a", size_bytes=10, pool_candidates=[global_workspace_pool]
)
bi_b = usmp_utils.BufferInfo(
name_hint="bi_b", size_bytes=10, pool_candidates=[global_workspace_pool]
)
bi_c = usmp_utils.BufferInfo(
name_hint="bi_c", size_bytes=10, pool_candidates=[global_workspace_pool]
)
bi_a.set_conflicts([bi_b])
bi_b.set_conflicts([bi_c])
bi_c.set_conflicts([bi_a])
buffer_info_arr = [bi_a, bi_b, bi_c]
fusmp_algo = tvm.get_global_func(f"tir.usmp.algo.{algorithm}")
buffer_pool_allocations = fusmp_algo(buffer_info_arr)
assert buffer_pool_allocations[bi_a].byte_offset == 20
assert buffer_pool_allocations[bi_b].byte_offset == 10
assert buffer_pool_allocations[bi_c].byte_offset == 0
# This is tested for several times to check stability
for x in range(0, 10):
_test()
@pytest.mark.parametrize(
["algorithm", "workspace_size"],
[("greedy_by_size", 140), ("greedy_by_conflicts", 140)],
)
def test_linear(algorithm, workspace_size):
"""
The test case here represent BufferInfo objects
that could get generated for a linear sequence
such as :
(Op A)
|
bi_a
|
(Op B)
|
bi_b
|
.
.
.
(Op F)
|
bi_f
"""
target = Target("c")
global_workspace_pool = usmp_utils.PoolInfo(
pool_name="global_workspace",
target_access={target: usmp_utils.PoolInfo.READ_WRITE_ACCESS},
)
bi_a = usmp_utils.BufferInfo(
name_hint="bi_a", size_bytes=10, pool_candidates=[global_workspace_pool]
)
bi_b = usmp_utils.BufferInfo(
name_hint="bi_b", size_bytes=20, pool_candidates=[global_workspace_pool]
)
bi_c = usmp_utils.BufferInfo(
name_hint="bi_c", size_bytes=100, pool_candidates=[global_workspace_pool]
)
bi_d = usmp_utils.BufferInfo(
name_hint="bi_d", size_bytes=40, pool_candidates=[global_workspace_pool]
)
bi_e = usmp_utils.BufferInfo(
name_hint="bi_e", size_bytes=50, pool_candidates=[global_workspace_pool]
)
bi_f = usmp_utils.BufferInfo(
name_hint="bi_f", size_bytes=50, pool_candidates=[global_workspace_pool]
)
# Creating conflicts for a linear graph
bi_a.set_conflicts([bi_b])
bi_b.set_conflicts([bi_a, bi_c])
bi_c.set_conflicts([bi_b, bi_d])
bi_d.set_conflicts([bi_c, bi_e])
bi_e.set_conflicts([bi_d, bi_f])
bi_f.set_conflicts([bi_e])
buffer_info_arr = [bi_a, bi_b, bi_c, bi_d, bi_e, bi_f]
fusmp_algo = tvm.get_global_func(f"tir.usmp.algo.{algorithm}")
buffer_pool_allocations = fusmp_algo(buffer_info_arr)
_check_max_workspace_size(buffer_pool_allocations, global_workspace_pool, workspace_size)
@pytest.mark.parametrize(
["algorithm", "workspace_size"],
[("greedy_by_size", 190), ("greedy_by_conflicts", 320)],
)
def test_fanout(algorithm, workspace_size):
"""
The test case here represent BufferInfo objects
that could get generated for a fanout topology
such as :
(Op A)
|
bi_a ---------
| |
(Op B) (Op C)
| |
bi_b bi_c
| |
(Op D) (Op E)
| |
bi_d bi_e
| |
(Op F) ------
|
bi_f
|
(Op G)
|
bi_g
"""
target = Target("c")
global_workspace_pool = usmp_utils.PoolInfo(
pool_name="global_workspace",
target_access={target: usmp_utils.PoolInfo.READ_WRITE_ACCESS},
)
bi_a = usmp_utils.BufferInfo(
name_hint="bi_a", size_bytes=10, pool_candidates=[global_workspace_pool]
)
bi_b = usmp_utils.BufferInfo(
name_hint="bi_b", size_bytes=20, pool_candidates=[global_workspace_pool]
)
bi_c = usmp_utils.BufferInfo(
name_hint="bi_c", size_bytes=100, pool_candidates=[global_workspace_pool]
)
bi_d = usmp_utils.BufferInfo(
name_hint="bi_d", size_bytes=40, pool_candidates=[global_workspace_pool]
)
bi_e = usmp_utils.BufferInfo(
name_hint="bi_e", size_bytes=50, pool_candidates=[global_workspace_pool]
)
bi_f = usmp_utils.BufferInfo(
name_hint="bi_f", size_bytes=60, pool_candidates=[global_workspace_pool]
)
bi_g = usmp_utils.BufferInfo(
name_hint="bi_g", size_bytes=70, pool_candidates=[global_workspace_pool]
)
# Creating conflicts for a linear graph
bi_a.set_conflicts([bi_b, bi_c])
bi_b.set_conflicts([bi_a, bi_c, bi_e])
bi_c.set_conflicts([bi_e, bi_a, bi_b, bi_d])
bi_d.set_conflicts([bi_b, bi_f, bi_c, bi_e])
bi_e.set_conflicts([bi_c, bi_f, bi_b, bi_d])
bi_f.set_conflicts([bi_d, bi_e, bi_f])
bi_g.set_conflicts([bi_f])
buffer_info_arr = [bi_a, bi_b, bi_c, bi_d, bi_e, bi_f, bi_g]
fusmp_algo = tvm.get_global_func(f"tir.usmp.algo.{algorithm}")
buffer_pool_allocations = fusmp_algo(buffer_info_arr)
_check_max_workspace_size(buffer_pool_allocations, global_workspace_pool, workspace_size)
# fmt: off
@tvm.script.ir_module
class MobilenetStructure:
@T.prim_func
def tvmgen_default_fused_cast_subtract(placeholder_2: T.handle, placeholder_3: T.handle, T_subtract: T.handle) -> None:
# function attr dict
T.func_attr({"global_symbol": "tvmgen_default_fused_cast_subtract", "tir.noalias": True})
placeholder_4 = T.match_buffer(placeholder_2, [1, 224, 224, 3], dtype="uint8", elem_offset=0, align=128, offset_factor=1)
placeholder_5 = T.match_buffer(placeholder_3, [], dtype="int16", elem_offset=0, align=128, offset_factor=1)
T_subtract_1 = T.match_buffer(T_subtract, [1, 224, 224, 3], dtype="int16", elem_offset=0, align=128, offset_factor=1)
# body
for ax0_ax1_fused_1 in T.serial(0, 224):
for ax2_1, ax3_inner_1 in T.grid(224, 3):
T.store(T_subtract_1.data, (((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1), (T.cast(T.load("uint8", placeholder_4.data, (((ax0_ax1_fused_1*672) + (ax2_1*3)) + ax3_inner_1)), "int16") - T.load("int16", placeholder_5.data, 0)), True)
@T.prim_func
def tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast(placeholder_62: T.handle, placeholder_63: T.handle, placeholder_64: T.handle, T_cast_20: T.handle) -> None:
# function attr dict
T.func_attr({"global_symbol": "tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast", "tir.noalias": True})
placeholder_65 = T.match_buffer(placeholder_62, [1, 224, 224, 3], dtype="int16", elem_offset=0, align=128, offset_factor=1)
placeholder_66 = T.match_buffer(placeholder_63, [7, 7, 3, 64], dtype="int16", elem_offset=0, align=128, offset_factor=1)
placeholder_67 = T.match_buffer(placeholder_64, [1, 1, 1, 64], dtype="int32", elem_offset=0, align=128, offset_factor=1)
T_cast_21 = T.match_buffer(T_cast_20, [1, 112, 112, 64], dtype="uint8", elem_offset=0, align=128, offset_factor=1)
# body
PaddedInput_7 = T.allocate([157323], "int16", "global")
for i0_i1_fused_7 in T.serial(0, 229):
for i2_7, i3_7 in T.grid(229, 3):
T.store(PaddedInput_7, (((i0_i1_fused_7*687) + (i2_7*3)) + i3_7), T.if_then_else(((((2 <= i0_i1_fused_7) and (i0_i1_fused_7 < 226)) and (2 <= i2_7)) and (i2_7 < 226)), T.load("int16", placeholder_65.data, ((((i0_i1_fused_7*672) + (i2_7*3)) + i3_7) - 1350)), T.int16(0), dtype="int16"), True)
for ax0_ax1_fused_ax2_fused_7 in T.serial(0, 12544):
Conv2dOutput_7 = T.allocate([64], "int32", "global")
for ff_3 in T.serial(0, 64):
T.store(Conv2dOutput_7, ff_3, 0, True)
for ry_2, rx_2, rc_7 in T.grid(7, 7, 3):
T.store(Conv2dOutput_7, ff_3, (T.load("int32", Conv2dOutput_7, ff_3) + (T.cast(T.load("int16", PaddedInput_7, (((((T.floordiv(ax0_ax1_fused_ax2_fused_7, 112)*1374) + (ry_2*687)) + (T.floormod(ax0_ax1_fused_ax2_fused_7, 112)*6)) + (rx_2*3)) + rc_7)), "int32")*T.cast(T.load("int16", placeholder_66.data, ((((ry_2*1344) + (rx_2*192)) + (rc_7*64)) + ff_3)), "int32"))), True)
for ax3_inner_7 in T.serial(0, 64):
T.store(T_cast_21.data, ((ax0_ax1_fused_ax2_fused_7*64) + ax3_inner_7), T.cast(T.max(T.min(T.q_multiply_shift((T.load("int32", Conv2dOutput_7, ax3_inner_7) + T.load("int32", placeholder_67.data, ax3_inner_7)), 1939887962, 31, -9, dtype="int32"), 255), 0), "uint8"), True)
@T.prim_func
def tvmgen_default_fused_nn_max_pool2d_cast(placeholder_28: T.handle, T_cast_6: T.handle) -> None:
# function attr dict
T.func_attr({"global_symbol": "tvmgen_default_fused_nn_max_pool2d_cast", "tir.noalias": True})
placeholder_29 = T.match_buffer(placeholder_28, [1, 112, 112, 64], dtype="uint8", elem_offset=0, align=128, offset_factor=1)
T_cast_7 = T.match_buffer(T_cast_6, [1, 56, 56, 64], dtype="int16", elem_offset=0, align=128, offset_factor=1)
# body
tensor_2 = T.allocate([200704], "uint8", "global")
for ax0_ax1_fused_4 in T.serial(0, 56):
for ax2_4 in T.serial(0, 56):
for ax3_init in T.serial(0, 64):
T.store(tensor_2, (((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_init), T.uint8(0), True)
for rv0_rv1_fused_1, ax3_2 in T.grid(9, 64):
T.store(tensor_2, (((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_2), T.max(T.load("uint8", tensor_2, (((ax0_ax1_fused_4*3584) + (ax2_4*64)) + ax3_2)), T.if_then_else(((((ax0_ax1_fused_4*2) + T.floordiv(rv0_rv1_fused_1, 3)) < 112) and (((ax2_4*2) + T.floormod(rv0_rv1_fused_1, 3)) < 112)), T.load("uint8", placeholder_29.data, (((((ax0_ax1_fused_4*14336) + (T.floordiv(rv0_rv1_fused_1, 3)*7168)) + (ax2_4*128)) + (T.floormod(rv0_rv1_fused_1, 3)*64)) + ax3_2)), T.uint8(0), dtype="uint8")), True)
for ax0_ax1_fused_5 in T.serial(0, 56):
for ax2_5, ax3_3 in T.grid(56, 64):
T.store(T_cast_7.data, (((ax0_ax1_fused_5*3584) + (ax2_5*64)) + ax3_3), T.cast(T.load("uint8", tensor_2, (((ax0_ax1_fused_5*3584) + (ax2_5*64)) + ax3_3)), "int16"), True)
@T.prim_func
def run_model(input: T.handle, output: T.handle) -> None:
# function attr dict
T.func_attr({"global_symbol": "tvmgen_default_run_model", "runner_function": True})
# body
T.attr("default", "device_id", 0)
T.attr("default", "device_type", 1)
sid_9 = T.allocate([301056], "int8", "global")
sid_8 = T.allocate([802816], "int8", "global")
T.evaluate(T.call_extern("tvmgen_default_fused_cast_subtract", input, T.lookup_param("p0", dtype="handle"), sid_9, dtype="int32"))
T.evaluate(T.call_extern("tvmgen_default_fused_nn_conv2d_add_fixed_point_multiply_clip_cast", sid_9, T.lookup_param("p1", dtype="handle"), T.lookup_param("p2", dtype="handle"), sid_8, dtype="int32"))
T.evaluate(T.call_extern("tvmgen_default_fused_nn_max_pool2d_cast", sid_8, output, dtype="int32"))
__tvm_meta__ = None
# fmt: on
@pytest.mark.parametrize(
["algorithm", "fast_memory_size", "slow_memory_size"],
[("greedy_by_size", 200704, 1418528), ("greedy_by_conflicts", 200704, 1418528)],
)
def test_mobilenet_subgraph(algorithm, fast_memory_size, slow_memory_size):
target = Target("c")
fast_memory_pool = usmp_utils.PoolInfo(
pool_name="fast_memory",
target_access={target: usmp_utils.PoolInfo.READ_WRITE_ACCESS},
size_hint_bytes=200704,
)
slow_memory_pool = usmp_utils.PoolInfo(
pool_name="slow_memory", | |
devtools: bool = False,
slowMo: timedelta = timedelta(seconds=0),
channel: Optional[str] = None,
) -> str:
"""Create a new playwright Browser with specified options.
See `Browser, Context and Page` for more information about Browser and related concepts.
Returns a stable identifier for the created browser.
``browser`` Opens the specified browser. Defaults to chromium.
``headless`` Set to False if you want a GUI. Defaults to False.
``executablePath`` Path to a browser executable to run instead of the bundled one.
If executablePath is a relative path, then it is resolved relative to current working
directory. Note that Playwright only works with the bundled Chromium, Firefox or
WebKit, use at your own risk. Defaults to None.
``args`` Additional arguments to pass to the browser instance. The list of
Chromium flags can be found [http://peter.sh/experiments/chromium-command-line-switches/ | here].
Defaults to None.
``ignoreDefaultArgs`` If an array is given, then filters out the given default arguments.
Defaults to None.
``proxy`` Network proxy settings.
- server <string> Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example ``http://myproxy.com:3128`` or ``socks5://myproxy.com:3128``. Short form ``myproxy.com:3128`` is considered an HTTP proxy.
- bypass <string> Optional coma-separated domains to bypass proxy, for example ``".com, chromium.org, .domain.com"``.
- username <string> Optional username to use if HTTP proxy requires authentication.
- password <string> Optional password to use if HTTP proxy requires authentication.
``downloadsPath`` If specified, accepted downloads are downloaded into this folder.
Otherwise, temporary folder is created and is deleted when browser is closed.
``handleSIGINT`` Close the browser process on Ctrl-C. Defaults to True.
``handleSIGTERM`` Close the browser process on SIGTERM. Defaults to True.
``handleSIGHUP`` Close the browser process on SIGHUP. Defaults to True.
``timeout`` Maximum time in milliseconds to wait for the browser instance to start.
Defaults to 30000 (30 seconds). Pass 0 to disable timeout.
``env`` <Dict<str, str|int|bool>> Specify environment variables that will
be visible to the browser. Defaults to None.
``devtools`` Chromium-only Whether to auto-open a Developer Tools panel for each tab.
If this option is true, the headless option will be set false.
``slowMo`` Slows down Playwright operations by the specified amount of milliseconds.
Useful so that you can see what is going on. Defaults to no delay.
``channel`` Allows to operate against the stock Google Chrome and Microsoft Edge browsers.
For more details see:
[https://playwright.dev/docs/browsers/#google-chrome--microsoft-edge|Playwright documentation].
"""
params = locals_to_params(locals())
params = convert_typed_dict(self.new_context.__annotations__, params)
if timeout:
params["timeout"] = self.convert_timeout(timeout)
params["slowMo"] = self.convert_timeout(slowMo)
browser_path = self.library.external_browser_executable.get(browser)
if browser_path:
params["executablePath"] = browser_path
if channel and browser != SupportedBrowsers.chromium:
raise ValueError(
f"Must use {SupportedBrowsers.chromium.name} browser with channel definition"
)
trace_dir = self.traces_output / str(uuid4())
params["tracesDir"] = str(trace_dir)
options = json.dumps(params, default=str)
logger.info(options)
with self.playwright.grpc_channel() as stub:
response = stub.NewBrowser(
Request().Browser(browser=browser.name, rawOptions=options)
)
logger.info(response.log)
return response.body
@keyword(tags=("Setter", "BrowserControl"))
@attribute_warning(
old_args=("videosPath", "videoSize"), new_args=("recordVideo", "recordVideo")
)
def new_context(
self,
acceptDownloads: bool = False,
ignoreHTTPSErrors: bool = False,
bypassCSP: bool = False,
viewport: Optional[ViewportDimensions] = None,
userAgent: Optional[str] = None,
deviceScaleFactor: float = 1.0,
isMobile: bool = False,
hasTouch: bool = False,
javaScriptEnabled: bool = True,
timezoneId: Optional[str] = None,
geolocation: Optional[GeoLocation] = None,
locale: Optional[str] = None,
permissions: Optional[List[str]] = None,
extraHTTPHeaders: Optional[Dict[str, str]] = None,
offline: bool = False,
httpCredentials: Optional[HttpCredentials] = None,
colorScheme: Optional[ColorScheme] = None,
proxy: Optional[Proxy] = None,
videosPath: Optional[str] = None,
videoSize: Optional[ViewportDimensions] = None,
defaultBrowserType: Optional[SupportedBrowsers] = None,
hideRfBrowser: bool = False,
recordVideo: Optional[RecordVideo] = None,
recordHar: Optional[RecordHar] = None,
tracing: Optional[str] = None,
screen: Optional[Dict[str, int]] = None,
storageState: Optional[str] = None,
) -> str:
"""Create a new BrowserContext with specified options.
See `Browser, Context and Page` for more information about BrowserContext.
Returns a stable identifier for the created context
that can be used in `Switch Context`.
``acceptDownloads`` Whether to automatically downloads all the attachments.
Defaults to False where all the downloads are canceled.
``ignoreHTTPSErrors`` Whether to ignore HTTPS errors during navigation.
Defaults to False.
``bypassCSP`` Toggles bypassing page's Content-Security-Policy. Defaults to False.
``viewport`` Sets a consistent viewport for each page.
Defaults to an ``{'width': 1280, 'height': 720}`` viewport.
Value of ``viewport`` can be a dict or a string
representation of a dictionary.
``userAgent`` Specific user agent to use in this context.
``deviceScaleFactor`` Specify device scale factor
(can be thought of as dpr). Defaults to 1.
``isMobile`` Whether the meta viewport tag is taken into account
and touch events are enabled. Defaults to False. Not supported in Firefox.
``hasTouch`` Specifies if viewport supports touch events. Defaults to False.
``javaScriptEnabled`` Whether or not to enable JavaScript in the context.
Defaults to True.
``timezoneId`` Changes the timezone of the context. See
[https://source.chromium.org/chromium/chromium/src/+/master:third_party/icu/source/data/misc/metaZones.txt | ICU’s metaZones.txt]
for a list of supported timezone IDs.
``geolocation`` Sets the geolocation. No location is set by default.
- ``latitude`` <number> Latitude between -90 and 90.
- ``longitude`` <number> Longitude between -180 and 180.
- ``accuracy`` Optional <number> Non-negative accuracy value. Defaults to 0.
Example usage: ``{'latitude': 59.95, 'longitude': 30.31667}``
``locale`` Specify user locale, for example ``en-GB``, ``de-DE``, etc.
Locale will affect ``navigator.language`` value, ``Accept-Language`` request header value
as well as number and date formatting rules.
``permissions`` A list of permissions to grant to all pages in this context. See
[https://playwright.dev/docs/api/class-browsercontext#browsercontextgrantpermissionspermissions-options| grantPermissions]
for more details.
``extraHTTPHeaders`` A dictionary containing additional HTTP headers
to be sent with every request. All header values must be strings.
``offline`` Whether to emulate network being offline. Defaults to False.
``httpCredentials`` Credentials for
[https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication|HTTP authentication].
- example: ``{'username': '$username', 'password': <PASSWORD>'}``
- ``username``
- ``password``
Direct usage of username and password is not recommended, but is possible. If username and password
is directly used, it can leak secret information to Robot Framework output files. Instead the username
and password values can be prefixed with ``$`` or ``%``. Then keyword will internally resolve the
values and secrets are not leaked to Robot Framework output files. The ``$`` prefix will resolve Robot
Framework variable and ``%`` will resolve environment variable. If
[https://marketsquare.github.io/robotframework-browser/Browser.html#Importing|enable_playwright_debug]
is enabled, all secrets are written as plain text in Playwright debugs logs.
``colorScheme`` Emulates 'prefers-colors-scheme'
media feature, supported values are 'light', 'dark', 'no-preference'. See
[https://playwright.dev/docs/api/class-page#pageemulatemediaparams|emulateMedia(options)]
for more details. Defaults to ``light``.
``proxy`` Network proxy settings to use with this context.
Note that browser needs to be launched with the global proxy for this option to work.
If all contexts override the proxy, global proxy will be never used and can be any string
``videosPath`` is deprecated by playwright, use recordVideo instead.
Enables video recording for all pages to videosPath
folder. If videosPath is not existing folder, videosPath folder is created
under ${OUTPUT_DIR}/browser/video/ folder. If videosPath is not specified,
videos are not recorded.
``videoSize`` is deprecated by playwright, use recordVideo instead.
Specifies dimensions of the automatically recorded
video. Can only be used if videosPath is set. If not specified the size will
be equal to viewport. If viewport is not configured explicitly the video size
defaults to 1280x720. Actual picture of the page will be scaled down if
necessary to fit specified size.
- Example {"width": 1280, "height": 720}
``defaultBrowserType`` If no browser is open and `New Context` opens a new browser
with defaults, it now uses this setting.
Very useful together with `Get Device` keyword:
``recordVideo`` enables video recording for all pages into a folder. If not
specified videos are not recorded. Make sure to close context for videos to be saved.
``recordVideo`` is dictionary containing `dir` and `size` keys. If `dir` is not
existing folder, videosPath folder is created under
${OUTPUT_DIR}/browser/video/ folder. `size` Optional dimensions of the recorded
videos. If not specified the size will be equal to viewport. If viewport is not
configured explicitly the video size defaults to 1280x720. Actual picture of
each page will be scaled down if necessary to fit the specified size.
`size` is dictionary containing `width` (Video frame width) and `height`
(Video frame height) keys.
``recordHar`` Enables [http://www.softwareishard.com/blog/har-12-spec/|HAR] recording
for | |
#!/usr/bin/python
import xml.dom.minidom
import sys
from optparse import OptionParser
import random
from hadoop_conf import *
chunk_size = []
def xml_children(node, children_name):
"""return list of node's children nodes with name of children_name"""
return node.getElementsByTagName(children_name)
def xml_text(node):
return node.childNodes[0].nodeValue
def xml_child_text(node, child_name):
"""probably encoded in utf-8, be careful."""
return xml_text(xml_children(node, child_name)[0])
class empty_t:
pass
class hnode_t:
"""HDFS node for a HDFS tree.
5-level hierarchy: rack_group (multiple identical racks), rack, node_group
(multiple identical nodes), node, and disk.
disk should be initiated with a capacity. Other nodes' capacity are
calculated by summing up children's capacity."""
def __init__(self, parent, capacity=None, num=1):
self.parent = parent
self._capacity = capacity
self._num = num
self._children = []
self.used = 0
self.end = None
self.reserved = None
if parent <> None:
self.index_stack = parent.index_stack[:] + [len(parent.children())]
parent.children().append(self)
if parent._capacity <> None:
parent._capacity = None
else:
self.index_stack = []
def clone(self, parent=None):
'''clone a node from self, and append it to parent's children'''
if parent == None:
parent = self.parent
node = hnode_t(parent, self._capacity)
node._children = []
if self._children <> []:
for child in self._children:
#print self, self.parent, self._children
child.clone(node)
#node._children.append(child.clone(node)) ## wrong!!!
node.used = 0
node.reserved = self.reserved
return node
def capacity(self):
if self._capacity <> None:
return self._capacity
else :
assert self._children <> []
self._capacity = 0
for child in self._children:
self._capacity += child.capacity()
return self._capacity
def children(self):
return self._children;
def add_chunk(self):
if self.used >= self.capacity():
print 'error: node full' + self.index_stack
self.used += chunk_size
parent = self.parent
if parent != None:
parent.add_chunk()
def name(self):
if len(self.index_stack) == 5: #disk
return 'd_rg%d_%d_ng%d_%d_disk%d' % tuple(self.index_stack)
elif len(self.index_stack) == 4: #node
return 'n_rg%d_%d_ng%d_%d' % tuple(self.index_stack)
elif len(self.index_stack) == 3: #node group template
return 'n_rg%d_%d_ng%d' % tuple(self.index_stack)
elif len(self.index_stack) == 2: #rack
return 'r_rg%d_%d' % tuple(self.index_stack)
elif len(self.index_stack) == 1: #rack_group
return 'rg_rg%d' % tuple(self.index_stack)
else:
print 'error: request name for unknown node type. (' \
+ self.index_stack + ')'
def dump(self, level=0):
if options.verbose == False:
return
print self.index_stack, self.used, self._capacity, len(self.children())
node = self
if node.children() <> []:
for child in node.children():
child.dump()
def prev_node(self):
if self.index_stack == []:
return None
myindex = self.index_stack[-1]
if myindex == 0:
return self.parent.prev_node()
siblings = self.parent.children()
return siblings[myindex-1]
def global_end(self):
'''global index at the end of a node'''
if self.end <> None:
return self.end
# end should be previous node's end + self.capacity()
prev = self.prev_node()
if prev <> None:
self.end = prev.global_end() + self.capacity()
else:
# Otherwise, this is a first node
self.end = self.capacity()
return self.end
def choose_disk(self):
'''when a node is chosen for replication, it needs to choose a disk to put the data.'''
if self.used >= self.capacity():
return None
disk_id = random.randrange(len(self.children()))
disk = self.children()[disk_id]
if disk.used < disk.capacity():
return disk
else:
return self.choose_disk()
class machine_type_t:
def __init__(self, mt):
disk = xml_children(mt, u'disk')[0]
self.disk = empty_t()
self.disk.type = str(xml_child_text(disk, u'type'))
self.disk.capacity = int(xml_child_text(disk, u'capa'))*1024 # in MB
self.disk.num = int(xml_child_text(disk, u'num'))
cpu = xml_children(mt, u'cpu')[0]
self.cpu = empty_t()
self.cpu.type = str(xml_child_text(cpu, u'type'))
self.cpu.cores = int(xml_child_text(cpu, u'number_of_cores'))
self.cpu.num = int(xml_child_text(cpu, u'num'))
mem = xml_children(mt, u'mem')[0]
self.mem = empty_t()
self.mem.type = str(xml_child_text(mem, u'type'))
self.mem.capacity = str(xml_child_text(mem, u'capa')) # in MB
# TODO: other parts of machine_type
class topology_t:
def __init__(self, topo_xml):
root = xml.dom.minidom.parse(topo_xml)
self.htree = hnode_t(None)
self.dmt = {} # dict of machine type
topo = root.getElementsByTagName(u"topo")[0]
# populate dict of machine type
list_machine_type = topo.getElementsByTagName(u'machine_type')
for mt_node in list_machine_type:
name = str(xml_child_text(mt_node, u'name'))
self.dmt[name] = machine_type_t(mt_node)
# topology
for rack_group in xml_children(topo, u"rack_group"):
rg_node = hnode_t(self.htree)
# rgname not in use currently. maybe a name-node map is needed.
rg_node.rgname = str(xml_child_text(rack_group, u'name'))
num_rack = len(xml_children(rack_group, u"rack_index"))
self.racks = num_rack
rack_node = hnode_t(rg_node)
# populate the first rack_node
for node_group in xml_children(rack_group, u"compute_node_group"):
ng_node = hnode_t(rack_node)
# machine type and disk
mt_name = str(xml_child_text(node_group, u'machine_type_name'))
mt = self.dmt[mt_name]
ng_node.reserved = mt
num_node = len(xml_children(node_group, u'node_index'))
self.nodes = num_node
node_node = hnode_t(ng_node)
# populate the first node_node
for i in range(mt.disk.num):
disk_node = hnode_t(node_node, mt.disk.capacity)
#self.htree.dump()
# clone other node_nodes
for i in range(num_node-1):
new_node_node = node_node.clone()
#self.htree.dump()
# clone other rack_nodes
for i in range(num_rack-1):
new_rack_node = rack_node.clone()
#self.htree.dump()
self.routers = []
for router in xml_children(topo, u'router'):
rt = empty_t()
rt.connect_to_groups = []
for connect_to_group in xml_children(router, u'connect_to_group'):
rgname = str(xml_child_text(connect_to_group, u'rack_group_name'))
switch = empty_t()
switch.rg = self.find_hnode(tuple([int(rgname[5:])]))
switch.index = int(xml_child_text(connect_to_group, u'switch_index'))
rt.connect_to_groups.append(switch)
rt.name = str(xml_child_text(router, u'name'))
self.routers.append(rt)
self.data_nodes = int(xml_child_text(topo, u'data_nodes'))
self.job_tracker = str(xml_child_text(topo, u'job_tracker'))
topology = xml_children(topo, u'topology')
if len(topology) > 0 :
self.topology = str(xml_text(topology[0]))
else:
self.topology = None
def find_hnode(self, index_stack):
if len(index_stack) > 5:
print 'Wrong index stack' + index_stack
return None
node = self.htree
for i in index_stack:
children = node.children()
node = children[i]
return node
def totcl(self, topo_tcl):
f = open(topo_tcl, 'w')
f.write('set int_bw %s\n' % (int_bw))
f.write('set int_latency %s\n' % (int_latency))
num_of_nodes = 0
if self.topology == 'dcell':
# special case, assume everything is symmetric
# take the first ng to get mt (machine type)
# number of nodes in a rack matters,
# number of racks does not matter.
rg = self.htree.children()[0]
racks = len(rg.children())
r = rg.children()[0]
ng = r.children()[0]
nodes = len(ng.children())
mt = ng.reserved
f.write('set cpu_freq %f\n' % (freq_table[mt.cpu.type]))
f.write('set cpu_cores %d\n' % (mt.cpu.cores * mt.cpu.num))
f.write('set rbw %f\n' % (read_bw_table[mt.disk.type]))
f.write('set wbw %f\n' % (write_bw_table[mt.disk.type]))
f.write("\nset num_of_nodes %d\n" % (self.data_nodes))
f.write('setup_2level_dcell %d\n' % (nodes))
f.write('\n')
f.write('set jt $%s\n' % (self.job_tracker))
f.write('set racks %d\n' % (racks))
f.write('set nodes %d\n' % (nodes))
f.write('set data_nodes %d\n' % (self.data_nodes))
f.write('set_mapnodes %d %d %d\n' % (racks, nodes, self.data_nodes))
f.write('\n')
f.close()
return
for rg in self.htree.children():
self.racks = len(rg.children())
for r in rg.children():
f.write('set %s [$ns node]\n' % (r.name()))
for ng in r.children():
self.nodes = len(ng.children())
mt = ng.reserved
# cpu information for all nodes in a node group
freq = freq_table[mt.cpu.type]
cores = mt.cpu.cores * mt.cpu.num
# disk read and write bandwidths
rbw = read_bw_table[mt.disk.type]
wbw = write_bw_table[mt.disk.type]
f.write('for {set i 0} {$i < %d} {incr i} {\n' \
% (len(ng.children())))
f.write('\tnewnode "%s_$i" $%s\n' % (ng.name(), r.name()))
num_of_nodes += len(ng.children())
#f.write('\t$n30 set freq %f\n' % (freq))
f.write('\t$n30 set tasklist [new MRPerf/TaskList %f %d]\n' % (freq, cores))
f.write('\tfor {set j 0} {$j < %d} {incr j} {\n' \
% (mt.disk.num))
f.write('\t\t$n30 newdisk %f %f\n' % (rbw, wbw))
f.write('\t}\n')
f.write('}\n')
f.write('\n')
if True:
# Guanying 2009.3.10: add a dedicated jobtracker
# it does not count into num_of_nodes
rg = self.htree.children()[0]
r = rg.children()[0]
ng = r.children()[0]
mt = ng.reserved
# cpu information for all nodes in a node group
freq = freq_table[mt.cpu.type]
cores = mt.cpu.cores * mt.cpu.num
# disk read and write bandwidths
rbw = read_bw_table[mt.disk.type]
wbw = write_bw_table[mt.disk.type]
'''
jt = ng.name()+'_jobtracker'
f.write('\nnewnode "%s" $%s\n' % (jt, r.name()))
f.write('set jt $%s\n' % (jt))
f.write('$jt set tasklist [new MRPerf/TaskList %f %d]\n' % (freq, cores))
f.write('for {set j 0} {$j < %d} {incr j} {\n' \
% (mt.disk.num))
f.write('\t$jt newdisk %f %f\n' % (rbw, wbw))
f.write('}\n')'''
#f.write("\nset num_of_nodes %d\n" % (num_of_nodes))
f.write("\nset num_of_nodes %d\n" % (self.data_nodes))
for rt in self.routers:
f.write('set %s [$ns node]\n' % (rt.name))
f.write('$%s shape hexagon\n' % (rt.name))
f.write('\n')
for switch in rt.connect_to_groups:
for r in switch.rg.children():
f.write('$ns duplex-link $%s $%s %s %s DropTail\n' \
% (r.name(), rt.name, ext_bw, ext_latency))
f.write('\n')
f.write('set jt $%s\n' % (self.job_tracker))
f.write('set racks %d\n' % (self.racks))
f.write('set nodes %d\n' % (self.nodes))
f.write('set data_nodes %d\n' % (self.data_nodes))
f.write('set_mapnodes %d %d %d\n' % (self.racks, self.nodes, self.data_nodes))
f.write('\n')
f.close()
def totcl2(self, mapnodes_tcl):
f = open(mapnodes_tcl, 'w')
for rg_id in range(len(self.htree.children())):
rg = self.htree.children()[rg_id]
racks = len(rg.children())
f.write('for {set i 0} {$i < %d} {incr i} {\n' % (racks))
r = rg.children()[0]
for ng_id in range(len(r.children())):
ng = r.children()[ng_id]
nodes = len(ng.children())
f.write('\tfor {set j 0} {$j < %d} {incr j} {\n' % (nodes))
n = ng.children()[0]
'''
set mn [format "%s%s%s%s" "\$n_rg0_" $i "_ng0_" $j]
set tcp0 [new Agent/TCP/FullTcp]
set dummy [new MRPerf/NodeApp $tcp0]
eval "$dummy set hnode $mn"
set app11 [$dummy new-connection $jt]
$ns at 0.05 "$app11 snd {heartbeat}"
'''
f.write('\t\tset mn [format "%%s%%s%%s%%s" "\\$n_rg%d_" $i "_ng%d_" $j]\n' % (rg_id, ng_id))
f.write('\t\tset tcp0 [new Agent/TCP/FullTcp]\n')
f.write('\t\tset dummy [new MRPerf/NodeApp $tcp0]\n')
f.write('\t\teval "$dummy set hnode $mn"\n')
f.write('\t\tset app11 [$dummy new-connection $jt]\n')
f.write('\t\t$ns at 0.05 "$app11 send_heartbeat"\n')
f.write('\t}\n')
f.write('}\n')
f.write('\n')
f.close()
class conf_t:
def __init__(self, gen_xml):
root = xml.dom.minidom.parse(gen_xml)
conf = xml_children(root, u'conf')[0]
self.path = str(xml_child_text(conf, u'path'))
files_node = xml_children(conf, u'number_files')[0]
self.files = empty_t()
self.files.min = int(xml_child_text(files_node, u'min_files'))
self.files.max = int(xml_child_text(files_node, u'max_files'))
size_node = xml_children(conf, u'file_size')[0]
self.size = empty_t()
self.size.unit_size = int(xml_child_text(size_node, u'unit_size')) #MB
global chunk_size
chunk_size = self.size.unit_size
self.size.min_unit = int(xml_child_text(size_node, u'min_unit'))
self.size.max_unit = int(xml_child_text(size_node, u'max_unit'))
self.replicas = int(xml_child_text(conf, u'replication_level'))
self.method = str(xml_child_text(conf, u'gen_method'))
self.name_node = str(xml_child_text(conf, u'name_node'))
#TODO: move into xml
self.factor = 0.5
class job_t:
def __init__(self, job_xml):
root = xml.dom.minidom.parse(job_xml)
job_node = xml_children(root, u'job')[0]
self.tcl = 'set cycles_per_byte ' + \
str(xml_child_text(job_node, u'cycles_per_byte')) + \
'\n\t# in cycles per byte, 1G cycles per 1GB\n\n'
filter_ratio_node = xml_children(job_node, u'filter_ratio')[0]
distr_node = [node for node in filter_ratio_node.childNodes \
if node.nodeType == node.ELEMENT_NODE][0]
s = str(distr_node.nodeName)
self.tcl += 'set filter_ratio [new RandomVariable/%s]\n' % \
(s.capitalize())
if (distr_node.nodeName == u'constant'):
self.tcl += '$filter_ratio set val_ %s \n' % (xml_text(distr_node))
elif (distr_node.nodeName == u'uniform'):
self.tcl += '$filter_ratio set min_ ' + \
str(xml_child_text(distr_node, u'uniform_min')) + '\n'
self.tcl += '$filter_ratio set max_ ' + \
str(xml_child_text(distr_node, u'uniform_max')) + '\n'
elif (distr_node.nodeName == u'pareto'):
self.tcl += '$filter_ratio set avg_ %s\n' % \
(xml_child_text(distr_node, u'pareto_scale'))
self.tcl += '$filter_ratio set shape_ %s\n' % \
(xml_child_text(distr_node, u'pareto_shape'))
elif (distr_node.nodeName == u'exponential'):
self.tcl += '$filter_ratio set avg_ %f\n' % \
(1/float(xml_child_text(distr_node, u'exp_lambda')))
elif (distr_node.nodeName == u'normal'):
self.tcl += '$filter_ratio set avg_ %s\n' % \
(xml_child_text(distr_node, u'normal_average'))
self.tcl += '$filter_ratio set std_ %s\n' % \
(xml_child_text(distr_node, u'normal_variance'))
else:
print 'warning: unknown distribution method'
self.tcl += '\n'
self.tcl += 'set avg_record_size %s\n\t# in byte\n' % \
(xml_child_text(job_node, u'average_record_size'))
self.tcl += 'set jt $%s\n' % (xml_child_text(job_node, u'job_tracker'))
self.input = str(xml_child_text(job_node, u'input_dir'))
self.output = str(xml_child_text(job_node, u'output_dir'))
self.tcl += '\n'
def _const(self):
return self.constant
def _uniform(self):
return random.uniform(self.uniform.min, self.uniform.max)
def _pareto(self):
return random.paretovariate(self.pareto.alpha)
def _gauss(self):
return random.gauss(self.gauss.mu, self.gauss.sigma)
def _expo(self):
return random.expovariate(self.expo.lambd)
global_i = 0
def get_new_filename():
global global_i
filename = 'file_'+str(global_i).zfill(8)
global_i += 1
return filename
class disk_t:
def __init__(self, rg, rack, ng, node, disk):
self.rg = rg
self.rack = rack
self.ng = ng
self.node = node
self.disk = disk
def name(self):
return 'n_rg%d_%d_ng%d_%d_disk%d' % (rg, rack, ng, node, disk)
global_last_chunk_on_disk = None
global_linear_chunk_index = 0
class distribute_linear:
def __init__(self, topo):
self.topo = topo
def distribute_chunk(self, replicas=1):
'''search the tree to find a node with used < capacity().'''
'''wanggy 2008.7.9:
Note that | |
'O local que a pessoa vai, que pode ser genérico (para Relatórios) ou preciso (para exibir em um mapa). Digite alguns caracteres para procurar nos locais disponíveis.',
'The Media Library provides a catalog of digital media.': 'A Biblioteca de mídias fornece um catálogo de mídia digital.',
'The Messaging Module is the main communications hub of the Sahana system. It is used to send alerts and/or messages using SMS & Email to various groups and individuals before, during and after a disaster.': 'O módulo de mensagens é o hub de comunicação principal do sistema Sahana. É utilizado para enviar alertas e/ou mensagens utilizando o SMS & e-mail para diferentes grupos e indivíduos antes, durante e após um desastre.',
'The Organization Registry keeps track of all the relief organizations working in the area.': 'O registro Da Organização mantém controle de todos as organizações de apoio que trabalham na área.',
'The Organization Registry keeps track of all the relief organizations working in the disaster region. It captures not only the places where they are active, but also captures information on the range of projects they are providing in each area.': 'O registro da Organização mantém controle de todas organizações de ajuda trabalhando numa região de desastre. Ele captura não apenas os locais onde elas estão ativas, mas também captura informações sobre o conjunto de projetos que está fornecendo em cada região.',
'The Patient Tracking system keeps track of all the evacuated patients & their relatives.': 'The Patient Tracking system keeps track of all the evacuated patients & their relatives.',
'The Person currently filling this Role.': 'A pessoa atualmente preenchendo esta função.',
'The Project Tracking module allows the creation of Activities to meet Gaps in Needs Assessments.': 'O módulo acompanhamento do projeto permite a criação de atividades para preencher Lacunas nas avaliações de necessidades.',
'The Requests Management System is a central online repository where all relief organizations, relief workers, government agents and camp sites for displaced personnel can coordinate the supply of aid with their demand. It allows users to allocate the available resources to fulfill the demands effectively and efficiently.': 'O sistema De Gerenciamento De Pedidos é um repositório online central em todas as organizações de ajuda, trabalhadores de assistência, agentes do governo e sites de acampamento para a equipe de refugiados pode coordenar o fornecimento da ajuda com seu pedido. Ela permite que usuários aloquem os recursos disponíveis para suprir as demandas de forma efetiva e eficiente.',
'The Role this person plays within this hospital.': 'A Função desta pessoa neste hospital.',
'The Role to which this Role reports.': 'A função à qual essa função responde.',
'The Shelter Registry tracks all shelters and stores basic details regarding them. It collaborates with other modules to track people associated with a shelter, the services available etc.': 'O registro do Abrigo rastreia todos os detalhes básicos abrigos e armazena sobre eles. Ele colabora com outros módulos para rastrear as pessoas associadas com um abrigo, os serviços disponíveis etc.',
'The Shelter this Request is from': 'O pedido deste abrigo é de',
'The Shelter this Request is from (optional).': 'O pedido este Abrigo é de (opcional).',
'The Shelter this person is checking into.': 'O abrigo esta pessoa está verificando no.',
'The URL for the GetCapabilities of a WMS Service whose layers you want accessible via the Map.': 'A URL para o GetCapabilities de um serviço WMS cujas camadas você deseja acessíveis através do mapa.',
'The URL for the GetCapabilities page of a Web Map Service (WMS) whose layers you want available via the Browser panel on the Map.': 'A URL para a página do GetCapabilities de um Web Map Service (WMS), cujas camadas que você deseja disponíveis através do painel do navegador no Mapa.',
"The URL of the image file. If you don't upload an image file, then you must specify its location here.": 'A URL do arquivo de imagem. Se voce não fizer o upload de um arquivo de imagem, então voce deverá especificar sua localização aqui.',
'The URL of your web gateway without the post parameters': 'A URL de seu gateway da web sem os parâmetros post',
'The URL to access the service.': 'A URL para acessar o serviço.',
'The Unique Identifier (UUID) as assigned to this facility by the government.': 'O Idenfificador Único (UUID) conforme designado pelo governo para esta filial.',
'The asset must be assigned to a site OR location.': 'O ativo deve ser assinalado para um site ou local.',
'The attribute which is used for the title of popups.': 'O atributo que é usado para o título de popups.',
'The attribute within the KML which is used for the title of popups.': 'O Atributo dentro do KML que é utilizado para o título dos pop-ups.',
'The attribute(s) within the KML which are used for the body of popups. (Use a space between attributes)': 'O Atributo(s) no KML que são utilizados para o corpo dos pop-ups. ( utilizar um espaço entre atributos )',
'The body height (crown to heel) in cm.': 'A altura do corpo (cabeça até o calcanhar) em cm.',
'The contact person for this organization.': 'A pessoa de contato nessa organização.',
'The country the person usually lives in.': 'O país que a pessoa vive habitualmente',
'The default Facility for which this person is acting.': 'The default Facility for which this person is acting.',
'The default Facility for which you are acting.': 'The default Facility for which you are acting.',
'The default Organization for whom this person is acting.': 'A Organização padrão para quem esta pessoa está atuando.',
'The default Organization for whom you are acting.': 'A Organização padrão para quem você está atuando.',
'The duplicate record will be deleted': 'O registro duplicado será excluído',
'The first or only name of the person (mandatory).': 'O primeiro nome ou único nome da pessoa (obrigatório).',
'The form of the URL is http://your/web/map/service?service=WMS&request=GetCapabilities where your/web/map/service stands for the URL path to the WMS.': 'O formulário da URL é http://your/web/map/service?service=WMS&request=GetCapabilities where your/web/map/service que representa o caminho da URL para o WMS.',
'The language you wish the site to be displayed in.': 'O idioma que você deseja que o site seja exibido.',
'The last known location of the missing person before disappearance.': 'A última localização conhecida da pessoa desaparecida antes do desaparecimento.',
'The level at which Searches are filtered.': 'The level at which Searches are filtered.',
'The list of Brands are maintained by the Administrators.': 'A lista de Marcas serão mantidas pelos administradores.',
'The list of Catalogs are maintained by the Administrators.': 'A lista de catálogos é mantida pelos administradores.',
'The list of Item categories are maintained by the Administrators.': 'A lista de categorias dos itens são mantidas pelos administradores.',
'The map will be displayed initially with this latitude at the center.': 'O mapa será exibido inicialmente com esta latitude no centro.',
'The map will be displayed initially with this longitude at the center.': 'O mapa será exibido inicialmente com esta longitude no centro.',
'The minimum number of features to form a cluster.': 'O número mínimo de recursos para formar um cluster.',
'The name to be used when calling for or directly addressing the person (optional).': 'O nome a ser usado ao chamar por ou diretamente endereçar a pessoa (opcional).',
'The next screen will allow you to detail the number of people here & their needs.': 'A próxima tela permitirá que você detalhe o número de pessoas aqui e as suas necessidades.',
'The number of Units of Measure of the Alternative Items which is equal to One Unit of Measure of the Item': 'O número de unidades de medida dos Itens alternativos é igual a uma unidade de medida do Item',
'The number of pixels apart that features need to be before they are clustered.': 'O número de separado de pixels de funcionalidades tem que ser antes que eles sejam agrupados.',
'The number of tiles around the visible map to download. Zero means that the 1st page loads faster, higher numbers mean subsequent panning is faster.': 'O número de títulos em torno do mapa visível para | |
"""
Module contains basic handlers:
* BaseHandler - to be used for custom handlers. For instance - RPC, if you wish.
* ApiHandler - Abstract for API handlers above.
* ApiListHandler - Create (POST), List view (GET).
* ApiItemHandler - detailed view (GET), Update (PUT), Delete (DELETE).
"""
import json
import operator
import traceback
from abc import ABCMeta, abstractmethod
import peewee
from jsonschema.validators import validator_for
from playhouse.shortcuts import model_to_dict
from tornado import web
from tornado.gen import multi
from tornado.escape import xhtml_escape
from tcrudge.exceptions import HTTPError
from tcrudge.models import FILTER_MAP
from tcrudge.response import response_json, response_msgpack
from tcrudge.utils.validation import prepare
from tcrudge.utils.xhtml_escape import xhtml_escape_complex_object
class BaseHandler(web.RequestHandler):
"""
Base helper class. Provides basic handy responses.
To be used for customized handlers that don't fit REST API recommendations.
Defines response types in relation to Accept header. Response interface is
described in corresponding module.
By default, inherited handlers have callback functions for JSON and
MessagePack responses.
"""
response_callbacks = {
'application/json': response_json,
'application/x-msgpack': response_msgpack,
}
default_callback = staticmethod(response_json)
def get_query_argument(self, name, default= object(), strip=True):
val = super().get_query_argument(name, default, strip)
if isinstance(val, str):
return xhtml_escape(val)
return val
def get_response(self, result=None, errors=None, **kwargs):
"""
Method returns conventional formatted byte answer.
It gets Accept header, returns answer processed by callback.
:param result: contains result if succeeded
:param errors: contains errors if any
:param kwargs: other answer attributes
:return: byte answer of appropriate content type
:rtype: bytes
"""
_errors = xhtml_escape_complex_object(errors) if errors else []
# Set success flag
success = not _errors
answer = {
'result': result,
'errors': _errors,
'success': success,
}
accept = self.request.headers.get('Accept', 'application/json')
# Get callback
callback = self.response_callbacks.get(accept, self.default_callback)
return callback(self, {**answer, **kwargs})
def response(self, result=None, errors=None, **kwargs):
"""
Method writes the response and finishes the request.
:param result: contains result if succeeded
:param errors: contains errors if any
:param kwargs: other answer attributes
"""
self.write(self.get_response(result, errors, **kwargs))
self.finish()
def write_error(self, status_code, **kwargs):
"""
Method gets traceback, writes it into response, finishes response.
:param status_code: tornado parameter to format html, we don't use it.
:type status_code: int
:param kwargs: in debug mode must contain exc_info.
:type kwargs: dict
"""
exc_info = kwargs.get('exc_info')
if self.settings.get(
"serve_traceback") and exc_info: # pragma: no cover
# in debug mode, try to send a traceback
self.set_header('Content-Type', 'text/plain')
for line in traceback.format_exception(*exc_info):
self.write(line)
# exc_info[1] - HTTPError instance
# Finish request with exception body or exception reason
err_text = getattr(exc_info[1], 'body', self._reason)
self.write(err_text)
self.finish()
async def validate(self, data, schema, format_checker=None, **kwargs):
"""
Method to validate parameters.
Raises HTTPError(400) with error info for invalid data.
:param data: bytes or dict
:param schema: dict, valid JSON schema
(http://json-schema.org/latest/json-schema-validation.html)
:return: None if data is not valid. Else dict(data)
"""
# Get and parse arguments
if isinstance(data, dict):
_data = data # pragma: no cover
else:
try:
_data = json.loads(data.decode())
except ValueError as exc:
# json.loads error
raise HTTPError(
400,
body=self.get_response(
errors=[
{
'code': '',
'message': 'Request body is not a valid json object',
'detail': str(exc)
}
]
)
)
v = validator_for(schema)(schema, format_checker=format_checker)
errors = []
for error in v.iter_errors(_data):
# error is an instance of jsonschema.exceptions.ValidationError
err_msg = xhtml_escape(error.message)
errors.append({'code': '',
'message': 'Validation failed',
'detail': err_msg})
if errors:
# data does not pass validation
raise HTTPError(400, body=self.get_response(errors=errors))
return _data
async def bad_permissions(self):
"""
Returns answer of access denied.
:raises: HTTPError 401
"""
raise HTTPError(
401,
body=self.get_response(
errors=[
{
'code': '',
'message': 'Access denied'
}
]
)
)
async def is_auth(self):
"""
Validate user authorized. Abstract. Auth logic is up to user.
"""
return True
async def get_roles(self):
"""
Gets roles. Abstract. Auth logic is up to user.
"""
return []
class ApiHandler(BaseHandler, metaclass=ABCMeta):
"""
Base helper class for API functions.
model_cls MUST be defined.
"""
# Fields to be excluded by default from serialization
exclude_fields = ()
# Serializer recursion
recurse = False
# Serializer max depth
max_depth = None
@property
@abstractmethod
def model_cls(self): # pragma: no cover
"""
Model class must be defined. Otherwise it'll crash a little later even
if nothing seems to be accessing a model class. If you think you don't
need a model class, consider the architecture. Maybe it doesn't
fit REST. In that case use BaseHandler.
https://github.com/CodeTeam/tcrudge/issues/6
"""
raise NotImplementedError('Model class must be defined.')
@property
def get_schema_output(self): # pragma: no cover
"""
Maybe you'd ask: "What's a get-schema?"
The answer is that we wanted to check input of every request method
in a homologous way. So we decided to describe any input and output
using JSON schema.
Schema must be a dict.
"""
return {}
async def serialize(self, model):
"""
Method to serialize a model.
By default all fields are serialized by model_to_dict.
The model can be any model instance to pass through this method. It
MUST be a Model instance, it won't work for basic types containing
such instances.
User have to handle it by their own hands.
:param model: Model instance to serialize.
:type model: Model instance.
:return: serialized model.
:rtype: dict
"""
return model_to_dict(model,
recurse=self.recurse,
exclude=self.exclude_fields,
max_depth=self.max_depth)
def get_base_queryset(self):
return self.model_cls.select()
class ApiListHandler(ApiHandler):
"""
Base List API Handler. Supports C, L from CRUDL.
Handles pagination,
* default limit is defined
* maximum limit is defined
One can redefine that in their code.
Other pagination parameters are:
* limit - a positive number of items to show on a single page, int.
* offset - a positive int to define the position in result set to start with.
* total - A boolean to define total amount of items to be put in result set or not. 1 or 0.
Those parameters can be sent as either GET parameters or HTTP headers.
HTTP headers are more significant during parameters processing, but GET
parameters are preferable to use as conservative way of pagination.
HTTP headers are:
* X-Limit
* X-Offset
* X-Total
"exclude" filter args are for pagination, you must not redefine them ever.
Otherwise you'd have to also redefine the prepare method.
Some fieldnames can be added to that list. Those are fields one wishes not
to be included to filters.
"""
# Pagination settings
# Default amount of items to be listed (if no limit passed by request
# headers or querystring)
default_limit = 50
# Maximum amount of items to be listed (if limit passed by request is
# greater than this amount - it will be truncated)
max_limit = 100
# Arguments that should not be passed to filter
exclude_filter_args = ['limit', 'offset', 'total']
def __init__(self, *args, **kwargs):
super(ApiListHandler, self).__init__(*args, **kwargs)
# Pagination params
# Number of items to fetch
self.limit = None
# Number of items to skip
self.offset = None
# Should total amount of items be included in result?
self.total = False
# Prefetch queries
self.prefetch_queries = []
@property
def get_schema_input(self):
"""
JSON Schema to validate GET Url parameters.
By default it contains pagination parameters as required fields.
If you wish to use query filters via GET parameters, you need to
redefine get_schema_input so that request with filter parameters
would be valid.
In schema you must define every possible way to filter a field,
you wish to be filtered, in every manner it should be filtered.
For example, if you wish to filter by a field "name" so that the query
returns you every object with name like given string::
{
"type": "object",
"additionalProperties": False,
"properties": {
"name__like": {"type": "string"},
"total": {"type": "string"},
"limit": {"type": "string"},
"offset": {"type": "string"},
"order_by": {"type": "string"},
},
}
If you wish to filter by a field "created_dt" by given range::
{
"type": "object",
"additionalProperties": False,
"properties": {
"created_dt__gte": {"type": "string"},
"created_dt__lte": {"type": "string"},
"total": {"type": "string"},
"limit": {"type": "string"},
"offset": {"type": "string"},
"order_by": {"type": "string"},
},
}
To cut it short, you need to add parameters like "field__operator"
for every field you wish to be filtered and for every operator you
wish to be used.
Every schema must be a dict.
:return: returns schema.
:rtype: dict
"""
return {
"type": "object",
"additionalProperties": False,
"properties": {
| |
from util.util import add_dummy_to_tensor
import torch.utils.data as data
import torch
from PIL import Image
import torchvision.transforms as transforms
import numpy as np
import random
class BaseDataset(data.Dataset):
def __init__(self):
super(BaseDataset, self).__init__()
def name(self):
return 'BaseDataset'
def initialize(self, opt):
pass
def init_frame_idx_parser(self, A_paths):
self.n_of_seqs = len(A_paths) # number of sequences to train
self.seq_len_max = max([len(A) for A in A_paths]) # max number of frames in the training sequences
self.seq_idx = 0 # index for current sequence
self.frame_idx = self.opt.start_frame if not self.opt.isTrain else 0 # index for current frame in the sequence
self.frames_count = [] # number of frames in each sequence
for path in A_paths:
self.frames_count.append(len(path) - self.opt.n_frames_G + 1)
self.video_len = len(A_paths[0])
self.folder_prob = [count / sum(self.frames_count) for count in self.frames_count]
self.n_frames_total = self.opt.n_frames_total if self.opt.isTrain else 1
self.TParsing, self.SPose, self.SParsing, self.SFG = None, None, None, None
def init_frame_idx_cloth(self, A_paths):
self.n_of_seqs = len(A_paths) # number of sequences to train
self.seq_len_max = max([len(A) for A in A_paths]) # max number of frames in the training sequences
self.seq_idx = 0 # index for current sequence
self.frame_idx = self.opt.start_frame if not self.opt.isTrain else 0 # index for current frame in the sequence
self.frames_count = [] # number of frames in each sequence
for path in A_paths:
self.frames_count.append(len(path) - self.opt.n_frames_G + 1)
self.video_len = len(A_paths[0])
self.folder_prob = [count / sum(self.frames_count) for count in self.frames_count]
self.n_frames_total = self.opt.n_frames_total if self.opt.isTrain else 1
self.TParsing, self.TFG, self.SParsing, self.SFG, self.SFG_full = None, None, None, None, None
def init_frame_idx_composer(self, A_paths):
self.n_of_seqs = len(A_paths) # number of sequences to train
self.seq_len_max = max([len(A) for A in A_paths]) # max number of frames in the training sequences
self.seq_idx = 0 # index for current sequence
self.frame_idx = self.opt.start_frame if not self.opt.isTrain else 0 # index for current frame in the sequence
self.frames_count = [] # number of frames in each sequence
for path in A_paths:
self.frames_count.append(len(path) - self.opt.n_frames_G + 1)
self.video_len = len(A_paths[0])
self.folder_prob = [count / sum(self.frames_count) for count in self.frames_count]
self.n_frames_total = self.opt.n_frames_total if self.opt.isTrain else 1
self.TParsing, self.TFG, self.SPose, self.SParsing, self.SFG, self.SFG_full, self.BG, self.BG_flag, self.SI = None, None, None, None, None, None, None, None, None
def init_frame_idx_full(self, A_paths):
self.n_of_seqs = len(A_paths) # number of sequences to train
self.seq_len_max = max([len(A) for A in A_paths]) # max number of frames in the training sequences
self.seq_idx = 0 # index for current sequence
self.frame_idx = self.opt.start_frame if not self.opt.isTrain else 0 # index for current frame in the sequence
self.frames_count = [] # number of frames in each sequence
for path in A_paths:
self.frames_count.append(len(path) - self.opt.n_frames_G + 1 - 2)
self.video_len = len(A_paths[0])
self.folder_prob = [count / sum(self.frames_count) for count in self.frames_count]
self.n_frames_total = self.opt.n_frames_total if self.opt.isTrain else 1
self.TPose, self.TParsing, self.TFG, self.TPose_uncloth, self.TParsing_uncloth, self.TFG_uncloth, self.TPose_cloth, self.TParsing_cloth, self.TFG_cloth, self.SPose, self.SParsing, self.SI, self.BG, self.BG_flag = None, None, None, None, None, None, None, None, None, None, None, None, None, None
def update_frame_idx_parser(self, A_paths, index):
if self.opt.isTrain:
seq_idx = int(index / (self.video_len - self.opt.n_frames_G + 1))
self.frame_idx = index % (self.video_len - self.opt.n_frames_G + 1)
return None, None, None, None, seq_idx
else:
self.change_seq = self.frame_idx >= self.frames_count[self.seq_idx]
if self.change_seq:
self.seq_idx += 1
self.frame_idx = 0
self.TParsing, self.SPose, self.SParsing, self.SFG = None, None, None, None
return self.TParsing, self.SPose, self.SParsing, self.SFG, self.seq_idx
def update_frame_idx_cloth(self, A_paths, index):
if self.opt.isTrain:
seq_idx = int(index / (self.video_len - self.opt.n_frames_G + 1))
self.frame_idx = index % (self.video_len - self.opt.n_frames_G + 1)
return None, None, None, None, None, seq_idx
else:
self.change_seq = self.frame_idx >= self.frames_count[self.seq_idx]
if self.change_seq:
self.seq_idx += 1
self.frame_idx = 0
self.TParsing, self.TFG, self.SParsing, self.SFG, self.SFG_full = None, None, None, None, None
return self.TParsing, self.TFG, self.SParsing, self.SFG, self.SFG_full, self.seq_idx
def update_frame_idx_composer(self, A_paths, index):
if self.opt.isTrain:
seq_idx = int(index / (self.video_len - self.opt.n_frames_G + 1))
self.frame_idx = index % (self.video_len - self.opt.n_frames_G + 1)
return None, None, None, None, None, None, None, None, None, seq_idx
else:
self.change_seq = self.frame_idx >= self.frames_count[self.seq_idx]
if self.change_seq:
self.seq_idx += 1
self.frame_idx = 0
self.TParsing, self.TFG, self.SPose, self.SParsing, self.SFG, self.SFG_full, self.BG, self.BG_flag, self.SI = None, None, None, None, None, None, None, None, None
return self.TParsing, self.TFG, self.SPose, self.SParsing, self.SFG, self.SFG_full, self.BG, self.BG_flag, self.SI, self.seq_idx
def update_frame_idx_full(self, A_paths, index):
self.change_seq = self.frame_idx >= self.frames_count[self.seq_idx]
if self.change_seq:
self.seq_idx += 1
self.frame_idx = 0
self.TPose, self.TParsing, self.TFG, self.TPose_uncloth, self.TParsing_uncloth, self.TFG_uncloth, self.TPose_cloth, self.TParsing_cloth, self.TFG_cloth, self.SPose, self.SParsing, self.SI, self.BG, self.BG_flag = None, None, None, None, None, None, None, None, None, None, None, None, None, None
return self.TPose, self.TParsing, self.TFG, self.TPose_uncloth, self.TParsing_uncloth, self.TFG_uncloth, self.TPose_cloth, self.TParsing_cloth, self.TFG_cloth, self.SPose, self.SParsing, self.SI, self.BG, self.BG_flag, self.seq_idx
def update_frame_idx(self, A_paths, index):
if self.opt.isTrain:
if self.opt.dataset_mode == 'pose':
seq_idx = np.random.choice(len(A_paths), p=self.folder_prob) # randomly pick sequence to train
self.frame_idx = index
else:
seq_idx = index % self.n_of_seqs
return None, None, None, seq_idx
else:
self.change_seq = self.frame_idx >= self.frames_count[self.seq_idx]
if self.change_seq:
self.seq_idx += 1
self.frame_idx = 0
self.A, self.B, self.I = None, None, None
return self.A, self.B, self.I, self.seq_idx
def init_data_params(self, data, n_gpus, tG):
opt = self.opt
_, n_frames_total, self.height, self.width = data['SI'].size() # n_frames_total = n_frames_load * n_loadings + tG - 1
n_frames_total = n_frames_total // opt.output_nc_3
n_frames_load = opt.max_frames_per_gpu * n_gpus # number of total frames loaded into GPU at a time for each batch
n_frames_load = min(n_frames_load, n_frames_total - tG + 1)
self.t_len = n_frames_load + tG - 1 # number of loaded frames plus previous frames
return n_frames_total-self.t_len+1, n_frames_load, self.t_len
def init_data_params_parser(self, data, n_gpus, tG):
opt = self.opt
_, n_frames_total, self.height, self.width = data['SParsing'].size() # n_frames_total = n_frames_load * n_loadings + tG - 1
n_frames_load = opt.max_frames_per_gpu * n_gpus # number of total frames loaded into GPU at a time for each batch
n_frames_load = min(n_frames_load, n_frames_total - tG + 1)
self.t_len = n_frames_load + tG - 1 # number of loaded frames plus previous frames
return n_frames_total-self.t_len+1, n_frames_load, self.t_len
def init_data_params_cloth(self, data, n_gpus, tG):
opt = self.opt
_, n_frames_total, self.height, self.width = data['SFG'].size() # n_frames_total = n_frames_load * n_loadings + tG - 1
n_frames_total = n_frames_total // 3
n_frames_load = opt.max_frames_per_gpu * n_gpus # number of total frames loaded into GPU at a time for each batch
n_frames_load = min(n_frames_load, n_frames_total - tG + 1)
self.t_len = n_frames_load + tG - 1 # number of loaded frames plus previous frames
return n_frames_total-self.t_len+1, n_frames_load, self.t_len
def init_data(self, t_scales):
fake_B_last = None # the last generated frame from previous training batch (which becomes input to the next batch)
real_B_all, fake_B_all, flow_ref_all, conf_ref_all = None, None, None, None # all real/generated frames so far
if self.opt.sparse_D:
real_B_all, fake_B_all, flow_ref_all, conf_ref_all = [None]*t_scales, [None]*t_scales, [None]*t_scales, [None]*t_scales
frames_all = real_B_all, fake_B_all, flow_ref_all, conf_ref_all
return fake_B_last, frames_all
def init_data_parser(self, t_scales):
fake_B_last = None # the last generated frame from previous training batch (which becomes input to the next batch)
real_B_all, fake_B_all, flow_ref_all, conf_ref_all, real_sfg_all = None, None, None, None, None # all real/generated frames so far
if self.opt.sparse_D:
real_B_all, fake_B_all = [None]*t_scales, [None]*t_scales
frames_all = real_B_all, fake_B_all, flow_ref_all, conf_ref_all, real_sfg_all
return fake_B_last, frames_all
def init_data_cloth(self, t_scales):
fake_B_last = None # the last generated frame from previous training batch (which becomes input to the next batch)
real_B_all, fake_B_all, flow_ref_all, conf_ref_all, real_slo_all = None, None, None, None, None # all real/generated frames so far
if self.opt.sparse_D:
real_B_all, fake_B_all = [None]*t_scales, [None]*t_scales
frames_all = real_B_all, fake_B_all, flow_ref_all, conf_ref_all, real_slo_all
return fake_B_last, frames_all
def prepare_data(self, data, i, input_nc, output_nc):
t_len, height, width = self.t_len, self.height, self.width
# 5D tensor: batchSize, # of frames, # of channels, height, width
input_A = (data['A'][:, i*input_nc:(i+t_len)*input_nc, ...]).view(-1, t_len, input_nc, height, width)
input_B = (data['B'][:, i*output_nc:(i+t_len)*output_nc, ...]).view(-1, t_len, output_nc, height, width)
inst_A = (data['inst'][:, i:i+t_len, ...]).view(-1, t_len, 1, height, width) if len(data['inst'].size()) > 2 else None
return [input_A, input_B, inst_A]
def prepare_data_composer(self, data, i):
t_len, height, width = self.t_len, self.height, self.width
# 5D tensor: batchSize, # of frames, # of channels, height, width
input_TParsing = (data['TParsing']).view(-1, | |
import numpy as np
tss = np.array([[13.25539804, 1413.250347, 2561.9326, 1007.772729, 152.012186],
[255.3217538, 3388.986757, 6639.253742, 5888.099069, 3065.611859],
[-79.8970679, -3209.156273, -5619.538006, -3973.767508, -1546.755417],
[195.001956, 1453.189894, 2106.965705, 1956.082474, 1180.965793],
[-347.6926018, -2812.519798, -5276.951152, -4544.191741, -2712.716526],
[0.3973046034, 1607.694575, 3716.245708, 1497.560875, 192.5421054],
[174.5316027, 5411.997496, 13359.03475, 12793.54815, 7481.308423],
[-23.35668432, -4048.293303, -8923.118125, -7000.144307, -2990.146935],
[428.5107065, 5763.317904, 10533.53613, 10375.63086, 6452.196295],
[-400.5955764, -6665.784469, -14293.45731, -13758.3819, -9311.657731],
[10.91783806, 2576.897249, 5815.10129, 2040.430518, 67.95145094],
[231.1235658, 8607.73881, 22381.07333, 20724.2707, 10880.48087],
[-64.87034621, -6391.771568, -14074.84055, -10177.61292, -3192.221706],
[451.0944052, 14749.11298, 32335.30659, 33633.23739, 21572.74305],
[-407.5943909, -12115.94957, -27692.94504, -27853.52345, -19604.74342],
[-0.1622864939, 1582.448621, 4448.980831, 879.836665, -564.0789001],
[20.66583971, 5464.278466, 17216.99977, 11755.54062, -3042.746045],
[-4.106874805, -3982.413713, -10788.01118, -5005.020217, 3641.862842],
[-244.9537855, 10525.51121, 31294.44794, 36842.11984, 26607.22528],
[10.825289, -7821.318422, -21793.67842, -19740.51455, -8773.289193],
[6.969519442, 1862.681642, 5321.615127, 1052.862248, -845.5116889],
[99.14809699, 5899.77377, 18941.61758, 10185.95498, -15301.47936],
[-35.75424066, -4629.55141, -12814.91867, -5391.129821, 7800.243345],
[-77.11980961, -11556.80966, -28569.99406, -29855.92571, -14824.70914],
[-114.8389102, -4910.266539, -17099.33616, -7588.764721, 15603.73369],
[2.838045646, 355.3506268, 1855.759384, -50.47223937, -1017.444788],
[-112.1078206, 2561.050018, 10759.12212, 10322.53311, -2097.764676],
[-0.4433978304, -1192.865402, -5136.070414, -2309.88031, 5465.778093],
[107.4992199, -125.1672575, -2484.659131, -2485.822262, 3149.415804],
[399.4372386, -5142.76967, -16105.8905, -21795.94233, -15491.71049],
[16.10195878, -1178.009932, -2614.872817, -2299.144186, -1792.790224],
[158.4046678, -5686.161661, -18758.20973, -21662.58363, -19320.5991],
[-74.12900346, 3245.503342, 7541.8203, 10855.33649, 13988.37832],
[-34.55378744, 1941.225718, 5017.661232, 5318.922966, -620.7342789],
[-207.0295882, 12038.37331, 37601.3263, 30622.10372, -4539.431427],
[22.7534948, 482.7613468, 1836.091848, 734.3952846, -1119.482987],
[-233.5493121, 3441.049646, 13422.80658, 15304.21767, 4390.753073],
[-63.84998082, -1552.962277, -5493.858857, -5627.390706, 2952.17543],
[4.779104523, -718.5278467, -1513.06483, -1808.514559, -1327.451528],
[20.7746195, -6907.875657, -19158.24575, -16316.03841, -7201.850067],
[49.20154366, -1187.068679, -5185.20933, -2439.048656, -1838.923414],
[139.3056306, -3333.315354, -14665.34093, -12019.74265, 12658.48049],
[-324.4424523, 3125.83098, 12908.99484, 10785.60416, 2433.480132],
[0.1490629538, 109.4077536, 166.5050017, 254.530322, 787.0373924],
[21.35258296, 1220.357614, 366.2175899, 1705.709709, 8959.813558],
[-58.42712912, 1116.497337, 4360.651257, 2453.184802, -2356.448334],
[-158.3722924, 4142.211324, 16175.24228, 12800.84334, -4948.89388],
[-82.7303545, -2026.672127, -7786.512178, -4914.221808, 5087.281938],
[-0.3341216639, 2.138247571, 21.33920771, 13.41491883, -191.650718],
[-23.70307931, 530.8706281, 4207.829478, 2640.498918, -3241.191775],
[-186.0731254, 241.7507168, 785.3331105, 2787.236046, -3089.997231],
[109.039177, -2232.9368, -8253.487501, -6820.734791, -1876.311884],
[287.9703869, 2007.09292, 6963.923738, 4369.534647, -10734.00506],
[0.1046095319, -4.288653843, -10.89936917, -12.71855819, 22.89587098],
[11.61799927, -374.0412307, -2212.570029, -1581.882978, 375.0633295],
[-42.12650667, 1610.945795, 5409.724335, 4506.548208, -8051.379908],
[-48.0354373, 597.4109334, 2128.850954, 1932.75153, 2061.080192],
[-237.4279218, -978.1077288, -3313.321114, -2858.809415, 6576.094231],
[-0.01993909017, 0.9559599404, 2.007489643, 2.736241932, -0.09157485222],
[-3.64277905, 109.5464428, 599.603489, 464.8436734, 112.7994803],
[85.34232763, -679.2994761, -2769.368086, -2269.821481, -1136.646006],
[14.24194314, 106.0523856, 251.2069477, 160.0499888, -1155.026743],
[104.4439846, 1005.19438, 3175.62371, 3023.269179, -3787.707002],
[0.002660826013, -0.112646871, -0.2078567171, -0.3246745441, -0.6234105676],
[0.7942294559, -15.46511845, -73.99022951, -67.4189736, -79.69108605],
[4.770045828, -213.4507825, -125.572585, -639.3539647, 6758.267975],
[-2.758556969, -170.6503933, -470.7474776, -411.8486264, 473.0142648],
[-23.90987296, -805.1737415, -2459.158838, -2241.210983, 1907.186619],
[-0.0002520465807, 0.0051266216, 0.007708521717, 0.0164679712, 0.1621568982],
[-0.1196121512, -0.8188571651, -10.04047953, -3.884378163, 26.78301103],
[-44.13661853, 226.4973178, 386.1546517, 761.718215, -4801.725215],
[0.2496181491, 81.15966318, 218.8488833, 203.3498859, -142.8725456],
[-0.4164982984, 386.0208285, 1140.71956, 1043.233799, -713.0206101],
[1.511020603e-05, 0.0007942566154, 0.001454835647, 0.001833910158, -0.02595854277],
[0.01041401758, 1.008747946, 7.40537784, 4.828327164, -6.204706618],
[-0.1192315041, -0.1039004631, -0.1037764722, -0.105474855, -0.1098200713],
[0.08089158143, 0.08415142137, 0.08289173533, 0.0833276273, 0.08222202821],
[0.1021836245, 0.09791085633, 0.09792480989, 0.09563917472, 0.09327852053],
[0.03905866076, 0.03975123479, 0.03781082252, 0.03958834221, 0.04454373405],
[0.0623069271, 0.06242141261, 0.0654873257, 0.06476937287, 0.06527850671]])
tse = np.array([[[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0]],
[[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0]],
[[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0]],
[[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0]],
[[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0]],
[[-1635.691948, -153.3676502, -12510.99836, 3968.169109],
[471.0648177, -160.5346318, 387.4572241, -10078.14225],
[3618.057554, -956.9159973, 1114.40411, -1275.64899],
[-13783.44671, -357.210792, 1905.715873, -1035.340294],
[-932.5379008, 548.7059122, -2055.990625, 3756.093256]],
[[-28930.97135, -2291.16678, 23741.30362, -8129.605534],
[4657.810326, -5405.836237, 7806.929525, -29426.86961],
[12788.95907, -12108.15199, 23849.81449, -16634.06866],
[9436.537277, -21779.34849, 10618.69862, -19041.12744],
[1687.854879, -1221.778391, 3973.419038, -4635.142096]],
[[8245.823066, 256.7201787, 1471.271517, -1234.785613],
[-2682.87243, 2176.225259, -1402.781098, 25082.98545],
[-6347.761316, 4251.469821, -6592.016308, 5457.084923],
[11954.5074, 2344.338145, -9774.232125, 4306.112238],
[928.0484479, -498.2371056, -3804.537867, 1979.391861]],
[[-29925.08403, -4920.613115, 14532.75294, -5324.362057],
[1934.482342, -15306.46149, 10224.23225, -23253.02364],
[13277.10046, -21139.17184, 59570.34212, -44566.29953],
[8574.185406, -11517.58347, 12407.89971, -30205.58228],
[2044.49374, -1290.427153, -3785.871973, 2266.916067]],
[[42275.94074, 5111.351218, -23557.17662, 9809.099364],
[-4064.487443, 14086.26259, -13158.34457, 30725.03575],
[-20216.7339, 17368.22578, -51352.25184, 39953.33906],
[-13887.96148, 27273.30578, -11269.92332, 41533.73028],
[-3131.196405, 2152.768253, 5360.032464, -2899.035622]],
[[806.6684224, 39.00569341, -4789.916584, 503.3910459],
[292.9248911, 2054.980104, -601.6365433, -526.8927921],
[-995.5349461, 641.8654077, -27.97272393, -382.6256178],
[20251.62627, 252.5834848, 553.2835823, -546.615249],
[-4029.967093, 1833.408335, 3924.741065, -4246.522389]],
[[560.8077583, -5955.430382, 10665.99003, -474.9596156],
[1172.65706, 10761.22876, -7211.89351, 408.7001197],
[736.5059856, 3932.128542, 6030.981398, -5412.946644],
[223.4185485, -2221.374481, 3735.279433, -9506.002391],
[-3113.78159, 2412.287085, -8553.693203, 5428.713032]],
[[-2513.682257, 337.7489222, 443.4387757, -191.0029229],
[-1373.572228, -8688.621863, 1671.217958, 851.0795171],
[1393.83746, -2296.15016, -655.5342866, 1665.083584],
[-18821.27226, -852.9594572, -3240.802524, 2237.215734],
[5803.433982, -3087.080045, 8843.626789, -2956.98123]],
[[-23549.41085, -25306.2762, 12564.74323, 1020.994781],
[-6405.273827, -7075.372738, -15648.57677, 7854.513212],
[7892.701526, -11184.8691, 45719.50403, -23637.9266],
[12801.70542, -11541.58617, 3630.548093, -15228.45639],
[3491.313276, 771.2911136, 1796.299125, -4796.011338]],
[[10103.35539, 16080.37071, -13900.22009, -341.918824],
[2655.244934, -3913.11565, 13167.90009, -4116.467712],
[-5303.617599, -1644.613179, -22122.59993, 15485.7239],
[-7967.05216, 7114.454121, -3869.569152, 20453.68449],
[-64.94642303, -1639.795674, -6994.231884, 5179.651742]],
[[-76.23276554, -10108.10163, -4587.563439, 2944.20397],
[718.4082435, 1072.471941, 377.8157383, -8842.314975],
[624.7468943, -1081.336296, 414.3043798, -1221.847867],
[19519.12475, -36.22575206, 1754.944065, -1054.319469],
[1104.374977, -1009.048421, -1406.876206, 8592.615258]],
[[5803.489808, 22417.75066, 5691.880396, -4100.977662],
[9941.585815, 10194.25852, 13321.2518, -22013.5336],
[-245.3916845, -7008.301772, 13991.43345, -11933.79394],
[-4415.200082, 10169.79128, 12143.92944, -8499.257654],
[-974.9986165, -6591.314865, -644.6175509, -10355.00526]],
[[-470.6579522, 1781.631639, 666.9007434, -1002.655911],
[-5030.852873, -6074.895647, -1899.731125, 21267.19114],
[-965.9764341, 3728.485337, -3319.505243, 4854.403342],
[-17733.48937, -398.2684635, -10413.061, 3837.043445],
[-903.5218828, 3358.282077, 6287.783493, 3004.717657]],
[[21658.8498, 3099.357366, -24883.73605, 6571.693376],
[-4407.576868, -351.0399978, -1013.01433, 18675.47393],
[-12351.01328, 6258.849986, -34567.43688, 26511.25653],
[6941.946147, 13184.20308, -11108.41131, 33980.5572],
[6630.650789, 5467.774993, -13527.25889, -7470.282026]],
[[-14132.13783, -21861.57088, 4927.655675, 274.2527157],
[-7740.8642, -12452.3454, -20436.2114, 11060.76519],
[5189.716871, 6090.003027, -22798.44697, 13365.17784],
[1180.68412, -15349.12472, -8345.577623, -7761.867948],
[-851.1588278, 3828.156667, 1169.479219, 791.3326517]],
[[14.06899727, 5604.657205, -5747.861409, 961.9400286],
[-125.4509581, 337.9263571, -2155.420381, -37.93926918],
[-324.8626611, -251.7646059, -1076.820762, -890.9856459],
[-5284.295469, -460.6763511, -1161.956926, -1170.785353],
[3852.320261, 7222.456913, -10430.31429, -9598.482229]],
[[-2243.113362, -9140.400932, 13803.78991, -2194.237486],
[549.5241683, 4210.746945, -4086.208958, 1242.252998],
[3448.320787, -7981.44778, 1814.098929, -5139.316012],
[7977.130903, -5961.47366, 1919.202869, -8887.184949],
[-2271.458417, -4014.369878, 12696.14242, 11176.94867]],
[[246.3587424, -1276.738046, 399.9872563, -267.8497029],
[268.2114495, -2236.824494, 5059.809786, -158.6290427],
[144.6730679, 1697.170133, 3586.445885, 3235.687519],
[4229.40986, 1809.118875, 1642.674775, 4265.679002],
[-4318.320557, -9056.505074, 6666.844032, -735.5418407]],
[[-4691.478961, -1823.300973, -10404.86842, 2055.05521],
[-3307.277386, -6784.725503, -5442.210698, -219.8867251],
[-1680.008732, 1935.097152, -3576.021184, -4196.229995],
[5099.938243, -3950.208442, -6173.139534, -6106.694456],
[1387.600728, 11625.85902, -12326.69059, 2830.452813]],
[[4769.58611, 5989.453327, -14693.09545, 1936.310585],
[-1579.583299, -5559.931347, -7848.208719, -3879.951117],
[-7174.864126, 16136.38716, -35194.84425, -3541.229228],
[-13617.29398, 4612.492705, -18652.64479, 2653.061769],
[4275.535661, 7949.112961, -15077.93692, -6622.80934]],
[[-43.61281785, -569.1364939, 10237.57775, -1216.651434],
[-85.57463696, -122.3033383, -2059.092636, -3118.350507],
[-2103.608289, 1269.698288, -1802.697685, -2041.693204],
[7397.565801, -1008.441855, -4063.848935, -1788.086226],
[3157.721167, 11799.7423, -14323.67665, 902.1370448]],
[[4982.765351, 2655.87064, -21377.06693, 4193.80019],
[-3045.659611, -99.68787985, -13511.09786, -130.1528642],
[-7366.433303, 17924.55797, -31997.32604, -16810.58151],
[6028.456646, -1630.201605, -21761.04058, -11564.17668],
[-1806.281992, -978.5540825, 21109.36965, -676.0796821]],
[[-367.8342988, 52.9249016, -1002.464267, 203.9428018],
[1040.287938, -86.45423979, 5898.876091, 5956.137418],
[3752.251737, -6664.665731, 10209.73294, 8407.726119],
[-7229.457645, 3866.112272, 20646.65433, 7291.938596],
[-3360.69516, -16305.14247, -287.7744305, 1200.411423]],
[[-3406.973074, -1284.065123, 12731.90847, -4069.466415],
[2473.333006, 3206.265844, 1410.982746, -5724.730567],
[5137.922758, -1170.854394, 5425.508492, -3140.16979],
[-9778.586776, -3789.011794, 3040.300954, -15543.91438],
[617.0093913, 399.2419484, -10589.099, -5989.671363]],
[[-11915.00792, -5438.169614, 20804.56003, -5109.422115],
[4384.731947, 8013.281241, 357.7801407, -20430.71926],
[8855.068755, -14743.58864, 42578.81157, -22855.40133],
[-14861.94084, -11927.94152, 7532.016882, -32071.31554],
[2241.594698, 10482.67607, -18952.72128, -11251.20486]],
[[-241.9393467, 6252.04893, -6892.208596, 567.4301756],
[-88.50386591, -451.8515118, -857.1215503, 946.2629542],
[1621.214948, -1479.249159, -1197.493975, -1145.10431],
[-1272.927462, -1324.929732, -686.8912691, -779.3392626],
[43.2808187, 3973.063929, 1785.979142, 499.1976667]],
[[-8765.720963, -10428.27438, 12903.10078, -502.643181],
[-764.2691265, 8170.767364, -12204.18506, -1753.231782],
[4578.122803, 14505.18225, -13147.07361, -20395.21396],
[1211.387402, -16870.32361, -2989.299966, -32746.54341],
[-3434.00944, -13997.28121, -6533.920956, 416.8553631]],
[[2052.948947, -1176.40673, 830.3210808, -401.1933806],
[657.5020888, -2208.624252, 3330.023529, -1187.3753],
[-2700.761714, -540.9172571, 6182.394052, 5995.349028],
[1276.859015, 6198.241555, 3319.529545, 6004.235763],
[1260.22321, 469.0496744, 9256.9847, -3190.578409]],
[[1967.31966, 541.0453412, -4807.899188, 2022.075464],
[-741.7227357, 394.8105037, -611.8258485, 1645.831088],
[-2660.858072, 388.3795249, -1965.284079, 1122.172198],
[-1778.313739, 1803.877769, -2006.839954, 5966.735179],
[352.1218913, 1534.038972, -931.2362851, 89.25759967]],
[[7815.662746, -1575.603839, -12068.07855, 4400.871928],
[-2953.919108, 3024.089465, -7399.158959, 8355.346344],
[-6504.927202, 17804.66889, -29048.45815, 9353.779118],
[-5354.394491, -2350.457635, -12985.02912, 9174.021916],
[-1955.946766, -5907.105565, 3095.23949, -496.7378854]],
[[944.6143675, -5727.252131, 6272.637643, 1239.900044],
[203.3355925, -4289.504144, 2875.561408, 1162.096889],
[-318.0217215, -7953.39473, -658.0380304, -389.8368869],
[-6817.274613, -570.0633956, 196.0217172, 1698.635135],
[1231.661652, 10769.24528, -5061.471682, 166.1082826]],
[[2255.108158, 3063.184878, -12369.79829, 3287.277452],
[-2686.487179, -7915.835569, 2665.404552, 9065.033297],
[-3744.299081, 875.8009245, -1191.075734, 14793.43124],
[-4267.716007, 5537.960149, 7604.86562, 19566.14776],
[-2759.871499, -20261.6483, 3617.798178, -1057.165205]],
[[-3128.529423, 1713.531964, -584.7546086, -1056.272167],
[-40.33760783, 13434.59805, -7137.229225, -4408.112151],
[898.8715105, 20317.53458, 2779.224069, 60.63135053],
[6611.480108, 1601.791156, -4076.097952, -5918.326066],
[-382.325407, -7741.697836, 9849.237239, 4709.051329]],
[[-585.81942, -273.0630735, 622.1424912, -293.625644],
[-63.23114168, -568.8148415, 27.02489231, 13.9226195],
[657.4500435, -50.61437331, 305.0984266, -253.7280804],
[3039.039229, -713.8468942, 371.9777937, -1821.610571],
[-555.4112023, -2392.083464, 4822.453061, 768.9340365]],
[[-4187.52969, -958.2825689, -591.8245198, -122.6689234],
[-954.7897018, -4403.387263, 945.1906461, 2114.674352],
[1886.368886, -4246.442977, 7094.265251, -3105.088874],
[14623.41517, -1710.360176, 3857.053692, -3188.337739],
[-2623.210024, -13566.53796, 8336.650897, 3674.798002]],
[[700.0942102, -3811.487979, -8155.726091, 3151.639774],
[422.6821176, -1048.969071, 2401.423164, -1622.994128],
[1985.300583, -4786.405305, -188.7611992, -1616.715476],
[6667.434161, -1065.696994, -1517.183984, 176.6932945],
[467.1455431, 2806.396473, -1422.824407, -2650.33985]],
[[-2454.797575, -1922.775363, 8837.785118, -1321.874528],
[2295.395291, 11791.50685, 1120.764298, -7360.439678],
[1345.445613, 3981.494912, 16979.57837, -3789.710913],
[-3193.023802, | |
<filename>cortex/polyutils.py<gh_stars>0
from collections import OrderedDict
import numpy as np
from scipy.spatial import distance, Delaunay
from scipy import sparse
import scipy.sparse.linalg
import functools
import numexpr as ne
def _memo(fn):
"""Helper decorator memoizes the given zero-argument function.
Really helpful for memoizing properties so they don't have to be recomputed
dozens of times.
"""
@functools.wraps(fn)
def memofn(self, *args, **kwargs):
if id(fn) not in self._cache:
self._cache[id(fn)] = fn(self)
return self._cache[id(fn)]
return memofn
class Surface(object):
"""Represents a single cortical hemisphere surface. Can be the white matter surface,
pial surface, fiducial (mid-cortical) surface, inflated surface, flattened surface,
etc.
Implements some useful functions for dealing with functions across surfaces.
"""
def __init__(self, pts, polys):
"""Initialize Surface.
Parameters
----------
pts : 2D ndarray, shape (total_verts, 3)
Location of each vertex in space (mm). Order is x, y, z.
polys : 2D ndarray, shape (total_polys, 3)
Indices of the vertices in each triangle in the surface.
"""
self.pts = pts.astype(np.double)
self.polys = polys
self._cache = dict()
self._rlfac_solvers = dict()
self._nLC_solvers = dict()
@property
@_memo
def ppts(self):
"""3D matrix of points in each face: n faces x 3 points per face x 3 coords per point.
"""
return self.pts[self.polys]
@property
@_memo
def connected(self):
"""Sparse matrix of vertex-face associations.
"""
npt = len(self.pts)
npoly = len(self.polys)
return sparse.coo_matrix((np.ones((3*npoly,)), # data
(np.hstack(self.polys.T), # row
np.tile(range(npoly),(1,3)).squeeze())), # col
(npt, npoly)).tocsr() # size
@property
@_memo
def adj(self):
"""Sparse vertex adjacency matrix.
"""
npt = len(self.pts)
npoly = len(self.polys)
adj1 = sparse.coo_matrix((np.ones((npoly,)),
(self.polys[:,0], self.polys[:,1])), (npt,npt))
adj2 = sparse.coo_matrix((np.ones((npoly,)),
(self.polys[:,0], self.polys[:,2])), (npt,npt))
adj3 = sparse.coo_matrix((np.ones((npoly,)),
(self.polys[:,1], self.polys[:,2])), (npt,npt))
alladj = (adj1 + adj2 + adj3).tocsr()
return alladj + alladj.T
@property
@_memo
def face_normals(self):
"""Normal vector for each face.
"""
# Compute normal vector direction
nnfnorms = np.cross(self.ppts[:,1] - self.ppts[:,0],
self.ppts[:,2] - self.ppts[:,0])
# Normalize to norm 1
nfnorms = nnfnorms / np.sqrt((nnfnorms**2).sum(1))[:,np.newaxis]
# Ensure that there are no nans (shouldn't be a problem with well-formed surfaces)
return np.nan_to_num(nfnorms)
@property
@_memo
def vertex_normals(self):
"""Normal vector for each vertex (average of normals for neighboring faces).
"""
# Average adjacent face normals
nnvnorms = np.nan_to_num(self.connected.dot(self.face_normals) / self.connected.sum(1)).A
# Normalize to norm 1
return nnvnorms / np.sqrt((nnvnorms**2).sum(1))[:,np.newaxis]
@property
@_memo
def face_areas(self):
"""Area of each face.
"""
# Compute normal vector (length is face area)
nnfnorms = np.cross(self.ppts[:,1] - self.ppts[:,0],
self.ppts[:,2] - self.ppts[:,0])
# Compute vector length
return np.sqrt((nnfnorms**2).sum(-1)) / 2
@property
@_memo
def cotangent_weights(self):
"""Cotangent of angle opposite each vertex in each face.
"""
ppts = self.ppts
cots1 = ((ppts[:,1]-ppts[:,0]) *
(ppts[:,2]-ppts[:,0])).sum(1) / np.sqrt((np.cross(ppts[:,1]-ppts[:,0],
ppts[:,2]-ppts[:,0])**2).sum(1))
cots2 = ((ppts[:,2]-ppts[:,1]) *
(ppts[:,0]-ppts[:,1])).sum(1) / np.sqrt((np.cross(ppts[:,2]-ppts[:,1],
ppts[:,0]-ppts[:,1])**2).sum(1))
cots3 = ((ppts[:,0]-ppts[:,2]) *
(ppts[:,1]-ppts[:,2])).sum(1) / np.sqrt((np.cross(ppts[:,0]-ppts[:,2],
ppts[:,1]-ppts[:,2])**2).sum(1))
# Then we have to sanitize the fuck out of everything..
cots = np.vstack([cots1, cots2, cots3])
cots[np.isinf(cots)] = 0
cots[np.isnan(cots)] = 0
return cots
@property
@_memo
def laplace_operator(self):
"""Laplace-Beltrami operator for this surface. A sparse adjacency matrix with
edge weights determined by the cotangents of the angles opposite each edge.
Returns a 4-tuple (B,D,W,V) where D is the 'lumped mass matrix', W is the weighted
adjacency matrix, and V is a diagonal matrix that normalizes the adjacencies.
The 'stiffness matrix', A, can be computed as V - W.
The full LB operator can be computed as D^{-1} (V - W).
B is the finite element method (FEM) 'mass matrix', which replaces D in FEM analyses.
See 'Discrete Laplace-Beltrami operators for shape analysis and segmentation'
by Reuter et al., 2009 for details.
"""
## Lumped mass matrix
D = self.connected.dot(self.face_areas) / 3.0
## Stiffness matrix
npt = len(self.pts)
cots1, cots2, cots3 = self.cotangent_weights
# W is weighted adjacency matrix
W1 = sparse.coo_matrix((cots1, (self.polys[:,1], self.polys[:,2])), (npt, npt))
W2 = sparse.coo_matrix((cots2, (self.polys[:,2], self.polys[:,0])), (npt, npt))
W3 = sparse.coo_matrix((cots3, (self.polys[:,0], self.polys[:,1])), (npt, npt))
W = (W1 + W1.T + W2 + W2.T + W3 + W3.T).tocsr() / 2.0
# V is sum of each col
V = sparse.dia_matrix((np.array(W.sum(0)).ravel(),[0]), (npt,npt))
# A is stiffness matrix
#A = W - V # negative operator -- more useful in practice
# For FEM:
Be1 = sparse.coo_matrix((self.face_areas, (self.polys[:,1], self.polys[:,2])), (npt, npt))
Be2 = sparse.coo_matrix((self.face_areas, (self.polys[:,2], self.polys[:,0])), (npt, npt))
Be3 = sparse.coo_matrix((self.face_areas, (self.polys[:,0], self.polys[:,1])), (npt, npt))
Bd = self.connected.dot(self.face_areas) / 6
dBd = scipy.sparse.dia_matrix((Bd,[0]), (len(D),len(D)))
B = (Be1 + Be1.T + Be2 + Be2.T + Be3 + Be3.T)/12 + dBd
return B, D, W, V
def mean_curvature(self):
"""Compute mean curvature of this surface using the Laplace-Beltrami operator.
Curvature is computed at each vertex. It's probably pretty noisy, and should
be smoothed using smooth().
Negative values of mean curvature mean that the surface is folded inward
(as in a sulcus), positive values of curvature mean that the surface is
folded outward (as on a gyrus).
Returns
-------
curv : 1D ndarray, shape (total_verts,)
The mean curvature at each vertex.
"""
B,D,W,V = self.laplace_operator
npt = len(D)
Dinv = sparse.dia_matrix((D**-1,[0]), (npt,npt)).tocsr() # construct Dinv
L = Dinv.dot((V-W))
curv = (L.dot(self.pts) * self.vertex_normals).sum(1)
return curv
def smooth(self, scalars, factor=1.0, iterations=1):
"""Smooth vertex-wise function given by `scalars` across the surface using
mean curvature flow method (see http://brickisland.net/cs177fa12/?p=302).
Amount of smoothing is controlled by `factor`.
Parameters
----------
scalars : 1D ndarray, shape (total_verts,)
A scalar-valued function across the cortex, such as the curvature
supplied by mean_curvature.
factor : float, optional
Amount of smoothing to perform, larger values smooth more.
iterations : int, optional
Number of times to repeat smoothing, larger values smooths more.
Returns
-------
smscalars : 1D ndarray, shape (total_verts,)
Smoothed scalar values.
"""
if factor == 0.0:
return scalars
B,D,W,V = self.laplace_operator
npt = len(D)
lfac = sparse.dia_matrix((D,[0]), (npt,npt)) - factor * (W-V)
goodrows = np.nonzero(~np.array(lfac.sum(0) == 0).ravel())[0]
lfac_solver = sparse.linalg.dsolve.factorized(lfac[goodrows][:,goodrows])
to_smooth = scalars.copy()
for _ in range(iterations):
from_smooth = lfac_solver((D * to_smooth)[goodrows])
to_smooth[goodrows] = from_smooth
smscalars = np.zeros(scalars.shape)
smscalars[goodrows] = from_smooth
return smscalars
@property
@_memo
def avg_edge_length(self):
"""Average length of all edges in the surface.
"""
adj = self.adj
tadj = sparse.triu(adj, 1) # only entries above main diagonal, in coo format
edgelens = np.sqrt(((self.pts[tadj.row] - self.pts[tadj.col])**2).sum(1))
return edgelens.mean()
def surface_gradient(self, scalars, at_verts=True):
"""Gradient of a function with values `scalars` at each vertex on the surface.
If `at_verts`, returns values at each vertex. Otherwise, returns values at each
face.
Parameters
----------
scalars : 1D ndarray, shape (total_verts,)
A scalar-valued function across the cortex.
at_verts : bool, optional
If True (default), values will be returned for each vertex. Otherwise,
values will be retruned for each face.
Returns
-------
gradu : 2D ndarray, shape (total_verts,3) or (total_polys,3)
Contains the x-, y-, and z-axis gradients of the given `scalars` at either
each vertex (if `at_verts` is True) or each face.
"""
pu = scalars[self.polys]
fe12, fe23, fe31 = [f.T for f in self._facenorm_cross_edge]
pu1, pu2, pu3 = pu.T
fa = self.face_areas
# numexpr is much faster than doing this using numpy!
#gradu = ((fe12.T * pu[:,2] +
# fe23.T * pu[:,0] +
# fe31.T * pu[:,1]) / (2 * self.face_areas)).T
gradu = np.nan_to_num(ne.evaluate("(fe12 * pu3 + fe23 * pu1 + fe31 * pu2) / (2 * fa)").T)
if at_verts:
return (self.connected.dot(gradu).T / self.connected.sum(1).A.squeeze()).T
return gradu
def _create_biharmonic_solver(self, boundary_verts, clip_D=0.1):
"""Set up biharmonic equation with Dirichlet boundary conditions on the cortical
mesh and precompute Cholesky factorization for solving it. The vertices listed in
`boundary_verts` are considered part of the boundary, and will not be included in
the factorization.
To facilitate Cholesky decomposition (which requires a symmetric matrix), the
squared Laplace-Beltrami operator is separated into left-hand-side (L2) and
right-hand-side (Dinv) parts. If we write the L-B operator as the product of
the stiffness matrix (V-W) and the inverse mass matrix (Dinv), the biharmonic
problem is as follows (with `\\b` denoting non-boundary vertices)
.. math::
L^2_{\\b} \phi = -\rho_{\\b} \\
\left[ D^{-1} (V-W) D^{-1} (V-W) \right]_{\\b} \phi = -\rho_{\\b} \\
\left[ (V-W) D^{-1} (V-W) \right]_{\\b} \phi = -\left[D \rho\right]_{\\b}
Parameters
----------
boundary_verts : list or ndarray of length V
Indices of vertices that | |
"""
Small collection of robust statistical estimators based on functions from
<NAME> (Hughes STX) statistics library (called ROBLIB) that have
been incorporated into the AstroIDL User's Library. Function included are:
* medabsdev - median absolute deviation
* biweightMean - biweighted mean estimator
* mean - robust estimator of the mean of a data set
* mode - robust estimate of the mode of a data set using the half-sample
method
* std - robust estimator of the standard deviation of a data set
* checkfit - return the standard deviation and biweights for a fit in order
to determine its quality
* linefit - outlier resistant fit of a line to data
* polyfit - outlier resistant fit of a polynomial to data
For the fitting routines, the coefficients are returned in the same order as
np.polyfit, i.e., with the coefficient of the highest power listed first.
For additional information about the original IDL routines, see:
http://idlastro.gsfc.nasa.gov/contents.html#C17
"""
from __future__ import division, print_function#, unicode_literals
import numpy as np
from numpy import median
import logging
_log = logging.getLogger('webbpsf_ext')
__version__ = '0.4'
__revision__ = '$Rev$'
__all__ = ['medabsdev','biweightMean', 'mean', 'mode', 'std', \
'checkfit', 'linefit', 'polyfit', \
'__version__', '__revision__', '__all__']
# Numerical precision
__epsilon = np.finfo(float).eps
__delta = 5.0e-7
def medabsdev(data, axis=None, keepdims=False, nan=True):
"""Median Absolute Deviation
A "robust" version of standard deviation. Runtime is the
same as `astropy.stats.funcs.mad_std`.
Parameters
----------
data : ndarray
The input data.
axis : None or int or tuple of ints, optional
Axis or axes along which the deviation is computed. The
default is to compute the deviation of the flattened array.
If this is a tuple of ints, a standard deviation is performed over
multiple axes, instead of a single axis or all the axes as before.
This is the equivalent of reshaping the input data and then taking
the standard devation.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `arr`.
nan : bool, optional
Ignore NaNs? Default is True.
"""
medfunc = np.nanmedian if nan else np.median
meanfunc = np.nanmean if nan else np.mean
if (axis is None) and (keepdims==False):
data = data.ravel()
# Scale factor to return result equivalent to standard deviation.
sig_scale = 0.6744897501960817
med = medfunc(data, axis=axis, keepdims=True)
absdiff = np.abs(data - med)
sigma = medfunc(absdiff, axis=axis, keepdims=True) / sig_scale
# Check if anything is near 0.0 (below machine precision)
mask = sigma < __epsilon
if np.any(mask):
sigma[mask] = (meanfunc(absdiff, axis=axis, keepdims=True))[mask] / 0.8
mask = sigma < __epsilon
if np.any(mask):
sigma[mask] = 0.0
if len(sigma)==1:
return sigma[0]
elif not keepdims:
return np.squeeze(sigma)
else:
return sigma
def biweightMean(inputData, axis=None, dtype=None, iterMax=25):
"""Biweight Mean
Calculate the mean of a data set using bisquare weighting.
Based on the biweight_mean routine from the AstroIDL User's
Library.
.. versionchanged:: 1.0.3
Added the 'axis' and 'dtype' keywords to make this function more
compatible with np.mean()
"""
if axis is not None:
fnc = lambda x: biweightMean(x, dtype=dtype)
y0 = np.apply_along_axis(fnc, axis, inputData)
else:
y = inputData.ravel()
if type(y).__name__ == "MaskedArray":
y = y.compressed()
if dtype is not None:
y = y.astype(dtype)
n = len(y)
closeEnough = 0.03*np.sqrt(0.5/(n-1))
diff = 1.0e30
nIter = 0
y0 = np.median(y)
deviation = y - y0
sigma = std(deviation)
if sigma < __epsilon:
diff = 0
while diff > closeEnough:
nIter = nIter + 1
if nIter > iterMax:
break
uu = ((y-y0)/(6.0*sigma))**2.0
uu = np.where(uu > 1.0, 1.0, uu)
weights = (1.0-uu)**2.0
weights /= weights.sum()
y0 = (weights*y).sum()
deviation = y - y0
prevSigma = sigma
sigma = std(deviation, Zero=True)
if sigma > __epsilon:
diff = np.abs(prevSigma - sigma) / prevSigma
else:
diff = 0.0
return y0
def mean(inputData, Cut=3.0, axis=None, dtype=None, keepdims=False,
return_std=False, return_mask=False):
"""Robust Mean
Robust estimator of the mean of a data set. Based on the `resistant_mean`
function from the AstroIDL User's Library. NaN values are excluded.
This function trims away outliers using the median and the median
absolute deviation. An approximation formula is used to correct for
the truncation caused by trimming away outliers.
Parameters
==========
inputData : ndarray
The input data.
Keyword Args
============
Cut : float
Sigma for rejection; default is 3.0.
axis : None or int or tuple of ints, optional
Axis or axes along which the deviation is computed. The
default is to compute the deviation of the flattened array.
If this is a tuple of ints, a standard deviation is performed over
multiple axes, instead of a single axis or all the axes as before.
This is the equivalent of reshaping the input data and then taking
the standard devation.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `arr`.
return_std : bool
Also return the std dev calculated using only the "good" data?
return_mask : bool
If set to True, then return only boolean array of good (1) and
rejected (0) values.
"""
inputData = np.array(inputData)
if np.isnan(inputData).sum() > 0:
medfunc = np.nanmedian
meanfunc = np.nanmean
else:
medfunc = np.median
meanfunc = np.mean
if axis is None:
data = inputData.ravel()
else:
data = inputData
if type(data).__name__ == "MaskedArray":
data = data.compressed()
if dtype is not None:
data = data.astype(dtype)
# Scale factor to return result equivalent to standard deviation.
sig_scale = 0.6744897501960817
# Calculate the median absolute deviation
data0 = medfunc(data, axis=axis, keepdims=True)
absdiff = np.abs(data-data0)
medAbsDev = medfunc(absdiff, axis=axis, keepdims=True) / sig_scale
mask = medAbsDev < __epsilon
if np.any(mask):
medAbsDev[mask] = (meanfunc(absdiff, axis=axis, keepdims=True))[mask] / 0.8
# First cut using the median absolute deviation
cutOff = Cut*medAbsDev
good = absdiff <= cutOff
data_naned = data.copy()
data_naned[~good] = np.nan
dataMean = np.nanmean(data_naned, axis=axis, keepdims=True)
dataSigma = np.nanstd(data_naned, axis=axis, keepdims=True)
#dataSigma = np.sqrt( np.nansum((data_naned-dataMean)**2.0) / len(good) )
# Calculate sigma
if Cut > 1.0:
sigmaCut = Cut
else:
sigmaCut = 1.0
if sigmaCut <= 4.5:
poly_sigcut = -0.15405 + 0.90723*sigmaCut - 0.23584*sigmaCut**2.0 + 0.020142*sigmaCut**3.0
dataSigma = dataSigma / poly_sigcut
cutOff = Cut*dataSigma
good = absdiff <= cutOff
if return_mask:
return np.reshape(~np.isnan(data_naned), inputData.shape)
data_naned = data.copy()
data_naned[~good] = np.nan
dataMean = np.nanmean(data_naned, axis=axis, keepdims=True)
if return_std:
dataSigma = np.nanstd(data_naned, axis=axis, keepdims=True)
if len(dataMean)==1:
if return_std:
return dataMean[0], dataSigma[0]
else:
return dataMean[0]
if not keepdims:
if return_std:
return np.squeeze(dataMean), np.squeeze(dataSigma)
else:
return np.squeeze(dataMean)
else:
if return_std:
return dataMean, dataSigma
else:
return dataMean
def _mean_old(inputData, Cut=3.0, axis=None, dtype=None):
"""Robust mean
Robust estimator of the mean of a data set. Based on the
resistant_mean function from the AstroIDL User's Library.
.. versionchanged:: 1.0.3
Added the 'axis' and 'dtype' keywords to make this function more
compatible with np.mean()
"""
inputData = np.array(inputData)
if axis is not None:
fnc = lambda x: _mean_old(x, dtype=dtype)
dataMean = np.apply_along_axis(fnc, axis, inputData)
else:
data = inputData.ravel()
if type(data).__name__ == "MaskedArray":
data = data.compressed()
if dtype is not None:
data = data.astype(dtype)
data0 = np.median(data)
absdiff = np.abs(data-data0)
medAbsDev = np.median(absdiff) / 0.6745
if medAbsDev < __epsilon:
medAbsDev = absdiff.mean() / 0.8000
cutOff = Cut*medAbsDev
good = np.where( absdiff <= cutOff )
good = good[0]
dataMean = data[good].mean()
dataSigma = np.sqrt( ((data[good]-dataMean)**2.0).sum() / len(good) )
if Cut > 1.0:
sigmaCut = Cut
else:
sigmaCut = 1.0
if sigmaCut <= 4.5:
dataSigma = dataSigma / (-0.15405 + 0.90723*sigmaCut - 0.23584*sigmaCut**2.0 + 0.020142*sigmaCut**3.0)
cutOff = Cut*dataSigma
good = np.where( absdiff <= cutOff )
good = good[0]
dataMean = data[good].mean()
if len(good) > 3:
dataSigma = np.sqrt( ((data[good]-dataMean)**2.0).sum() / len(good) )
if Cut > 1.0:
sigmaCut = Cut
else:
sigmaCut = 1.0
if sigmaCut <= 4.5:
dataSigma |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.