file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
image_processor_2.0.py | #!/usr/bin/python
#Team3238 Cyborg Ferrets 2014 Object Detection Code
#Start with
#python image_processor.py 'path/to/image.jpg'
#don't pass an image argument to use the VideoCapture(0) stream.
# Video capture mode updates the frame to process every video_pause milliseconds, so adjust that.
#set enable_dashboard = True to send range and bearing over smart dashboard network_tables interface.
#set show_windows = False for on-robot, no monitor processing on pandaboard.
#This code is a merge of vision_lib.py, bearing_formula.py, distance_formula.py and team341 java vision detection code from (2012?) competition.
#java -jar SmartDashboard ip 127.0.0.1, for example, will start the dashboard if running on this same host.
#Now tuned for green leds.
#expected camera settings (sorry no numbers on camera interface.)
# exposure -> far right
# gain -> far left
# brightness ~ 20% from left
# contrast ~ 20% from left
# color intensity ~ 18% from left
enable_dashboard = True
show_windows = False
window_scale = 0.5
window_size = (int(640*window_scale), int(480*window_scale))
from cv2 import *
import numpy as np
import sys
import math
import commands
if enable_dashboard:
from pynetworktables import *
if enable_dashboard:
SmartDashboard.init()
#pretend the robot is on the network reporting its heading to the SmartDashboard,
# then let the SmartDashboard user modify it and send it back to this code to simulate movement.
camera_exposure_title = 'Camera Exposure:'
class ImageProcessor:
#all these values could be put into the SmartDashboard for live tuning as conditions change.
default_shape = (480,640,3)
h = np.zeros(default_shape, dtype=np.uint8)
s = np.zeros(default_shape, dtype=np.uint8)
v = np.zeros(default_shape, dtype=np.uint8)
combined = np.zeros(default_shape, dtype=np.uint8)
img = np.zeros(default_shape, dtype=np.uint8)
h_title = "hue"
s_title = "sat"
v_title = "val"
combined_title = "Combined + Morphed"
targets_title = "Targets"
#for video capture mode, what approx frame rate do we want? frame rate = approx video_pause + processing time
video_pause = 1 #0 milliseconds means wait for key press, waitKey takes an integer so 1 millisecond is minimal with this approach.
#tuned for the camera settings above and the green leds. (Red didn't work as well and requires changing the threshold function to use OR of inverse and normal threshold, because red is on the top and bottom of the hue scale (wraps around.).)
hue_delta = 15
sat_delta = 25
val_delta = 100
hue_thresh = 80
sat_thresh = 233
val_thresh = 212
max_thresh = 255
#used for the morphologyEx method that fills in the pixels in the combined image prior to identifying polygons and contours.
kernel = getStructuringElement(MORPH_RECT, (2,2), anchor=(1,1))
morph_close_iterations = 9
#colors in BGR format for drawing the targets over the image.
selected_target_color = (0,0,255)
passed_up_target_color = (255,0,0)
possible_target_color = (0,255,0)
#used to judge whether a polygon side is near vertical or near horizontal, for filtering out shapes that don't match expected target characteristics
vert_threshold = math.tan(math.radians(90-20))
horiz_threshold = math.tan(math.radians(20))
#used to look for only horizontal or vertical rectangles of an aspect ratio that matches the targets.
#currently open wide to find both horizontal and vertical targets
max_target_aspect_ratio = 10 # 1.0 # top target is expected to be 24.5 in x 4 in.
min_target_aspect_ratio = 0.1 #0.01# 3# 0.5
angle_to_robot = 0 #camera's 0 bearing to robot's 0 bearing
camera_offset_position = 0
morph_close_iterations = 9
angle_to_shooter = 0 #camera's 0 bearing to shooter's 0 bearing
camera_color_intensity = 0 #value subject to change
camera_saturation = 0 #value subject to change
camera_contrast = 0 #value subject to change
camera_color_hue = 0 #value subject to change
camera_brightness = 20 #value subject to change
camera_gain = 0 #value subject to change
camera_exposure = 20
robot_heading = 0.0 #input from SmartDashboard if enabled, else hard coded here.
x_resolution = 640 #needs to match the camera.
y_resolution = 480
#theta = math.radians(49.165) #half of field of view of the camera
# field_of_view_degrees = 53.0 horizontal field of view
field_of_view_degrees = 26.4382 # vertical field of view
theta = math.radians(field_of_view_degrees/2.0) #half of field of view of the camera, in radians to work with math.tan function.
# real_target_width = 24.5 #inches #24 * 0.0254 #1 inch / 0.254 meters target is 24 inches wide
real_target_height = 28.5 #using these constants and may not be correct for current robot configuration.
angle_to_shooter = 0
#not currently using these constants and may not be correct for current robot configuration.
# target_min_width = 20
# target_max_width = 200
# degrees_horiz_field_of_view = 47.0
# degrees_vert_field_of_view = 480.0/640*degrees_horiz_field_of_view
# inches_camera_height = 54.0
# inches_top_target_height = 98 + 2 + 98
# degrees_camera_pitch = 21.0
# degrees_sighting_offset = -1.55
def | (self, img_path):
self.img_path = img_path
self.layout_result_windows(self.h,self.s,self.v)
self.vc = VideoCapture(0)
SmartDashboard.PutNumber(angle_to_robot_title, self.angle_to_robot)
SmartDashboard.PutNumber(camera_offset_position_title, self.camera_offset_position)
SmartDashboard.PutNumber(morph_close_iterations_title, self.morph_close_iterations)
SmartDashboard.PutNumber(angle_to_shooter_title, self.angle_to_shooter)
SmartDashboard.PutNumber(camera_color_intensity_title, self.camera_color_intensity)
SmartDashboard.PutNumber(camera_exposure_title, self.camera_exposure)
SmartDashboard.PutNumber(camera_saturation.title, self.saturation)
SmartDashboard.PutNumber(camera_contrast_title, self.contrast)
SmartDashboard.PutNumber(camera_color_hue_title, self.camera_color_hue)
SmartDashboard.PutNumber(camera_brihtness_title, self.camera_brightness)
def video_feed(self):
while True:
if self.img is not None:
self.process()
if self.img_path is None:
rval, self.img = self.vc.read() #might set to None
else:
self.img = imread(self.img_path)
def process(self):
if enable_dashboard:
self.camera_saturation = int(SmartDashboard.GetNumber(camera_saturation_title)
self.angle_to_robot = int(SmartDashboard.GetNumber(angle_to_robot_title)
self.camera_offset_postion = int(SmartDashboard.GetNumber(camera_offset_position_title)
self.morph_close_iterations = int(SmartDashboard.GetNumber(morph_close_iterations_title)
self.angle_to_shooter = int(SmartDashboard.GetNumber(angle_to_shooter_title)
self.camera_color_intensity = int(SmartDashboard.GetNumber(camera_color_intensity_title)
self.camera_contrast = int(SmartDashboard.GetNumber(camera_contrast_title)
self.camera_color_hue = int(SmartDashboard.GetNumber(camera_color_hue_title)
self.camera_brightness = int(SmartDashboard.GetNumber(camera_brightness_title)
self.camera_exposure = int(SmartDashboard.GetNumber(camera_exposure_title)
self.camera_gain = int(SmartDashboard.GetNumber(camera_gain_title)
if self.img_path is None:
commands.getoutput(" yavta --set-control '0x009a0901 1' /dev/video0")
#print(commands.getoutput(" yavta --get-control '0x009a0901' /dev/video0") )
commands.getoutput("yavta --set-control '0x009a0902 %s' /dev/video0" % self.camera_exposure)
#print(commands.getoutput(" yavta --get-control '0x009a0902' /dev/video0"))
drawing = np.zeros(self.img.shape, dtype=np.uint8)
self.hsv = cvtColor(self.img, cv.CV_BGR2HSV)
self.h, self.s, self.v = split(self.hsv)
self.h_clipped = self.threshold_in_range(self.h, self.hue_thresh-self.hue_delta, self.hue_thresh+self.hue_delta)
self.s_clipped = self.threshold_in_range(self.s, self.sat_thresh-self.sat_delta, self.sat_thresh+self.sat_delta)
self.v_clipped = self.threshold_in_range(self.v, self.val_thresh-self.val_delta, self.val_thresh+self.val_delta)
if show_windows:
h_scaled = resize(self.h_clipped, window_size)
s_scaled = resize(self.s_clipped, window_size)
v_scaled = resize(self.v_clipped, window_size)
imshow(self.h_title, h_scaled)
imshow(self.s_title, s_scaled)
imshow(self.v_title, v_scaled)
self.find_targets()
if waitKey(self.video_pause) == ord('q'):
exit(1)
def layout_result_windows(self, h, s, v):
if show_windows:
pos_x, pos_y = 500,500
# imshow(self.img_path, self.img)
h_scaled = resize(h, window_size)
s_scaled = resize(s, window_size)
v_scaled = resize(v, window_size)
combined_scaled = resize(self.combined, window_size)
img_scaled = resize(self.img, window_size)
imshow(self.h_title , h_scaled)
imshow(self.s_title , s_scaled)
imshow(self.v_title , v_scaled)
imshow(self.combined_title, combined_scaled)
imshow(self.targets_title , img_scaled)
#moveWindow(self.h_title, pos_x*1, pos_y*0);
#moveWindow(self.s_title, pos_x*0, pos_y*1);
#moveWindow(self.v_title, pos_x*1, pos_y*1);
#moveWindow(self.combined_title, pos_x*2, pos_y*0);
#moveWindow(self.targets_title, pos_x*2, pos_y*1);
#these seem to be placed alphabetically....
# createTrackbar( "Hue High Threshold:", self.source_title, self.hue_high_thresh, self.max_thresh, self.update_hue_high_threshold);
# createTrackbar( "Hue Low Threshold:", self.source_title, self.hue_low_thresh, self.max_thresh, self.update_hue_low_threshold);
# createTrackbar( "Sat High Threshold:", self.source_title, self.sat_high_thresh, self.max_thresh, self.update_sat_high_threshold);
# createTrackbar( "Sat Low Threshold:", self.source_title, self.sat_low_thresh, self.max_thresh, self.update_sat_low_threshold);
# createTrackbar( "Val High Threshold:", self.source_title, self.val_high_thresh, self.max_thresh, self.update_val_high_threshold);
# createTrackbar( "Val Low Threshold:", self.source_title, self.val_low_thresh, self.max_thresh, self.update_val_low_threshold);
def update_hue_threshold(self, thresh):
delta = 15
self.h_clipped = self.threshold_in_range(self.h, thresh-delta, thresh+delta)
imshow(self.h_title, self.h_clipped)
self.find_targets()
def update_sat_threshold(self, thresh):
delta = 25
self.s_clipped = self.threshold_in_range(self.s, thresh-delta, thresh+delta)
imshow(self.s_title, self.s_clipped)
self.find_targets()
def update_val_threshold(self, thresh):
delta = 100
self.v_clipped = self.threshold_in_range(self.v, thresh-delta, thresh+delta)
imshow(self.v_title, self.v_clipped)
self.find_targets()
def threshold_in_range(self, img, low, high):
unused, above = threshold(img, low, self.max_thresh, THRESH_BINARY)
unused, below = threshold(img, high, self.max_thresh, THRESH_BINARY_INV)
return bitwise_and(above, below)
def find_targets(self):
#combine all the masks together to get their overlapping regions.
if True:
self.reset_targeting()
self.combined = bitwise_and(self.h_clipped, bitwise_and(self.s_clipped, self.v_clipped))
#comment above line and uncomment next line to ignore hue channel til we sort out red light hue matching around zero.
#self.combined = bitwise_and(self.s_clipped, self.v_clipped)
self.combined = morphologyEx(src=self.combined, op=MORPH_CLOSE, kernel=self.kernel, iterations=self.morph_close_iterations)
if show_windows:
combined_scaled = resize(self.combined, window_size)
imshow(self.combined_title, combined_scaled )
self.contoured = self.combined.copy()
contours, heirarchy = findContours(self.contoured, RETR_LIST, CHAIN_APPROX_TC89_KCOS)
#print("number of contours found = "+str(len(contours)))
#contours = [convexHull(c.astype(np.float32),clockwise=True,returnPoints=True) for c in contours]
#
polygon_tuples = self.contours_to_polygon_tuples(contours)
polygons = [self.unpack_polygon(t) for t in polygon_tuples]
for polygon_tuple in polygon_tuples:
self.mark_correct_shape_and_orientation(polygon_tuple)
if self.selected_target is not None:
self.draw_target(self.lowest_found_so_far_x, self.lowest_found_so_far, self.selected_target_color)
drawContours(self.drawing, contours, -1, self.selected_target_color, thickness=10)
# drawContours(self.drawing, [self.unpack_polygon(self.selected_target).astype(np.int32)], -1, self.selected_target_color, thickness=10)
self.aim()
if show_windows:
drawing_scaled = resize(self.drawing, window_size)
imshow(self.targets_title, drawing_scaled)
if enable_dashboard:
SmartDashboard.PutNumber("Potential Targets:", len(polygons))
print("Potential Targets:", len(polygons))
def aim(self):
if enable_dashboard:
self.robot_heading = SmartDashboard.GetNumber(robot_heading_title)
polygon, x, y, w, h = self.selected_target
self.target_bearing = self.get_bearing(x + w/2.0)
self.target_range = self.get_range(x, y, w, h)
#self.target_elevation = self.get_elevation(x, y, w, h)
print("Range = " + str(self.target_range))
print("Bearing = " + str(self.target_bearing))
if enable_dashboard:
SmartDashboard.PutNumber("Target Range:", self.target_range)
SmartDashboard.PutNumber("Target Bearing:", self.target_bearing)
SmartDashboard.PutNumber("Target Elevation:",self.target_elevation)
SmartDashboard.PutString("Target: ","Acquired!")
def get_bearing(self, target_center_x):
return (self.field_of_view_degrees/self.x_resolution)*(target_center_x-(self.x_resolution/2))-self.angle_to_shooter
def get_range(self, x, y, w, h):
if enable_dashboard:
SmartDashboard.PutNumber("TargetWidth: ",w)
SmartDashboard.PutNumber("TargetHeight",h)
SmartDashboard.PutNumber("TargetX",x)
SmartDashboard.PutNumber("TargetY",y)
return self.distance(h)
def distance(self, pix_height):
fovr = self.x_resolution * self.real_target_height / pix_height
if enable_dashboard:
SmartDashboard.PutNumber("FieldOfViewReal", fovr) # = 2w_real
SmartDashboard.PutNumber("TanTheta", math.tan(self.theta))
SmartDashboard.PutNumber("fovr/tan(theta)", fovr/math.tan(self.theta))
return self.real_target_height*self.y_resolution/(2*pix_height*math.tan(self.theta))
def reset_targeting(self):
if enable_dashboard:
SmartDashboard.PutString("Target: ","lost...")
self.drawing = self.img.copy()
self.selected_target = None
self.lowest_found_so_far_x = None
self.lowest_found_so_far = 0
self.target_range = 0
self.target_bearing = -1
self.target_elevation = 0
def mark_correct_shape_and_orientation(self, polygon_tuple):
p,x,y,w,h = polygon_tuple
if True: #isContourConvex(p) and 4==len(p) and self.slope_angles_correct(p):
center_x = int(x + w/2.0)
center_y = int(y + h/2.0)
self.draw_target(center_x, center_y, self.possible_target_color)
if center_y > self.lowest_found_so_far:
self.selected_target = polygon_tuple
self.lowest_found_so_far = center_y
self.lowest_found_so_far_x = center_x
else:
drawContours(self.drawing, [p.astype(np.int32)], -1, self.passed_up_target_color, thickness=7)
def draw_target(self, center_x, center_y, a_color):
#circle(self.drawing,(center_x, center_y), radius=10, color=self.selected_target_color, thickness=5)
radius = 10
a_thickness = 5
line(self.drawing, (center_x - radius, center_y), (center_x + radius, center_y), color=a_color, thickness=a_thickness)
line(self.drawing, (center_x, center_y-radius), (center_x, center_y+radius), color=a_color, thickness=a_thickness)
def slope_angles_correct(self, polygon):
num_near_vert, num_near_horiz = 0,0
for line_starting_point_index in xrange(0,4):
slope = self.get_slope(polygon, line_starting_point_index)
if slope < self.horiz_threshold:
num_near_horiz += 1
if slope > self.vert_threshold:
num_near_vert += 1
return 1 <= num_near_horiz and 2 == num_near_vert
def get_slope(self, p, line_starting_point_index):
line_ending_point_index = (line_starting_point_index+1)%4
dy = p[line_starting_point_index, 0, 1] - p[line_ending_point_index, 0, 1]
dx = p[line_starting_point_index, 0, 0] - p[line_ending_point_index, 0, 0]
slope = sys.float_info.max
if 0 != dx:
slope = abs(float(dy)/dx)
return slope
def unpack_polygon(self,t):
p,x,y,w,h = t
return p
def contours_to_polygon_tuples(self, contours):
polygon_tuples = []
for c in contours:
x, y, w, h = boundingRect(c)
if self.aspect_ratio_and_size_correct(w,h):
p = approxPolyDP(c, 20, False)
polygon_tuples.append((p,x,y,w,h))
return polygon_tuples
def aspect_ratio_and_size_correct(self, width, height):
ratio = float(width)/height #float(height)/width
return ratio < self.max_target_aspect_ratio and ratio > self.min_target_aspect_ratio #and width > self.target_min_width and width < self.target_max_width
#note: we don't want to ignore potential targets based on pixel width and height since range will change the pixel coverage of a real target.
if '__main__'==__name__:
try:
img_path = sys.argv[1]
except:
img_path= None
# print('Please add an image path argument and try again.')
# sys.exit(2)
ImageProcessor(img_path).video_feed()
| __init__ | identifier_name |
image_processor_2.0.py | #!/usr/bin/python
#Team3238 Cyborg Ferrets 2014 Object Detection Code
#Start with
#python image_processor.py 'path/to/image.jpg'
#don't pass an image argument to use the VideoCapture(0) stream.
# Video capture mode updates the frame to process every video_pause milliseconds, so adjust that.
#set enable_dashboard = True to send range and bearing over smart dashboard network_tables interface.
#set show_windows = False for on-robot, no monitor processing on pandaboard.
#This code is a merge of vision_lib.py, bearing_formula.py, distance_formula.py and team341 java vision detection code from (2012?) competition.
#java -jar SmartDashboard ip 127.0.0.1, for example, will start the dashboard if running on this same host.
#Now tuned for green leds.
#expected camera settings (sorry no numbers on camera interface.)
# exposure -> far right
# gain -> far left
# brightness ~ 20% from left
# contrast ~ 20% from left
# color intensity ~ 18% from left
enable_dashboard = True
show_windows = False
window_scale = 0.5
window_size = (int(640*window_scale), int(480*window_scale))
from cv2 import *
import numpy as np
import sys
import math
import commands
if enable_dashboard:
from pynetworktables import *
if enable_dashboard:
SmartDashboard.init()
#pretend the robot is on the network reporting its heading to the SmartDashboard,
# then let the SmartDashboard user modify it and send it back to this code to simulate movement.
camera_exposure_title = 'Camera Exposure:'
class ImageProcessor:
#all these values could be put into the SmartDashboard for live tuning as conditions change.
default_shape = (480,640,3)
h = np.zeros(default_shape, dtype=np.uint8)
s = np.zeros(default_shape, dtype=np.uint8)
v = np.zeros(default_shape, dtype=np.uint8)
combined = np.zeros(default_shape, dtype=np.uint8)
img = np.zeros(default_shape, dtype=np.uint8)
h_title = "hue"
s_title = "sat"
v_title = "val"
combined_title = "Combined + Morphed"
targets_title = "Targets"
#for video capture mode, what approx frame rate do we want? frame rate = approx video_pause + processing time
video_pause = 1 #0 milliseconds means wait for key press, waitKey takes an integer so 1 millisecond is minimal with this approach.
#tuned for the camera settings above and the green leds. (Red didn't work as well and requires changing the threshold function to use OR of inverse and normal threshold, because red is on the top and bottom of the hue scale (wraps around.).)
hue_delta = 15
sat_delta = 25
val_delta = 100
hue_thresh = 80
sat_thresh = 233
val_thresh = 212
max_thresh = 255
#used for the morphologyEx method that fills in the pixels in the combined image prior to identifying polygons and contours.
kernel = getStructuringElement(MORPH_RECT, (2,2), anchor=(1,1))
morph_close_iterations = 9
#colors in BGR format for drawing the targets over the image.
selected_target_color = (0,0,255)
passed_up_target_color = (255,0,0)
possible_target_color = (0,255,0)
#used to judge whether a polygon side is near vertical or near horizontal, for filtering out shapes that don't match expected target characteristics
vert_threshold = math.tan(math.radians(90-20))
horiz_threshold = math.tan(math.radians(20))
#used to look for only horizontal or vertical rectangles of an aspect ratio that matches the targets.
#currently open wide to find both horizontal and vertical targets
max_target_aspect_ratio = 10 # 1.0 # top target is expected to be 24.5 in x 4 in.
min_target_aspect_ratio = 0.1 #0.01# 3# 0.5
angle_to_robot = 0 #camera's 0 bearing to robot's 0 bearing
camera_offset_position = 0
morph_close_iterations = 9
angle_to_shooter = 0 #camera's 0 bearing to shooter's 0 bearing
camera_color_intensity = 0 #value subject to change
camera_saturation = 0 #value subject to change
camera_contrast = 0 #value subject to change
camera_color_hue = 0 #value subject to change
camera_brightness = 20 #value subject to change
camera_gain = 0 #value subject to change
camera_exposure = 20
robot_heading = 0.0 #input from SmartDashboard if enabled, else hard coded here.
x_resolution = 640 #needs to match the camera.
y_resolution = 480
#theta = math.radians(49.165) #half of field of view of the camera
# field_of_view_degrees = 53.0 horizontal field of view
field_of_view_degrees = 26.4382 # vertical field of view
theta = math.radians(field_of_view_degrees/2.0) #half of field of view of the camera, in radians to work with math.tan function.
# real_target_width = 24.5 #inches #24 * 0.0254 #1 inch / 0.254 meters target is 24 inches wide
real_target_height = 28.5 #using these constants and may not be correct for current robot configuration.
angle_to_shooter = 0
#not currently using these constants and may not be correct for current robot configuration.
# target_min_width = 20
# target_max_width = 200
# degrees_horiz_field_of_view = 47.0
# degrees_vert_field_of_view = 480.0/640*degrees_horiz_field_of_view
# inches_camera_height = 54.0
# inches_top_target_height = 98 + 2 + 98
# degrees_camera_pitch = 21.0
# degrees_sighting_offset = -1.55
def __init__(self, img_path):
self.img_path = img_path
self.layout_result_windows(self.h,self.s,self.v)
self.vc = VideoCapture(0)
SmartDashboard.PutNumber(angle_to_robot_title, self.angle_to_robot)
SmartDashboard.PutNumber(camera_offset_position_title, self.camera_offset_position)
SmartDashboard.PutNumber(morph_close_iterations_title, self.morph_close_iterations)
SmartDashboard.PutNumber(angle_to_shooter_title, self.angle_to_shooter)
SmartDashboard.PutNumber(camera_color_intensity_title, self.camera_color_intensity)
SmartDashboard.PutNumber(camera_exposure_title, self.camera_exposure)
SmartDashboard.PutNumber(camera_saturation.title, self.saturation)
SmartDashboard.PutNumber(camera_contrast_title, self.contrast)
SmartDashboard.PutNumber(camera_color_hue_title, self.camera_color_hue)
SmartDashboard.PutNumber(camera_brihtness_title, self.camera_brightness)
def video_feed(self):
while True:
if self.img is not None:
|
if self.img_path is None:
rval, self.img = self.vc.read() #might set to None
else:
self.img = imread(self.img_path)
def process(self):
if enable_dashboard:
self.camera_saturation = int(SmartDashboard.GetNumber(camera_saturation_title)
self.angle_to_robot = int(SmartDashboard.GetNumber(angle_to_robot_title)
self.camera_offset_postion = int(SmartDashboard.GetNumber(camera_offset_position_title)
self.morph_close_iterations = int(SmartDashboard.GetNumber(morph_close_iterations_title)
self.angle_to_shooter = int(SmartDashboard.GetNumber(angle_to_shooter_title)
self.camera_color_intensity = int(SmartDashboard.GetNumber(camera_color_intensity_title)
self.camera_contrast = int(SmartDashboard.GetNumber(camera_contrast_title)
self.camera_color_hue = int(SmartDashboard.GetNumber(camera_color_hue_title)
self.camera_brightness = int(SmartDashboard.GetNumber(camera_brightness_title)
self.camera_exposure = int(SmartDashboard.GetNumber(camera_exposure_title)
self.camera_gain = int(SmartDashboard.GetNumber(camera_gain_title)
if self.img_path is None:
commands.getoutput(" yavta --set-control '0x009a0901 1' /dev/video0")
#print(commands.getoutput(" yavta --get-control '0x009a0901' /dev/video0") )
commands.getoutput("yavta --set-control '0x009a0902 %s' /dev/video0" % self.camera_exposure)
#print(commands.getoutput(" yavta --get-control '0x009a0902' /dev/video0"))
drawing = np.zeros(self.img.shape, dtype=np.uint8)
self.hsv = cvtColor(self.img, cv.CV_BGR2HSV)
self.h, self.s, self.v = split(self.hsv)
self.h_clipped = self.threshold_in_range(self.h, self.hue_thresh-self.hue_delta, self.hue_thresh+self.hue_delta)
self.s_clipped = self.threshold_in_range(self.s, self.sat_thresh-self.sat_delta, self.sat_thresh+self.sat_delta)
self.v_clipped = self.threshold_in_range(self.v, self.val_thresh-self.val_delta, self.val_thresh+self.val_delta)
if show_windows:
h_scaled = resize(self.h_clipped, window_size)
s_scaled = resize(self.s_clipped, window_size)
v_scaled = resize(self.v_clipped, window_size)
imshow(self.h_title, h_scaled)
imshow(self.s_title, s_scaled)
imshow(self.v_title, v_scaled)
self.find_targets()
if waitKey(self.video_pause) == ord('q'):
exit(1)
def layout_result_windows(self, h, s, v):
if show_windows:
pos_x, pos_y = 500,500
# imshow(self.img_path, self.img)
h_scaled = resize(h, window_size)
s_scaled = resize(s, window_size)
v_scaled = resize(v, window_size)
combined_scaled = resize(self.combined, window_size)
img_scaled = resize(self.img, window_size)
imshow(self.h_title , h_scaled)
imshow(self.s_title , s_scaled)
imshow(self.v_title , v_scaled)
imshow(self.combined_title, combined_scaled)
imshow(self.targets_title , img_scaled)
#moveWindow(self.h_title, pos_x*1, pos_y*0);
#moveWindow(self.s_title, pos_x*0, pos_y*1);
#moveWindow(self.v_title, pos_x*1, pos_y*1);
#moveWindow(self.combined_title, pos_x*2, pos_y*0);
#moveWindow(self.targets_title, pos_x*2, pos_y*1);
#these seem to be placed alphabetically....
# createTrackbar( "Hue High Threshold:", self.source_title, self.hue_high_thresh, self.max_thresh, self.update_hue_high_threshold);
# createTrackbar( "Hue Low Threshold:", self.source_title, self.hue_low_thresh, self.max_thresh, self.update_hue_low_threshold);
# createTrackbar( "Sat High Threshold:", self.source_title, self.sat_high_thresh, self.max_thresh, self.update_sat_high_threshold);
# createTrackbar( "Sat Low Threshold:", self.source_title, self.sat_low_thresh, self.max_thresh, self.update_sat_low_threshold);
# createTrackbar( "Val High Threshold:", self.source_title, self.val_high_thresh, self.max_thresh, self.update_val_high_threshold);
# createTrackbar( "Val Low Threshold:", self.source_title, self.val_low_thresh, self.max_thresh, self.update_val_low_threshold);
def update_hue_threshold(self, thresh):
delta = 15
self.h_clipped = self.threshold_in_range(self.h, thresh-delta, thresh+delta)
imshow(self.h_title, self.h_clipped)
self.find_targets()
def update_sat_threshold(self, thresh):
delta = 25
self.s_clipped = self.threshold_in_range(self.s, thresh-delta, thresh+delta)
imshow(self.s_title, self.s_clipped)
self.find_targets()
def update_val_threshold(self, thresh):
delta = 100
self.v_clipped = self.threshold_in_range(self.v, thresh-delta, thresh+delta)
imshow(self.v_title, self.v_clipped)
self.find_targets()
def threshold_in_range(self, img, low, high):
unused, above = threshold(img, low, self.max_thresh, THRESH_BINARY)
unused, below = threshold(img, high, self.max_thresh, THRESH_BINARY_INV)
return bitwise_and(above, below)
def find_targets(self):
#combine all the masks together to get their overlapping regions.
if True:
self.reset_targeting()
self.combined = bitwise_and(self.h_clipped, bitwise_and(self.s_clipped, self.v_clipped))
#comment above line and uncomment next line to ignore hue channel til we sort out red light hue matching around zero.
#self.combined = bitwise_and(self.s_clipped, self.v_clipped)
self.combined = morphologyEx(src=self.combined, op=MORPH_CLOSE, kernel=self.kernel, iterations=self.morph_close_iterations)
if show_windows:
combined_scaled = resize(self.combined, window_size)
imshow(self.combined_title, combined_scaled )
self.contoured = self.combined.copy()
contours, heirarchy = findContours(self.contoured, RETR_LIST, CHAIN_APPROX_TC89_KCOS)
#print("number of contours found = "+str(len(contours)))
#contours = [convexHull(c.astype(np.float32),clockwise=True,returnPoints=True) for c in contours]
#
polygon_tuples = self.contours_to_polygon_tuples(contours)
polygons = [self.unpack_polygon(t) for t in polygon_tuples]
for polygon_tuple in polygon_tuples:
self.mark_correct_shape_and_orientation(polygon_tuple)
if self.selected_target is not None:
self.draw_target(self.lowest_found_so_far_x, self.lowest_found_so_far, self.selected_target_color)
drawContours(self.drawing, contours, -1, self.selected_target_color, thickness=10)
# drawContours(self.drawing, [self.unpack_polygon(self.selected_target).astype(np.int32)], -1, self.selected_target_color, thickness=10)
self.aim()
if show_windows:
drawing_scaled = resize(self.drawing, window_size)
imshow(self.targets_title, drawing_scaled)
if enable_dashboard:
SmartDashboard.PutNumber("Potential Targets:", len(polygons))
print("Potential Targets:", len(polygons))
def aim(self):
if enable_dashboard:
self.robot_heading = SmartDashboard.GetNumber(robot_heading_title)
polygon, x, y, w, h = self.selected_target
self.target_bearing = self.get_bearing(x + w/2.0)
self.target_range = self.get_range(x, y, w, h)
#self.target_elevation = self.get_elevation(x, y, w, h)
print("Range = " + str(self.target_range))
print("Bearing = " + str(self.target_bearing))
if enable_dashboard:
SmartDashboard.PutNumber("Target Range:", self.target_range)
SmartDashboard.PutNumber("Target Bearing:", self.target_bearing)
SmartDashboard.PutNumber("Target Elevation:",self.target_elevation)
SmartDashboard.PutString("Target: ","Acquired!")
def get_bearing(self, target_center_x):
return (self.field_of_view_degrees/self.x_resolution)*(target_center_x-(self.x_resolution/2))-self.angle_to_shooter
def get_range(self, x, y, w, h):
if enable_dashboard:
SmartDashboard.PutNumber("TargetWidth: ",w)
SmartDashboard.PutNumber("TargetHeight",h)
SmartDashboard.PutNumber("TargetX",x)
SmartDashboard.PutNumber("TargetY",y)
return self.distance(h)
def distance(self, pix_height):
fovr = self.x_resolution * self.real_target_height / pix_height
if enable_dashboard:
SmartDashboard.PutNumber("FieldOfViewReal", fovr) # = 2w_real
SmartDashboard.PutNumber("TanTheta", math.tan(self.theta))
SmartDashboard.PutNumber("fovr/tan(theta)", fovr/math.tan(self.theta))
return self.real_target_height*self.y_resolution/(2*pix_height*math.tan(self.theta))
def reset_targeting(self):
if enable_dashboard:
SmartDashboard.PutString("Target: ","lost...")
self.drawing = self.img.copy()
self.selected_target = None
self.lowest_found_so_far_x = None
self.lowest_found_so_far = 0
self.target_range = 0
self.target_bearing = -1
self.target_elevation = 0
def mark_correct_shape_and_orientation(self, polygon_tuple):
p,x,y,w,h = polygon_tuple
if True: #isContourConvex(p) and 4==len(p) and self.slope_angles_correct(p):
center_x = int(x + w/2.0)
center_y = int(y + h/2.0)
self.draw_target(center_x, center_y, self.possible_target_color)
if center_y > self.lowest_found_so_far:
self.selected_target = polygon_tuple
self.lowest_found_so_far = center_y
self.lowest_found_so_far_x = center_x
else:
drawContours(self.drawing, [p.astype(np.int32)], -1, self.passed_up_target_color, thickness=7)
def draw_target(self, center_x, center_y, a_color):
#circle(self.drawing,(center_x, center_y), radius=10, color=self.selected_target_color, thickness=5)
radius = 10
a_thickness = 5
line(self.drawing, (center_x - radius, center_y), (center_x + radius, center_y), color=a_color, thickness=a_thickness)
line(self.drawing, (center_x, center_y-radius), (center_x, center_y+radius), color=a_color, thickness=a_thickness)
def slope_angles_correct(self, polygon):
num_near_vert, num_near_horiz = 0,0
for line_starting_point_index in xrange(0,4):
slope = self.get_slope(polygon, line_starting_point_index)
if slope < self.horiz_threshold:
num_near_horiz += 1
if slope > self.vert_threshold:
num_near_vert += 1
return 1 <= num_near_horiz and 2 == num_near_vert
def get_slope(self, p, line_starting_point_index):
line_ending_point_index = (line_starting_point_index+1)%4
dy = p[line_starting_point_index, 0, 1] - p[line_ending_point_index, 0, 1]
dx = p[line_starting_point_index, 0, 0] - p[line_ending_point_index, 0, 0]
slope = sys.float_info.max
if 0 != dx:
slope = abs(float(dy)/dx)
return slope
def unpack_polygon(self,t):
p,x,y,w,h = t
return p
def contours_to_polygon_tuples(self, contours):
polygon_tuples = []
for c in contours:
x, y, w, h = boundingRect(c)
if self.aspect_ratio_and_size_correct(w,h):
p = approxPolyDP(c, 20, False)
polygon_tuples.append((p,x,y,w,h))
return polygon_tuples
def aspect_ratio_and_size_correct(self, width, height):
ratio = float(width)/height #float(height)/width
return ratio < self.max_target_aspect_ratio and ratio > self.min_target_aspect_ratio #and width > self.target_min_width and width < self.target_max_width
#note: we don't want to ignore potential targets based on pixel width and height since range will change the pixel coverage of a real target.
if '__main__'==__name__:
try:
img_path = sys.argv[1]
except:
img_path= None
# print('Please add an image path argument and try again.')
# sys.exit(2)
ImageProcessor(img_path).video_feed()
| self.process() | conditional_block |
image_processor_2.0.py | #!/usr/bin/python
#Team3238 Cyborg Ferrets 2014 Object Detection Code
#Start with
#python image_processor.py 'path/to/image.jpg'
#don't pass an image argument to use the VideoCapture(0) stream.
# Video capture mode updates the frame to process every video_pause milliseconds, so adjust that.
#set enable_dashboard = True to send range and bearing over smart dashboard network_tables interface.
#set show_windows = False for on-robot, no monitor processing on pandaboard.
#This code is a merge of vision_lib.py, bearing_formula.py, distance_formula.py and team341 java vision detection code from (2012?) competition.
#java -jar SmartDashboard ip 127.0.0.1, for example, will start the dashboard if running on this same host.
#Now tuned for green leds.
#expected camera settings (sorry no numbers on camera interface.)
# exposure -> far right
# gain -> far left
# brightness ~ 20% from left
# contrast ~ 20% from left
# color intensity ~ 18% from left
enable_dashboard = True
show_windows = False
window_scale = 0.5
window_size = (int(640*window_scale), int(480*window_scale))
from cv2 import *
import numpy as np
import sys
import math
import commands
if enable_dashboard:
from pynetworktables import *
if enable_dashboard:
SmartDashboard.init()
#pretend the robot is on the network reporting its heading to the SmartDashboard,
# then let the SmartDashboard user modify it and send it back to this code to simulate movement.
camera_exposure_title = 'Camera Exposure:'
class ImageProcessor:
#all these values could be put into the SmartDashboard for live tuning as conditions change.
default_shape = (480,640,3)
h = np.zeros(default_shape, dtype=np.uint8)
s = np.zeros(default_shape, dtype=np.uint8)
v = np.zeros(default_shape, dtype=np.uint8)
combined = np.zeros(default_shape, dtype=np.uint8)
img = np.zeros(default_shape, dtype=np.uint8)
h_title = "hue"
s_title = "sat"
v_title = "val"
combined_title = "Combined + Morphed"
targets_title = "Targets"
#for video capture mode, what approx frame rate do we want? frame rate = approx video_pause + processing time
video_pause = 1 #0 milliseconds means wait for key press, waitKey takes an integer so 1 millisecond is minimal with this approach.
#tuned for the camera settings above and the green leds. (Red didn't work as well and requires changing the threshold function to use OR of inverse and normal threshold, because red is on the top and bottom of the hue scale (wraps around.).)
hue_delta = 15
sat_delta = 25
val_delta = 100
hue_thresh = 80
sat_thresh = 233
val_thresh = 212
max_thresh = 255
#used for the morphologyEx method that fills in the pixels in the combined image prior to identifying polygons and contours.
kernel = getStructuringElement(MORPH_RECT, (2,2), anchor=(1,1))
morph_close_iterations = 9
#colors in BGR format for drawing the targets over the image.
selected_target_color = (0,0,255)
passed_up_target_color = (255,0,0)
possible_target_color = (0,255,0)
#used to judge whether a polygon side is near vertical or near horizontal, for filtering out shapes that don't match expected target characteristics
vert_threshold = math.tan(math.radians(90-20))
horiz_threshold = math.tan(math.radians(20))
#used to look for only horizontal or vertical rectangles of an aspect ratio that matches the targets.
#currently open wide to find both horizontal and vertical targets
max_target_aspect_ratio = 10 # 1.0 # top target is expected to be 24.5 in x 4 in.
min_target_aspect_ratio = 0.1 #0.01# 3# 0.5
angle_to_robot = 0 #camera's 0 bearing to robot's 0 bearing
camera_offset_position = 0
morph_close_iterations = 9
angle_to_shooter = 0 #camera's 0 bearing to shooter's 0 bearing
camera_color_intensity = 0 #value subject to change
camera_saturation = 0 #value subject to change
camera_contrast = 0 #value subject to change
camera_color_hue = 0 #value subject to change
camera_brightness = 20 #value subject to change
camera_gain = 0 #value subject to change
camera_exposure = 20
robot_heading = 0.0 #input from SmartDashboard if enabled, else hard coded here.
x_resolution = 640 #needs to match the camera.
y_resolution = 480
#theta = math.radians(49.165) #half of field of view of the camera
# field_of_view_degrees = 53.0 horizontal field of view
field_of_view_degrees = 26.4382 # vertical field of view
theta = math.radians(field_of_view_degrees/2.0) #half of field of view of the camera, in radians to work with math.tan function.
# real_target_width = 24.5 #inches #24 * 0.0254 #1 inch / 0.254 meters target is 24 inches wide
real_target_height = 28.5 #using these constants and may not be correct for current robot configuration.
angle_to_shooter = 0
#not currently using these constants and may not be correct for current robot configuration.
# target_min_width = 20
# target_max_width = 200
# degrees_horiz_field_of_view = 47.0
# degrees_vert_field_of_view = 480.0/640*degrees_horiz_field_of_view
# inches_camera_height = 54.0
# inches_top_target_height = 98 + 2 + 98
# degrees_camera_pitch = 21.0
# degrees_sighting_offset = -1.55
def __init__(self, img_path):
self.img_path = img_path
self.layout_result_windows(self.h,self.s,self.v)
self.vc = VideoCapture(0)
SmartDashboard.PutNumber(angle_to_robot_title, self.angle_to_robot)
SmartDashboard.PutNumber(camera_offset_position_title, self.camera_offset_position)
SmartDashboard.PutNumber(morph_close_iterations_title, self.morph_close_iterations)
SmartDashboard.PutNumber(angle_to_shooter_title, self.angle_to_shooter)
SmartDashboard.PutNumber(camera_color_intensity_title, self.camera_color_intensity)
SmartDashboard.PutNumber(camera_exposure_title, self.camera_exposure)
SmartDashboard.PutNumber(camera_saturation.title, self.saturation)
SmartDashboard.PutNumber(camera_contrast_title, self.contrast)
SmartDashboard.PutNumber(camera_color_hue_title, self.camera_color_hue)
SmartDashboard.PutNumber(camera_brihtness_title, self.camera_brightness)
def video_feed(self):
while True:
if self.img is not None:
self.process()
if self.img_path is None:
rval, self.img = self.vc.read() #might set to None
else:
self.img = imread(self.img_path)
def process(self):
if enable_dashboard:
self.camera_saturation = int(SmartDashboard.GetNumber(camera_saturation_title)
self.angle_to_robot = int(SmartDashboard.GetNumber(angle_to_robot_title)
self.camera_offset_postion = int(SmartDashboard.GetNumber(camera_offset_position_title)
self.morph_close_iterations = int(SmartDashboard.GetNumber(morph_close_iterations_title)
self.angle_to_shooter = int(SmartDashboard.GetNumber(angle_to_shooter_title)
self.camera_color_intensity = int(SmartDashboard.GetNumber(camera_color_intensity_title)
self.camera_contrast = int(SmartDashboard.GetNumber(camera_contrast_title)
self.camera_color_hue = int(SmartDashboard.GetNumber(camera_color_hue_title)
self.camera_brightness = int(SmartDashboard.GetNumber(camera_brightness_title)
self.camera_exposure = int(SmartDashboard.GetNumber(camera_exposure_title)
self.camera_gain = int(SmartDashboard.GetNumber(camera_gain_title)
if self.img_path is None:
commands.getoutput(" yavta --set-control '0x009a0901 1' /dev/video0")
#print(commands.getoutput(" yavta --get-control '0x009a0901' /dev/video0") )
commands.getoutput("yavta --set-control '0x009a0902 %s' /dev/video0" % self.camera_exposure)
#print(commands.getoutput(" yavta --get-control '0x009a0902' /dev/video0"))
drawing = np.zeros(self.img.shape, dtype=np.uint8)
self.hsv = cvtColor(self.img, cv.CV_BGR2HSV)
self.h, self.s, self.v = split(self.hsv)
self.h_clipped = self.threshold_in_range(self.h, self.hue_thresh-self.hue_delta, self.hue_thresh+self.hue_delta)
self.s_clipped = self.threshold_in_range(self.s, self.sat_thresh-self.sat_delta, self.sat_thresh+self.sat_delta)
self.v_clipped = self.threshold_in_range(self.v, self.val_thresh-self.val_delta, self.val_thresh+self.val_delta)
if show_windows:
h_scaled = resize(self.h_clipped, window_size)
s_scaled = resize(self.s_clipped, window_size)
v_scaled = resize(self.v_clipped, window_size)
imshow(self.h_title, h_scaled)
imshow(self.s_title, s_scaled)
imshow(self.v_title, v_scaled)
self.find_targets()
if waitKey(self.video_pause) == ord('q'):
exit(1)
def layout_result_windows(self, h, s, v):
if show_windows:
pos_x, pos_y = 500,500
# imshow(self.img_path, self.img)
h_scaled = resize(h, window_size)
s_scaled = resize(s, window_size)
v_scaled = resize(v, window_size)
combined_scaled = resize(self.combined, window_size)
img_scaled = resize(self.img, window_size)
imshow(self.h_title , h_scaled)
imshow(self.s_title , s_scaled)
imshow(self.v_title , v_scaled)
imshow(self.combined_title, combined_scaled)
imshow(self.targets_title , img_scaled)
#moveWindow(self.h_title, pos_x*1, pos_y*0);
#moveWindow(self.s_title, pos_x*0, pos_y*1);
#moveWindow(self.v_title, pos_x*1, pos_y*1);
#moveWindow(self.combined_title, pos_x*2, pos_y*0);
#moveWindow(self.targets_title, pos_x*2, pos_y*1);
#these seem to be placed alphabetically....
# createTrackbar( "Hue High Threshold:", self.source_title, self.hue_high_thresh, self.max_thresh, self.update_hue_high_threshold);
# createTrackbar( "Hue Low Threshold:", self.source_title, self.hue_low_thresh, self.max_thresh, self.update_hue_low_threshold);
# createTrackbar( "Sat High Threshold:", self.source_title, self.sat_high_thresh, self.max_thresh, self.update_sat_high_threshold);
# createTrackbar( "Sat Low Threshold:", self.source_title, self.sat_low_thresh, self.max_thresh, self.update_sat_low_threshold);
# createTrackbar( "Val High Threshold:", self.source_title, self.val_high_thresh, self.max_thresh, self.update_val_high_threshold);
# createTrackbar( "Val Low Threshold:", self.source_title, self.val_low_thresh, self.max_thresh, self.update_val_low_threshold);
def update_hue_threshold(self, thresh):
delta = 15
self.h_clipped = self.threshold_in_range(self.h, thresh-delta, thresh+delta)
imshow(self.h_title, self.h_clipped)
self.find_targets()
def update_sat_threshold(self, thresh):
delta = 25
self.s_clipped = self.threshold_in_range(self.s, thresh-delta, thresh+delta)
imshow(self.s_title, self.s_clipped)
self.find_targets()
def update_val_threshold(self, thresh):
delta = 100
self.v_clipped = self.threshold_in_range(self.v, thresh-delta, thresh+delta)
imshow(self.v_title, self.v_clipped)
self.find_targets()
def threshold_in_range(self, img, low, high):
unused, above = threshold(img, low, self.max_thresh, THRESH_BINARY)
unused, below = threshold(img, high, self.max_thresh, THRESH_BINARY_INV)
return bitwise_and(above, below)
def find_targets(self):
#combine all the masks together to get their overlapping regions.
if True:
self.reset_targeting()
self.combined = bitwise_and(self.h_clipped, bitwise_and(self.s_clipped, self.v_clipped))
#comment above line and uncomment next line to ignore hue channel til we sort out red light hue matching around zero.
#self.combined = bitwise_and(self.s_clipped, self.v_clipped)
self.combined = morphologyEx(src=self.combined, op=MORPH_CLOSE, kernel=self.kernel, iterations=self.morph_close_iterations)
if show_windows:
combined_scaled = resize(self.combined, window_size)
imshow(self.combined_title, combined_scaled )
self.contoured = self.combined.copy()
contours, heirarchy = findContours(self.contoured, RETR_LIST, CHAIN_APPROX_TC89_KCOS)
#print("number of contours found = "+str(len(contours)))
#contours = [convexHull(c.astype(np.float32),clockwise=True,returnPoints=True) for c in contours]
#
polygon_tuples = self.contours_to_polygon_tuples(contours)
polygons = [self.unpack_polygon(t) for t in polygon_tuples]
for polygon_tuple in polygon_tuples:
self.mark_correct_shape_and_orientation(polygon_tuple)
if self.selected_target is not None:
self.draw_target(self.lowest_found_so_far_x, self.lowest_found_so_far, self.selected_target_color)
drawContours(self.drawing, contours, -1, self.selected_target_color, thickness=10)
# drawContours(self.drawing, [self.unpack_polygon(self.selected_target).astype(np.int32)], -1, self.selected_target_color, thickness=10)
self.aim()
if show_windows:
drawing_scaled = resize(self.drawing, window_size)
imshow(self.targets_title, drawing_scaled)
if enable_dashboard:
SmartDashboard.PutNumber("Potential Targets:", len(polygons))
print("Potential Targets:", len(polygons))
def aim(self):
if enable_dashboard:
self.robot_heading = SmartDashboard.GetNumber(robot_heading_title)
polygon, x, y, w, h = self.selected_target
self.target_bearing = self.get_bearing(x + w/2.0)
self.target_range = self.get_range(x, y, w, h) | #self.target_elevation = self.get_elevation(x, y, w, h)
print("Range = " + str(self.target_range))
print("Bearing = " + str(self.target_bearing))
if enable_dashboard:
SmartDashboard.PutNumber("Target Range:", self.target_range)
SmartDashboard.PutNumber("Target Bearing:", self.target_bearing)
SmartDashboard.PutNumber("Target Elevation:",self.target_elevation)
SmartDashboard.PutString("Target: ","Acquired!")
def get_bearing(self, target_center_x):
return (self.field_of_view_degrees/self.x_resolution)*(target_center_x-(self.x_resolution/2))-self.angle_to_shooter
def get_range(self, x, y, w, h):
if enable_dashboard:
SmartDashboard.PutNumber("TargetWidth: ",w)
SmartDashboard.PutNumber("TargetHeight",h)
SmartDashboard.PutNumber("TargetX",x)
SmartDashboard.PutNumber("TargetY",y)
return self.distance(h)
def distance(self, pix_height):
fovr = self.x_resolution * self.real_target_height / pix_height
if enable_dashboard:
SmartDashboard.PutNumber("FieldOfViewReal", fovr) # = 2w_real
SmartDashboard.PutNumber("TanTheta", math.tan(self.theta))
SmartDashboard.PutNumber("fovr/tan(theta)", fovr/math.tan(self.theta))
return self.real_target_height*self.y_resolution/(2*pix_height*math.tan(self.theta))
def reset_targeting(self):
if enable_dashboard:
SmartDashboard.PutString("Target: ","lost...")
self.drawing = self.img.copy()
self.selected_target = None
self.lowest_found_so_far_x = None
self.lowest_found_so_far = 0
self.target_range = 0
self.target_bearing = -1
self.target_elevation = 0
def mark_correct_shape_and_orientation(self, polygon_tuple):
p,x,y,w,h = polygon_tuple
if True: #isContourConvex(p) and 4==len(p) and self.slope_angles_correct(p):
center_x = int(x + w/2.0)
center_y = int(y + h/2.0)
self.draw_target(center_x, center_y, self.possible_target_color)
if center_y > self.lowest_found_so_far:
self.selected_target = polygon_tuple
self.lowest_found_so_far = center_y
self.lowest_found_so_far_x = center_x
else:
drawContours(self.drawing, [p.astype(np.int32)], -1, self.passed_up_target_color, thickness=7)
def draw_target(self, center_x, center_y, a_color):
#circle(self.drawing,(center_x, center_y), radius=10, color=self.selected_target_color, thickness=5)
radius = 10
a_thickness = 5
line(self.drawing, (center_x - radius, center_y), (center_x + radius, center_y), color=a_color, thickness=a_thickness)
line(self.drawing, (center_x, center_y-radius), (center_x, center_y+radius), color=a_color, thickness=a_thickness)
def slope_angles_correct(self, polygon):
num_near_vert, num_near_horiz = 0,0
for line_starting_point_index in xrange(0,4):
slope = self.get_slope(polygon, line_starting_point_index)
if slope < self.horiz_threshold:
num_near_horiz += 1
if slope > self.vert_threshold:
num_near_vert += 1
return 1 <= num_near_horiz and 2 == num_near_vert
def get_slope(self, p, line_starting_point_index):
line_ending_point_index = (line_starting_point_index+1)%4
dy = p[line_starting_point_index, 0, 1] - p[line_ending_point_index, 0, 1]
dx = p[line_starting_point_index, 0, 0] - p[line_ending_point_index, 0, 0]
slope = sys.float_info.max
if 0 != dx:
slope = abs(float(dy)/dx)
return slope
def unpack_polygon(self,t):
p,x,y,w,h = t
return p
def contours_to_polygon_tuples(self, contours):
polygon_tuples = []
for c in contours:
x, y, w, h = boundingRect(c)
if self.aspect_ratio_and_size_correct(w,h):
p = approxPolyDP(c, 20, False)
polygon_tuples.append((p,x,y,w,h))
return polygon_tuples
def aspect_ratio_and_size_correct(self, width, height):
ratio = float(width)/height #float(height)/width
return ratio < self.max_target_aspect_ratio and ratio > self.min_target_aspect_ratio #and width > self.target_min_width and width < self.target_max_width
#note: we don't want to ignore potential targets based on pixel width and height since range will change the pixel coverage of a real target.
if '__main__'==__name__:
try:
img_path = sys.argv[1]
except:
img_path= None
# print('Please add an image path argument and try again.')
# sys.exit(2)
ImageProcessor(img_path).video_feed() | random_line_split | |
App.js | // Copyright (c) 2019 Chris DeMartini
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// 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 Software.
//
// THE SOFTWARE IS 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 SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/* eslint-disable complexity */
import React, {Component} from 'react';
import {connect} from 'react-redux';
import throttle from 'lodash.throttle';
import debounce from 'lodash.debounce';
import './App.css';
// actions
import {markerSelect} from './actions';
// Custom config components
import SplashScreen from './components/SplashScreen';
import {
PickSheets,
CustomizeViolin,
Stepper,
StepButtons
} from './components/Configuration';
// Viz components
import KeplerGlComponent from './components/KeplerGL/index';
import {withStyles} from '@material-ui/core/styles';
// Tableau Styles and Tableau
// import './assets/tableau/vendor/slick.js/slick/slick.css';
// import './assets/tableau/css/style.min.css';
import {tableau} from './tableau-extensions-1.latest';
// tableau settings handler
import * as TableauSettings from './TableauSettings';
// initial default settings
import defaultSettings from './components/Configuration/defaultSettings';
// utils and variables
import {
columnToKeplerField,
dataToKeplerRow,
dataTableToKepler,
log
} from './utils';
import {
selectMarksByField,
applyFilterByField,
clearMarksByField,
clearFilterByField
} from './utils/interaction-utils';
//logos
import dbLogo from './assets/dblogo.png';
import ssLogo from './assets/sslogo.jpg';
import kepLogo from './assets/kepler.gl-logo_2x.png';
const MAPBOX_ACCESS_TOKEN =
'pk.eyJ1IjoidWJlcmRhdGEiLCJhIjoiY2p2OGVvejQwMDJxZzRma2dvdWQ2OTQwcSJ9.VbuIamTa_JayuD2yr5tjaA';
// begin constants to move to another file later
// material ui styles
const KEPLER_GL_VERSION = '__PACKAGE_VERSION__';
const styles = theme => ({
root: {
display: 'flex'
},
button: {
margin: theme.spacing.unit
},
leftIcon: {
marginRight: theme.spacing.unit
},
rightIcon: {
marginLeft: theme.spacing.unit
},
iconSmall: {
fontSize: 20
}
});
const tableauExt = window.tableau.extensions;
//tableau get summary data options
const options = {
ignoreAliases: false,
ignoreSelection: true,
maxRows: 0
};
function findColumnIndexByFieldName(state, fieldName) {
return (state.ConfigSheetColumns || []).findIndex(
f => f.fieldName === fieldName
);
}
// end constants to move to another file later
class App extends Component {
constructor(props) {
super(props);
this.state = {
isConfig: this.props.isConfig || false,
isLoading: true,
isSplash: true,
configuration: false,
height: 300,
width: 300,
dashboardName: '',
sheetNames: [],
tableauSettings: {},
demoType: 'Violin',
stepIndex: 1,
isMissingData: true,
highlightOn: undefined,
unregisterHandlerFunctions: [],
filterKeplerObject: [],
theme: 'light'
};
TableauSettings.setEnvName(this.props.isConfig ? 'CONFIG' : 'EXTENSION');
this.unregisterHandlerFunctions = [];
this.applyingMouseActions = false;
this.clickCallBack = throttle(this.clickCallBack, 200);
this.hoverCallBack = throttle(this.hoverCallBack, 200);
this.configCallBack = debounce(this.configCallBack, 500);
}
// eslint-disable-next-line react/sort-comp
addEventListeners = () => {
// Whenever we restore the filters table, remove all save handling functions,
// since we add them back later in this function.
// provided by tableau extension samples
log('%c addEventListeners', 'background: purple; color:yellow');
this.removeEventListeners();
const localUnregisterHandlerFunctions = [];
// add filter change event listener with callback to re-query data after change
// go through each worksheet and then add a filter change event listener
// need to check whether this is being applied more than once
tableauExt.dashboardContent.dashboard.worksheets.map(worksheet => {
// add event listener
const unregisterFilterHandlerFunction = worksheet.addEventListener(
window.tableau.TableauEventType.FilterChanged,
this.filterChanged
);
// provided by tableau extension samples, may need to push this to state for react
localUnregisterHandlerFunctions.push(unregisterFilterHandlerFunction);
const unregisterMarkerHandlerFunction = worksheet.addEventListener(
window.tableau.TableauEventType.MarkSelectionChanged,
this.marksSelected
);
// provided by tableau extension samples, may need to push this to state for react
localUnregisterHandlerFunctions.push(unregisterMarkerHandlerFunction);
});
this.unregisterHandlerFunctions = localUnregisterHandlerFunctions;
// log(`%c added ${this.unregisterHandlerFunctions.length} EventListeners`, 'background: purple, color:yellow');
};
removeEventListeners = () => {
log(
`%c remove ${this.unregisterHandlerFunctions.length} EventListeners`,
'background: green; color:black'
);
this.unregisterHandlerFunctions.forEach(unregisterHandlerFunction => {
unregisterHandlerFunction();
});
this.unregisterHandlerFunctions = [];
};
onNextStep = () => {
if (this.state.stepIndex === 2) {
this.customCallBack('configuration');
} else {
this.setState((previousState, currentProps) => {
return {stepIndex: previousState.stepIndex + 1};
});
}
};
onPrevStep = () => {
this.setState((previousState, currentProps) => {
return {stepIndex: previousState.stepIndex - 1};
});
};
clickCallBack = d => {
const {clickField, clickAction} = this.state.tableauSettings;
log(
'%c in on click callback',
'background: brown'
// d,
// findColumnIndexByFieldName(this.state, clickField),
// clickAction
);
this.applyMouseActionsToSheets(d, clickAction, clickField);
};
hoverCallBack = d => {
const {hoverField, hoverAction} = this.state.tableauSettings;
log(
'%c in on hover callback',
'background: OLIVE'
// d,
// findColumnIndexByFieldName(this.state, hoverField),
// hoverAction
);
this.applyMouseActionsToSheets(d, hoverAction, hoverField);
// go through each worksheet and select marks
};
applyMouseActionsToSheets = (d, action, fieldName) => {
if (this.applyingMouseActions) {
return;
}
const {ConfigSheet} = this.state.tableauSettings;
const toHighlight =
action === 'Highlight' && (fieldName || 'None') !== 'None';
const toFilter = action === 'Filter' && (fieldName || 'None') !== 'None';
// if no action should be taken
if (!toHighlight && !toFilter) {
return;
}
// remove EventListeners before apply any async actions
this.removeEventListeners();
this.applyingMouseActions = true;
let tasks = [];
if (d) {
// select marks or filter
const fieldIdx = findColumnIndexByFieldName(this.state, fieldName);
const fieldValues =
typeof d[0] === 'object'
? d.map(childD => childD[fieldIdx])
: [d[fieldIdx]];
const actionToApply = toHighlight
? selectMarksByField
: applyFilterByField;
tasks = actionToApply(fieldName, fieldValues, ConfigSheet);
} else {
// clear marks or filer
const actionToApply = toHighlight
? clearMarksByField
: clearFilterByField;
tasks = actionToApply(fieldName, ConfigSheet);
}
Promise.all(tasks).then(() => {
// all selection should be completed
// Add event listeners back
this.addEventListeners();
this.applyingMouseActions = false;
});
};
demoChange = event => {
this.setState({demoType: event.target.value});
log('in demo change', event.target.value, this.state.demoType);
};
handleChange = event => {
log('event', event);
if (TableauSettings.ShouldUse) {
// create a single k/v pair
const kv = {};
kv[event.target.name] = event.target.value;
// update the settings
log(
'%c handleChange=======TableauSettings.updateAndSave',
'background: red; color: white'
);
TableauSettings.updateAndSave(kv, settings => {
this.setState({
tableauSettings: settings
});
});
} else {
tableauExt.settings.set(event.target.name, event.target.value);
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll()
});
});
}
};
configCallBack = (field, columnName) => {
if (TableauSettings.ShouldUse) {
log(
'%c configCallBack=======TableauSettings.updateAndSave',
'background: red; color: white'
);
TableauSettings.updateAndSave(
{
// ['is' + field]: true,
[field]: columnName
},
settings => {
this.setState({
// ['is' + field]: true,
tableauSettings: settings
});
}
);
} else {
tableauExt.settings.set(field, columnName);
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll()
});
});
}
};
eraseCallBack = field => {
log('triggered erase', field);
if (TableauSettings.ShouldUse) {
log(
'%c eraseCallBack=======TableauSettings.eraseAndSave',
'background: red; color: white'
);
TableauSettings.eraseAndSave([field], settings => {
this.setState({
tableauSettings: settings
});
});
} else {
// erase all the settings, there has got be a better way.
tableauExt.settings.erase(field);
// save async the erased settings
// wip - should be able to get rid of state as this is all captured in tableu settings (written to state)
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll()
});
});
}
};
customCallBack = confSetting => {
log('in custom call back', confSetting);
if (TableauSettings.ShouldUse) {
log(
'%c customCallBack=======TableauSettings.updateAndSave',
'background: red; color: white'
);
TableauSettings.updateAndSave(
{
[confSetting]: true
},
settings => {
this.setState({
[confSetting]: true,
tableauSettings: settings
});
if (confSetting === 'configuration') {
tableauExt.ui.closeDialog('false');
}
}
);
} else {
tableauExt.settings.set(confSetting, true);
tableauExt.settings.saveAsync().then(() => {
this.setState({
[confSetting]: true,
tableauSettings: tableauExt.settings.getAll()
});
if (confSetting === 'configuration') {
tableauExt.ui.closeDialog('false');
}
});
}
};
// needs to be updated to handle if more than one data set is selected
// find all sheets in array and then call get summary, for now hardcoding
filterChanged = e => {
const selectedSheet = tableauExt.settings.get('ConfigSheet');
if (selectedSheet && selectedSheet === e.worksheet.name) {
log(
'%c ==============App filter has changed',
'background: red; color: white'
);
this.getConfigSheetSummaryData(selectedSheet);
}
};
marksSelected = e => {
if (this.state.tableauSettings.keplerFilterField) {
if (this.applyingMouseActions) {
return;
}
log(
'%c ==============App Marker selected',
'background: red; color: white'
);
// remove event listeners
this.removeEventListeners();
// get selected marks and pass to kepler via state object
e.getMarksAsync().then(marks => {
const {keplerFilterField} = this.state.tableauSettings;
// loop through marks table and adjust the class for opacity
const marksDataTable = marks.data[0];
const col_indexes = {};
const keplerFields = [];
// write column names to array
for (let k = 0; k < marksDataTable.columns.length; k++) {
col_indexes[marksDataTable.columns[k].fieldName] = k;
keplerFields.push(columnToKeplerField(marksDataTable.columns[k], k));
}
const keplerData = dataToKeplerRow(marksDataTable.data, keplerFields);
const filterKeplerObject = {
field: keplerFilterField,
values: keplerData.map(
childD => childD[col_indexes[keplerFilterField]]
)
};
// @shan you can remove this console once you are good with the object
this.props.dispatch(markerSelect(filterKeplerObject));
this.setState({filterKeplerObject}, () => this.addEventListeners());
});
}
};
getConfigSheetSummaryData = selectedSheet => {
// get sheet information this.state.selectedSheet should be syncronized with settings
// can possibly remove the || in the sheetName part
const sheetName = selectedSheet;
const sheetObject = tableauExt.dashboardContent.dashboard.worksheets.find(
worksheet => worksheet.name === sheetName
);
if (!sheetObject) {
return;
}
// clean up event listeners (taken from tableau example)
this.removeEventListeners();
if (TableauSettings.ShouldUse) {
this.setState({
isLoading: true
});
} else {
this.setState({isLoading: true});
tableauExt.settings.set('isLoading', true);
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll()
});
});
}
//working here on pulling out summmary data
//may want to limit to a single row when getting column names
sheetObject.getSummaryDataAsync(options).then(t => {
log('in getData().getSummaryDataAsync', t, this.state);
const newDataState = dataTableToKepler(t);
if (TableauSettings.ShouldUse) {
this.setState({
...newDataState,
selectedSheet: sheetName,
isLoading: false,
isMissingData: false
});
} else {
log(
'%c getConfigSheetSummaryData TableauSettings.ShouldUse false',
'color: purple'
);
this.setState({isLoading: false});
tableauExt.settings.set('isLoading', false);
tableauExt.settings.saveAsync().then(() => {
this.setState({
...newDataState,
isLoading: false,
tableauSettings: tableauExt.settings.getAll()
});
});
}
this.addEventListeners();
});
};
clearSheet() {
log('triggered erase');
if (TableauSettings.ShouldUse) {
TableauSettings.eraseAndSave(['isLoading', 'configuration'], settings => {
this.setState({
tableauSettings: settings,
configuration: false,
isSplash: true
});
});
} else {
// erase all the settings, there has got be a better way.
tableauExt.settings.erase('isLoading');
tableauExt.settings.erase('configuration');
// save async the erased settings
// wip - should be able to get rid of state as this is all captured in tableu settings (written to state)
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll(),
configuration: false,
isSplash: true
});
});
}
}
clearSplash = () => {
this.setState({
isSplash: false
});
};
configure = () => {
this.clearSheet();
const popUpUrl = window.location.href + '#true';
const popUpOptions = {
height: 625,
width: 720
};
tableauExt.ui
.displayDialogAsync(popUpUrl, '', popUpOptions)
.then(closePayload => {
log('configuring', closePayload, tableauExt.settings.getAll());
if (closePayload === 'false') {
this.setState({
isSplash: false,
isConfig: false,
tableauSettings: tableauExt.settings.getAll()
});
}
})
.catch(error => {
// One expected error condition is when the popup is closed by the user (meaning the user
// clicks the 'X' in the top right of the dialog). This can be checked for like so:
switch (error.errorCode) {
case window.tableau.ErrorCodes.DialogClosedByUser:
log('closed by user');
break;
default:
console.error(error.message);
}
});
};
componentWillUnmount() {
window.removeEventListener('resize', this.resize, true);
}
resize = () => {
this.setState({
width: window.innerWidth,
height: window.innerHeight
});
};
componentDidMount() {
window.addEventListener('resize', this.resize, true);
this.resize();
tableauExt.initializeAsync({configure: this.configure}).then(() => {
// console.log('tableau config', configJson);
// default tableau settings on initial entry into the extension
// we know if we haven't done anything yet when tableauSettings state = []
log('did mount', tableauExt.settings.get('mapboxAPIKey'));
if (tableauExt.settings.get('mapboxAPIKey') === '') {
log(
'defaultSettings triggered',
defaultSettings.length,
defaultSettings
);
defaultSettings.defaultKeys.map((defaultSetting, index) => {
log(
'defaultSetting',
index,
defaultSetting,
defaultSettings.defaults[defaultSetting]
);
this.configCallBack(
defaultSetting,
defaultSettings.defaults[defaultSetting]
);
});
}
// this is where the majority of the code is going to go for this extension I think
log('will mount', tableauExt.settings.getAll());
//get sheetNames and dashboard name from workbook
const dashboardName = tableauExt.dashboardContent.dashboard.name;
const sheetNames = tableauExt.dashboardContent.dashboard.worksheets.map(
worksheet => worksheet.name
);
log('checking field in getAll()', tableauExt.settings.getAll());
// add event listeners (this includes an initial removal)
this.addEventListeners();
// Initialize the current saved settings global
TableauSettings.init();
// default to uber's Kepler key that they requested if user does not enter
this.setState({
tableauKey: MAPBOX_ACCESS_TOKEN,
isLoading: false,
height: window.innerHeight,
width: window.innerWidth,
sheetNames,
dashboardName,
demoType: tableauExt.settings.get('ConfigType') || 'violin',
tableauSettings: tableauExt.settings.getAll()
});
if (
this.state.tableauSettings.configuration &&
this.state.tableauSettings.configuration === 'true'
) {
this.setState({
isSplash: false,
isConfig: false
});
}
});
}
componentWillUpdate(nextProps, nextState) {
if (tableauExt.settings) {
// get selectedSheet from Settings
// hardcoding this for now because I know i have two possibilities
const selectedSheet = tableauExt.settings.get('ConfigSheet');
if (
selectedSheet &&
this.state.tableauSettings.ConfigSheet !==
nextState.tableauSettings.ConfigSheet
) {
this.getConfigSheetSummaryData(selectedSheet);
}
}
}
render() {
// short cut this cause we use it ALOT
const tableauSettingsState = this.state.tableauSettings;
// loading screen jsx
let isLoading = false;
if (
!this.state.isSplash &&
!this.state.isConfig &&
(this.state.isLoading || this.state.isMissingData)
) {
isLoading = true;
}
// config screen jsx
if (this.state.isConfig) {
const stepNames = ['Select Sheet', 'Customize Kepler.gl'];
if (this.state.stepIndex === 1) {
// Placeholder sheet names. TODO: Bind to worksheet data
return (
<React.Fragment>
<Stepper stepIndex={this.state.stepIndex} steps={stepNames} />
<PickSheets
sheetNames={this.state.sheetNames}
configCallBack={this.configCallBack}
field={'ConfigSheet'}
ConfigSheet={tableauSettingsState.ConfigSheet || ''}
/>
<StepButtons
onNextClick={this.onNextStep}
onPrevClick={this.onPrevStep}
stepIndex={this.state.stepIndex}
maxStepCount={stepNames.length}
nextText={
this.state.stepIndex !== stepNames.length ? 'Next' : 'Save'
}
backText="Back"
/>
</React.Fragment>
);
}
if (this.state.stepIndex === 2) {
return (
<React.Fragment>
<Stepper stepIndex={this.state.stepIndex} steps={stepNames} />
<CustomizeViolin
handleChange={this.handleChange}
customCallBack={this.customCallBack}
field={'configuration'}
tableauSettings={tableauSettingsState}
configSheetColumns={this.state.ConfigSheetStringColumns || []}
/>
<StepButtons
onNextClick={this.onNextStep}
onPrevClick={this.onPrevStep}
stepIndex={this.state.stepIndex}
maxStepCount={stepNames.length}
nextText={
this.state.stepIndex !== stepNames.length ? 'Next' : 'Save'
}
backText="Back"
/>
</React.Fragment>
);
}
}
// splash screen jsx
if (this.state.isSplash) |
const readOnly = tableauSettingsState.readOnly === 'true';
log(`readOnly============== ${readOnly}`);
return (
<KeplerGlComponent
className={'tableau-kepler-gl'}
width={this.state.width}
height={this.state.height}
data={this.state.ConfigSheetData}
selectedSheet={this.state.selectedSheet}
tableauSettings={tableauSettingsState}
theme={tableauSettingsState.theme}
readOnly={readOnly}
keplerConfig={tableauSettingsState.keplerConfig}
mapboxAPIKey={
tableauSettingsState.mapboxAPIKey
? tableauSettingsState.mapboxAPIKey
: this.state.tableauKey
}
isLoading={isLoading}
// persist state to tableau
configCallBack={readOnly ? null : this.configCallBack}
// interactivity
clickCallBack={this.clickCallBack}
hoverCallBack={this.hoverCallBack}
dispatch={this.props.dispatch}
/>
);
}
}
App.propTypes = {};
const mapStateToProps = state => state;
const dispatchToProps = dispatch => ({dispatch});
const ConnectedApp = connect(mapStateToProps, dispatchToProps)(App);
export default withStyles(styles)(ConnectedApp);
| {
log(`%c this.state.isSplash=true}`, 'color: purple');
return (
<div className="splashScreen" style={{padding: 5}}>
<SplashScreen
configure={this.configure}
title="Kepler.gl within Tableau"
desc="Leverage the brilliance of Kepler.gl functionality, directly within Tableau!"
ctaText="Configure"
poweredBy={
<React.Fragment>
<p className="info">
For information on how to use this extension check out the{' '}
<a
href="https://github.com/uber/kepler.gl-tableau/tree/feat/docs/docs"
target="_blank"
rel="noopener noreferrer"
>
user guide
</a>
<br /> Tableau Requirements: Tableau Desktop (Mac Only) 2018.3
or >= 2019.1.2 or Tableau Server >= 2018.3
</p>
<p className="info">Brought to you by: </p>
<a
href="http://www.datablick.com/"
target="_blank"
rel="noopener noreferrer"
>
<img src={dbLogo} />
</a>{' '}
<a
href="https://starschema.com/"
target="_blank"
rel="noopener noreferrer"
>
<img src={ssLogo} />
</a>
<p className="info">Powered by: </p>
<a
href="https://github.com/uber/kepler.gl"
target="_blank"
rel="noopener noreferrer"
>
<img src={kepLogo} />
</a>
<p className="info">Version: {KEPLER_GL_VERSION}</p>
</React.Fragment>
}
/>
</div>
);
} | conditional_block |
App.js | // Copyright (c) 2019 Chris DeMartini
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// 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 Software.
//
// THE SOFTWARE IS 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 SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/* eslint-disable complexity */
import React, {Component} from 'react';
import {connect} from 'react-redux';
import throttle from 'lodash.throttle';
import debounce from 'lodash.debounce';
import './App.css';
// actions
import {markerSelect} from './actions';
// Custom config components
import SplashScreen from './components/SplashScreen';
import {
PickSheets,
CustomizeViolin,
Stepper,
StepButtons
} from './components/Configuration';
// Viz components
import KeplerGlComponent from './components/KeplerGL/index';
import {withStyles} from '@material-ui/core/styles';
// Tableau Styles and Tableau
// import './assets/tableau/vendor/slick.js/slick/slick.css';
// import './assets/tableau/css/style.min.css';
import {tableau} from './tableau-extensions-1.latest';
// tableau settings handler
import * as TableauSettings from './TableauSettings';
// initial default settings
import defaultSettings from './components/Configuration/defaultSettings';
// utils and variables
import {
columnToKeplerField,
dataToKeplerRow,
dataTableToKepler,
log
} from './utils';
import {
selectMarksByField,
applyFilterByField,
clearMarksByField,
clearFilterByField
} from './utils/interaction-utils';
//logos
import dbLogo from './assets/dblogo.png';
import ssLogo from './assets/sslogo.jpg';
import kepLogo from './assets/kepler.gl-logo_2x.png';
const MAPBOX_ACCESS_TOKEN =
'pk.eyJ1IjoidWJlcmRhdGEiLCJhIjoiY2p2OGVvejQwMDJxZzRma2dvdWQ2OTQwcSJ9.VbuIamTa_JayuD2yr5tjaA';
// begin constants to move to another file later
// material ui styles
const KEPLER_GL_VERSION = '__PACKAGE_VERSION__';
const styles = theme => ({
root: {
display: 'flex'
},
button: {
margin: theme.spacing.unit
},
leftIcon: {
marginRight: theme.spacing.unit
},
rightIcon: {
marginLeft: theme.spacing.unit
},
iconSmall: {
fontSize: 20
}
});
const tableauExt = window.tableau.extensions;
//tableau get summary data options
const options = {
ignoreAliases: false,
ignoreSelection: true,
maxRows: 0
};
function findColumnIndexByFieldName(state, fieldName) {
return (state.ConfigSheetColumns || []).findIndex(
f => f.fieldName === fieldName
);
}
// end constants to move to another file later
class App extends Component {
constructor(props) {
super(props);
this.state = {
isConfig: this.props.isConfig || false,
isLoading: true,
isSplash: true,
configuration: false,
height: 300,
width: 300,
dashboardName: '',
sheetNames: [],
tableauSettings: {},
demoType: 'Violin',
stepIndex: 1,
isMissingData: true,
highlightOn: undefined,
unregisterHandlerFunctions: [],
filterKeplerObject: [],
theme: 'light'
};
TableauSettings.setEnvName(this.props.isConfig ? 'CONFIG' : 'EXTENSION');
this.unregisterHandlerFunctions = [];
this.applyingMouseActions = false;
this.clickCallBack = throttle(this.clickCallBack, 200);
this.hoverCallBack = throttle(this.hoverCallBack, 200);
this.configCallBack = debounce(this.configCallBack, 500);
}
// eslint-disable-next-line react/sort-comp
addEventListeners = () => {
// Whenever we restore the filters table, remove all save handling functions,
// since we add them back later in this function.
// provided by tableau extension samples
log('%c addEventListeners', 'background: purple; color:yellow');
this.removeEventListeners();
const localUnregisterHandlerFunctions = [];
// add filter change event listener with callback to re-query data after change
// go through each worksheet and then add a filter change event listener
// need to check whether this is being applied more than once
tableauExt.dashboardContent.dashboard.worksheets.map(worksheet => {
// add event listener
const unregisterFilterHandlerFunction = worksheet.addEventListener(
window.tableau.TableauEventType.FilterChanged,
this.filterChanged
);
// provided by tableau extension samples, may need to push this to state for react
localUnregisterHandlerFunctions.push(unregisterFilterHandlerFunction);
const unregisterMarkerHandlerFunction = worksheet.addEventListener(
window.tableau.TableauEventType.MarkSelectionChanged,
this.marksSelected
);
// provided by tableau extension samples, may need to push this to state for react
localUnregisterHandlerFunctions.push(unregisterMarkerHandlerFunction);
});
this.unregisterHandlerFunctions = localUnregisterHandlerFunctions;
// log(`%c added ${this.unregisterHandlerFunctions.length} EventListeners`, 'background: purple, color:yellow');
};
removeEventListeners = () => {
log(
`%c remove ${this.unregisterHandlerFunctions.length} EventListeners`,
'background: green; color:black'
);
this.unregisterHandlerFunctions.forEach(unregisterHandlerFunction => {
unregisterHandlerFunction();
});
this.unregisterHandlerFunctions = [];
};
onNextStep = () => {
if (this.state.stepIndex === 2) {
this.customCallBack('configuration');
} else {
this.setState((previousState, currentProps) => {
return {stepIndex: previousState.stepIndex + 1};
});
}
};
onPrevStep = () => {
this.setState((previousState, currentProps) => {
return {stepIndex: previousState.stepIndex - 1};
});
};
clickCallBack = d => {
const {clickField, clickAction} = this.state.tableauSettings;
log(
'%c in on click callback',
'background: brown'
// d,
// findColumnIndexByFieldName(this.state, clickField),
// clickAction
);
this.applyMouseActionsToSheets(d, clickAction, clickField);
};
hoverCallBack = d => {
const {hoverField, hoverAction} = this.state.tableauSettings;
log(
'%c in on hover callback',
'background: OLIVE'
// d,
// findColumnIndexByFieldName(this.state, hoverField),
// hoverAction
);
this.applyMouseActionsToSheets(d, hoverAction, hoverField);
// go through each worksheet and select marks
};
applyMouseActionsToSheets = (d, action, fieldName) => {
if (this.applyingMouseActions) {
return;
}
const {ConfigSheet} = this.state.tableauSettings;
const toHighlight =
action === 'Highlight' && (fieldName || 'None') !== 'None';
const toFilter = action === 'Filter' && (fieldName || 'None') !== 'None';
// if no action should be taken
if (!toHighlight && !toFilter) {
return;
}
// remove EventListeners before apply any async actions
this.removeEventListeners();
this.applyingMouseActions = true;
let tasks = [];
if (d) {
// select marks or filter
const fieldIdx = findColumnIndexByFieldName(this.state, fieldName);
const fieldValues =
typeof d[0] === 'object'
? d.map(childD => childD[fieldIdx])
: [d[fieldIdx]];
const actionToApply = toHighlight
? selectMarksByField
: applyFilterByField;
tasks = actionToApply(fieldName, fieldValues, ConfigSheet);
} else {
// clear marks or filer
const actionToApply = toHighlight
? clearMarksByField
: clearFilterByField;
tasks = actionToApply(fieldName, ConfigSheet);
}
Promise.all(tasks).then(() => {
// all selection should be completed
// Add event listeners back
this.addEventListeners();
this.applyingMouseActions = false;
});
};
demoChange = event => {
this.setState({demoType: event.target.value});
log('in demo change', event.target.value, this.state.demoType);
};
handleChange = event => {
log('event', event);
if (TableauSettings.ShouldUse) {
// create a single k/v pair
const kv = {};
kv[event.target.name] = event.target.value;
// update the settings
log(
'%c handleChange=======TableauSettings.updateAndSave',
'background: red; color: white'
);
TableauSettings.updateAndSave(kv, settings => {
this.setState({
tableauSettings: settings
});
});
} else {
tableauExt.settings.set(event.target.name, event.target.value);
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll()
});
});
}
};
configCallBack = (field, columnName) => {
if (TableauSettings.ShouldUse) {
log(
'%c configCallBack=======TableauSettings.updateAndSave',
'background: red; color: white'
);
TableauSettings.updateAndSave(
{
// ['is' + field]: true,
[field]: columnName
},
settings => {
this.setState({
// ['is' + field]: true,
tableauSettings: settings
});
}
);
} else {
tableauExt.settings.set(field, columnName);
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll()
});
});
}
};
eraseCallBack = field => {
log('triggered erase', field);
if (TableauSettings.ShouldUse) {
log(
'%c eraseCallBack=======TableauSettings.eraseAndSave',
'background: red; color: white'
);
TableauSettings.eraseAndSave([field], settings => {
this.setState({
tableauSettings: settings
});
});
} else {
// erase all the settings, there has got be a better way.
tableauExt.settings.erase(field);
// save async the erased settings
// wip - should be able to get rid of state as this is all captured in tableu settings (written to state)
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll()
});
});
}
};
customCallBack = confSetting => {
log('in custom call back', confSetting);
if (TableauSettings.ShouldUse) {
log(
'%c customCallBack=======TableauSettings.updateAndSave',
'background: red; color: white'
);
TableauSettings.updateAndSave(
{
[confSetting]: true
},
settings => {
this.setState({
[confSetting]: true,
tableauSettings: settings
});
if (confSetting === 'configuration') {
tableauExt.ui.closeDialog('false');
}
}
);
} else {
tableauExt.settings.set(confSetting, true);
tableauExt.settings.saveAsync().then(() => {
this.setState({
[confSetting]: true,
tableauSettings: tableauExt.settings.getAll()
});
if (confSetting === 'configuration') {
tableauExt.ui.closeDialog('false');
}
});
}
};
// needs to be updated to handle if more than one data set is selected
// find all sheets in array and then call get summary, for now hardcoding
filterChanged = e => {
const selectedSheet = tableauExt.settings.get('ConfigSheet');
if (selectedSheet && selectedSheet === e.worksheet.name) {
log(
'%c ==============App filter has changed',
'background: red; color: white'
);
this.getConfigSheetSummaryData(selectedSheet);
}
};
marksSelected = e => {
if (this.state.tableauSettings.keplerFilterField) {
if (this.applyingMouseActions) {
return;
}
log(
'%c ==============App Marker selected',
'background: red; color: white'
);
// remove event listeners
this.removeEventListeners();
// get selected marks and pass to kepler via state object
e.getMarksAsync().then(marks => {
const {keplerFilterField} = this.state.tableauSettings;
// loop through marks table and adjust the class for opacity
const marksDataTable = marks.data[0];
const col_indexes = {};
const keplerFields = [];
// write column names to array
for (let k = 0; k < marksDataTable.columns.length; k++) {
col_indexes[marksDataTable.columns[k].fieldName] = k;
keplerFields.push(columnToKeplerField(marksDataTable.columns[k], k));
}
const keplerData = dataToKeplerRow(marksDataTable.data, keplerFields);
const filterKeplerObject = {
field: keplerFilterField,
values: keplerData.map(
childD => childD[col_indexes[keplerFilterField]]
)
};
// @shan you can remove this console once you are good with the object
this.props.dispatch(markerSelect(filterKeplerObject));
this.setState({filterKeplerObject}, () => this.addEventListeners());
});
}
};
getConfigSheetSummaryData = selectedSheet => {
// get sheet information this.state.selectedSheet should be syncronized with settings
// can possibly remove the || in the sheetName part
const sheetName = selectedSheet;
const sheetObject = tableauExt.dashboardContent.dashboard.worksheets.find(
worksheet => worksheet.name === sheetName
);
if (!sheetObject) {
return;
}
// clean up event listeners (taken from tableau example)
this.removeEventListeners();
if (TableauSettings.ShouldUse) {
this.setState({
isLoading: true
});
} else {
this.setState({isLoading: true});
tableauExt.settings.set('isLoading', true);
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll()
});
});
}
//working here on pulling out summmary data
//may want to limit to a single row when getting column names
sheetObject.getSummaryDataAsync(options).then(t => {
log('in getData().getSummaryDataAsync', t, this.state);
const newDataState = dataTableToKepler(t);
if (TableauSettings.ShouldUse) {
this.setState({
...newDataState,
selectedSheet: sheetName,
isLoading: false,
isMissingData: false
});
} else {
log(
'%c getConfigSheetSummaryData TableauSettings.ShouldUse false',
'color: purple'
);
this.setState({isLoading: false});
tableauExt.settings.set('isLoading', false);
tableauExt.settings.saveAsync().then(() => {
this.setState({
...newDataState,
isLoading: false,
tableauSettings: tableauExt.settings.getAll()
});
});
}
this.addEventListeners();
});
};
clearSheet() {
log('triggered erase');
if (TableauSettings.ShouldUse) {
TableauSettings.eraseAndSave(['isLoading', 'configuration'], settings => {
this.setState({
tableauSettings: settings,
configuration: false,
isSplash: true
});
});
} else {
// erase all the settings, there has got be a better way.
tableauExt.settings.erase('isLoading');
tableauExt.settings.erase('configuration');
// save async the erased settings
// wip - should be able to get rid of state as this is all captured in tableu settings (written to state)
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll(),
configuration: false,
isSplash: true
});
});
}
}
clearSplash = () => {
this.setState({
isSplash: false
});
};
configure = () => {
this.clearSheet();
const popUpUrl = window.location.href + '#true';
const popUpOptions = {
height: 625,
width: 720
};
tableauExt.ui
.displayDialogAsync(popUpUrl, '', popUpOptions)
.then(closePayload => {
log('configuring', closePayload, tableauExt.settings.getAll());
if (closePayload === 'false') {
this.setState({
isSplash: false,
isConfig: false,
tableauSettings: tableauExt.settings.getAll()
});
}
})
.catch(error => {
// One expected error condition is when the popup is closed by the user (meaning the user
// clicks the 'X' in the top right of the dialog). This can be checked for like so:
switch (error.errorCode) {
case window.tableau.ErrorCodes.DialogClosedByUser:
log('closed by user');
break;
default:
console.error(error.message);
}
});
};
componentWillUnmount() {
window.removeEventListener('resize', this.resize, true);
}
resize = () => {
this.setState({
width: window.innerWidth,
height: window.innerHeight
});
};
componentDidMount() |
componentWillUpdate(nextProps, nextState) {
if (tableauExt.settings) {
// get selectedSheet from Settings
// hardcoding this for now because I know i have two possibilities
const selectedSheet = tableauExt.settings.get('ConfigSheet');
if (
selectedSheet &&
this.state.tableauSettings.ConfigSheet !==
nextState.tableauSettings.ConfigSheet
) {
this.getConfigSheetSummaryData(selectedSheet);
}
}
}
render() {
// short cut this cause we use it ALOT
const tableauSettingsState = this.state.tableauSettings;
// loading screen jsx
let isLoading = false;
if (
!this.state.isSplash &&
!this.state.isConfig &&
(this.state.isLoading || this.state.isMissingData)
) {
isLoading = true;
}
// config screen jsx
if (this.state.isConfig) {
const stepNames = ['Select Sheet', 'Customize Kepler.gl'];
if (this.state.stepIndex === 1) {
// Placeholder sheet names. TODO: Bind to worksheet data
return (
<React.Fragment>
<Stepper stepIndex={this.state.stepIndex} steps={stepNames} />
<PickSheets
sheetNames={this.state.sheetNames}
configCallBack={this.configCallBack}
field={'ConfigSheet'}
ConfigSheet={tableauSettingsState.ConfigSheet || ''}
/>
<StepButtons
onNextClick={this.onNextStep}
onPrevClick={this.onPrevStep}
stepIndex={this.state.stepIndex}
maxStepCount={stepNames.length}
nextText={
this.state.stepIndex !== stepNames.length ? 'Next' : 'Save'
}
backText="Back"
/>
</React.Fragment>
);
}
if (this.state.stepIndex === 2) {
return (
<React.Fragment>
<Stepper stepIndex={this.state.stepIndex} steps={stepNames} />
<CustomizeViolin
handleChange={this.handleChange}
customCallBack={this.customCallBack}
field={'configuration'}
tableauSettings={tableauSettingsState}
configSheetColumns={this.state.ConfigSheetStringColumns || []}
/>
<StepButtons
onNextClick={this.onNextStep}
onPrevClick={this.onPrevStep}
stepIndex={this.state.stepIndex}
maxStepCount={stepNames.length}
nextText={
this.state.stepIndex !== stepNames.length ? 'Next' : 'Save'
}
backText="Back"
/>
</React.Fragment>
);
}
}
// splash screen jsx
if (this.state.isSplash) {
log(`%c this.state.isSplash=true}`, 'color: purple');
return (
<div className="splashScreen" style={{padding: 5}}>
<SplashScreen
configure={this.configure}
title="Kepler.gl within Tableau"
desc="Leverage the brilliance of Kepler.gl functionality, directly within Tableau!"
ctaText="Configure"
poweredBy={
<React.Fragment>
<p className="info">
For information on how to use this extension check out the{' '}
<a
href="https://github.com/uber/kepler.gl-tableau/tree/feat/docs/docs"
target="_blank"
rel="noopener noreferrer"
>
user guide
</a>
<br /> Tableau Requirements: Tableau Desktop (Mac Only) 2018.3
or >= 2019.1.2 or Tableau Server >= 2018.3
</p>
<p className="info">Brought to you by: </p>
<a
href="http://www.datablick.com/"
target="_blank"
rel="noopener noreferrer"
>
<img src={dbLogo} />
</a>{' '}
<a
href="https://starschema.com/"
target="_blank"
rel="noopener noreferrer"
>
<img src={ssLogo} />
</a>
<p className="info">Powered by: </p>
<a
href="https://github.com/uber/kepler.gl"
target="_blank"
rel="noopener noreferrer"
>
<img src={kepLogo} />
</a>
<p className="info">Version: {KEPLER_GL_VERSION}</p>
</React.Fragment>
}
/>
</div>
);
}
const readOnly = tableauSettingsState.readOnly === 'true';
log(`readOnly============== ${readOnly}`);
return (
<KeplerGlComponent
className={'tableau-kepler-gl'}
width={this.state.width}
height={this.state.height}
data={this.state.ConfigSheetData}
selectedSheet={this.state.selectedSheet}
tableauSettings={tableauSettingsState}
theme={tableauSettingsState.theme}
readOnly={readOnly}
keplerConfig={tableauSettingsState.keplerConfig}
mapboxAPIKey={
tableauSettingsState.mapboxAPIKey
? tableauSettingsState.mapboxAPIKey
: this.state.tableauKey
}
isLoading={isLoading}
// persist state to tableau
configCallBack={readOnly ? null : this.configCallBack}
// interactivity
clickCallBack={this.clickCallBack}
hoverCallBack={this.hoverCallBack}
dispatch={this.props.dispatch}
/>
);
}
}
App.propTypes = {};
const mapStateToProps = state => state;
const dispatchToProps = dispatch => ({dispatch});
const ConnectedApp = connect(mapStateToProps, dispatchToProps)(App);
export default withStyles(styles)(ConnectedApp);
| {
window.addEventListener('resize', this.resize, true);
this.resize();
tableauExt.initializeAsync({configure: this.configure}).then(() => {
// console.log('tableau config', configJson);
// default tableau settings on initial entry into the extension
// we know if we haven't done anything yet when tableauSettings state = []
log('did mount', tableauExt.settings.get('mapboxAPIKey'));
if (tableauExt.settings.get('mapboxAPIKey') === '') {
log(
'defaultSettings triggered',
defaultSettings.length,
defaultSettings
);
defaultSettings.defaultKeys.map((defaultSetting, index) => {
log(
'defaultSetting',
index,
defaultSetting,
defaultSettings.defaults[defaultSetting]
);
this.configCallBack(
defaultSetting,
defaultSettings.defaults[defaultSetting]
);
});
}
// this is where the majority of the code is going to go for this extension I think
log('will mount', tableauExt.settings.getAll());
//get sheetNames and dashboard name from workbook
const dashboardName = tableauExt.dashboardContent.dashboard.name;
const sheetNames = tableauExt.dashboardContent.dashboard.worksheets.map(
worksheet => worksheet.name
);
log('checking field in getAll()', tableauExt.settings.getAll());
// add event listeners (this includes an initial removal)
this.addEventListeners();
// Initialize the current saved settings global
TableauSettings.init();
// default to uber's Kepler key that they requested if user does not enter
this.setState({
tableauKey: MAPBOX_ACCESS_TOKEN,
isLoading: false,
height: window.innerHeight,
width: window.innerWidth,
sheetNames,
dashboardName,
demoType: tableauExt.settings.get('ConfigType') || 'violin',
tableauSettings: tableauExt.settings.getAll()
});
if (
this.state.tableauSettings.configuration &&
this.state.tableauSettings.configuration === 'true'
) {
this.setState({
isSplash: false,
isConfig: false
});
}
});
} | identifier_body |
App.js | // Copyright (c) 2019 Chris DeMartini
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// 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 Software.
//
// THE SOFTWARE IS 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 SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/* eslint-disable complexity */
import React, {Component} from 'react';
import {connect} from 'react-redux';
import throttle from 'lodash.throttle';
import debounce from 'lodash.debounce';
import './App.css';
// actions
import {markerSelect} from './actions';
// Custom config components
import SplashScreen from './components/SplashScreen';
import {
PickSheets,
CustomizeViolin,
Stepper,
StepButtons
} from './components/Configuration';
// Viz components
import KeplerGlComponent from './components/KeplerGL/index';
import {withStyles} from '@material-ui/core/styles';
// Tableau Styles and Tableau
// import './assets/tableau/vendor/slick.js/slick/slick.css';
// import './assets/tableau/css/style.min.css';
import {tableau} from './tableau-extensions-1.latest';
// tableau settings handler
import * as TableauSettings from './TableauSettings';
// initial default settings
import defaultSettings from './components/Configuration/defaultSettings';
// utils and variables
import {
columnToKeplerField,
dataToKeplerRow,
dataTableToKepler,
log
} from './utils';
import {
selectMarksByField,
applyFilterByField,
clearMarksByField,
clearFilterByField
} from './utils/interaction-utils';
//logos
import dbLogo from './assets/dblogo.png';
import ssLogo from './assets/sslogo.jpg';
import kepLogo from './assets/kepler.gl-logo_2x.png';
const MAPBOX_ACCESS_TOKEN =
'pk.eyJ1IjoidWJlcmRhdGEiLCJhIjoiY2p2OGVvejQwMDJxZzRma2dvdWQ2OTQwcSJ9.VbuIamTa_JayuD2yr5tjaA';
// begin constants to move to another file later
// material ui styles
const KEPLER_GL_VERSION = '__PACKAGE_VERSION__';
const styles = theme => ({
root: {
display: 'flex'
},
button: {
margin: theme.spacing.unit
},
leftIcon: {
marginRight: theme.spacing.unit
},
rightIcon: {
marginLeft: theme.spacing.unit
},
iconSmall: {
fontSize: 20
}
});
const tableauExt = window.tableau.extensions;
//tableau get summary data options
const options = {
ignoreAliases: false,
ignoreSelection: true,
maxRows: 0
};
function findColumnIndexByFieldName(state, fieldName) {
return (state.ConfigSheetColumns || []).findIndex(
f => f.fieldName === fieldName
);
}
// end constants to move to another file later
class App extends Component {
constructor(props) {
super(props);
this.state = {
isConfig: this.props.isConfig || false,
isLoading: true,
isSplash: true,
configuration: false,
height: 300,
width: 300,
dashboardName: '',
sheetNames: [],
tableauSettings: {},
demoType: 'Violin',
stepIndex: 1,
isMissingData: true,
highlightOn: undefined,
unregisterHandlerFunctions: [],
filterKeplerObject: [],
theme: 'light'
};
TableauSettings.setEnvName(this.props.isConfig ? 'CONFIG' : 'EXTENSION');
this.unregisterHandlerFunctions = [];
this.applyingMouseActions = false;
this.clickCallBack = throttle(this.clickCallBack, 200);
this.hoverCallBack = throttle(this.hoverCallBack, 200);
this.configCallBack = debounce(this.configCallBack, 500);
}
// eslint-disable-next-line react/sort-comp
addEventListeners = () => {
// Whenever we restore the filters table, remove all save handling functions,
// since we add them back later in this function.
// provided by tableau extension samples
log('%c addEventListeners', 'background: purple; color:yellow');
this.removeEventListeners();
const localUnregisterHandlerFunctions = [];
// add filter change event listener with callback to re-query data after change
// go through each worksheet and then add a filter change event listener
// need to check whether this is being applied more than once
tableauExt.dashboardContent.dashboard.worksheets.map(worksheet => {
// add event listener
const unregisterFilterHandlerFunction = worksheet.addEventListener(
window.tableau.TableauEventType.FilterChanged,
this.filterChanged
);
// provided by tableau extension samples, may need to push this to state for react
localUnregisterHandlerFunctions.push(unregisterFilterHandlerFunction);
const unregisterMarkerHandlerFunction = worksheet.addEventListener(
window.tableau.TableauEventType.MarkSelectionChanged,
this.marksSelected
);
// provided by tableau extension samples, may need to push this to state for react
localUnregisterHandlerFunctions.push(unregisterMarkerHandlerFunction);
});
this.unregisterHandlerFunctions = localUnregisterHandlerFunctions;
// log(`%c added ${this.unregisterHandlerFunctions.length} EventListeners`, 'background: purple, color:yellow');
};
removeEventListeners = () => {
log(
`%c remove ${this.unregisterHandlerFunctions.length} EventListeners`,
'background: green; color:black'
);
this.unregisterHandlerFunctions.forEach(unregisterHandlerFunction => {
unregisterHandlerFunction();
});
this.unregisterHandlerFunctions = [];
};
onNextStep = () => {
if (this.state.stepIndex === 2) {
this.customCallBack('configuration');
} else {
this.setState((previousState, currentProps) => {
return {stepIndex: previousState.stepIndex + 1};
});
}
};
onPrevStep = () => {
this.setState((previousState, currentProps) => {
return {stepIndex: previousState.stepIndex - 1};
});
};
clickCallBack = d => {
const {clickField, clickAction} = this.state.tableauSettings;
log(
'%c in on click callback',
'background: brown'
// d,
// findColumnIndexByFieldName(this.state, clickField),
// clickAction
);
this.applyMouseActionsToSheets(d, clickAction, clickField);
};
hoverCallBack = d => {
const {hoverField, hoverAction} = this.state.tableauSettings;
log(
'%c in on hover callback',
'background: OLIVE'
// d,
// findColumnIndexByFieldName(this.state, hoverField),
// hoverAction
);
this.applyMouseActionsToSheets(d, hoverAction, hoverField);
// go through each worksheet and select marks
};
applyMouseActionsToSheets = (d, action, fieldName) => {
if (this.applyingMouseActions) {
return;
}
const {ConfigSheet} = this.state.tableauSettings;
const toHighlight =
action === 'Highlight' && (fieldName || 'None') !== 'None';
const toFilter = action === 'Filter' && (fieldName || 'None') !== 'None';
// if no action should be taken
if (!toHighlight && !toFilter) {
return;
}
// remove EventListeners before apply any async actions
this.removeEventListeners();
this.applyingMouseActions = true;
let tasks = [];
if (d) {
// select marks or filter
const fieldIdx = findColumnIndexByFieldName(this.state, fieldName);
const fieldValues =
typeof d[0] === 'object'
? d.map(childD => childD[fieldIdx])
: [d[fieldIdx]];
const actionToApply = toHighlight
? selectMarksByField
: applyFilterByField;
tasks = actionToApply(fieldName, fieldValues, ConfigSheet);
} else {
// clear marks or filer
const actionToApply = toHighlight
? clearMarksByField
: clearFilterByField;
tasks = actionToApply(fieldName, ConfigSheet);
}
Promise.all(tasks).then(() => {
// all selection should be completed
// Add event listeners back
this.addEventListeners();
this.applyingMouseActions = false;
});
};
demoChange = event => {
this.setState({demoType: event.target.value});
log('in demo change', event.target.value, this.state.demoType);
};
handleChange = event => {
log('event', event);
if (TableauSettings.ShouldUse) {
// create a single k/v pair
const kv = {};
kv[event.target.name] = event.target.value;
// update the settings
log(
'%c handleChange=======TableauSettings.updateAndSave',
'background: red; color: white'
);
TableauSettings.updateAndSave(kv, settings => {
this.setState({
tableauSettings: settings
});
});
} else {
tableauExt.settings.set(event.target.name, event.target.value);
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll()
});
});
}
};
configCallBack = (field, columnName) => {
if (TableauSettings.ShouldUse) {
log(
'%c configCallBack=======TableauSettings.updateAndSave',
'background: red; color: white'
);
TableauSettings.updateAndSave(
{
// ['is' + field]: true,
[field]: columnName
},
settings => {
this.setState({
// ['is' + field]: true,
tableauSettings: settings
});
}
);
} else {
tableauExt.settings.set(field, columnName);
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll()
});
});
}
};
eraseCallBack = field => {
log('triggered erase', field);
if (TableauSettings.ShouldUse) {
log(
'%c eraseCallBack=======TableauSettings.eraseAndSave',
'background: red; color: white'
);
TableauSettings.eraseAndSave([field], settings => {
this.setState({
tableauSettings: settings
});
});
} else {
// erase all the settings, there has got be a better way.
tableauExt.settings.erase(field);
// save async the erased settings
// wip - should be able to get rid of state as this is all captured in tableu settings (written to state)
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll()
});
});
}
};
customCallBack = confSetting => {
log('in custom call back', confSetting);
if (TableauSettings.ShouldUse) {
log(
'%c customCallBack=======TableauSettings.updateAndSave',
'background: red; color: white'
);
TableauSettings.updateAndSave(
{
[confSetting]: true
},
settings => {
this.setState({
[confSetting]: true,
tableauSettings: settings
});
if (confSetting === 'configuration') {
tableauExt.ui.closeDialog('false');
}
}
);
} else {
tableauExt.settings.set(confSetting, true);
tableauExt.settings.saveAsync().then(() => {
this.setState({
[confSetting]: true,
tableauSettings: tableauExt.settings.getAll()
});
if (confSetting === 'configuration') {
tableauExt.ui.closeDialog('false');
}
});
}
};
// needs to be updated to handle if more than one data set is selected
// find all sheets in array and then call get summary, for now hardcoding
filterChanged = e => {
const selectedSheet = tableauExt.settings.get('ConfigSheet');
if (selectedSheet && selectedSheet === e.worksheet.name) {
log(
'%c ==============App filter has changed',
'background: red; color: white'
);
this.getConfigSheetSummaryData(selectedSheet);
}
};
marksSelected = e => {
if (this.state.tableauSettings.keplerFilterField) {
if (this.applyingMouseActions) {
return;
}
log(
'%c ==============App Marker selected',
'background: red; color: white'
);
// remove event listeners
this.removeEventListeners();
// get selected marks and pass to kepler via state object
e.getMarksAsync().then(marks => {
const {keplerFilterField} = this.state.tableauSettings;
// loop through marks table and adjust the class for opacity
const marksDataTable = marks.data[0];
const col_indexes = {};
const keplerFields = [];
// write column names to array
for (let k = 0; k < marksDataTable.columns.length; k++) {
col_indexes[marksDataTable.columns[k].fieldName] = k;
keplerFields.push(columnToKeplerField(marksDataTable.columns[k], k));
}
const keplerData = dataToKeplerRow(marksDataTable.data, keplerFields);
const filterKeplerObject = {
field: keplerFilterField,
values: keplerData.map(
childD => childD[col_indexes[keplerFilterField]]
)
};
// @shan you can remove this console once you are good with the object
this.props.dispatch(markerSelect(filterKeplerObject));
this.setState({filterKeplerObject}, () => this.addEventListeners());
});
}
};
getConfigSheetSummaryData = selectedSheet => {
// get sheet information this.state.selectedSheet should be syncronized with settings
// can possibly remove the || in the sheetName part
const sheetName = selectedSheet;
const sheetObject = tableauExt.dashboardContent.dashboard.worksheets.find(
worksheet => worksheet.name === sheetName
);
if (!sheetObject) {
return;
}
// clean up event listeners (taken from tableau example)
this.removeEventListeners();
if (TableauSettings.ShouldUse) {
this.setState({
isLoading: true
});
} else {
this.setState({isLoading: true});
tableauExt.settings.set('isLoading', true);
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll()
});
});
}
//working here on pulling out summmary data
//may want to limit to a single row when getting column names
sheetObject.getSummaryDataAsync(options).then(t => {
log('in getData().getSummaryDataAsync', t, this.state);
const newDataState = dataTableToKepler(t);
if (TableauSettings.ShouldUse) {
this.setState({
...newDataState,
selectedSheet: sheetName,
isLoading: false,
isMissingData: false
}); | 'color: purple'
);
this.setState({isLoading: false});
tableauExt.settings.set('isLoading', false);
tableauExt.settings.saveAsync().then(() => {
this.setState({
...newDataState,
isLoading: false,
tableauSettings: tableauExt.settings.getAll()
});
});
}
this.addEventListeners();
});
};
clearSheet() {
log('triggered erase');
if (TableauSettings.ShouldUse) {
TableauSettings.eraseAndSave(['isLoading', 'configuration'], settings => {
this.setState({
tableauSettings: settings,
configuration: false,
isSplash: true
});
});
} else {
// erase all the settings, there has got be a better way.
tableauExt.settings.erase('isLoading');
tableauExt.settings.erase('configuration');
// save async the erased settings
// wip - should be able to get rid of state as this is all captured in tableu settings (written to state)
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll(),
configuration: false,
isSplash: true
});
});
}
}
clearSplash = () => {
this.setState({
isSplash: false
});
};
configure = () => {
this.clearSheet();
const popUpUrl = window.location.href + '#true';
const popUpOptions = {
height: 625,
width: 720
};
tableauExt.ui
.displayDialogAsync(popUpUrl, '', popUpOptions)
.then(closePayload => {
log('configuring', closePayload, tableauExt.settings.getAll());
if (closePayload === 'false') {
this.setState({
isSplash: false,
isConfig: false,
tableauSettings: tableauExt.settings.getAll()
});
}
})
.catch(error => {
// One expected error condition is when the popup is closed by the user (meaning the user
// clicks the 'X' in the top right of the dialog). This can be checked for like so:
switch (error.errorCode) {
case window.tableau.ErrorCodes.DialogClosedByUser:
log('closed by user');
break;
default:
console.error(error.message);
}
});
};
componentWillUnmount() {
window.removeEventListener('resize', this.resize, true);
}
resize = () => {
this.setState({
width: window.innerWidth,
height: window.innerHeight
});
};
componentDidMount() {
window.addEventListener('resize', this.resize, true);
this.resize();
tableauExt.initializeAsync({configure: this.configure}).then(() => {
// console.log('tableau config', configJson);
// default tableau settings on initial entry into the extension
// we know if we haven't done anything yet when tableauSettings state = []
log('did mount', tableauExt.settings.get('mapboxAPIKey'));
if (tableauExt.settings.get('mapboxAPIKey') === '') {
log(
'defaultSettings triggered',
defaultSettings.length,
defaultSettings
);
defaultSettings.defaultKeys.map((defaultSetting, index) => {
log(
'defaultSetting',
index,
defaultSetting,
defaultSettings.defaults[defaultSetting]
);
this.configCallBack(
defaultSetting,
defaultSettings.defaults[defaultSetting]
);
});
}
// this is where the majority of the code is going to go for this extension I think
log('will mount', tableauExt.settings.getAll());
//get sheetNames and dashboard name from workbook
const dashboardName = tableauExt.dashboardContent.dashboard.name;
const sheetNames = tableauExt.dashboardContent.dashboard.worksheets.map(
worksheet => worksheet.name
);
log('checking field in getAll()', tableauExt.settings.getAll());
// add event listeners (this includes an initial removal)
this.addEventListeners();
// Initialize the current saved settings global
TableauSettings.init();
// default to uber's Kepler key that they requested if user does not enter
this.setState({
tableauKey: MAPBOX_ACCESS_TOKEN,
isLoading: false,
height: window.innerHeight,
width: window.innerWidth,
sheetNames,
dashboardName,
demoType: tableauExt.settings.get('ConfigType') || 'violin',
tableauSettings: tableauExt.settings.getAll()
});
if (
this.state.tableauSettings.configuration &&
this.state.tableauSettings.configuration === 'true'
) {
this.setState({
isSplash: false,
isConfig: false
});
}
});
}
componentWillUpdate(nextProps, nextState) {
if (tableauExt.settings) {
// get selectedSheet from Settings
// hardcoding this for now because I know i have two possibilities
const selectedSheet = tableauExt.settings.get('ConfigSheet');
if (
selectedSheet &&
this.state.tableauSettings.ConfigSheet !==
nextState.tableauSettings.ConfigSheet
) {
this.getConfigSheetSummaryData(selectedSheet);
}
}
}
render() {
// short cut this cause we use it ALOT
const tableauSettingsState = this.state.tableauSettings;
// loading screen jsx
let isLoading = false;
if (
!this.state.isSplash &&
!this.state.isConfig &&
(this.state.isLoading || this.state.isMissingData)
) {
isLoading = true;
}
// config screen jsx
if (this.state.isConfig) {
const stepNames = ['Select Sheet', 'Customize Kepler.gl'];
if (this.state.stepIndex === 1) {
// Placeholder sheet names. TODO: Bind to worksheet data
return (
<React.Fragment>
<Stepper stepIndex={this.state.stepIndex} steps={stepNames} />
<PickSheets
sheetNames={this.state.sheetNames}
configCallBack={this.configCallBack}
field={'ConfigSheet'}
ConfigSheet={tableauSettingsState.ConfigSheet || ''}
/>
<StepButtons
onNextClick={this.onNextStep}
onPrevClick={this.onPrevStep}
stepIndex={this.state.stepIndex}
maxStepCount={stepNames.length}
nextText={
this.state.stepIndex !== stepNames.length ? 'Next' : 'Save'
}
backText="Back"
/>
</React.Fragment>
);
}
if (this.state.stepIndex === 2) {
return (
<React.Fragment>
<Stepper stepIndex={this.state.stepIndex} steps={stepNames} />
<CustomizeViolin
handleChange={this.handleChange}
customCallBack={this.customCallBack}
field={'configuration'}
tableauSettings={tableauSettingsState}
configSheetColumns={this.state.ConfigSheetStringColumns || []}
/>
<StepButtons
onNextClick={this.onNextStep}
onPrevClick={this.onPrevStep}
stepIndex={this.state.stepIndex}
maxStepCount={stepNames.length}
nextText={
this.state.stepIndex !== stepNames.length ? 'Next' : 'Save'
}
backText="Back"
/>
</React.Fragment>
);
}
}
// splash screen jsx
if (this.state.isSplash) {
log(`%c this.state.isSplash=true}`, 'color: purple');
return (
<div className="splashScreen" style={{padding: 5}}>
<SplashScreen
configure={this.configure}
title="Kepler.gl within Tableau"
desc="Leverage the brilliance of Kepler.gl functionality, directly within Tableau!"
ctaText="Configure"
poweredBy={
<React.Fragment>
<p className="info">
For information on how to use this extension check out the{' '}
<a
href="https://github.com/uber/kepler.gl-tableau/tree/feat/docs/docs"
target="_blank"
rel="noopener noreferrer"
>
user guide
</a>
<br /> Tableau Requirements: Tableau Desktop (Mac Only) 2018.3
or >= 2019.1.2 or Tableau Server >= 2018.3
</p>
<p className="info">Brought to you by: </p>
<a
href="http://www.datablick.com/"
target="_blank"
rel="noopener noreferrer"
>
<img src={dbLogo} />
</a>{' '}
<a
href="https://starschema.com/"
target="_blank"
rel="noopener noreferrer"
>
<img src={ssLogo} />
</a>
<p className="info">Powered by: </p>
<a
href="https://github.com/uber/kepler.gl"
target="_blank"
rel="noopener noreferrer"
>
<img src={kepLogo} />
</a>
<p className="info">Version: {KEPLER_GL_VERSION}</p>
</React.Fragment>
}
/>
</div>
);
}
const readOnly = tableauSettingsState.readOnly === 'true';
log(`readOnly============== ${readOnly}`);
return (
<KeplerGlComponent
className={'tableau-kepler-gl'}
width={this.state.width}
height={this.state.height}
data={this.state.ConfigSheetData}
selectedSheet={this.state.selectedSheet}
tableauSettings={tableauSettingsState}
theme={tableauSettingsState.theme}
readOnly={readOnly}
keplerConfig={tableauSettingsState.keplerConfig}
mapboxAPIKey={
tableauSettingsState.mapboxAPIKey
? tableauSettingsState.mapboxAPIKey
: this.state.tableauKey
}
isLoading={isLoading}
// persist state to tableau
configCallBack={readOnly ? null : this.configCallBack}
// interactivity
clickCallBack={this.clickCallBack}
hoverCallBack={this.hoverCallBack}
dispatch={this.props.dispatch}
/>
);
}
}
App.propTypes = {};
const mapStateToProps = state => state;
const dispatchToProps = dispatch => ({dispatch});
const ConnectedApp = connect(mapStateToProps, dispatchToProps)(App);
export default withStyles(styles)(ConnectedApp); |
} else {
log(
'%c getConfigSheetSummaryData TableauSettings.ShouldUse false', | random_line_split |
App.js | // Copyright (c) 2019 Chris DeMartini
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// 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 Software.
//
// THE SOFTWARE IS 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 SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/* eslint-disable complexity */
import React, {Component} from 'react';
import {connect} from 'react-redux';
import throttle from 'lodash.throttle';
import debounce from 'lodash.debounce';
import './App.css';
// actions
import {markerSelect} from './actions';
// Custom config components
import SplashScreen from './components/SplashScreen';
import {
PickSheets,
CustomizeViolin,
Stepper,
StepButtons
} from './components/Configuration';
// Viz components
import KeplerGlComponent from './components/KeplerGL/index';
import {withStyles} from '@material-ui/core/styles';
// Tableau Styles and Tableau
// import './assets/tableau/vendor/slick.js/slick/slick.css';
// import './assets/tableau/css/style.min.css';
import {tableau} from './tableau-extensions-1.latest';
// tableau settings handler
import * as TableauSettings from './TableauSettings';
// initial default settings
import defaultSettings from './components/Configuration/defaultSettings';
// utils and variables
import {
columnToKeplerField,
dataToKeplerRow,
dataTableToKepler,
log
} from './utils';
import {
selectMarksByField,
applyFilterByField,
clearMarksByField,
clearFilterByField
} from './utils/interaction-utils';
//logos
import dbLogo from './assets/dblogo.png';
import ssLogo from './assets/sslogo.jpg';
import kepLogo from './assets/kepler.gl-logo_2x.png';
const MAPBOX_ACCESS_TOKEN =
'pk.eyJ1IjoidWJlcmRhdGEiLCJhIjoiY2p2OGVvejQwMDJxZzRma2dvdWQ2OTQwcSJ9.VbuIamTa_JayuD2yr5tjaA';
// begin constants to move to another file later
// material ui styles
const KEPLER_GL_VERSION = '__PACKAGE_VERSION__';
const styles = theme => ({
root: {
display: 'flex'
},
button: {
margin: theme.spacing.unit
},
leftIcon: {
marginRight: theme.spacing.unit
},
rightIcon: {
marginLeft: theme.spacing.unit
},
iconSmall: {
fontSize: 20
}
});
const tableauExt = window.tableau.extensions;
//tableau get summary data options
const options = {
ignoreAliases: false,
ignoreSelection: true,
maxRows: 0
};
function findColumnIndexByFieldName(state, fieldName) {
return (state.ConfigSheetColumns || []).findIndex(
f => f.fieldName === fieldName
);
}
// end constants to move to another file later
class App extends Component {
constructor(props) {
super(props);
this.state = {
isConfig: this.props.isConfig || false,
isLoading: true,
isSplash: true,
configuration: false,
height: 300,
width: 300,
dashboardName: '',
sheetNames: [],
tableauSettings: {},
demoType: 'Violin',
stepIndex: 1,
isMissingData: true,
highlightOn: undefined,
unregisterHandlerFunctions: [],
filterKeplerObject: [],
theme: 'light'
};
TableauSettings.setEnvName(this.props.isConfig ? 'CONFIG' : 'EXTENSION');
this.unregisterHandlerFunctions = [];
this.applyingMouseActions = false;
this.clickCallBack = throttle(this.clickCallBack, 200);
this.hoverCallBack = throttle(this.hoverCallBack, 200);
this.configCallBack = debounce(this.configCallBack, 500);
}
// eslint-disable-next-line react/sort-comp
addEventListeners = () => {
// Whenever we restore the filters table, remove all save handling functions,
// since we add them back later in this function.
// provided by tableau extension samples
log('%c addEventListeners', 'background: purple; color:yellow');
this.removeEventListeners();
const localUnregisterHandlerFunctions = [];
// add filter change event listener with callback to re-query data after change
// go through each worksheet and then add a filter change event listener
// need to check whether this is being applied more than once
tableauExt.dashboardContent.dashboard.worksheets.map(worksheet => {
// add event listener
const unregisterFilterHandlerFunction = worksheet.addEventListener(
window.tableau.TableauEventType.FilterChanged,
this.filterChanged
);
// provided by tableau extension samples, may need to push this to state for react
localUnregisterHandlerFunctions.push(unregisterFilterHandlerFunction);
const unregisterMarkerHandlerFunction = worksheet.addEventListener(
window.tableau.TableauEventType.MarkSelectionChanged,
this.marksSelected
);
// provided by tableau extension samples, may need to push this to state for react
localUnregisterHandlerFunctions.push(unregisterMarkerHandlerFunction);
});
this.unregisterHandlerFunctions = localUnregisterHandlerFunctions;
// log(`%c added ${this.unregisterHandlerFunctions.length} EventListeners`, 'background: purple, color:yellow');
};
removeEventListeners = () => {
log(
`%c remove ${this.unregisterHandlerFunctions.length} EventListeners`,
'background: green; color:black'
);
this.unregisterHandlerFunctions.forEach(unregisterHandlerFunction => {
unregisterHandlerFunction();
});
this.unregisterHandlerFunctions = [];
};
onNextStep = () => {
if (this.state.stepIndex === 2) {
this.customCallBack('configuration');
} else {
this.setState((previousState, currentProps) => {
return {stepIndex: previousState.stepIndex + 1};
});
}
};
onPrevStep = () => {
this.setState((previousState, currentProps) => {
return {stepIndex: previousState.stepIndex - 1};
});
};
clickCallBack = d => {
const {clickField, clickAction} = this.state.tableauSettings;
log(
'%c in on click callback',
'background: brown'
// d,
// findColumnIndexByFieldName(this.state, clickField),
// clickAction
);
this.applyMouseActionsToSheets(d, clickAction, clickField);
};
hoverCallBack = d => {
const {hoverField, hoverAction} = this.state.tableauSettings;
log(
'%c in on hover callback',
'background: OLIVE'
// d,
// findColumnIndexByFieldName(this.state, hoverField),
// hoverAction
);
this.applyMouseActionsToSheets(d, hoverAction, hoverField);
// go through each worksheet and select marks
};
applyMouseActionsToSheets = (d, action, fieldName) => {
if (this.applyingMouseActions) {
return;
}
const {ConfigSheet} = this.state.tableauSettings;
const toHighlight =
action === 'Highlight' && (fieldName || 'None') !== 'None';
const toFilter = action === 'Filter' && (fieldName || 'None') !== 'None';
// if no action should be taken
if (!toHighlight && !toFilter) {
return;
}
// remove EventListeners before apply any async actions
this.removeEventListeners();
this.applyingMouseActions = true;
let tasks = [];
if (d) {
// select marks or filter
const fieldIdx = findColumnIndexByFieldName(this.state, fieldName);
const fieldValues =
typeof d[0] === 'object'
? d.map(childD => childD[fieldIdx])
: [d[fieldIdx]];
const actionToApply = toHighlight
? selectMarksByField
: applyFilterByField;
tasks = actionToApply(fieldName, fieldValues, ConfigSheet);
} else {
// clear marks or filer
const actionToApply = toHighlight
? clearMarksByField
: clearFilterByField;
tasks = actionToApply(fieldName, ConfigSheet);
}
Promise.all(tasks).then(() => {
// all selection should be completed
// Add event listeners back
this.addEventListeners();
this.applyingMouseActions = false;
});
};
demoChange = event => {
this.setState({demoType: event.target.value});
log('in demo change', event.target.value, this.state.demoType);
};
handleChange = event => {
log('event', event);
if (TableauSettings.ShouldUse) {
// create a single k/v pair
const kv = {};
kv[event.target.name] = event.target.value;
// update the settings
log(
'%c handleChange=======TableauSettings.updateAndSave',
'background: red; color: white'
);
TableauSettings.updateAndSave(kv, settings => {
this.setState({
tableauSettings: settings
});
});
} else {
tableauExt.settings.set(event.target.name, event.target.value);
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll()
});
});
}
};
configCallBack = (field, columnName) => {
if (TableauSettings.ShouldUse) {
log(
'%c configCallBack=======TableauSettings.updateAndSave',
'background: red; color: white'
);
TableauSettings.updateAndSave(
{
// ['is' + field]: true,
[field]: columnName
},
settings => {
this.setState({
// ['is' + field]: true,
tableauSettings: settings
});
}
);
} else {
tableauExt.settings.set(field, columnName);
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll()
});
});
}
};
eraseCallBack = field => {
log('triggered erase', field);
if (TableauSettings.ShouldUse) {
log(
'%c eraseCallBack=======TableauSettings.eraseAndSave',
'background: red; color: white'
);
TableauSettings.eraseAndSave([field], settings => {
this.setState({
tableauSettings: settings
});
});
} else {
// erase all the settings, there has got be a better way.
tableauExt.settings.erase(field);
// save async the erased settings
// wip - should be able to get rid of state as this is all captured in tableu settings (written to state)
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll()
});
});
}
};
customCallBack = confSetting => {
log('in custom call back', confSetting);
if (TableauSettings.ShouldUse) {
log(
'%c customCallBack=======TableauSettings.updateAndSave',
'background: red; color: white'
);
TableauSettings.updateAndSave(
{
[confSetting]: true
},
settings => {
this.setState({
[confSetting]: true,
tableauSettings: settings
});
if (confSetting === 'configuration') {
tableauExt.ui.closeDialog('false');
}
}
);
} else {
tableauExt.settings.set(confSetting, true);
tableauExt.settings.saveAsync().then(() => {
this.setState({
[confSetting]: true,
tableauSettings: tableauExt.settings.getAll()
});
if (confSetting === 'configuration') {
tableauExt.ui.closeDialog('false');
}
});
}
};
// needs to be updated to handle if more than one data set is selected
// find all sheets in array and then call get summary, for now hardcoding
filterChanged = e => {
const selectedSheet = tableauExt.settings.get('ConfigSheet');
if (selectedSheet && selectedSheet === e.worksheet.name) {
log(
'%c ==============App filter has changed',
'background: red; color: white'
);
this.getConfigSheetSummaryData(selectedSheet);
}
};
marksSelected = e => {
if (this.state.tableauSettings.keplerFilterField) {
if (this.applyingMouseActions) {
return;
}
log(
'%c ==============App Marker selected',
'background: red; color: white'
);
// remove event listeners
this.removeEventListeners();
// get selected marks and pass to kepler via state object
e.getMarksAsync().then(marks => {
const {keplerFilterField} = this.state.tableauSettings;
// loop through marks table and adjust the class for opacity
const marksDataTable = marks.data[0];
const col_indexes = {};
const keplerFields = [];
// write column names to array
for (let k = 0; k < marksDataTable.columns.length; k++) {
col_indexes[marksDataTable.columns[k].fieldName] = k;
keplerFields.push(columnToKeplerField(marksDataTable.columns[k], k));
}
const keplerData = dataToKeplerRow(marksDataTable.data, keplerFields);
const filterKeplerObject = {
field: keplerFilterField,
values: keplerData.map(
childD => childD[col_indexes[keplerFilterField]]
)
};
// @shan you can remove this console once you are good with the object
this.props.dispatch(markerSelect(filterKeplerObject));
this.setState({filterKeplerObject}, () => this.addEventListeners());
});
}
};
getConfigSheetSummaryData = selectedSheet => {
// get sheet information this.state.selectedSheet should be syncronized with settings
// can possibly remove the || in the sheetName part
const sheetName = selectedSheet;
const sheetObject = tableauExt.dashboardContent.dashboard.worksheets.find(
worksheet => worksheet.name === sheetName
);
if (!sheetObject) {
return;
}
// clean up event listeners (taken from tableau example)
this.removeEventListeners();
if (TableauSettings.ShouldUse) {
this.setState({
isLoading: true
});
} else {
this.setState({isLoading: true});
tableauExt.settings.set('isLoading', true);
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll()
});
});
}
//working here on pulling out summmary data
//may want to limit to a single row when getting column names
sheetObject.getSummaryDataAsync(options).then(t => {
log('in getData().getSummaryDataAsync', t, this.state);
const newDataState = dataTableToKepler(t);
if (TableauSettings.ShouldUse) {
this.setState({
...newDataState,
selectedSheet: sheetName,
isLoading: false,
isMissingData: false
});
} else {
log(
'%c getConfigSheetSummaryData TableauSettings.ShouldUse false',
'color: purple'
);
this.setState({isLoading: false});
tableauExt.settings.set('isLoading', false);
tableauExt.settings.saveAsync().then(() => {
this.setState({
...newDataState,
isLoading: false,
tableauSettings: tableauExt.settings.getAll()
});
});
}
this.addEventListeners();
});
};
clearSheet() {
log('triggered erase');
if (TableauSettings.ShouldUse) {
TableauSettings.eraseAndSave(['isLoading', 'configuration'], settings => {
this.setState({
tableauSettings: settings,
configuration: false,
isSplash: true
});
});
} else {
// erase all the settings, there has got be a better way.
tableauExt.settings.erase('isLoading');
tableauExt.settings.erase('configuration');
// save async the erased settings
// wip - should be able to get rid of state as this is all captured in tableu settings (written to state)
tableauExt.settings.saveAsync().then(() => {
this.setState({
tableauSettings: tableauExt.settings.getAll(),
configuration: false,
isSplash: true
});
});
}
}
clearSplash = () => {
this.setState({
isSplash: false
});
};
configure = () => {
this.clearSheet();
const popUpUrl = window.location.href + '#true';
const popUpOptions = {
height: 625,
width: 720
};
tableauExt.ui
.displayDialogAsync(popUpUrl, '', popUpOptions)
.then(closePayload => {
log('configuring', closePayload, tableauExt.settings.getAll());
if (closePayload === 'false') {
this.setState({
isSplash: false,
isConfig: false,
tableauSettings: tableauExt.settings.getAll()
});
}
})
.catch(error => {
// One expected error condition is when the popup is closed by the user (meaning the user
// clicks the 'X' in the top right of the dialog). This can be checked for like so:
switch (error.errorCode) {
case window.tableau.ErrorCodes.DialogClosedByUser:
log('closed by user');
break;
default:
console.error(error.message);
}
});
};
componentWillUnmount() {
window.removeEventListener('resize', this.resize, true);
}
resize = () => {
this.setState({
width: window.innerWidth,
height: window.innerHeight
});
};
componentDidMount() {
window.addEventListener('resize', this.resize, true);
this.resize();
tableauExt.initializeAsync({configure: this.configure}).then(() => {
// console.log('tableau config', configJson);
// default tableau settings on initial entry into the extension
// we know if we haven't done anything yet when tableauSettings state = []
log('did mount', tableauExt.settings.get('mapboxAPIKey'));
if (tableauExt.settings.get('mapboxAPIKey') === '') {
log(
'defaultSettings triggered',
defaultSettings.length,
defaultSettings
);
defaultSettings.defaultKeys.map((defaultSetting, index) => {
log(
'defaultSetting',
index,
defaultSetting,
defaultSettings.defaults[defaultSetting]
);
this.configCallBack(
defaultSetting,
defaultSettings.defaults[defaultSetting]
);
});
}
// this is where the majority of the code is going to go for this extension I think
log('will mount', tableauExt.settings.getAll());
//get sheetNames and dashboard name from workbook
const dashboardName = tableauExt.dashboardContent.dashboard.name;
const sheetNames = tableauExt.dashboardContent.dashboard.worksheets.map(
worksheet => worksheet.name
);
log('checking field in getAll()', tableauExt.settings.getAll());
// add event listeners (this includes an initial removal)
this.addEventListeners();
// Initialize the current saved settings global
TableauSettings.init();
// default to uber's Kepler key that they requested if user does not enter
this.setState({
tableauKey: MAPBOX_ACCESS_TOKEN,
isLoading: false,
height: window.innerHeight,
width: window.innerWidth,
sheetNames,
dashboardName,
demoType: tableauExt.settings.get('ConfigType') || 'violin',
tableauSettings: tableauExt.settings.getAll()
});
if (
this.state.tableauSettings.configuration &&
this.state.tableauSettings.configuration === 'true'
) {
this.setState({
isSplash: false,
isConfig: false
});
}
});
}
componentWillUpdate(nextProps, nextState) {
if (tableauExt.settings) {
// get selectedSheet from Settings
// hardcoding this for now because I know i have two possibilities
const selectedSheet = tableauExt.settings.get('ConfigSheet');
if (
selectedSheet &&
this.state.tableauSettings.ConfigSheet !==
nextState.tableauSettings.ConfigSheet
) {
this.getConfigSheetSummaryData(selectedSheet);
}
}
}
| () {
// short cut this cause we use it ALOT
const tableauSettingsState = this.state.tableauSettings;
// loading screen jsx
let isLoading = false;
if (
!this.state.isSplash &&
!this.state.isConfig &&
(this.state.isLoading || this.state.isMissingData)
) {
isLoading = true;
}
// config screen jsx
if (this.state.isConfig) {
const stepNames = ['Select Sheet', 'Customize Kepler.gl'];
if (this.state.stepIndex === 1) {
// Placeholder sheet names. TODO: Bind to worksheet data
return (
<React.Fragment>
<Stepper stepIndex={this.state.stepIndex} steps={stepNames} />
<PickSheets
sheetNames={this.state.sheetNames}
configCallBack={this.configCallBack}
field={'ConfigSheet'}
ConfigSheet={tableauSettingsState.ConfigSheet || ''}
/>
<StepButtons
onNextClick={this.onNextStep}
onPrevClick={this.onPrevStep}
stepIndex={this.state.stepIndex}
maxStepCount={stepNames.length}
nextText={
this.state.stepIndex !== stepNames.length ? 'Next' : 'Save'
}
backText="Back"
/>
</React.Fragment>
);
}
if (this.state.stepIndex === 2) {
return (
<React.Fragment>
<Stepper stepIndex={this.state.stepIndex} steps={stepNames} />
<CustomizeViolin
handleChange={this.handleChange}
customCallBack={this.customCallBack}
field={'configuration'}
tableauSettings={tableauSettingsState}
configSheetColumns={this.state.ConfigSheetStringColumns || []}
/>
<StepButtons
onNextClick={this.onNextStep}
onPrevClick={this.onPrevStep}
stepIndex={this.state.stepIndex}
maxStepCount={stepNames.length}
nextText={
this.state.stepIndex !== stepNames.length ? 'Next' : 'Save'
}
backText="Back"
/>
</React.Fragment>
);
}
}
// splash screen jsx
if (this.state.isSplash) {
log(`%c this.state.isSplash=true}`, 'color: purple');
return (
<div className="splashScreen" style={{padding: 5}}>
<SplashScreen
configure={this.configure}
title="Kepler.gl within Tableau"
desc="Leverage the brilliance of Kepler.gl functionality, directly within Tableau!"
ctaText="Configure"
poweredBy={
<React.Fragment>
<p className="info">
For information on how to use this extension check out the{' '}
<a
href="https://github.com/uber/kepler.gl-tableau/tree/feat/docs/docs"
target="_blank"
rel="noopener noreferrer"
>
user guide
</a>
<br /> Tableau Requirements: Tableau Desktop (Mac Only) 2018.3
or >= 2019.1.2 or Tableau Server >= 2018.3
</p>
<p className="info">Brought to you by: </p>
<a
href="http://www.datablick.com/"
target="_blank"
rel="noopener noreferrer"
>
<img src={dbLogo} />
</a>{' '}
<a
href="https://starschema.com/"
target="_blank"
rel="noopener noreferrer"
>
<img src={ssLogo} />
</a>
<p className="info">Powered by: </p>
<a
href="https://github.com/uber/kepler.gl"
target="_blank"
rel="noopener noreferrer"
>
<img src={kepLogo} />
</a>
<p className="info">Version: {KEPLER_GL_VERSION}</p>
</React.Fragment>
}
/>
</div>
);
}
const readOnly = tableauSettingsState.readOnly === 'true';
log(`readOnly============== ${readOnly}`);
return (
<KeplerGlComponent
className={'tableau-kepler-gl'}
width={this.state.width}
height={this.state.height}
data={this.state.ConfigSheetData}
selectedSheet={this.state.selectedSheet}
tableauSettings={tableauSettingsState}
theme={tableauSettingsState.theme}
readOnly={readOnly}
keplerConfig={tableauSettingsState.keplerConfig}
mapboxAPIKey={
tableauSettingsState.mapboxAPIKey
? tableauSettingsState.mapboxAPIKey
: this.state.tableauKey
}
isLoading={isLoading}
// persist state to tableau
configCallBack={readOnly ? null : this.configCallBack}
// interactivity
clickCallBack={this.clickCallBack}
hoverCallBack={this.hoverCallBack}
dispatch={this.props.dispatch}
/>
);
}
}
App.propTypes = {};
const mapStateToProps = state => state;
const dispatchToProps = dispatch => ({dispatch});
const ConnectedApp = connect(mapStateToProps, dispatchToProps)(App);
export default withStyles(styles)(ConnectedApp);
| render | identifier_name |
hubtype-service.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.HubtypeService = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _axios = _interopRequireDefault(require("axios"));
var _pusherJs = _interopRequireDefault(require("pusher-js"));
var _utils = require("./utils");
function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) | return target; }
var _WEBCHAT_PUSHER_KEY_ = (0, _utils.getWebpackEnvVar)( // eslint-disable-next-line no-undef
typeof WEBCHAT_PUSHER_KEY !== 'undefined' && WEBCHAT_PUSHER_KEY, 'WEBCHAT_PUSHER_KEY', '434ca667c8e6cb3f641c');
var _HUBTYPE_API_URL_ = (0, _utils.getWebpackEnvVar)( // eslint-disable-next-line no-undef
typeof HUBTYPE_API_URL !== 'undefined' && HUBTYPE_API_URL, 'HUBTYPE_API_URL', 'https://api.hubtype.com');
var ACTIVITY_TIMEOUT = 20 * 1000; // https://pusher.com/docs/channels/using_channels/connection#activitytimeout-integer-
var PONG_TIMEOUT = 5 * 1000; // https://pusher.com/docs/channels/using_channels/connection#pongtimeout-integer-
var HubtypeService = /*#__PURE__*/function () {
function HubtypeService(_ref) {
var appId = _ref.appId,
user = _ref.user,
lastMessageId = _ref.lastMessageId,
lastMessageUpdateDate = _ref.lastMessageUpdateDate,
onEvent = _ref.onEvent,
unsentInputs = _ref.unsentInputs,
server = _ref.server;
(0, _classCallCheck2["default"])(this, HubtypeService);
this.appId = appId;
this.user = user || {};
this.lastMessageId = lastMessageId;
this.lastMessageUpdateDate = lastMessageUpdateDate;
this.onEvent = onEvent;
this.unsentInputs = unsentInputs;
this.server = server;
if (user.id && (lastMessageId || lastMessageUpdateDate)) {
this.init();
}
}
(0, _createClass2["default"])(HubtypeService, [{
key: "resolveServerConfig",
value: function resolveServerConfig() {
if (!this.server) {
return {
activityTimeout: ACTIVITY_TIMEOUT,
pongTimeout: PONG_TIMEOUT
};
}
return {
activityTimeout: this.server.activityTimeout || ACTIVITY_TIMEOUT,
pongTimeout: this.server.pongTimeout || PONG_TIMEOUT
};
}
}, {
key: "updateAuthHeaders",
value: function updateAuthHeaders() {
if (this.pusher) {
this.pusher.config.auth.headers = _objectSpread(_objectSpread({}, this.pusher.config.auth.headers), this.constructHeaders());
}
}
}, {
key: "init",
value: function init(user, lastMessageId, lastMessageUpdateDate) {
var _this = this;
if (user) this.user = user;
if (lastMessageId) this.lastMessageId = lastMessageId;
if (lastMessageUpdateDate) this.lastMessageUpdateDate = lastMessageUpdateDate;
if (this.pusher || !this.user.id || !this.appId) return null;
this.pusher = new _pusherJs["default"](_WEBCHAT_PUSHER_KEY_, _objectSpread({
cluster: 'eu',
authEndpoint: "".concat(_HUBTYPE_API_URL_, "/v1/provider_accounts/webhooks/webchat/").concat(this.appId, "/auth/"),
forceTLS: true,
auth: {
headers: this.constructHeaders()
}
}, this.resolveServerConfig()));
this.channel = this.pusher.subscribe(this.pusherChannel);
var connectionPromise = new Promise(function (resolve, reject) {
var cleanAndReject = function cleanAndReject(msg) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
clearTimeout(connectTimeout);
_this.destroyPusher();
reject(msg);
};
var connectTimeout = setTimeout(function () {
return cleanAndReject('Connection Timeout');
}, 10000);
_this.channel.bind('pusher:subscription_succeeded', function () {
// Once subscribed, we know that authentication has been done: https://pusher.com/docs/channels/server_api/authenticating-users
_this.onConnectionRegained();
clearTimeout(connectTimeout);
resolve();
});
_this.channel.bind('botonic_response', function (data) {
return _this.onPusherEvent(data);
});
_this.channel.bind('update_message_info', function (data) {
return _this.onPusherEvent(data);
});
_this.pusher.connection.bind('error', function (event) {
if (event.type == 'WebSocketError') _this.handleConnectionChange(false);else {
var errorMsg = event.error && event.error.data ? event.error.data.code || event.error.data.message : 'Connection error';
cleanAndReject("Pusher error (".concat(errorMsg, ")"));
}
});
});
this.pusher.connection.bind('state_change', function (states) {
if (states.current === 'connecting') _this.updateAuthHeaders();
if (states.current === 'connected') _this.handleConnectionChange(true);
if (states.current === 'unavailable') _this.handleConnectionChange(false);
});
return connectionPromise;
}
}, {
key: "constructHeaders",
value: function constructHeaders() {
var headers = {};
if (this.user && this.user.id) headers['X-BOTONIC-USER-ID'] = this.user.id;
if (this.lastMessageId) headers['X-BOTONIC-LAST-MESSAGE-ID'] = this.lastMessageId;
if (this.lastMessageUpdateDate) headers['X-BOTONIC-LAST-MESSAGE-UPDATE-DATE'] = this.lastMessageUpdateDate;
return headers;
}
}, {
key: "handleConnectionChange",
value: function handleConnectionChange(online) {
this.onPusherEvent({
action: 'connectionChange',
online: online
});
}
}, {
key: "onPusherEvent",
value: function onPusherEvent(event) {
if (this.onEvent && typeof this.onEvent === 'function') this.onEvent(event);
}
}, {
key: "pusherChannel",
get: function get() {
return "private-encrypted-".concat(this.appId, "-").concat(this.user.id);
}
}, {
key: "handleSentInput",
value: function handleSentInput(message) {
this.onEvent({
action: 'update_message_info',
message: {
id: message.id,
ack: 1
}
});
}
}, {
key: "handleUnsentInput",
value: function handleUnsentInput(message) {
this.onEvent({
action: 'update_message_info',
message: {
id: message.id,
ack: 0,
unsentInput: message
}
});
}
}, {
key: "postMessage",
value: function () {
var _postMessage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(user, message) {
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_context.next = 3;
return this.init(user);
case 3:
_context.next = 5;
return _axios["default"].post("".concat(_HUBTYPE_API_URL_, "/v1/provider_accounts/webhooks/webchat/").concat(this.appId, "/"), {
sender: this.user,
message: message
}, {
validateStatus: function validateStatus(status) {
return status === 200;
}
});
case 5:
this.handleSentInput(message);
_context.next = 11;
break;
case 8:
_context.prev = 8;
_context.t0 = _context["catch"](0);
this.handleUnsentInput(message);
case 11:
case "end":
return _context.stop();
}
}
}, _callee, this, [[0, 8]]);
}));
function postMessage(_x, _x2) {
return _postMessage.apply(this, arguments);
}
return postMessage;
}()
}, {
key: "destroyPusher",
value: function destroyPusher() {
if (!this.pusher) return;
this.pusher.disconnect();
this.pusher.unsubscribe(this.pusherChannel);
this.pusher.unbind_all();
this.pusher.channels = {};
this.pusher = null;
}
}, {
key: "onConnectionRegained",
value: function () {
var _onConnectionRegained = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() {
return _regenerator["default"].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.resendUnsentInputs();
case 2:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function onConnectionRegained() {
return _onConnectionRegained.apply(this, arguments);
}
return onConnectionRegained;
}()
}, {
key: "resendUnsentInputs",
value: function () {
var _resendUnsentInputs = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() {
var _iterator, _step, message;
return _regenerator["default"].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_iterator = _createForOfIteratorHelper(this.unsentInputs());
_context3.prev = 1;
_iterator.s();
case 3:
if ((_step = _iterator.n()).done) {
_context3.next = 11;
break;
}
message = _step.value;
_context3.t0 = message.unsentInput;
if (!_context3.t0) {
_context3.next = 9;
break;
}
_context3.next = 9;
return this.postMessage(this.user, message.unsentInput);
case 9:
_context3.next = 3;
break;
case 11:
_context3.next = 16;
break;
case 13:
_context3.prev = 13;
_context3.t1 = _context3["catch"](1);
_iterator.e(_context3.t1);
case 16:
_context3.prev = 16;
_iterator.f();
return _context3.finish(16);
case 19:
case "end":
return _context3.stop();
}
}
}, _callee3, this, [[1, 13, 16, 19]]);
}));
function resendUnsentInputs() {
return _resendUnsentInputs.apply(this, arguments);
}
return resendUnsentInputs;
}()
}], [{
key: "getWebchatVisibility",
value: function () {
var _getWebchatVisibility = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(_ref2) {
var appId;
return _regenerator["default"].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
appId = _ref2.appId;
return _context4.abrupt("return", _axios["default"].get("".concat(_HUBTYPE_API_URL_, "/v1/provider_accounts/").concat(appId, "/visibility/")));
case 2:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
function getWebchatVisibility(_x3) {
return _getWebchatVisibility.apply(this, arguments);
}
return getWebchatVisibility;
}()
}]);
return HubtypeService;
}();
exports.HubtypeService = HubtypeService;
//# sourceMappingURL=hubtype-service.js.map | { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } | conditional_block |
hubtype-service.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.HubtypeService = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _axios = _interopRequireDefault(require("axios"));
var _pusherJs = _interopRequireDefault(require("pusher-js"));
var _utils = require("./utils");
function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var _WEBCHAT_PUSHER_KEY_ = (0, _utils.getWebpackEnvVar)( // eslint-disable-next-line no-undef
typeof WEBCHAT_PUSHER_KEY !== 'undefined' && WEBCHAT_PUSHER_KEY, 'WEBCHAT_PUSHER_KEY', '434ca667c8e6cb3f641c');
var _HUBTYPE_API_URL_ = (0, _utils.getWebpackEnvVar)( // eslint-disable-next-line no-undef
typeof HUBTYPE_API_URL !== 'undefined' && HUBTYPE_API_URL, 'HUBTYPE_API_URL', 'https://api.hubtype.com');
var ACTIVITY_TIMEOUT = 20 * 1000; // https://pusher.com/docs/channels/using_channels/connection#activitytimeout-integer-
var PONG_TIMEOUT = 5 * 1000; // https://pusher.com/docs/channels/using_channels/connection#pongtimeout-integer-
var HubtypeService = /*#__PURE__*/function () {
function HubtypeService(_ref) {
var appId = _ref.appId,
user = _ref.user,
lastMessageId = _ref.lastMessageId,
lastMessageUpdateDate = _ref.lastMessageUpdateDate,
onEvent = _ref.onEvent,
unsentInputs = _ref.unsentInputs,
server = _ref.server;
(0, _classCallCheck2["default"])(this, HubtypeService);
this.appId = appId;
this.user = user || {};
this.lastMessageId = lastMessageId;
this.lastMessageUpdateDate = lastMessageUpdateDate;
this.onEvent = onEvent;
this.unsentInputs = unsentInputs;
this.server = server;
if (user.id && (lastMessageId || lastMessageUpdateDate)) {
this.init();
}
}
(0, _createClass2["default"])(HubtypeService, [{
key: "resolveServerConfig",
value: function resolveServerConfig() {
if (!this.server) {
return {
activityTimeout: ACTIVITY_TIMEOUT,
pongTimeout: PONG_TIMEOUT
};
}
return {
activityTimeout: this.server.activityTimeout || ACTIVITY_TIMEOUT,
pongTimeout: this.server.pongTimeout || PONG_TIMEOUT
};
}
}, {
key: "updateAuthHeaders",
value: function updateAuthHeaders() {
if (this.pusher) {
this.pusher.config.auth.headers = _objectSpread(_objectSpread({}, this.pusher.config.auth.headers), this.constructHeaders());
}
}
}, {
key: "init",
value: function init(user, lastMessageId, lastMessageUpdateDate) {
var _this = this;
if (user) this.user = user;
if (lastMessageId) this.lastMessageId = lastMessageId;
if (lastMessageUpdateDate) this.lastMessageUpdateDate = lastMessageUpdateDate;
if (this.pusher || !this.user.id || !this.appId) return null;
this.pusher = new _pusherJs["default"](_WEBCHAT_PUSHER_KEY_, _objectSpread({
cluster: 'eu',
authEndpoint: "".concat(_HUBTYPE_API_URL_, "/v1/provider_accounts/webhooks/webchat/").concat(this.appId, "/auth/"),
forceTLS: true,
auth: {
headers: this.constructHeaders()
}
}, this.resolveServerConfig()));
this.channel = this.pusher.subscribe(this.pusherChannel);
var connectionPromise = new Promise(function (resolve, reject) {
var cleanAndReject = function cleanAndReject(msg) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
clearTimeout(connectTimeout);
_this.destroyPusher();
reject(msg);
};
var connectTimeout = setTimeout(function () {
return cleanAndReject('Connection Timeout');
}, 10000);
_this.channel.bind('pusher:subscription_succeeded', function () {
// Once subscribed, we know that authentication has been done: https://pusher.com/docs/channels/server_api/authenticating-users
_this.onConnectionRegained();
clearTimeout(connectTimeout);
resolve();
});
_this.channel.bind('botonic_response', function (data) {
return _this.onPusherEvent(data);
});
_this.channel.bind('update_message_info', function (data) {
return _this.onPusherEvent(data);
});
_this.pusher.connection.bind('error', function (event) {
if (event.type == 'WebSocketError') _this.handleConnectionChange(false);else {
var errorMsg = event.error && event.error.data ? event.error.data.code || event.error.data.message : 'Connection error';
cleanAndReject("Pusher error (".concat(errorMsg, ")"));
}
});
});
this.pusher.connection.bind('state_change', function (states) {
if (states.current === 'connecting') _this.updateAuthHeaders();
if (states.current === 'connected') _this.handleConnectionChange(true);
if (states.current === 'unavailable') _this.handleConnectionChange(false);
});
return connectionPromise;
}
}, {
key: "constructHeaders",
value: function constructHeaders() {
var headers = {};
if (this.user && this.user.id) headers['X-BOTONIC-USER-ID'] = this.user.id;
if (this.lastMessageId) headers['X-BOTONIC-LAST-MESSAGE-ID'] = this.lastMessageId;
if (this.lastMessageUpdateDate) headers['X-BOTONIC-LAST-MESSAGE-UPDATE-DATE'] = this.lastMessageUpdateDate;
return headers;
}
}, {
key: "handleConnectionChange",
value: function handleConnectionChange(online) {
this.onPusherEvent({
action: 'connectionChange',
online: online
});
}
}, {
key: "onPusherEvent",
value: function onPusherEvent(event) {
if (this.onEvent && typeof this.onEvent === 'function') this.onEvent(event);
}
}, {
key: "pusherChannel",
get: function get() {
return "private-encrypted-".concat(this.appId, "-").concat(this.user.id);
}
}, {
key: "handleSentInput",
value: function handleSentInput(message) {
this.onEvent({
action: 'update_message_info',
message: {
id: message.id,
ack: 1
}
});
}
}, {
key: "handleUnsentInput",
value: function handleUnsentInput(message) {
this.onEvent({
action: 'update_message_info',
message: {
id: message.id,
ack: 0,
unsentInput: message
}
});
}
}, {
key: "postMessage",
value: function () {
var _postMessage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(user, message) {
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_context.next = 3;
return this.init(user);
case 3:
_context.next = 5;
return _axios["default"].post("".concat(_HUBTYPE_API_URL_, "/v1/provider_accounts/webhooks/webchat/").concat(this.appId, "/"), {
sender: this.user,
message: message
}, {
validateStatus: function validateStatus(status) {
return status === 200;
}
});
case 5:
this.handleSentInput(message);
_context.next = 11;
break;
case 8:
_context.prev = 8;
_context.t0 = _context["catch"](0);
this.handleUnsentInput(message);
case 11:
case "end":
return _context.stop();
}
}
}, _callee, this, [[0, 8]]);
}));
function postMessage(_x, _x2) {
return _postMessage.apply(this, arguments);
}
return postMessage;
}()
}, {
key: "destroyPusher",
value: function destroyPusher() {
if (!this.pusher) return;
this.pusher.disconnect();
this.pusher.unsubscribe(this.pusherChannel);
this.pusher.unbind_all();
this.pusher.channels = {};
this.pusher = null;
}
}, {
key: "onConnectionRegained",
value: function () {
var _onConnectionRegained = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() {
return _regenerator["default"].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.resendUnsentInputs();
case 2:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function onConnectionRegained() {
return _onConnectionRegained.apply(this, arguments);
}
return onConnectionRegained;
}()
}, {
key: "resendUnsentInputs",
value: function () {
var _resendUnsentInputs = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() {
var _iterator, _step, message;
return _regenerator["default"].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_iterator = _createForOfIteratorHelper(this.unsentInputs());
_context3.prev = 1;
_iterator.s();
case 3:
if ((_step = _iterator.n()).done) {
_context3.next = 11;
break;
}
message = _step.value;
_context3.t0 = message.unsentInput;
if (!_context3.t0) {
_context3.next = 9;
break;
}
_context3.next = 9;
return this.postMessage(this.user, message.unsentInput);
case 9:
_context3.next = 3;
break;
case 11:
_context3.next = 16;
break;
| _context3.prev = 13;
_context3.t1 = _context3["catch"](1);
_iterator.e(_context3.t1);
case 16:
_context3.prev = 16;
_iterator.f();
return _context3.finish(16);
case 19:
case "end":
return _context3.stop();
}
}
}, _callee3, this, [[1, 13, 16, 19]]);
}));
function resendUnsentInputs() {
return _resendUnsentInputs.apply(this, arguments);
}
return resendUnsentInputs;
}()
}], [{
key: "getWebchatVisibility",
value: function () {
var _getWebchatVisibility = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(_ref2) {
var appId;
return _regenerator["default"].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
appId = _ref2.appId;
return _context4.abrupt("return", _axios["default"].get("".concat(_HUBTYPE_API_URL_, "/v1/provider_accounts/").concat(appId, "/visibility/")));
case 2:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
function getWebchatVisibility(_x3) {
return _getWebchatVisibility.apply(this, arguments);
}
return getWebchatVisibility;
}()
}]);
return HubtypeService;
}();
exports.HubtypeService = HubtypeService;
//# sourceMappingURL=hubtype-service.js.map | case 13: | random_line_split |
hubtype-service.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.HubtypeService = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _axios = _interopRequireDefault(require("axios"));
var _pusherJs = _interopRequireDefault(require("pusher-js"));
var _utils = require("./utils");
function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var _WEBCHAT_PUSHER_KEY_ = (0, _utils.getWebpackEnvVar)( // eslint-disable-next-line no-undef
typeof WEBCHAT_PUSHER_KEY !== 'undefined' && WEBCHAT_PUSHER_KEY, 'WEBCHAT_PUSHER_KEY', '434ca667c8e6cb3f641c');
var _HUBTYPE_API_URL_ = (0, _utils.getWebpackEnvVar)( // eslint-disable-next-line no-undef
typeof HUBTYPE_API_URL !== 'undefined' && HUBTYPE_API_URL, 'HUBTYPE_API_URL', 'https://api.hubtype.com');
var ACTIVITY_TIMEOUT = 20 * 1000; // https://pusher.com/docs/channels/using_channels/connection#activitytimeout-integer-
var PONG_TIMEOUT = 5 * 1000; // https://pusher.com/docs/channels/using_channels/connection#pongtimeout-integer-
var HubtypeService = /*#__PURE__*/function () {
function HubtypeService(_ref) {
var appId = _ref.appId,
user = _ref.user,
lastMessageId = _ref.lastMessageId,
lastMessageUpdateDate = _ref.lastMessageUpdateDate,
onEvent = _ref.onEvent,
unsentInputs = _ref.unsentInputs,
server = _ref.server;
(0, _classCallCheck2["default"])(this, HubtypeService);
this.appId = appId;
this.user = user || {};
this.lastMessageId = lastMessageId;
this.lastMessageUpdateDate = lastMessageUpdateDate;
this.onEvent = onEvent;
this.unsentInputs = unsentInputs;
this.server = server;
if (user.id && (lastMessageId || lastMessageUpdateDate)) {
this.init();
}
}
(0, _createClass2["default"])(HubtypeService, [{
key: "resolveServerConfig",
value: function resolveServerConfig() {
if (!this.server) {
return {
activityTimeout: ACTIVITY_TIMEOUT,
pongTimeout: PONG_TIMEOUT
};
}
return {
activityTimeout: this.server.activityTimeout || ACTIVITY_TIMEOUT,
pongTimeout: this.server.pongTimeout || PONG_TIMEOUT
};
}
}, {
key: "updateAuthHeaders",
value: function updateAuthHeaders() {
if (this.pusher) {
this.pusher.config.auth.headers = _objectSpread(_objectSpread({}, this.pusher.config.auth.headers), this.constructHeaders());
}
}
}, {
key: "init",
value: function init(user, lastMessageId, lastMessageUpdateDate) {
var _this = this;
if (user) this.user = user;
if (lastMessageId) this.lastMessageId = lastMessageId;
if (lastMessageUpdateDate) this.lastMessageUpdateDate = lastMessageUpdateDate;
if (this.pusher || !this.user.id || !this.appId) return null;
this.pusher = new _pusherJs["default"](_WEBCHAT_PUSHER_KEY_, _objectSpread({
cluster: 'eu',
authEndpoint: "".concat(_HUBTYPE_API_URL_, "/v1/provider_accounts/webhooks/webchat/").concat(this.appId, "/auth/"),
forceTLS: true,
auth: {
headers: this.constructHeaders()
}
}, this.resolveServerConfig()));
this.channel = this.pusher.subscribe(this.pusherChannel);
var connectionPromise = new Promise(function (resolve, reject) {
var cleanAndReject = function cleanAndReject(msg) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
clearTimeout(connectTimeout);
_this.destroyPusher();
reject(msg);
};
var connectTimeout = setTimeout(function () {
return cleanAndReject('Connection Timeout');
}, 10000);
_this.channel.bind('pusher:subscription_succeeded', function () {
// Once subscribed, we know that authentication has been done: https://pusher.com/docs/channels/server_api/authenticating-users
_this.onConnectionRegained();
clearTimeout(connectTimeout);
resolve();
});
_this.channel.bind('botonic_response', function (data) {
return _this.onPusherEvent(data);
});
_this.channel.bind('update_message_info', function (data) {
return _this.onPusherEvent(data);
});
_this.pusher.connection.bind('error', function (event) {
if (event.type == 'WebSocketError') _this.handleConnectionChange(false);else {
var errorMsg = event.error && event.error.data ? event.error.data.code || event.error.data.message : 'Connection error';
cleanAndReject("Pusher error (".concat(errorMsg, ")"));
}
});
});
this.pusher.connection.bind('state_change', function (states) {
if (states.current === 'connecting') _this.updateAuthHeaders();
if (states.current === 'connected') _this.handleConnectionChange(true);
if (states.current === 'unavailable') _this.handleConnectionChange(false);
});
return connectionPromise;
}
}, {
key: "constructHeaders",
value: function constructHeaders() {
var headers = {};
if (this.user && this.user.id) headers['X-BOTONIC-USER-ID'] = this.user.id;
if (this.lastMessageId) headers['X-BOTONIC-LAST-MESSAGE-ID'] = this.lastMessageId;
if (this.lastMessageUpdateDate) headers['X-BOTONIC-LAST-MESSAGE-UPDATE-DATE'] = this.lastMessageUpdateDate;
return headers;
}
}, {
key: "handleConnectionChange",
value: function handleConnectionChange(online) {
this.onPusherEvent({
action: 'connectionChange',
online: online
});
}
}, {
key: "onPusherEvent",
value: function onPusherEvent(event) {
if (this.onEvent && typeof this.onEvent === 'function') this.onEvent(event);
}
}, {
key: "pusherChannel",
get: function get() {
return "private-encrypted-".concat(this.appId, "-").concat(this.user.id);
}
}, {
key: "handleSentInput",
value: function handleSentInput(message) {
this.onEvent({
action: 'update_message_info',
message: {
id: message.id,
ack: 1
}
});
}
}, {
key: "handleUnsentInput",
value: function handleUnsentInput(message) {
this.onEvent({
action: 'update_message_info',
message: {
id: message.id,
ack: 0,
unsentInput: message
}
});
}
}, {
key: "postMessage",
value: function () {
var _postMessage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(user, message) {
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_context.next = 3;
return this.init(user);
case 3:
_context.next = 5;
return _axios["default"].post("".concat(_HUBTYPE_API_URL_, "/v1/provider_accounts/webhooks/webchat/").concat(this.appId, "/"), {
sender: this.user,
message: message
}, {
validateStatus: function validateStatus(status) {
return status === 200;
}
});
case 5:
this.handleSentInput(message);
_context.next = 11;
break;
case 8:
_context.prev = 8;
_context.t0 = _context["catch"](0);
this.handleUnsentInput(message);
case 11:
case "end":
return _context.stop();
}
}
}, _callee, this, [[0, 8]]);
}));
function postMessage(_x, _x2) {
return _postMessage.apply(this, arguments);
}
return postMessage;
}()
}, {
key: "destroyPusher",
value: function destroyPusher() {
if (!this.pusher) return;
this.pusher.disconnect();
this.pusher.unsubscribe(this.pusherChannel);
this.pusher.unbind_all();
this.pusher.channels = {};
this.pusher = null;
}
}, {
key: "onConnectionRegained",
value: function () {
var _onConnectionRegained = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() {
return _regenerator["default"].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.resendUnsentInputs();
case 2:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function onConnectionRegained() {
return _onConnectionRegained.apply(this, arguments);
}
return onConnectionRegained;
}()
}, {
key: "resendUnsentInputs",
value: function () {
var _resendUnsentInputs = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() {
var _iterator, _step, message;
return _regenerator["default"].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_iterator = _createForOfIteratorHelper(this.unsentInputs());
_context3.prev = 1;
_iterator.s();
case 3:
if ((_step = _iterator.n()).done) {
_context3.next = 11;
break;
}
message = _step.value;
_context3.t0 = message.unsentInput;
if (!_context3.t0) {
_context3.next = 9;
break;
}
_context3.next = 9;
return this.postMessage(this.user, message.unsentInput);
case 9:
_context3.next = 3;
break;
case 11:
_context3.next = 16;
break;
case 13:
_context3.prev = 13;
_context3.t1 = _context3["catch"](1);
_iterator.e(_context3.t1);
case 16:
_context3.prev = 16;
_iterator.f();
return _context3.finish(16);
case 19:
case "end":
return _context3.stop();
}
}
}, _callee3, this, [[1, 13, 16, 19]]);
}));
function resendUnsentInputs() |
return resendUnsentInputs;
}()
}], [{
key: "getWebchatVisibility",
value: function () {
var _getWebchatVisibility = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(_ref2) {
var appId;
return _regenerator["default"].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
appId = _ref2.appId;
return _context4.abrupt("return", _axios["default"].get("".concat(_HUBTYPE_API_URL_, "/v1/provider_accounts/").concat(appId, "/visibility/")));
case 2:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
function getWebchatVisibility(_x3) {
return _getWebchatVisibility.apply(this, arguments);
}
return getWebchatVisibility;
}()
}]);
return HubtypeService;
}();
exports.HubtypeService = HubtypeService;
//# sourceMappingURL=hubtype-service.js.map | {
return _resendUnsentInputs.apply(this, arguments);
} | identifier_body |
hubtype-service.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.HubtypeService = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _axios = _interopRequireDefault(require("axios"));
var _pusherJs = _interopRequireDefault(require("pusher-js"));
var _utils = require("./utils");
function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var _WEBCHAT_PUSHER_KEY_ = (0, _utils.getWebpackEnvVar)( // eslint-disable-next-line no-undef
typeof WEBCHAT_PUSHER_KEY !== 'undefined' && WEBCHAT_PUSHER_KEY, 'WEBCHAT_PUSHER_KEY', '434ca667c8e6cb3f641c');
var _HUBTYPE_API_URL_ = (0, _utils.getWebpackEnvVar)( // eslint-disable-next-line no-undef
typeof HUBTYPE_API_URL !== 'undefined' && HUBTYPE_API_URL, 'HUBTYPE_API_URL', 'https://api.hubtype.com');
var ACTIVITY_TIMEOUT = 20 * 1000; // https://pusher.com/docs/channels/using_channels/connection#activitytimeout-integer-
var PONG_TIMEOUT = 5 * 1000; // https://pusher.com/docs/channels/using_channels/connection#pongtimeout-integer-
var HubtypeService = /*#__PURE__*/function () {
function HubtypeService(_ref) {
var appId = _ref.appId,
user = _ref.user,
lastMessageId = _ref.lastMessageId,
lastMessageUpdateDate = _ref.lastMessageUpdateDate,
onEvent = _ref.onEvent,
unsentInputs = _ref.unsentInputs,
server = _ref.server;
(0, _classCallCheck2["default"])(this, HubtypeService);
this.appId = appId;
this.user = user || {};
this.lastMessageId = lastMessageId;
this.lastMessageUpdateDate = lastMessageUpdateDate;
this.onEvent = onEvent;
this.unsentInputs = unsentInputs;
this.server = server;
if (user.id && (lastMessageId || lastMessageUpdateDate)) {
this.init();
}
}
(0, _createClass2["default"])(HubtypeService, [{
key: "resolveServerConfig",
value: function resolveServerConfig() {
if (!this.server) {
return {
activityTimeout: ACTIVITY_TIMEOUT,
pongTimeout: PONG_TIMEOUT
};
}
return {
activityTimeout: this.server.activityTimeout || ACTIVITY_TIMEOUT,
pongTimeout: this.server.pongTimeout || PONG_TIMEOUT
};
}
}, {
key: "updateAuthHeaders",
value: function updateAuthHeaders() {
if (this.pusher) {
this.pusher.config.auth.headers = _objectSpread(_objectSpread({}, this.pusher.config.auth.headers), this.constructHeaders());
}
}
}, {
key: "init",
value: function init(user, lastMessageId, lastMessageUpdateDate) {
var _this = this;
if (user) this.user = user;
if (lastMessageId) this.lastMessageId = lastMessageId;
if (lastMessageUpdateDate) this.lastMessageUpdateDate = lastMessageUpdateDate;
if (this.pusher || !this.user.id || !this.appId) return null;
this.pusher = new _pusherJs["default"](_WEBCHAT_PUSHER_KEY_, _objectSpread({
cluster: 'eu',
authEndpoint: "".concat(_HUBTYPE_API_URL_, "/v1/provider_accounts/webhooks/webchat/").concat(this.appId, "/auth/"),
forceTLS: true,
auth: {
headers: this.constructHeaders()
}
}, this.resolveServerConfig()));
this.channel = this.pusher.subscribe(this.pusherChannel);
var connectionPromise = new Promise(function (resolve, reject) {
var cleanAndReject = function cleanAndReject(msg) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
clearTimeout(connectTimeout);
_this.destroyPusher();
reject(msg);
};
var connectTimeout = setTimeout(function () {
return cleanAndReject('Connection Timeout');
}, 10000);
_this.channel.bind('pusher:subscription_succeeded', function () {
// Once subscribed, we know that authentication has been done: https://pusher.com/docs/channels/server_api/authenticating-users
_this.onConnectionRegained();
clearTimeout(connectTimeout);
resolve();
});
_this.channel.bind('botonic_response', function (data) {
return _this.onPusherEvent(data);
});
_this.channel.bind('update_message_info', function (data) {
return _this.onPusherEvent(data);
});
_this.pusher.connection.bind('error', function (event) {
if (event.type == 'WebSocketError') _this.handleConnectionChange(false);else {
var errorMsg = event.error && event.error.data ? event.error.data.code || event.error.data.message : 'Connection error';
cleanAndReject("Pusher error (".concat(errorMsg, ")"));
}
});
});
this.pusher.connection.bind('state_change', function (states) {
if (states.current === 'connecting') _this.updateAuthHeaders();
if (states.current === 'connected') _this.handleConnectionChange(true);
if (states.current === 'unavailable') _this.handleConnectionChange(false);
});
return connectionPromise;
}
}, {
key: "constructHeaders",
value: function constructHeaders() {
var headers = {};
if (this.user && this.user.id) headers['X-BOTONIC-USER-ID'] = this.user.id;
if (this.lastMessageId) headers['X-BOTONIC-LAST-MESSAGE-ID'] = this.lastMessageId;
if (this.lastMessageUpdateDate) headers['X-BOTONIC-LAST-MESSAGE-UPDATE-DATE'] = this.lastMessageUpdateDate;
return headers;
}
}, {
key: "handleConnectionChange",
value: function handleConnectionChange(online) {
this.onPusherEvent({
action: 'connectionChange',
online: online
});
}
}, {
key: "onPusherEvent",
value: function onPusherEvent(event) {
if (this.onEvent && typeof this.onEvent === 'function') this.onEvent(event);
}
}, {
key: "pusherChannel",
get: function get() {
return "private-encrypted-".concat(this.appId, "-").concat(this.user.id);
}
}, {
key: "handleSentInput",
value: function handleSentInput(message) {
this.onEvent({
action: 'update_message_info',
message: {
id: message.id,
ack: 1
}
});
}
}, {
key: "handleUnsentInput",
value: function handleUnsentInput(message) {
this.onEvent({
action: 'update_message_info',
message: {
id: message.id,
ack: 0,
unsentInput: message
}
});
}
}, {
key: "postMessage",
value: function () {
var _postMessage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(user, message) {
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.prev = 0;
_context.next = 3;
return this.init(user);
case 3:
_context.next = 5;
return _axios["default"].post("".concat(_HUBTYPE_API_URL_, "/v1/provider_accounts/webhooks/webchat/").concat(this.appId, "/"), {
sender: this.user,
message: message
}, {
validateStatus: function validateStatus(status) {
return status === 200;
}
});
case 5:
this.handleSentInput(message);
_context.next = 11;
break;
case 8:
_context.prev = 8;
_context.t0 = _context["catch"](0);
this.handleUnsentInput(message);
case 11:
case "end":
return _context.stop();
}
}
}, _callee, this, [[0, 8]]);
}));
function postMessage(_x, _x2) {
return _postMessage.apply(this, arguments);
}
return postMessage;
}()
}, {
key: "destroyPusher",
value: function destroyPusher() {
if (!this.pusher) return;
this.pusher.disconnect();
this.pusher.unsubscribe(this.pusherChannel);
this.pusher.unbind_all();
this.pusher.channels = {};
this.pusher = null;
}
}, {
key: "onConnectionRegained",
value: function () {
var _onConnectionRegained = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() {
return _regenerator["default"].wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.resendUnsentInputs();
case 2:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function onConnectionRegained() {
return _onConnectionRegained.apply(this, arguments);
}
return onConnectionRegained;
}()
}, {
key: "resendUnsentInputs",
value: function () {
var _resendUnsentInputs = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() {
var _iterator, _step, message;
return _regenerator["default"].wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_iterator = _createForOfIteratorHelper(this.unsentInputs());
_context3.prev = 1;
_iterator.s();
case 3:
if ((_step = _iterator.n()).done) {
_context3.next = 11;
break;
}
message = _step.value;
_context3.t0 = message.unsentInput;
if (!_context3.t0) {
_context3.next = 9;
break;
}
_context3.next = 9;
return this.postMessage(this.user, message.unsentInput);
case 9:
_context3.next = 3;
break;
case 11:
_context3.next = 16;
break;
case 13:
_context3.prev = 13;
_context3.t1 = _context3["catch"](1);
_iterator.e(_context3.t1);
case 16:
_context3.prev = 16;
_iterator.f();
return _context3.finish(16);
case 19:
case "end":
return _context3.stop();
}
}
}, _callee3, this, [[1, 13, 16, 19]]);
}));
function | () {
return _resendUnsentInputs.apply(this, arguments);
}
return resendUnsentInputs;
}()
}], [{
key: "getWebchatVisibility",
value: function () {
var _getWebchatVisibility = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(_ref2) {
var appId;
return _regenerator["default"].wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
appId = _ref2.appId;
return _context4.abrupt("return", _axios["default"].get("".concat(_HUBTYPE_API_URL_, "/v1/provider_accounts/").concat(appId, "/visibility/")));
case 2:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
function getWebchatVisibility(_x3) {
return _getWebchatVisibility.apply(this, arguments);
}
return getWebchatVisibility;
}()
}]);
return HubtypeService;
}();
exports.HubtypeService = HubtypeService;
//# sourceMappingURL=hubtype-service.js.map | resendUnsentInputs | identifier_name |
main_test_xgb.py | #!/usr/bin/env python
'''
File name: main_hd_data.py
Author: Guillaume Viejo
Date created: 06/03/2017
Python Version: 2.7
To test the xbg algorithm and to see the splits
'''
import warnings
import pandas as pd
import scipy.io
import numpy as np
# Should not import fonctions if already using tensorflow for something else
from fonctions import *
import sys, os
import itertools
import cPickle as pickle
#####################################################################
# DATA LOADING
#####################################################################
# adrien_data = scipy.io.loadmat(os.path.expanduser('~/Dropbox (Peyrache Lab)/Peyrache Lab Team Folder/Data/HDCellData/data_test_boosted_tree.mat'))
adrien_data = scipy.io.loadmat(os.path.expanduser('../data/sessions/wake/boosted_tree.Mouse25-140124.mat'))
# m1_imported = scipy.io.loadmat('/home/guillaume/spykesML/data/m1_stevenson_2011.mat')
#####################################################################
# DATA ENGINEERING
#####################################################################
data = pd.DataFrame()
data['time'] = np.arange(len(adrien_data['Ang'])) # TODO : import real time from matlab script
data['ang'] = adrien_data['Ang'].flatten() # angular direction of the animal head
data['x'] = adrien_data['X'].flatten() # x position of the animal
data['y'] = adrien_data['Y'].flatten() # y position of the animal
data['vel'] = adrien_data['speed'].flatten() # velocity of the animal
# Engineering features
data['cos'] = np.cos(adrien_data['Ang'].flatten()) # cosinus of angular direction
data['sin'] = np.sin(adrien_data['Ang'].flatten()) # sinus of angular direction
# Firing data
for i in xrange(adrien_data['Pos'].shape[1]): data['Pos'+'.'+str(i)] = adrien_data['Pos'][:,i].astype('float')
for i in xrange(adrien_data['ADn'].shape[1]): data['ADn'+'.'+str(i)] = adrien_data['ADn'][:,i].astype('float')
#RANDOM DATA
for i in xrange(5):
data['rand'+str(i)] = np.random.uniform(0, 2*np.pi, len(adrien_data['Ang']))
#######################################################################
# FONCTIONS DEFINITIONS
#######################################################################
def extract_tree_threshold(trees):
n = len(trees.get_dump())
thr = {}
for t in xrange(n):
gv = xgb.to_graphviz(trees, num_trees=t)
body = gv.body
for i in xrange(len(body)):
for l in body[i].split('"'):
if 'f' in l and '<' in l:
tmp = l.split("<")
if thr.has_key(tmp[0]):
thr[tmp[0]].append(float(tmp[1]))
else:
thr[tmp[0]] = [float(tmp[1])]
for k in thr.iterkeys():
thr[k] = np.sort(np.array(thr[k]))
return thr
def tuning_curve(x, f, nb_bins):
bins = np.linspace(x.min(), x.max()+1e-8, nb_bins+1)
index = np.digitize(x, bins).flatten()
tcurve = np.array([np.mean(f[index == i]) for i in xrange(1, nb_bins+1)])
x = bins[0:-1] + (bins[1]-bins[0])/2.
return (x, tcurve)
def test_features(features, targets, learners = ['glm_pyglmnet', 'nn', 'xgb_run', 'ens']):
X = data[features].values
Y = np.vstack(data[targets].values)
Models = {method:{'PR2':[],'Yt_hat':[]} for method in learners}
learners_ = list(learners)
# print learners_
for i in xrange(Y.shape[1]):
y = Y[:,i]
# TODO : make sure that 'ens' is the last learner
for method in learners_:
print('Running '+method+'...')
print 'targets ', targets[i]
Yt_hat, PR2 = fit_cv(X, y, algorithm = method, n_cv=8, verbose=1)
Models[method]['Yt_hat'].append(Yt_hat)
Models[method]['PR2'].append(PR2)
for m in Models.iterkeys():
Models[m]['Yt_hat'] = np.array(Models[m]['Yt_hat'])
Models[m]['PR2'] = np.array(Models[m]['PR2'])
return Models
#####################################################################
# COMBINATIONS DEFINITION
#####################################################################
combination = {
14: {
'features' : ['rand0', 'rand1', 'ang', 'rand2', 'rand3'],
# 'targets' : [i for i in list(data) if i.split(".")[0] in ['Pos', 'ADn']],
'targets' : ['ADn.0'],
},
}
#####################################################################
# LEARNING XGB
#####################################################################
bsts = {i:{} for i in combination.iterkeys()} # to keep the boosted tree
params = {'objective': "count:poisson", #for poisson output
'eval_metric': "logloss", #loglikelihood loss
'seed': 2925, #for reproducibility
'silent': 0,
'learning_rate': 0.1,
'min_child_weight': 2, 'n_estimators': 1,
'subsample': 0.6, 'max_depth': 5, 'gamma': 0.5,
'tree_method':'exact'}
num_round = 600
X = data[['rand0', 'rand1', 'ang', 'rand2', 'rand3']].values
Y = data['ADn.0']
dtrain = xgb.DMatrix(np.vstack(X), label = np.vstack(Y))
bst = xgb.train(params, dtrain, num_round)
a = extract_tree_threshold(bst)
sys.exit()
# methods = ['xgb_run']
# for k in np.sort(combination.keys()):
# features = combination[k]['features']
# targets = combination[k]['targets']
# results = test_features(features, targets, methods)
# sys.exit()
##################################################################### | # TUNING CURVE
#####################################################################
X = data['ang'].values
Yall = data[[i for i in list(data) if i.split(".")[0] in ['Pos', 'ADn']]].values
tuningc = {targets[i]:tuning_curve(X, Yall[:,i], nb_bins = 100) for i in xrange(Yall.shape[1])}
sys.exit()
#####################################################################
# EXTRACT TREE STRUCTURE
#####################################################################
thresholds = {}
for i in bsts.iterkeys():
thresholds[i] = {}
for j in bsts[i].iterkeys():
thresholds[i][j] = extract_tree_threshold(bsts[i][j])
#####################################################################
# plot 11 (2.1)
#####################################################################
order = ['Pos.8', 'Pos.9', 'Pos.10', 'ADn.9', 'ADn.10', 'ADn.11']
rcParams.update({ 'backend':'pdf',
'savefig.pad_inches':0.1,
'font.size':8 })
figure(figsize = (12,15))
for k, i in zip(order, xrange(1,7)):
subplot(3,2,i)
[axvline(j, alpha = 0.1, color = 'grey') for j in thresholds[11][k]['f0']]
plot(tuningc[k][0], tuningc[k][1])
title(k)
xlim(0, 2*np.pi)
xlabel('Angle (rad)')
ylabel('f')
simpleaxis(gca())
subplots_adjust(hspace = 0.3, wspace = 0.3)
savefig(combination[11]['figure'], dpi = 900, bbox_inches = 'tight')
#####################################################################
# plot 12 (2.2)
#####################################################################
figure(figsize = (12,14))
for k, i in zip(order, xrange(1,7)):
subplot(3,2,i)
[axvline(j, alpha = 0.1, color = 'grey') for j in thresholds[12][k]['f0']]
[axhline(j, alpha = 0.1, color = 'grey') for j in thresholds[12][k]['f1']]
plot(data['x'].values, data['y'].values, '-', alpha = 0.3)
xlabel('x')
ylabel('y')
title(k)
simpleaxis(gca())
subplots_adjust(hspace = 0.3, wspace = 0.3)
savefig(combination[12]['figure'], dpi = 900, bbox_inches = 'tight')
#####################################################################
# plot 13 (2.3)
#####################################################################
trans = {'f0':'Ang','f1':'x','f2':'y'}
figure(figsize = (12,17))
for k, i in zip(order, xrange(1,18,3)):
subplot(6,3,i)
count = np.array([len(thresholds[13][k][f]) for f in thresholds[13][k].keys()])
name = np.array([trans[f] for f in thresholds[13][k].keys()])
bar(left = np.arange(len(count)), height = count, tick_label = name, align = 'center', facecolor = 'grey')
ylabel('Number of split')
simpleaxis(gca())
subplot(6,3,i+1)
[axvline(j, alpha = 0.1, color = 'grey') for j in thresholds[13][k]['f0']]
plot(tuningc[k][0], tuningc[k][1])
title(k)
xlim(0, 2*np.pi)
xlabel('Angle (rad)')
ylabel('f')
simpleaxis(gca())
subplot(6,3,i+2)
[axvline(j, alpha = 0.1, color = 'grey') for j in thresholds[13][k]['f1']]
[axhline(j, alpha = 0.1, color = 'grey') for j in thresholds[13][k]['f2']]
plot(data['x'].values, data['y'].values, '-', alpha = 0.5)
xlabel('x')
ylabel('y')
title(k)
simpleaxis(gca())
subplots_adjust(hspace = 0.3, wspace = 0.3)
savefig(combination[13]['figure'], dpi = 900, bbox_inches = 'tight')
#####################################################################
# plot 14 (2.4)
#####################################################################
angdens = {}
for k in thresholds[14].iterkeys():
thr = np.copy(thresholds[14][k]['f0'])
tun = np.copy(tuningc[k])
bins = np.linspace(0, 2.*np.pi+1e-8, 20+1)
hist, bin_edges = np.histogram(thr, bins, normed = True)
x = bins[0:-1] + (bins[1]-bins[0])/2.
x[x>np.pi] -= 2*np.pi
# correct x with offset of tuning curve
offset = tun[0][np.argmax(tun[1])]
if offset <= np.pi :
x -= offset
else :
x += (2.*np.pi - offset)
x[x>np.pi] -= 2*np.pi
x[x<= -np.pi] += 2*np.pi
hist = hist[np.argsort(x)]
angdens[k] = (np.sort(x), hist)
xydens = {}
for k in thresholds[15].iterkeys():
xt = np.copy(thresholds[15][k]['f0'])
yt = np.copy(thresholds[15][k]['f1'])
xbins = np.linspace(20, 100, 20+1)
ybins = np.linspace(0, 80, 20+1)
xh, bin_edges = np.histogram(xt, xbins, normed = True)
yh, bin_edges = np.histogram(yt, ybins, normed = True)
x = ybins[0:-1] + (ybins[1]-ybins[0])/2.
xydens[k] = (x, xh, yh)
rcParams.update({ 'backend':'pdf',
'savefig.pad_inches':0.1,
'font.size':6 })
figure(figsize = (4, 4))
subplot(4,2,1)
keys = [k for k in angdens.iterkeys() if 'ADn' in k]
for k in keys:
plot(angdens[k][0], angdens[k][1], '-', color = 'blue', linewidth = 0.4)
ylabel("Density of splits \n to center")
xlabel("Angle (rad)")
title("ADn")
simpleaxis(gca())
subplot(4,2,2)
keys = [k for k in angdens.iterkeys() if 'Pos' in k]
for k in keys:
plot(angdens[k][0], angdens[k][1], '-', color = 'green', linewidth = 0.4)
ylabel("Density of splits \n to center")
xlabel("Angle (rad)")
title("Pos")
simpleaxis(gca())
start = 3
for i,l in zip([1, 2], ['x', 'y']):
subplot(4,2,start)
keys = [k for k in xydens.iterkeys() if 'ADn' in k]
for k in keys:
plot(xydens[k][0], xydens[k][i], '-', color = 'blue', linewidth = 0.4)
ylabel("Density of splits")
xlabel(l+" pos")
simpleaxis(gca())
subplot(4,2,start+1)
keys = [k for k in xydens.iterkeys() if 'Pos' in k]
for k in keys:
plot(xydens[k][0], xydens[k][i], '-', color = 'green', linewidth = 0.4)
ylabel("Density of splits")
xlabel(l+" pos")
simpleaxis(gca())
start+=2
for s in ['ADn', 'Pos']:
subplot(4,2,start)
keys = [k for k in xydens.iterkeys() if s in k]
tmp = np.array([np.vstack(xydens[k][1])*xydens[k][2] for k in keys]).mean(0)
imshow(tmp, aspect = 'auto')
xlabel("x")
ylabel("y")
start+=1
subplots_adjust(hspace = 0.7, wspace = 0.7)
savefig(combination[15]['figure'], dpi = 900, bbox_inches = 'tight') | random_line_split | |
main_test_xgb.py | #!/usr/bin/env python
'''
File name: main_hd_data.py
Author: Guillaume Viejo
Date created: 06/03/2017
Python Version: 2.7
To test the xbg algorithm and to see the splits
'''
import warnings
import pandas as pd
import scipy.io
import numpy as np
# Should not import fonctions if already using tensorflow for something else
from fonctions import *
import sys, os
import itertools
import cPickle as pickle
#####################################################################
# DATA LOADING
#####################################################################
# adrien_data = scipy.io.loadmat(os.path.expanduser('~/Dropbox (Peyrache Lab)/Peyrache Lab Team Folder/Data/HDCellData/data_test_boosted_tree.mat'))
adrien_data = scipy.io.loadmat(os.path.expanduser('../data/sessions/wake/boosted_tree.Mouse25-140124.mat'))
# m1_imported = scipy.io.loadmat('/home/guillaume/spykesML/data/m1_stevenson_2011.mat')
#####################################################################
# DATA ENGINEERING
#####################################################################
data = pd.DataFrame()
data['time'] = np.arange(len(adrien_data['Ang'])) # TODO : import real time from matlab script
data['ang'] = adrien_data['Ang'].flatten() # angular direction of the animal head
data['x'] = adrien_data['X'].flatten() # x position of the animal
data['y'] = adrien_data['Y'].flatten() # y position of the animal
data['vel'] = adrien_data['speed'].flatten() # velocity of the animal
# Engineering features
data['cos'] = np.cos(adrien_data['Ang'].flatten()) # cosinus of angular direction
data['sin'] = np.sin(adrien_data['Ang'].flatten()) # sinus of angular direction
# Firing data
for i in xrange(adrien_data['Pos'].shape[1]): data['Pos'+'.'+str(i)] = adrien_data['Pos'][:,i].astype('float')
for i in xrange(adrien_data['ADn'].shape[1]): data['ADn'+'.'+str(i)] = adrien_data['ADn'][:,i].astype('float')
#RANDOM DATA
for i in xrange(5):
data['rand'+str(i)] = np.random.uniform(0, 2*np.pi, len(adrien_data['Ang']))
#######################################################################
# FONCTIONS DEFINITIONS
#######################################################################
def extract_tree_threshold(trees):
n = len(trees.get_dump())
thr = {}
for t in xrange(n):
gv = xgb.to_graphviz(trees, num_trees=t)
body = gv.body
for i in xrange(len(body)):
for l in body[i].split('"'):
if 'f' in l and '<' in l:
tmp = l.split("<")
if thr.has_key(tmp[0]):
thr[tmp[0]].append(float(tmp[1]))
else:
thr[tmp[0]] = [float(tmp[1])]
for k in thr.iterkeys():
thr[k] = np.sort(np.array(thr[k]))
return thr
def tuning_curve(x, f, nb_bins):
bins = np.linspace(x.min(), x.max()+1e-8, nb_bins+1)
index = np.digitize(x, bins).flatten()
tcurve = np.array([np.mean(f[index == i]) for i in xrange(1, nb_bins+1)])
x = bins[0:-1] + (bins[1]-bins[0])/2.
return (x, tcurve)
def | (features, targets, learners = ['glm_pyglmnet', 'nn', 'xgb_run', 'ens']):
X = data[features].values
Y = np.vstack(data[targets].values)
Models = {method:{'PR2':[],'Yt_hat':[]} for method in learners}
learners_ = list(learners)
# print learners_
for i in xrange(Y.shape[1]):
y = Y[:,i]
# TODO : make sure that 'ens' is the last learner
for method in learners_:
print('Running '+method+'...')
print 'targets ', targets[i]
Yt_hat, PR2 = fit_cv(X, y, algorithm = method, n_cv=8, verbose=1)
Models[method]['Yt_hat'].append(Yt_hat)
Models[method]['PR2'].append(PR2)
for m in Models.iterkeys():
Models[m]['Yt_hat'] = np.array(Models[m]['Yt_hat'])
Models[m]['PR2'] = np.array(Models[m]['PR2'])
return Models
#####################################################################
# COMBINATIONS DEFINITION
#####################################################################
combination = {
14: {
'features' : ['rand0', 'rand1', 'ang', 'rand2', 'rand3'],
# 'targets' : [i for i in list(data) if i.split(".")[0] in ['Pos', 'ADn']],
'targets' : ['ADn.0'],
},
}
#####################################################################
# LEARNING XGB
#####################################################################
bsts = {i:{} for i in combination.iterkeys()} # to keep the boosted tree
params = {'objective': "count:poisson", #for poisson output
'eval_metric': "logloss", #loglikelihood loss
'seed': 2925, #for reproducibility
'silent': 0,
'learning_rate': 0.1,
'min_child_weight': 2, 'n_estimators': 1,
'subsample': 0.6, 'max_depth': 5, 'gamma': 0.5,
'tree_method':'exact'}
num_round = 600
X = data[['rand0', 'rand1', 'ang', 'rand2', 'rand3']].values
Y = data['ADn.0']
dtrain = xgb.DMatrix(np.vstack(X), label = np.vstack(Y))
bst = xgb.train(params, dtrain, num_round)
a = extract_tree_threshold(bst)
sys.exit()
# methods = ['xgb_run']
# for k in np.sort(combination.keys()):
# features = combination[k]['features']
# targets = combination[k]['targets']
# results = test_features(features, targets, methods)
# sys.exit()
#####################################################################
# TUNING CURVE
#####################################################################
X = data['ang'].values
Yall = data[[i for i in list(data) if i.split(".")[0] in ['Pos', 'ADn']]].values
tuningc = {targets[i]:tuning_curve(X, Yall[:,i], nb_bins = 100) for i in xrange(Yall.shape[1])}
sys.exit()
#####################################################################
# EXTRACT TREE STRUCTURE
#####################################################################
thresholds = {}
for i in bsts.iterkeys():
thresholds[i] = {}
for j in bsts[i].iterkeys():
thresholds[i][j] = extract_tree_threshold(bsts[i][j])
#####################################################################
# plot 11 (2.1)
#####################################################################
order = ['Pos.8', 'Pos.9', 'Pos.10', 'ADn.9', 'ADn.10', 'ADn.11']
rcParams.update({ 'backend':'pdf',
'savefig.pad_inches':0.1,
'font.size':8 })
figure(figsize = (12,15))
for k, i in zip(order, xrange(1,7)):
subplot(3,2,i)
[axvline(j, alpha = 0.1, color = 'grey') for j in thresholds[11][k]['f0']]
plot(tuningc[k][0], tuningc[k][1])
title(k)
xlim(0, 2*np.pi)
xlabel('Angle (rad)')
ylabel('f')
simpleaxis(gca())
subplots_adjust(hspace = 0.3, wspace = 0.3)
savefig(combination[11]['figure'], dpi = 900, bbox_inches = 'tight')
#####################################################################
# plot 12 (2.2)
#####################################################################
figure(figsize = (12,14))
for k, i in zip(order, xrange(1,7)):
subplot(3,2,i)
[axvline(j, alpha = 0.1, color = 'grey') for j in thresholds[12][k]['f0']]
[axhline(j, alpha = 0.1, color = 'grey') for j in thresholds[12][k]['f1']]
plot(data['x'].values, data['y'].values, '-', alpha = 0.3)
xlabel('x')
ylabel('y')
title(k)
simpleaxis(gca())
subplots_adjust(hspace = 0.3, wspace = 0.3)
savefig(combination[12]['figure'], dpi = 900, bbox_inches = 'tight')
#####################################################################
# plot 13 (2.3)
#####################################################################
trans = {'f0':'Ang','f1':'x','f2':'y'}
figure(figsize = (12,17))
for k, i in zip(order, xrange(1,18,3)):
subplot(6,3,i)
count = np.array([len(thresholds[13][k][f]) for f in thresholds[13][k].keys()])
name = np.array([trans[f] for f in thresholds[13][k].keys()])
bar(left = np.arange(len(count)), height = count, tick_label = name, align = 'center', facecolor = 'grey')
ylabel('Number of split')
simpleaxis(gca())
subplot(6,3,i+1)
[axvline(j, alpha = 0.1, color = 'grey') for j in thresholds[13][k]['f0']]
plot(tuningc[k][0], tuningc[k][1])
title(k)
xlim(0, 2*np.pi)
xlabel('Angle (rad)')
ylabel('f')
simpleaxis(gca())
subplot(6,3,i+2)
[axvline(j, alpha = 0.1, color = 'grey') for j in thresholds[13][k]['f1']]
[axhline(j, alpha = 0.1, color = 'grey') for j in thresholds[13][k]['f2']]
plot(data['x'].values, data['y'].values, '-', alpha = 0.5)
xlabel('x')
ylabel('y')
title(k)
simpleaxis(gca())
subplots_adjust(hspace = 0.3, wspace = 0.3)
savefig(combination[13]['figure'], dpi = 900, bbox_inches = 'tight')
#####################################################################
# plot 14 (2.4)
#####################################################################
angdens = {}
for k in thresholds[14].iterkeys():
thr = np.copy(thresholds[14][k]['f0'])
tun = np.copy(tuningc[k])
bins = np.linspace(0, 2.*np.pi+1e-8, 20+1)
hist, bin_edges = np.histogram(thr, bins, normed = True)
x = bins[0:-1] + (bins[1]-bins[0])/2.
x[x>np.pi] -= 2*np.pi
# correct x with offset of tuning curve
offset = tun[0][np.argmax(tun[1])]
if offset <= np.pi :
x -= offset
else :
x += (2.*np.pi - offset)
x[x>np.pi] -= 2*np.pi
x[x<= -np.pi] += 2*np.pi
hist = hist[np.argsort(x)]
angdens[k] = (np.sort(x), hist)
xydens = {}
for k in thresholds[15].iterkeys():
xt = np.copy(thresholds[15][k]['f0'])
yt = np.copy(thresholds[15][k]['f1'])
xbins = np.linspace(20, 100, 20+1)
ybins = np.linspace(0, 80, 20+1)
xh, bin_edges = np.histogram(xt, xbins, normed = True)
yh, bin_edges = np.histogram(yt, ybins, normed = True)
x = ybins[0:-1] + (ybins[1]-ybins[0])/2.
xydens[k] = (x, xh, yh)
rcParams.update({ 'backend':'pdf',
'savefig.pad_inches':0.1,
'font.size':6 })
figure(figsize = (4, 4))
subplot(4,2,1)
keys = [k for k in angdens.iterkeys() if 'ADn' in k]
for k in keys:
plot(angdens[k][0], angdens[k][1], '-', color = 'blue', linewidth = 0.4)
ylabel("Density of splits \n to center")
xlabel("Angle (rad)")
title("ADn")
simpleaxis(gca())
subplot(4,2,2)
keys = [k for k in angdens.iterkeys() if 'Pos' in k]
for k in keys:
plot(angdens[k][0], angdens[k][1], '-', color = 'green', linewidth = 0.4)
ylabel("Density of splits \n to center")
xlabel("Angle (rad)")
title("Pos")
simpleaxis(gca())
start = 3
for i,l in zip([1, 2], ['x', 'y']):
subplot(4,2,start)
keys = [k for k in xydens.iterkeys() if 'ADn' in k]
for k in keys:
plot(xydens[k][0], xydens[k][i], '-', color = 'blue', linewidth = 0.4)
ylabel("Density of splits")
xlabel(l+" pos")
simpleaxis(gca())
subplot(4,2,start+1)
keys = [k for k in xydens.iterkeys() if 'Pos' in k]
for k in keys:
plot(xydens[k][0], xydens[k][i], '-', color = 'green', linewidth = 0.4)
ylabel("Density of splits")
xlabel(l+" pos")
simpleaxis(gca())
start+=2
for s in ['ADn', 'Pos']:
subplot(4,2,start)
keys = [k for k in xydens.iterkeys() if s in k]
tmp = np.array([np.vstack(xydens[k][1])*xydens[k][2] for k in keys]).mean(0)
imshow(tmp, aspect = 'auto')
xlabel("x")
ylabel("y")
start+=1
subplots_adjust(hspace = 0.7, wspace = 0.7)
savefig(combination[15]['figure'], dpi = 900, bbox_inches = 'tight')
| test_features | identifier_name |
main_test_xgb.py | #!/usr/bin/env python
'''
File name: main_hd_data.py
Author: Guillaume Viejo
Date created: 06/03/2017
Python Version: 2.7
To test the xbg algorithm and to see the splits
'''
import warnings
import pandas as pd
import scipy.io
import numpy as np
# Should not import fonctions if already using tensorflow for something else
from fonctions import *
import sys, os
import itertools
import cPickle as pickle
#####################################################################
# DATA LOADING
#####################################################################
# adrien_data = scipy.io.loadmat(os.path.expanduser('~/Dropbox (Peyrache Lab)/Peyrache Lab Team Folder/Data/HDCellData/data_test_boosted_tree.mat'))
adrien_data = scipy.io.loadmat(os.path.expanduser('../data/sessions/wake/boosted_tree.Mouse25-140124.mat'))
# m1_imported = scipy.io.loadmat('/home/guillaume/spykesML/data/m1_stevenson_2011.mat')
#####################################################################
# DATA ENGINEERING
#####################################################################
data = pd.DataFrame()
data['time'] = np.arange(len(adrien_data['Ang'])) # TODO : import real time from matlab script
data['ang'] = adrien_data['Ang'].flatten() # angular direction of the animal head
data['x'] = adrien_data['X'].flatten() # x position of the animal
data['y'] = adrien_data['Y'].flatten() # y position of the animal
data['vel'] = adrien_data['speed'].flatten() # velocity of the animal
# Engineering features
data['cos'] = np.cos(adrien_data['Ang'].flatten()) # cosinus of angular direction
data['sin'] = np.sin(adrien_data['Ang'].flatten()) # sinus of angular direction
# Firing data
for i in xrange(adrien_data['Pos'].shape[1]): data['Pos'+'.'+str(i)] = adrien_data['Pos'][:,i].astype('float')
for i in xrange(adrien_data['ADn'].shape[1]): data['ADn'+'.'+str(i)] = adrien_data['ADn'][:,i].astype('float')
#RANDOM DATA
for i in xrange(5):
data['rand'+str(i)] = np.random.uniform(0, 2*np.pi, len(adrien_data['Ang']))
#######################################################################
# FONCTIONS DEFINITIONS
#######################################################################
def extract_tree_threshold(trees):
|
def tuning_curve(x, f, nb_bins):
bins = np.linspace(x.min(), x.max()+1e-8, nb_bins+1)
index = np.digitize(x, bins).flatten()
tcurve = np.array([np.mean(f[index == i]) for i in xrange(1, nb_bins+1)])
x = bins[0:-1] + (bins[1]-bins[0])/2.
return (x, tcurve)
def test_features(features, targets, learners = ['glm_pyglmnet', 'nn', 'xgb_run', 'ens']):
X = data[features].values
Y = np.vstack(data[targets].values)
Models = {method:{'PR2':[],'Yt_hat':[]} for method in learners}
learners_ = list(learners)
# print learners_
for i in xrange(Y.shape[1]):
y = Y[:,i]
# TODO : make sure that 'ens' is the last learner
for method in learners_:
print('Running '+method+'...')
print 'targets ', targets[i]
Yt_hat, PR2 = fit_cv(X, y, algorithm = method, n_cv=8, verbose=1)
Models[method]['Yt_hat'].append(Yt_hat)
Models[method]['PR2'].append(PR2)
for m in Models.iterkeys():
Models[m]['Yt_hat'] = np.array(Models[m]['Yt_hat'])
Models[m]['PR2'] = np.array(Models[m]['PR2'])
return Models
#####################################################################
# COMBINATIONS DEFINITION
#####################################################################
combination = {
14: {
'features' : ['rand0', 'rand1', 'ang', 'rand2', 'rand3'],
# 'targets' : [i for i in list(data) if i.split(".")[0] in ['Pos', 'ADn']],
'targets' : ['ADn.0'],
},
}
#####################################################################
# LEARNING XGB
#####################################################################
bsts = {i:{} for i in combination.iterkeys()} # to keep the boosted tree
params = {'objective': "count:poisson", #for poisson output
'eval_metric': "logloss", #loglikelihood loss
'seed': 2925, #for reproducibility
'silent': 0,
'learning_rate': 0.1,
'min_child_weight': 2, 'n_estimators': 1,
'subsample': 0.6, 'max_depth': 5, 'gamma': 0.5,
'tree_method':'exact'}
num_round = 600
X = data[['rand0', 'rand1', 'ang', 'rand2', 'rand3']].values
Y = data['ADn.0']
dtrain = xgb.DMatrix(np.vstack(X), label = np.vstack(Y))
bst = xgb.train(params, dtrain, num_round)
a = extract_tree_threshold(bst)
sys.exit()
# methods = ['xgb_run']
# for k in np.sort(combination.keys()):
# features = combination[k]['features']
# targets = combination[k]['targets']
# results = test_features(features, targets, methods)
# sys.exit()
#####################################################################
# TUNING CURVE
#####################################################################
X = data['ang'].values
Yall = data[[i for i in list(data) if i.split(".")[0] in ['Pos', 'ADn']]].values
tuningc = {targets[i]:tuning_curve(X, Yall[:,i], nb_bins = 100) for i in xrange(Yall.shape[1])}
sys.exit()
#####################################################################
# EXTRACT TREE STRUCTURE
#####################################################################
thresholds = {}
for i in bsts.iterkeys():
thresholds[i] = {}
for j in bsts[i].iterkeys():
thresholds[i][j] = extract_tree_threshold(bsts[i][j])
#####################################################################
# plot 11 (2.1)
#####################################################################
order = ['Pos.8', 'Pos.9', 'Pos.10', 'ADn.9', 'ADn.10', 'ADn.11']
rcParams.update({ 'backend':'pdf',
'savefig.pad_inches':0.1,
'font.size':8 })
figure(figsize = (12,15))
for k, i in zip(order, xrange(1,7)):
subplot(3,2,i)
[axvline(j, alpha = 0.1, color = 'grey') for j in thresholds[11][k]['f0']]
plot(tuningc[k][0], tuningc[k][1])
title(k)
xlim(0, 2*np.pi)
xlabel('Angle (rad)')
ylabel('f')
simpleaxis(gca())
subplots_adjust(hspace = 0.3, wspace = 0.3)
savefig(combination[11]['figure'], dpi = 900, bbox_inches = 'tight')
#####################################################################
# plot 12 (2.2)
#####################################################################
figure(figsize = (12,14))
for k, i in zip(order, xrange(1,7)):
subplot(3,2,i)
[axvline(j, alpha = 0.1, color = 'grey') for j in thresholds[12][k]['f0']]
[axhline(j, alpha = 0.1, color = 'grey') for j in thresholds[12][k]['f1']]
plot(data['x'].values, data['y'].values, '-', alpha = 0.3)
xlabel('x')
ylabel('y')
title(k)
simpleaxis(gca())
subplots_adjust(hspace = 0.3, wspace = 0.3)
savefig(combination[12]['figure'], dpi = 900, bbox_inches = 'tight')
#####################################################################
# plot 13 (2.3)
#####################################################################
trans = {'f0':'Ang','f1':'x','f2':'y'}
figure(figsize = (12,17))
for k, i in zip(order, xrange(1,18,3)):
subplot(6,3,i)
count = np.array([len(thresholds[13][k][f]) for f in thresholds[13][k].keys()])
name = np.array([trans[f] for f in thresholds[13][k].keys()])
bar(left = np.arange(len(count)), height = count, tick_label = name, align = 'center', facecolor = 'grey')
ylabel('Number of split')
simpleaxis(gca())
subplot(6,3,i+1)
[axvline(j, alpha = 0.1, color = 'grey') for j in thresholds[13][k]['f0']]
plot(tuningc[k][0], tuningc[k][1])
title(k)
xlim(0, 2*np.pi)
xlabel('Angle (rad)')
ylabel('f')
simpleaxis(gca())
subplot(6,3,i+2)
[axvline(j, alpha = 0.1, color = 'grey') for j in thresholds[13][k]['f1']]
[axhline(j, alpha = 0.1, color = 'grey') for j in thresholds[13][k]['f2']]
plot(data['x'].values, data['y'].values, '-', alpha = 0.5)
xlabel('x')
ylabel('y')
title(k)
simpleaxis(gca())
subplots_adjust(hspace = 0.3, wspace = 0.3)
savefig(combination[13]['figure'], dpi = 900, bbox_inches = 'tight')
#####################################################################
# plot 14 (2.4)
#####################################################################
angdens = {}
for k in thresholds[14].iterkeys():
thr = np.copy(thresholds[14][k]['f0'])
tun = np.copy(tuningc[k])
bins = np.linspace(0, 2.*np.pi+1e-8, 20+1)
hist, bin_edges = np.histogram(thr, bins, normed = True)
x = bins[0:-1] + (bins[1]-bins[0])/2.
x[x>np.pi] -= 2*np.pi
# correct x with offset of tuning curve
offset = tun[0][np.argmax(tun[1])]
if offset <= np.pi :
x -= offset
else :
x += (2.*np.pi - offset)
x[x>np.pi] -= 2*np.pi
x[x<= -np.pi] += 2*np.pi
hist = hist[np.argsort(x)]
angdens[k] = (np.sort(x), hist)
xydens = {}
for k in thresholds[15].iterkeys():
xt = np.copy(thresholds[15][k]['f0'])
yt = np.copy(thresholds[15][k]['f1'])
xbins = np.linspace(20, 100, 20+1)
ybins = np.linspace(0, 80, 20+1)
xh, bin_edges = np.histogram(xt, xbins, normed = True)
yh, bin_edges = np.histogram(yt, ybins, normed = True)
x = ybins[0:-1] + (ybins[1]-ybins[0])/2.
xydens[k] = (x, xh, yh)
rcParams.update({ 'backend':'pdf',
'savefig.pad_inches':0.1,
'font.size':6 })
figure(figsize = (4, 4))
subplot(4,2,1)
keys = [k for k in angdens.iterkeys() if 'ADn' in k]
for k in keys:
plot(angdens[k][0], angdens[k][1], '-', color = 'blue', linewidth = 0.4)
ylabel("Density of splits \n to center")
xlabel("Angle (rad)")
title("ADn")
simpleaxis(gca())
subplot(4,2,2)
keys = [k for k in angdens.iterkeys() if 'Pos' in k]
for k in keys:
plot(angdens[k][0], angdens[k][1], '-', color = 'green', linewidth = 0.4)
ylabel("Density of splits \n to center")
xlabel("Angle (rad)")
title("Pos")
simpleaxis(gca())
start = 3
for i,l in zip([1, 2], ['x', 'y']):
subplot(4,2,start)
keys = [k for k in xydens.iterkeys() if 'ADn' in k]
for k in keys:
plot(xydens[k][0], xydens[k][i], '-', color = 'blue', linewidth = 0.4)
ylabel("Density of splits")
xlabel(l+" pos")
simpleaxis(gca())
subplot(4,2,start+1)
keys = [k for k in xydens.iterkeys() if 'Pos' in k]
for k in keys:
plot(xydens[k][0], xydens[k][i], '-', color = 'green', linewidth = 0.4)
ylabel("Density of splits")
xlabel(l+" pos")
simpleaxis(gca())
start+=2
for s in ['ADn', 'Pos']:
subplot(4,2,start)
keys = [k for k in xydens.iterkeys() if s in k]
tmp = np.array([np.vstack(xydens[k][1])*xydens[k][2] for k in keys]).mean(0)
imshow(tmp, aspect = 'auto')
xlabel("x")
ylabel("y")
start+=1
subplots_adjust(hspace = 0.7, wspace = 0.7)
savefig(combination[15]['figure'], dpi = 900, bbox_inches = 'tight')
| n = len(trees.get_dump())
thr = {}
for t in xrange(n):
gv = xgb.to_graphviz(trees, num_trees=t)
body = gv.body
for i in xrange(len(body)):
for l in body[i].split('"'):
if 'f' in l and '<' in l:
tmp = l.split("<")
if thr.has_key(tmp[0]):
thr[tmp[0]].append(float(tmp[1]))
else:
thr[tmp[0]] = [float(tmp[1])]
for k in thr.iterkeys():
thr[k] = np.sort(np.array(thr[k]))
return thr | identifier_body |
main_test_xgb.py | #!/usr/bin/env python
'''
File name: main_hd_data.py
Author: Guillaume Viejo
Date created: 06/03/2017
Python Version: 2.7
To test the xbg algorithm and to see the splits
'''
import warnings
import pandas as pd
import scipy.io
import numpy as np
# Should not import fonctions if already using tensorflow for something else
from fonctions import *
import sys, os
import itertools
import cPickle as pickle
#####################################################################
# DATA LOADING
#####################################################################
# adrien_data = scipy.io.loadmat(os.path.expanduser('~/Dropbox (Peyrache Lab)/Peyrache Lab Team Folder/Data/HDCellData/data_test_boosted_tree.mat'))
adrien_data = scipy.io.loadmat(os.path.expanduser('../data/sessions/wake/boosted_tree.Mouse25-140124.mat'))
# m1_imported = scipy.io.loadmat('/home/guillaume/spykesML/data/m1_stevenson_2011.mat')
#####################################################################
# DATA ENGINEERING
#####################################################################
data = pd.DataFrame()
data['time'] = np.arange(len(adrien_data['Ang'])) # TODO : import real time from matlab script
data['ang'] = adrien_data['Ang'].flatten() # angular direction of the animal head
data['x'] = adrien_data['X'].flatten() # x position of the animal
data['y'] = adrien_data['Y'].flatten() # y position of the animal
data['vel'] = adrien_data['speed'].flatten() # velocity of the animal
# Engineering features
data['cos'] = np.cos(adrien_data['Ang'].flatten()) # cosinus of angular direction
data['sin'] = np.sin(adrien_data['Ang'].flatten()) # sinus of angular direction
# Firing data
for i in xrange(adrien_data['Pos'].shape[1]): data['Pos'+'.'+str(i)] = adrien_data['Pos'][:,i].astype('float')
for i in xrange(adrien_data['ADn'].shape[1]): data['ADn'+'.'+str(i)] = adrien_data['ADn'][:,i].astype('float')
#RANDOM DATA
for i in xrange(5):
data['rand'+str(i)] = np.random.uniform(0, 2*np.pi, len(adrien_data['Ang']))
#######################################################################
# FONCTIONS DEFINITIONS
#######################################################################
def extract_tree_threshold(trees):
n = len(trees.get_dump())
thr = {}
for t in xrange(n):
gv = xgb.to_graphviz(trees, num_trees=t)
body = gv.body
for i in xrange(len(body)):
for l in body[i].split('"'):
if 'f' in l and '<' in l:
tmp = l.split("<")
if thr.has_key(tmp[0]):
thr[tmp[0]].append(float(tmp[1]))
else:
thr[tmp[0]] = [float(tmp[1])]
for k in thr.iterkeys():
thr[k] = np.sort(np.array(thr[k]))
return thr
def tuning_curve(x, f, nb_bins):
bins = np.linspace(x.min(), x.max()+1e-8, nb_bins+1)
index = np.digitize(x, bins).flatten()
tcurve = np.array([np.mean(f[index == i]) for i in xrange(1, nb_bins+1)])
x = bins[0:-1] + (bins[1]-bins[0])/2.
return (x, tcurve)
def test_features(features, targets, learners = ['glm_pyglmnet', 'nn', 'xgb_run', 'ens']):
X = data[features].values
Y = np.vstack(data[targets].values)
Models = {method:{'PR2':[],'Yt_hat':[]} for method in learners}
learners_ = list(learners)
# print learners_
for i in xrange(Y.shape[1]):
y = Y[:,i]
# TODO : make sure that 'ens' is the last learner
for method in learners_:
print('Running '+method+'...')
print 'targets ', targets[i]
Yt_hat, PR2 = fit_cv(X, y, algorithm = method, n_cv=8, verbose=1)
Models[method]['Yt_hat'].append(Yt_hat)
Models[method]['PR2'].append(PR2)
for m in Models.iterkeys():
Models[m]['Yt_hat'] = np.array(Models[m]['Yt_hat'])
Models[m]['PR2'] = np.array(Models[m]['PR2'])
return Models
#####################################################################
# COMBINATIONS DEFINITION
#####################################################################
combination = {
14: {
'features' : ['rand0', 'rand1', 'ang', 'rand2', 'rand3'],
# 'targets' : [i for i in list(data) if i.split(".")[0] in ['Pos', 'ADn']],
'targets' : ['ADn.0'],
},
}
#####################################################################
# LEARNING XGB
#####################################################################
bsts = {i:{} for i in combination.iterkeys()} # to keep the boosted tree
params = {'objective': "count:poisson", #for poisson output
'eval_metric': "logloss", #loglikelihood loss
'seed': 2925, #for reproducibility
'silent': 0,
'learning_rate': 0.1,
'min_child_weight': 2, 'n_estimators': 1,
'subsample': 0.6, 'max_depth': 5, 'gamma': 0.5,
'tree_method':'exact'}
num_round = 600
X = data[['rand0', 'rand1', 'ang', 'rand2', 'rand3']].values
Y = data['ADn.0']
dtrain = xgb.DMatrix(np.vstack(X), label = np.vstack(Y))
bst = xgb.train(params, dtrain, num_round)
a = extract_tree_threshold(bst)
sys.exit()
# methods = ['xgb_run']
# for k in np.sort(combination.keys()):
# features = combination[k]['features']
# targets = combination[k]['targets']
# results = test_features(features, targets, methods)
# sys.exit()
#####################################################################
# TUNING CURVE
#####################################################################
X = data['ang'].values
Yall = data[[i for i in list(data) if i.split(".")[0] in ['Pos', 'ADn']]].values
tuningc = {targets[i]:tuning_curve(X, Yall[:,i], nb_bins = 100) for i in xrange(Yall.shape[1])}
sys.exit()
#####################################################################
# EXTRACT TREE STRUCTURE
#####################################################################
thresholds = {}
for i in bsts.iterkeys():
thresholds[i] = {}
for j in bsts[i].iterkeys():
|
#####################################################################
# plot 11 (2.1)
#####################################################################
order = ['Pos.8', 'Pos.9', 'Pos.10', 'ADn.9', 'ADn.10', 'ADn.11']
rcParams.update({ 'backend':'pdf',
'savefig.pad_inches':0.1,
'font.size':8 })
figure(figsize = (12,15))
for k, i in zip(order, xrange(1,7)):
subplot(3,2,i)
[axvline(j, alpha = 0.1, color = 'grey') for j in thresholds[11][k]['f0']]
plot(tuningc[k][0], tuningc[k][1])
title(k)
xlim(0, 2*np.pi)
xlabel('Angle (rad)')
ylabel('f')
simpleaxis(gca())
subplots_adjust(hspace = 0.3, wspace = 0.3)
savefig(combination[11]['figure'], dpi = 900, bbox_inches = 'tight')
#####################################################################
# plot 12 (2.2)
#####################################################################
figure(figsize = (12,14))
for k, i in zip(order, xrange(1,7)):
subplot(3,2,i)
[axvline(j, alpha = 0.1, color = 'grey') for j in thresholds[12][k]['f0']]
[axhline(j, alpha = 0.1, color = 'grey') for j in thresholds[12][k]['f1']]
plot(data['x'].values, data['y'].values, '-', alpha = 0.3)
xlabel('x')
ylabel('y')
title(k)
simpleaxis(gca())
subplots_adjust(hspace = 0.3, wspace = 0.3)
savefig(combination[12]['figure'], dpi = 900, bbox_inches = 'tight')
#####################################################################
# plot 13 (2.3)
#####################################################################
trans = {'f0':'Ang','f1':'x','f2':'y'}
figure(figsize = (12,17))
for k, i in zip(order, xrange(1,18,3)):
subplot(6,3,i)
count = np.array([len(thresholds[13][k][f]) for f in thresholds[13][k].keys()])
name = np.array([trans[f] for f in thresholds[13][k].keys()])
bar(left = np.arange(len(count)), height = count, tick_label = name, align = 'center', facecolor = 'grey')
ylabel('Number of split')
simpleaxis(gca())
subplot(6,3,i+1)
[axvline(j, alpha = 0.1, color = 'grey') for j in thresholds[13][k]['f0']]
plot(tuningc[k][0], tuningc[k][1])
title(k)
xlim(0, 2*np.pi)
xlabel('Angle (rad)')
ylabel('f')
simpleaxis(gca())
subplot(6,3,i+2)
[axvline(j, alpha = 0.1, color = 'grey') for j in thresholds[13][k]['f1']]
[axhline(j, alpha = 0.1, color = 'grey') for j in thresholds[13][k]['f2']]
plot(data['x'].values, data['y'].values, '-', alpha = 0.5)
xlabel('x')
ylabel('y')
title(k)
simpleaxis(gca())
subplots_adjust(hspace = 0.3, wspace = 0.3)
savefig(combination[13]['figure'], dpi = 900, bbox_inches = 'tight')
#####################################################################
# plot 14 (2.4)
#####################################################################
angdens = {}
for k in thresholds[14].iterkeys():
thr = np.copy(thresholds[14][k]['f0'])
tun = np.copy(tuningc[k])
bins = np.linspace(0, 2.*np.pi+1e-8, 20+1)
hist, bin_edges = np.histogram(thr, bins, normed = True)
x = bins[0:-1] + (bins[1]-bins[0])/2.
x[x>np.pi] -= 2*np.pi
# correct x with offset of tuning curve
offset = tun[0][np.argmax(tun[1])]
if offset <= np.pi :
x -= offset
else :
x += (2.*np.pi - offset)
x[x>np.pi] -= 2*np.pi
x[x<= -np.pi] += 2*np.pi
hist = hist[np.argsort(x)]
angdens[k] = (np.sort(x), hist)
xydens = {}
for k in thresholds[15].iterkeys():
xt = np.copy(thresholds[15][k]['f0'])
yt = np.copy(thresholds[15][k]['f1'])
xbins = np.linspace(20, 100, 20+1)
ybins = np.linspace(0, 80, 20+1)
xh, bin_edges = np.histogram(xt, xbins, normed = True)
yh, bin_edges = np.histogram(yt, ybins, normed = True)
x = ybins[0:-1] + (ybins[1]-ybins[0])/2.
xydens[k] = (x, xh, yh)
rcParams.update({ 'backend':'pdf',
'savefig.pad_inches':0.1,
'font.size':6 })
figure(figsize = (4, 4))
subplot(4,2,1)
keys = [k for k in angdens.iterkeys() if 'ADn' in k]
for k in keys:
plot(angdens[k][0], angdens[k][1], '-', color = 'blue', linewidth = 0.4)
ylabel("Density of splits \n to center")
xlabel("Angle (rad)")
title("ADn")
simpleaxis(gca())
subplot(4,2,2)
keys = [k for k in angdens.iterkeys() if 'Pos' in k]
for k in keys:
plot(angdens[k][0], angdens[k][1], '-', color = 'green', linewidth = 0.4)
ylabel("Density of splits \n to center")
xlabel("Angle (rad)")
title("Pos")
simpleaxis(gca())
start = 3
for i,l in zip([1, 2], ['x', 'y']):
subplot(4,2,start)
keys = [k for k in xydens.iterkeys() if 'ADn' in k]
for k in keys:
plot(xydens[k][0], xydens[k][i], '-', color = 'blue', linewidth = 0.4)
ylabel("Density of splits")
xlabel(l+" pos")
simpleaxis(gca())
subplot(4,2,start+1)
keys = [k for k in xydens.iterkeys() if 'Pos' in k]
for k in keys:
plot(xydens[k][0], xydens[k][i], '-', color = 'green', linewidth = 0.4)
ylabel("Density of splits")
xlabel(l+" pos")
simpleaxis(gca())
start+=2
for s in ['ADn', 'Pos']:
subplot(4,2,start)
keys = [k for k in xydens.iterkeys() if s in k]
tmp = np.array([np.vstack(xydens[k][1])*xydens[k][2] for k in keys]).mean(0)
imshow(tmp, aspect = 'auto')
xlabel("x")
ylabel("y")
start+=1
subplots_adjust(hspace = 0.7, wspace = 0.7)
savefig(combination[15]['figure'], dpi = 900, bbox_inches = 'tight')
| thresholds[i][j] = extract_tree_threshold(bsts[i][j]) | conditional_block |
tls.go | // Copyright 2018 The Operator-SDK 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.
package tlsutil
import (
"crypto/rsa"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"strings"
"k8s.io/api/core/v1"
apiErrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
)
// CertType defines the type of the cert.
type CertType int
const (
// ClientAndServingCert defines both client and serving cert.
ClientAndServingCert CertType = iota
// ServingCert defines a serving cert.
ServingCert
// ClientCert defines a client cert.
ClientCert
)
// CertConfig configures how to generate the Cert.
type CertConfig struct {
// CertName is the name of the cert.
CertName string
// Optional CertType. Serving, client or both; defaults to both.
CertType CertType
// Optional CommonName is the common name of the cert; defaults to "".
CommonName string
// Optional Organization is Organization of the cert; defaults to "".
Organization []string
// Optional CA Key, if user wants to provide custom CA key via a file path.
CAKey string
// Optional CA Certificate, if user wants to provide custom CA cert via file path.
CACert string
// TODO: consider to add passed in SAN fields.
}
// CertGenerator is an operator specific TLS tool that generates TLS assets for the deploying a user's application.
type CertGenerator interface {
// GenerateCert generates a secret containing TLS encryption key and cert, a Secret
// containing the CA key, and a ConfigMap containing the CA Certificate given the Custom
// Resource(CR) "cr", the Kubernetes Service "Service", and the CertConfig "config".
//
// GenerateCert creates and manages TLS key and cert and CA with the following:
// CA creation and management:
// - If CA is not given:
// - A unique CA is generated for the CR.
// - CA's key is packaged into a Secret as shown below.
// - CA's cert is packaged in a ConfigMap as shown below.
// - The CA Secret and ConfigMap are created on the k8s cluster in the CR's namespace before
// returned to the user. The CertGenerator manages the CA Secret and ConfigMap to ensure it's
// unqiue per CR.
// - If CA is given:
// - CA's key is packaged into a Secret as shown below.
// - CA's cert is packaged in a ConfigMap as shown below.
// - The CA Secret and ConfigMap are returned but not created in the K8s cluster in the CR's
// namespace. The CertGenerator doesn't manage the CA because the user controls the lifecycle
// of the CA.
//
// TLS Key and Cert Creation and Management:
// - A unique TLS cert and key pair is generated per CR + CertConfig.CertName.
// - The CA is used to generate and sign the TLS cert.
// - The signing process uses the passed in "service" to set the Subject Alternative Names(SAN)
// for the certificate. We assume that the deployed applications are typically communicated
// with via a Kubernetes Service. The SAN is set to the FQDN of the service
// `<service-name>.<service-namespace>.svc.cluster.local`.
// - Once TLS key and cert are created, they are packaged into a secret as shown below.
// - Finally, the secret are created on the k8s cluster in the CR's namespace before returned to
// the user. The CertGenerator manages this secret to ensure that it is unique per CR +
// CertConfig.CertName.
//
// TLS encryption key and cert Secret format:
// kind: Secret
// apiVersion: v1
// metadata:
// name: <cr-kind>-<cr-name>-<CertConfig.CertName>
// namespace: <cr-namespace>
// data:
// tls.crt: ...
// tls.key: ...
//
// CA Certificate ConfigMap format:
// kind: ConfigMap
// apiVersion: v1
// metadata:
// name: <cr-kind>-<cr-name>-ca
// namespace: <cr-namespace>
// data:
// ca.crt: ...
//
// CA Key Secret format:
// kind: Secret
// apiVersion: v1
// metadata:
// name: <cr-kind>-<cr-name>-ca
// namespace: <cr-namespace>
// data:
// ca.key: ..
GenerateCert(cr runtime.Object, service *v1.Service, config *CertConfig) (*v1.Secret, *v1.ConfigMap, *v1.Secret, error)
}
const (
// TLSPrivateCAKeyKey is the key for the private CA key field.
TLSPrivateCAKeyKey = "ca.key"
// TLSCertKey is the key for tls CA certificates.
TLSCACertKey = "ca.crt"
)
// NewSDKCertGenerator constructs a new CertGenerator given the kubeClient.
func NewSDKCertGenerator(kubeClient kubernetes.Interface) CertGenerator {
return &SDKCertGenerator{KubeClient: kubeClient}
}
type SDKCertGenerator struct {
KubeClient kubernetes.Interface
}
// GenerateCert returns a secret containing the TLS encryption key and cert,
// a ConfigMap containing the CA Certificate and a Secret containing the CA key or it
// returns a error incase something goes wrong.
func (scg *SDKCertGenerator) GenerateCert(cr runtime.Object, service *v1.Service, config *CertConfig) (*v1.Secret, *v1.ConfigMap, *v1.Secret, error) {
if err := verifyConfig(config); err != nil {
return nil, nil, nil, err
}
k, n, ns, err := toKindNameNamespace(cr)
if err != nil {
return nil, nil, nil, err
}
appSecretName := ToAppSecretName(k, n, config.CertName)
appSecret, err := getAppSecretInCluster(scg.KubeClient, appSecretName, ns)
if err != nil {
return nil, nil, nil, err
}
caSecretAndConfigMapName := ToCASecretAndConfigMapName(k, n)
var (
caSecret *v1.Secret
caConfigMap *v1.ConfigMap
)
caSecret, caConfigMap, err = getCASecretAndConfigMapInCluster(scg.KubeClient, caSecretAndConfigMapName, ns)
if err != nil {
return nil, nil, nil, err
}
if config.CAKey != "" && config.CACert != "" {
// custom CA provided by the user.
customCAKeyData, err := ioutil.ReadFile(config.CAKey)
if err != nil {
return nil, nil, nil, fmt.Errorf("error reading CA Key from the given file name: %v", err)
}
customCACertData, err := ioutil.ReadFile(config.CACert)
if err != nil {
return nil, nil, nil, fmt.Errorf("error reading CA Cert from the given file name: %v", err)
}
customCAKey, err := parsePEMEncodedPrivateKey(customCAKeyData)
if err != nil {
return nil, nil, nil, fmt.Errorf("error parsing CA Key from the given file name: %v", err)
}
customCACert, err := parsePEMEncodedCert(customCACertData)
if err != nil {
return nil, nil, nil, fmt.Errorf("error parsing CA Cert from the given file name: %v", err)
}
caSecret, caConfigMap = toCASecretAndConfigmap(customCAKey, customCACert, caSecretAndConfigMapName)
} else if config.CAKey != "" || config.CACert != "" {
// if only one of the custom CA Key or Cert is provided
return nil, nil, nil, ErrCAKeyAndCACertReq
}
hasAppSecret := appSecret != nil
hasCASecretAndConfigMap := caSecret != nil && caConfigMap != nil
switch {
case hasAppSecret && hasCASecretAndConfigMap:
return appSecret, caConfigMap, caSecret, nil
case hasAppSecret && !hasCASecretAndConfigMap:
return nil, nil, nil, ErrCANotFound
case !hasAppSecret && hasCASecretAndConfigMap:
// Note: if a custom CA is passed in my the user it takes preference over an already
// generated CA secret and CA configmap that might exist in the cluster
caKey, err := parsePEMEncodedPrivateKey(caSecret.Data[TLSPrivateCAKeyKey])
if err != nil {
return nil, nil, nil, err
}
caCert, err := parsePEMEncodedCert([]byte(caConfigMap.Data[TLSCACertKey]))
if err != nil {
return nil, nil, nil, err
}
key, err := newPrivateKey()
if err != nil {
return nil, nil, nil, err
}
cert, err := newSignedCertificate(config, service, key, caCert, caKey)
if err != nil {
return nil, nil, nil, err
}
appSecret, err := scg.KubeClient.CoreV1().Secrets(ns).Create(toTLSSecret(key, cert, appSecretName))
if err != nil {
return nil, nil, nil, err
}
return appSecret, caConfigMap, caSecret, nil
case !hasAppSecret && !hasCASecretAndConfigMap:
// If no custom CAKey and CACert are provided we have to generate them
caKey, err := newPrivateKey()
if err != nil {
return nil, nil, nil, err
}
caCert, err := newSelfSignedCACertificate(caKey)
if err != nil {
return nil, nil, nil, err
}
caSecret, caConfigMap := toCASecretAndConfigmap(caKey, caCert, caSecretAndConfigMapName)
caSecret, err = scg.KubeClient.CoreV1().Secrets(ns).Create(caSecret)
if err != nil {
return nil, nil, nil, err
}
caConfigMap, err = scg.KubeClient.CoreV1().ConfigMaps(ns).Create(caConfigMap)
if err != nil {
return nil, nil, nil, err
}
key, err := newPrivateKey()
if err != nil {
return nil, nil, nil, err
}
cert, err := newSignedCertificate(config, service, key, caCert, caKey)
if err != nil |
appSecret, err := scg.KubeClient.CoreV1().Secrets(ns).Create(toTLSSecret(key, cert, appSecretName))
if err != nil {
return nil, nil, nil, err
}
return appSecret, caConfigMap, caSecret, nil
default:
return nil, nil, nil, ErrInternal
}
}
func verifyConfig(config *CertConfig) error {
if config == nil {
return errors.New("nil CertConfig not allowed")
}
if config.CertName == "" {
return errors.New("empty CertConfig.CertName not allowed")
}
return nil
}
func ToAppSecretName(kind, name, certName string) string {
return strings.ToLower(kind) + "-" + name + "-" + certName
}
func ToCASecretAndConfigMapName(kind, name string) string {
return strings.ToLower(kind) + "-" + name + "-ca"
}
func getAppSecretInCluster(kubeClient kubernetes.Interface, name, namespace string) (*v1.Secret, error) {
se, err := kubeClient.CoreV1().Secrets(namespace).Get(name, metav1.GetOptions{})
if err != nil && !apiErrors.IsNotFound(err) {
return nil, err
}
if apiErrors.IsNotFound(err) {
return nil, nil
}
return se, nil
}
// getCASecretAndConfigMapInCluster gets CA secret and configmap of the given name and namespace.
// it only returns both if they are found and nil if both are not found. In the case if only one of them is found,
// then we error out because we expect either both CA secret and configmap exit or not.
//
// NOTE: both the CA secret and configmap have the same name with template `<cr-kind>-<cr-name>-ca` which is what the
// input parameter `name` refers to.
func getCASecretAndConfigMapInCluster(kubeClient kubernetes.Interface, name, namespace string) (*v1.Secret, *v1.ConfigMap, error) {
hasConfigMap := true
cm, err := kubeClient.CoreV1().ConfigMaps(namespace).Get(name, metav1.GetOptions{})
if err != nil && !apiErrors.IsNotFound(err) {
return nil, nil, err
}
if apiErrors.IsNotFound(err) {
hasConfigMap = false
}
hasSecret := true
se, err := kubeClient.CoreV1().Secrets(namespace).Get(name, metav1.GetOptions{})
if err != nil && !apiErrors.IsNotFound(err) {
return nil, nil, err
}
if apiErrors.IsNotFound(err) {
hasSecret = false
}
if hasConfigMap != hasSecret {
// TODO: this case can happen if creating CA configmap succeeds and creating CA secret failed. We need to handle this case properly.
return nil, nil, fmt.Errorf("expect either both ca configmap and secret both exist or not exist, but got hasCAConfigmap==%v and hasCASecret==%v", hasConfigMap, hasSecret)
}
if hasConfigMap == false {
return nil, nil, nil
}
return se, cm, nil
}
func toKindNameNamespace(cr runtime.Object) (string, string, string, error) {
a := meta.NewAccessor()
k, err := a.Kind(cr)
if err != nil {
return "", "", "", err
}
n, err := a.Name(cr)
if err != nil {
return "", "", "", err
}
ns, err := a.Namespace(cr)
if err != nil {
return "", "", "", err
}
return k, n, ns, nil
}
// toTLSSecret returns a client/server "kubernetes.io/tls" secret.
// TODO: add owner ref.
func toTLSSecret(key *rsa.PrivateKey, cert *x509.Certificate, name string) *v1.Secret {
return &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Data: map[string][]byte{
v1.TLSPrivateKeyKey: encodePrivateKeyPEM(key),
v1.TLSCertKey: encodeCertificatePEM(cert),
},
Type: v1.SecretTypeTLS,
}
}
// TODO: add owner ref.
func toCASecretAndConfigmap(key *rsa.PrivateKey, cert *x509.Certificate, name string) (*v1.Secret, *v1.ConfigMap) {
return &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Data: map[string][]byte{
TLSPrivateCAKeyKey: encodePrivateKeyPEM(key),
},
}, &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Data: map[string]string{
TLSCACertKey: string(encodeCertificatePEM(cert)),
},
}
}
| {
return nil, nil, nil, err
} | conditional_block |
tls.go | // Copyright 2018 The Operator-SDK 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.
package tlsutil
import (
"crypto/rsa"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"strings"
"k8s.io/api/core/v1"
apiErrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
)
// CertType defines the type of the cert.
type CertType int
const (
// ClientAndServingCert defines both client and serving cert.
ClientAndServingCert CertType = iota
// ServingCert defines a serving cert.
ServingCert
// ClientCert defines a client cert.
ClientCert
)
// CertConfig configures how to generate the Cert.
type CertConfig struct {
// CertName is the name of the cert.
CertName string
// Optional CertType. Serving, client or both; defaults to both.
CertType CertType
// Optional CommonName is the common name of the cert; defaults to "".
CommonName string
// Optional Organization is Organization of the cert; defaults to "".
Organization []string
// Optional CA Key, if user wants to provide custom CA key via a file path.
CAKey string
// Optional CA Certificate, if user wants to provide custom CA cert via file path.
CACert string
// TODO: consider to add passed in SAN fields.
}
// CertGenerator is an operator specific TLS tool that generates TLS assets for the deploying a user's application.
type CertGenerator interface {
// GenerateCert generates a secret containing TLS encryption key and cert, a Secret
// containing the CA key, and a ConfigMap containing the CA Certificate given the Custom
// Resource(CR) "cr", the Kubernetes Service "Service", and the CertConfig "config".
//
// GenerateCert creates and manages TLS key and cert and CA with the following:
// CA creation and management:
// - If CA is not given:
// - A unique CA is generated for the CR.
// - CA's key is packaged into a Secret as shown below.
// - CA's cert is packaged in a ConfigMap as shown below.
// - The CA Secret and ConfigMap are created on the k8s cluster in the CR's namespace before
// returned to the user. The CertGenerator manages the CA Secret and ConfigMap to ensure it's
// unqiue per CR.
// - If CA is given:
// - CA's key is packaged into a Secret as shown below.
// - CA's cert is packaged in a ConfigMap as shown below.
// - The CA Secret and ConfigMap are returned but not created in the K8s cluster in the CR's
// namespace. The CertGenerator doesn't manage the CA because the user controls the lifecycle
// of the CA.
//
// TLS Key and Cert Creation and Management:
// - A unique TLS cert and key pair is generated per CR + CertConfig.CertName.
// - The CA is used to generate and sign the TLS cert.
// - The signing process uses the passed in "service" to set the Subject Alternative Names(SAN)
// for the certificate. We assume that the deployed applications are typically communicated
// with via a Kubernetes Service. The SAN is set to the FQDN of the service
// `<service-name>.<service-namespace>.svc.cluster.local`.
// - Once TLS key and cert are created, they are packaged into a secret as shown below.
// - Finally, the secret are created on the k8s cluster in the CR's namespace before returned to
// the user. The CertGenerator manages this secret to ensure that it is unique per CR +
// CertConfig.CertName.
//
// TLS encryption key and cert Secret format:
// kind: Secret
// apiVersion: v1
// metadata:
// name: <cr-kind>-<cr-name>-<CertConfig.CertName>
// namespace: <cr-namespace>
// data:
// tls.crt: ...
// tls.key: ...
//
// CA Certificate ConfigMap format:
// kind: ConfigMap
// apiVersion: v1
// metadata:
// name: <cr-kind>-<cr-name>-ca
// namespace: <cr-namespace>
// data:
// ca.crt: ...
//
// CA Key Secret format:
// kind: Secret
// apiVersion: v1
// metadata:
// name: <cr-kind>-<cr-name>-ca
// namespace: <cr-namespace>
// data:
// ca.key: ..
GenerateCert(cr runtime.Object, service *v1.Service, config *CertConfig) (*v1.Secret, *v1.ConfigMap, *v1.Secret, error)
}
const (
// TLSPrivateCAKeyKey is the key for the private CA key field.
TLSPrivateCAKeyKey = "ca.key"
// TLSCertKey is the key for tls CA certificates.
TLSCACertKey = "ca.crt"
)
// NewSDKCertGenerator constructs a new CertGenerator given the kubeClient.
func NewSDKCertGenerator(kubeClient kubernetes.Interface) CertGenerator {
return &SDKCertGenerator{KubeClient: kubeClient}
}
type SDKCertGenerator struct {
KubeClient kubernetes.Interface
}
// GenerateCert returns a secret containing the TLS encryption key and cert,
// a ConfigMap containing the CA Certificate and a Secret containing the CA key or it
// returns a error incase something goes wrong.
func (scg *SDKCertGenerator) GenerateCert(cr runtime.Object, service *v1.Service, config *CertConfig) (*v1.Secret, *v1.ConfigMap, *v1.Secret, error) {
if err := verifyConfig(config); err != nil {
return nil, nil, nil, err
}
k, n, ns, err := toKindNameNamespace(cr)
if err != nil {
return nil, nil, nil, err
}
appSecretName := ToAppSecretName(k, n, config.CertName)
appSecret, err := getAppSecretInCluster(scg.KubeClient, appSecretName, ns)
if err != nil {
return nil, nil, nil, err
}
caSecretAndConfigMapName := ToCASecretAndConfigMapName(k, n)
var (
caSecret *v1.Secret
caConfigMap *v1.ConfigMap
)
caSecret, caConfigMap, err = getCASecretAndConfigMapInCluster(scg.KubeClient, caSecretAndConfigMapName, ns)
if err != nil {
return nil, nil, nil, err
}
if config.CAKey != "" && config.CACert != "" {
// custom CA provided by the user.
customCAKeyData, err := ioutil.ReadFile(config.CAKey)
if err != nil {
return nil, nil, nil, fmt.Errorf("error reading CA Key from the given file name: %v", err)
}
customCACertData, err := ioutil.ReadFile(config.CACert)
if err != nil {
return nil, nil, nil, fmt.Errorf("error reading CA Cert from the given file name: %v", err)
}
customCAKey, err := parsePEMEncodedPrivateKey(customCAKeyData)
if err != nil {
return nil, nil, nil, fmt.Errorf("error parsing CA Key from the given file name: %v", err)
}
customCACert, err := parsePEMEncodedCert(customCACertData)
if err != nil {
return nil, nil, nil, fmt.Errorf("error parsing CA Cert from the given file name: %v", err)
}
caSecret, caConfigMap = toCASecretAndConfigmap(customCAKey, customCACert, caSecretAndConfigMapName)
} else if config.CAKey != "" || config.CACert != "" {
// if only one of the custom CA Key or Cert is provided
return nil, nil, nil, ErrCAKeyAndCACertReq
}
hasAppSecret := appSecret != nil
hasCASecretAndConfigMap := caSecret != nil && caConfigMap != nil
switch {
case hasAppSecret && hasCASecretAndConfigMap:
return appSecret, caConfigMap, caSecret, nil
case hasAppSecret && !hasCASecretAndConfigMap:
return nil, nil, nil, ErrCANotFound
case !hasAppSecret && hasCASecretAndConfigMap:
// Note: if a custom CA is passed in my the user it takes preference over an already
// generated CA secret and CA configmap that might exist in the cluster
caKey, err := parsePEMEncodedPrivateKey(caSecret.Data[TLSPrivateCAKeyKey])
if err != nil {
return nil, nil, nil, err
}
caCert, err := parsePEMEncodedCert([]byte(caConfigMap.Data[TLSCACertKey]))
if err != nil {
return nil, nil, nil, err
}
key, err := newPrivateKey()
if err != nil {
return nil, nil, nil, err
}
cert, err := newSignedCertificate(config, service, key, caCert, caKey)
if err != nil {
return nil, nil, nil, err
}
appSecret, err := scg.KubeClient.CoreV1().Secrets(ns).Create(toTLSSecret(key, cert, appSecretName))
if err != nil {
return nil, nil, nil, err
}
return appSecret, caConfigMap, caSecret, nil
case !hasAppSecret && !hasCASecretAndConfigMap:
// If no custom CAKey and CACert are provided we have to generate them
caKey, err := newPrivateKey()
if err != nil {
return nil, nil, nil, err
}
caCert, err := newSelfSignedCACertificate(caKey)
if err != nil {
return nil, nil, nil, err
}
caSecret, caConfigMap := toCASecretAndConfigmap(caKey, caCert, caSecretAndConfigMapName)
caSecret, err = scg.KubeClient.CoreV1().Secrets(ns).Create(caSecret)
if err != nil {
return nil, nil, nil, err
}
caConfigMap, err = scg.KubeClient.CoreV1().ConfigMaps(ns).Create(caConfigMap)
if err != nil {
return nil, nil, nil, err
}
key, err := newPrivateKey()
if err != nil {
return nil, nil, nil, err
}
cert, err := newSignedCertificate(config, service, key, caCert, caKey)
if err != nil {
return nil, nil, nil, err
}
appSecret, err := scg.KubeClient.CoreV1().Secrets(ns).Create(toTLSSecret(key, cert, appSecretName))
if err != nil {
return nil, nil, nil, err
}
return appSecret, caConfigMap, caSecret, nil
default:
return nil, nil, nil, ErrInternal
}
}
func | (config *CertConfig) error {
if config == nil {
return errors.New("nil CertConfig not allowed")
}
if config.CertName == "" {
return errors.New("empty CertConfig.CertName not allowed")
}
return nil
}
func ToAppSecretName(kind, name, certName string) string {
return strings.ToLower(kind) + "-" + name + "-" + certName
}
func ToCASecretAndConfigMapName(kind, name string) string {
return strings.ToLower(kind) + "-" + name + "-ca"
}
func getAppSecretInCluster(kubeClient kubernetes.Interface, name, namespace string) (*v1.Secret, error) {
se, err := kubeClient.CoreV1().Secrets(namespace).Get(name, metav1.GetOptions{})
if err != nil && !apiErrors.IsNotFound(err) {
return nil, err
}
if apiErrors.IsNotFound(err) {
return nil, nil
}
return se, nil
}
// getCASecretAndConfigMapInCluster gets CA secret and configmap of the given name and namespace.
// it only returns both if they are found and nil if both are not found. In the case if only one of them is found,
// then we error out because we expect either both CA secret and configmap exit or not.
//
// NOTE: both the CA secret and configmap have the same name with template `<cr-kind>-<cr-name>-ca` which is what the
// input parameter `name` refers to.
func getCASecretAndConfigMapInCluster(kubeClient kubernetes.Interface, name, namespace string) (*v1.Secret, *v1.ConfigMap, error) {
hasConfigMap := true
cm, err := kubeClient.CoreV1().ConfigMaps(namespace).Get(name, metav1.GetOptions{})
if err != nil && !apiErrors.IsNotFound(err) {
return nil, nil, err
}
if apiErrors.IsNotFound(err) {
hasConfigMap = false
}
hasSecret := true
se, err := kubeClient.CoreV1().Secrets(namespace).Get(name, metav1.GetOptions{})
if err != nil && !apiErrors.IsNotFound(err) {
return nil, nil, err
}
if apiErrors.IsNotFound(err) {
hasSecret = false
}
if hasConfigMap != hasSecret {
// TODO: this case can happen if creating CA configmap succeeds and creating CA secret failed. We need to handle this case properly.
return nil, nil, fmt.Errorf("expect either both ca configmap and secret both exist or not exist, but got hasCAConfigmap==%v and hasCASecret==%v", hasConfigMap, hasSecret)
}
if hasConfigMap == false {
return nil, nil, nil
}
return se, cm, nil
}
func toKindNameNamespace(cr runtime.Object) (string, string, string, error) {
a := meta.NewAccessor()
k, err := a.Kind(cr)
if err != nil {
return "", "", "", err
}
n, err := a.Name(cr)
if err != nil {
return "", "", "", err
}
ns, err := a.Namespace(cr)
if err != nil {
return "", "", "", err
}
return k, n, ns, nil
}
// toTLSSecret returns a client/server "kubernetes.io/tls" secret.
// TODO: add owner ref.
func toTLSSecret(key *rsa.PrivateKey, cert *x509.Certificate, name string) *v1.Secret {
return &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Data: map[string][]byte{
v1.TLSPrivateKeyKey: encodePrivateKeyPEM(key),
v1.TLSCertKey: encodeCertificatePEM(cert),
},
Type: v1.SecretTypeTLS,
}
}
// TODO: add owner ref.
func toCASecretAndConfigmap(key *rsa.PrivateKey, cert *x509.Certificate, name string) (*v1.Secret, *v1.ConfigMap) {
return &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Data: map[string][]byte{
TLSPrivateCAKeyKey: encodePrivateKeyPEM(key),
},
}, &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Data: map[string]string{
TLSCACertKey: string(encodeCertificatePEM(cert)),
},
}
}
| verifyConfig | identifier_name |
tls.go | // Copyright 2018 The Operator-SDK 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, |
import (
"crypto/rsa"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"strings"
"k8s.io/api/core/v1"
apiErrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
)
// CertType defines the type of the cert.
type CertType int
const (
// ClientAndServingCert defines both client and serving cert.
ClientAndServingCert CertType = iota
// ServingCert defines a serving cert.
ServingCert
// ClientCert defines a client cert.
ClientCert
)
// CertConfig configures how to generate the Cert.
type CertConfig struct {
// CertName is the name of the cert.
CertName string
// Optional CertType. Serving, client or both; defaults to both.
CertType CertType
// Optional CommonName is the common name of the cert; defaults to "".
CommonName string
// Optional Organization is Organization of the cert; defaults to "".
Organization []string
// Optional CA Key, if user wants to provide custom CA key via a file path.
CAKey string
// Optional CA Certificate, if user wants to provide custom CA cert via file path.
CACert string
// TODO: consider to add passed in SAN fields.
}
// CertGenerator is an operator specific TLS tool that generates TLS assets for the deploying a user's application.
type CertGenerator interface {
// GenerateCert generates a secret containing TLS encryption key and cert, a Secret
// containing the CA key, and a ConfigMap containing the CA Certificate given the Custom
// Resource(CR) "cr", the Kubernetes Service "Service", and the CertConfig "config".
//
// GenerateCert creates and manages TLS key and cert and CA with the following:
// CA creation and management:
// - If CA is not given:
// - A unique CA is generated for the CR.
// - CA's key is packaged into a Secret as shown below.
// - CA's cert is packaged in a ConfigMap as shown below.
// - The CA Secret and ConfigMap are created on the k8s cluster in the CR's namespace before
// returned to the user. The CertGenerator manages the CA Secret and ConfigMap to ensure it's
// unqiue per CR.
// - If CA is given:
// - CA's key is packaged into a Secret as shown below.
// - CA's cert is packaged in a ConfigMap as shown below.
// - The CA Secret and ConfigMap are returned but not created in the K8s cluster in the CR's
// namespace. The CertGenerator doesn't manage the CA because the user controls the lifecycle
// of the CA.
//
// TLS Key and Cert Creation and Management:
// - A unique TLS cert and key pair is generated per CR + CertConfig.CertName.
// - The CA is used to generate and sign the TLS cert.
// - The signing process uses the passed in "service" to set the Subject Alternative Names(SAN)
// for the certificate. We assume that the deployed applications are typically communicated
// with via a Kubernetes Service. The SAN is set to the FQDN of the service
// `<service-name>.<service-namespace>.svc.cluster.local`.
// - Once TLS key and cert are created, they are packaged into a secret as shown below.
// - Finally, the secret are created on the k8s cluster in the CR's namespace before returned to
// the user. The CertGenerator manages this secret to ensure that it is unique per CR +
// CertConfig.CertName.
//
// TLS encryption key and cert Secret format:
// kind: Secret
// apiVersion: v1
// metadata:
// name: <cr-kind>-<cr-name>-<CertConfig.CertName>
// namespace: <cr-namespace>
// data:
// tls.crt: ...
// tls.key: ...
//
// CA Certificate ConfigMap format:
// kind: ConfigMap
// apiVersion: v1
// metadata:
// name: <cr-kind>-<cr-name>-ca
// namespace: <cr-namespace>
// data:
// ca.crt: ...
//
// CA Key Secret format:
// kind: Secret
// apiVersion: v1
// metadata:
// name: <cr-kind>-<cr-name>-ca
// namespace: <cr-namespace>
// data:
// ca.key: ..
GenerateCert(cr runtime.Object, service *v1.Service, config *CertConfig) (*v1.Secret, *v1.ConfigMap, *v1.Secret, error)
}
const (
// TLSPrivateCAKeyKey is the key for the private CA key field.
TLSPrivateCAKeyKey = "ca.key"
// TLSCertKey is the key for tls CA certificates.
TLSCACertKey = "ca.crt"
)
// NewSDKCertGenerator constructs a new CertGenerator given the kubeClient.
func NewSDKCertGenerator(kubeClient kubernetes.Interface) CertGenerator {
return &SDKCertGenerator{KubeClient: kubeClient}
}
type SDKCertGenerator struct {
KubeClient kubernetes.Interface
}
// GenerateCert returns a secret containing the TLS encryption key and cert,
// a ConfigMap containing the CA Certificate and a Secret containing the CA key or it
// returns a error incase something goes wrong.
func (scg *SDKCertGenerator) GenerateCert(cr runtime.Object, service *v1.Service, config *CertConfig) (*v1.Secret, *v1.ConfigMap, *v1.Secret, error) {
if err := verifyConfig(config); err != nil {
return nil, nil, nil, err
}
k, n, ns, err := toKindNameNamespace(cr)
if err != nil {
return nil, nil, nil, err
}
appSecretName := ToAppSecretName(k, n, config.CertName)
appSecret, err := getAppSecretInCluster(scg.KubeClient, appSecretName, ns)
if err != nil {
return nil, nil, nil, err
}
caSecretAndConfigMapName := ToCASecretAndConfigMapName(k, n)
var (
caSecret *v1.Secret
caConfigMap *v1.ConfigMap
)
caSecret, caConfigMap, err = getCASecretAndConfigMapInCluster(scg.KubeClient, caSecretAndConfigMapName, ns)
if err != nil {
return nil, nil, nil, err
}
if config.CAKey != "" && config.CACert != "" {
// custom CA provided by the user.
customCAKeyData, err := ioutil.ReadFile(config.CAKey)
if err != nil {
return nil, nil, nil, fmt.Errorf("error reading CA Key from the given file name: %v", err)
}
customCACertData, err := ioutil.ReadFile(config.CACert)
if err != nil {
return nil, nil, nil, fmt.Errorf("error reading CA Cert from the given file name: %v", err)
}
customCAKey, err := parsePEMEncodedPrivateKey(customCAKeyData)
if err != nil {
return nil, nil, nil, fmt.Errorf("error parsing CA Key from the given file name: %v", err)
}
customCACert, err := parsePEMEncodedCert(customCACertData)
if err != nil {
return nil, nil, nil, fmt.Errorf("error parsing CA Cert from the given file name: %v", err)
}
caSecret, caConfigMap = toCASecretAndConfigmap(customCAKey, customCACert, caSecretAndConfigMapName)
} else if config.CAKey != "" || config.CACert != "" {
// if only one of the custom CA Key or Cert is provided
return nil, nil, nil, ErrCAKeyAndCACertReq
}
hasAppSecret := appSecret != nil
hasCASecretAndConfigMap := caSecret != nil && caConfigMap != nil
switch {
case hasAppSecret && hasCASecretAndConfigMap:
return appSecret, caConfigMap, caSecret, nil
case hasAppSecret && !hasCASecretAndConfigMap:
return nil, nil, nil, ErrCANotFound
case !hasAppSecret && hasCASecretAndConfigMap:
// Note: if a custom CA is passed in my the user it takes preference over an already
// generated CA secret and CA configmap that might exist in the cluster
caKey, err := parsePEMEncodedPrivateKey(caSecret.Data[TLSPrivateCAKeyKey])
if err != nil {
return nil, nil, nil, err
}
caCert, err := parsePEMEncodedCert([]byte(caConfigMap.Data[TLSCACertKey]))
if err != nil {
return nil, nil, nil, err
}
key, err := newPrivateKey()
if err != nil {
return nil, nil, nil, err
}
cert, err := newSignedCertificate(config, service, key, caCert, caKey)
if err != nil {
return nil, nil, nil, err
}
appSecret, err := scg.KubeClient.CoreV1().Secrets(ns).Create(toTLSSecret(key, cert, appSecretName))
if err != nil {
return nil, nil, nil, err
}
return appSecret, caConfigMap, caSecret, nil
case !hasAppSecret && !hasCASecretAndConfigMap:
// If no custom CAKey and CACert are provided we have to generate them
caKey, err := newPrivateKey()
if err != nil {
return nil, nil, nil, err
}
caCert, err := newSelfSignedCACertificate(caKey)
if err != nil {
return nil, nil, nil, err
}
caSecret, caConfigMap := toCASecretAndConfigmap(caKey, caCert, caSecretAndConfigMapName)
caSecret, err = scg.KubeClient.CoreV1().Secrets(ns).Create(caSecret)
if err != nil {
return nil, nil, nil, err
}
caConfigMap, err = scg.KubeClient.CoreV1().ConfigMaps(ns).Create(caConfigMap)
if err != nil {
return nil, nil, nil, err
}
key, err := newPrivateKey()
if err != nil {
return nil, nil, nil, err
}
cert, err := newSignedCertificate(config, service, key, caCert, caKey)
if err != nil {
return nil, nil, nil, err
}
appSecret, err := scg.KubeClient.CoreV1().Secrets(ns).Create(toTLSSecret(key, cert, appSecretName))
if err != nil {
return nil, nil, nil, err
}
return appSecret, caConfigMap, caSecret, nil
default:
return nil, nil, nil, ErrInternal
}
}
func verifyConfig(config *CertConfig) error {
if config == nil {
return errors.New("nil CertConfig not allowed")
}
if config.CertName == "" {
return errors.New("empty CertConfig.CertName not allowed")
}
return nil
}
func ToAppSecretName(kind, name, certName string) string {
return strings.ToLower(kind) + "-" + name + "-" + certName
}
func ToCASecretAndConfigMapName(kind, name string) string {
return strings.ToLower(kind) + "-" + name + "-ca"
}
func getAppSecretInCluster(kubeClient kubernetes.Interface, name, namespace string) (*v1.Secret, error) {
se, err := kubeClient.CoreV1().Secrets(namespace).Get(name, metav1.GetOptions{})
if err != nil && !apiErrors.IsNotFound(err) {
return nil, err
}
if apiErrors.IsNotFound(err) {
return nil, nil
}
return se, nil
}
// getCASecretAndConfigMapInCluster gets CA secret and configmap of the given name and namespace.
// it only returns both if they are found and nil if both are not found. In the case if only one of them is found,
// then we error out because we expect either both CA secret and configmap exit or not.
//
// NOTE: both the CA secret and configmap have the same name with template `<cr-kind>-<cr-name>-ca` which is what the
// input parameter `name` refers to.
func getCASecretAndConfigMapInCluster(kubeClient kubernetes.Interface, name, namespace string) (*v1.Secret, *v1.ConfigMap, error) {
hasConfigMap := true
cm, err := kubeClient.CoreV1().ConfigMaps(namespace).Get(name, metav1.GetOptions{})
if err != nil && !apiErrors.IsNotFound(err) {
return nil, nil, err
}
if apiErrors.IsNotFound(err) {
hasConfigMap = false
}
hasSecret := true
se, err := kubeClient.CoreV1().Secrets(namespace).Get(name, metav1.GetOptions{})
if err != nil && !apiErrors.IsNotFound(err) {
return nil, nil, err
}
if apiErrors.IsNotFound(err) {
hasSecret = false
}
if hasConfigMap != hasSecret {
// TODO: this case can happen if creating CA configmap succeeds and creating CA secret failed. We need to handle this case properly.
return nil, nil, fmt.Errorf("expect either both ca configmap and secret both exist or not exist, but got hasCAConfigmap==%v and hasCASecret==%v", hasConfigMap, hasSecret)
}
if hasConfigMap == false {
return nil, nil, nil
}
return se, cm, nil
}
func toKindNameNamespace(cr runtime.Object) (string, string, string, error) {
a := meta.NewAccessor()
k, err := a.Kind(cr)
if err != nil {
return "", "", "", err
}
n, err := a.Name(cr)
if err != nil {
return "", "", "", err
}
ns, err := a.Namespace(cr)
if err != nil {
return "", "", "", err
}
return k, n, ns, nil
}
// toTLSSecret returns a client/server "kubernetes.io/tls" secret.
// TODO: add owner ref.
func toTLSSecret(key *rsa.PrivateKey, cert *x509.Certificate, name string) *v1.Secret {
return &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Data: map[string][]byte{
v1.TLSPrivateKeyKey: encodePrivateKeyPEM(key),
v1.TLSCertKey: encodeCertificatePEM(cert),
},
Type: v1.SecretTypeTLS,
}
}
// TODO: add owner ref.
func toCASecretAndConfigmap(key *rsa.PrivateKey, cert *x509.Certificate, name string) (*v1.Secret, *v1.ConfigMap) {
return &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Data: map[string][]byte{
TLSPrivateCAKeyKey: encodePrivateKeyPEM(key),
},
}, &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Data: map[string]string{
TLSCACertKey: string(encodeCertificatePEM(cert)),
},
}
} | // 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.
package tlsutil | random_line_split |
tls.go | // Copyright 2018 The Operator-SDK 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.
package tlsutil
import (
"crypto/rsa"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"strings"
"k8s.io/api/core/v1"
apiErrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
)
// CertType defines the type of the cert.
type CertType int
const (
// ClientAndServingCert defines both client and serving cert.
ClientAndServingCert CertType = iota
// ServingCert defines a serving cert.
ServingCert
// ClientCert defines a client cert.
ClientCert
)
// CertConfig configures how to generate the Cert.
type CertConfig struct {
// CertName is the name of the cert.
CertName string
// Optional CertType. Serving, client or both; defaults to both.
CertType CertType
// Optional CommonName is the common name of the cert; defaults to "".
CommonName string
// Optional Organization is Organization of the cert; defaults to "".
Organization []string
// Optional CA Key, if user wants to provide custom CA key via a file path.
CAKey string
// Optional CA Certificate, if user wants to provide custom CA cert via file path.
CACert string
// TODO: consider to add passed in SAN fields.
}
// CertGenerator is an operator specific TLS tool that generates TLS assets for the deploying a user's application.
type CertGenerator interface {
// GenerateCert generates a secret containing TLS encryption key and cert, a Secret
// containing the CA key, and a ConfigMap containing the CA Certificate given the Custom
// Resource(CR) "cr", the Kubernetes Service "Service", and the CertConfig "config".
//
// GenerateCert creates and manages TLS key and cert and CA with the following:
// CA creation and management:
// - If CA is not given:
// - A unique CA is generated for the CR.
// - CA's key is packaged into a Secret as shown below.
// - CA's cert is packaged in a ConfigMap as shown below.
// - The CA Secret and ConfigMap are created on the k8s cluster in the CR's namespace before
// returned to the user. The CertGenerator manages the CA Secret and ConfigMap to ensure it's
// unqiue per CR.
// - If CA is given:
// - CA's key is packaged into a Secret as shown below.
// - CA's cert is packaged in a ConfigMap as shown below.
// - The CA Secret and ConfigMap are returned but not created in the K8s cluster in the CR's
// namespace. The CertGenerator doesn't manage the CA because the user controls the lifecycle
// of the CA.
//
// TLS Key and Cert Creation and Management:
// - A unique TLS cert and key pair is generated per CR + CertConfig.CertName.
// - The CA is used to generate and sign the TLS cert.
// - The signing process uses the passed in "service" to set the Subject Alternative Names(SAN)
// for the certificate. We assume that the deployed applications are typically communicated
// with via a Kubernetes Service. The SAN is set to the FQDN of the service
// `<service-name>.<service-namespace>.svc.cluster.local`.
// - Once TLS key and cert are created, they are packaged into a secret as shown below.
// - Finally, the secret are created on the k8s cluster in the CR's namespace before returned to
// the user. The CertGenerator manages this secret to ensure that it is unique per CR +
// CertConfig.CertName.
//
// TLS encryption key and cert Secret format:
// kind: Secret
// apiVersion: v1
// metadata:
// name: <cr-kind>-<cr-name>-<CertConfig.CertName>
// namespace: <cr-namespace>
// data:
// tls.crt: ...
// tls.key: ...
//
// CA Certificate ConfigMap format:
// kind: ConfigMap
// apiVersion: v1
// metadata:
// name: <cr-kind>-<cr-name>-ca
// namespace: <cr-namespace>
// data:
// ca.crt: ...
//
// CA Key Secret format:
// kind: Secret
// apiVersion: v1
// metadata:
// name: <cr-kind>-<cr-name>-ca
// namespace: <cr-namespace>
// data:
// ca.key: ..
GenerateCert(cr runtime.Object, service *v1.Service, config *CertConfig) (*v1.Secret, *v1.ConfigMap, *v1.Secret, error)
}
const (
// TLSPrivateCAKeyKey is the key for the private CA key field.
TLSPrivateCAKeyKey = "ca.key"
// TLSCertKey is the key for tls CA certificates.
TLSCACertKey = "ca.crt"
)
// NewSDKCertGenerator constructs a new CertGenerator given the kubeClient.
func NewSDKCertGenerator(kubeClient kubernetes.Interface) CertGenerator {
return &SDKCertGenerator{KubeClient: kubeClient}
}
type SDKCertGenerator struct {
KubeClient kubernetes.Interface
}
// GenerateCert returns a secret containing the TLS encryption key and cert,
// a ConfigMap containing the CA Certificate and a Secret containing the CA key or it
// returns a error incase something goes wrong.
func (scg *SDKCertGenerator) GenerateCert(cr runtime.Object, service *v1.Service, config *CertConfig) (*v1.Secret, *v1.ConfigMap, *v1.Secret, error) {
if err := verifyConfig(config); err != nil {
return nil, nil, nil, err
}
k, n, ns, err := toKindNameNamespace(cr)
if err != nil {
return nil, nil, nil, err
}
appSecretName := ToAppSecretName(k, n, config.CertName)
appSecret, err := getAppSecretInCluster(scg.KubeClient, appSecretName, ns)
if err != nil {
return nil, nil, nil, err
}
caSecretAndConfigMapName := ToCASecretAndConfigMapName(k, n)
var (
caSecret *v1.Secret
caConfigMap *v1.ConfigMap
)
caSecret, caConfigMap, err = getCASecretAndConfigMapInCluster(scg.KubeClient, caSecretAndConfigMapName, ns)
if err != nil {
return nil, nil, nil, err
}
if config.CAKey != "" && config.CACert != "" {
// custom CA provided by the user.
customCAKeyData, err := ioutil.ReadFile(config.CAKey)
if err != nil {
return nil, nil, nil, fmt.Errorf("error reading CA Key from the given file name: %v", err)
}
customCACertData, err := ioutil.ReadFile(config.CACert)
if err != nil {
return nil, nil, nil, fmt.Errorf("error reading CA Cert from the given file name: %v", err)
}
customCAKey, err := parsePEMEncodedPrivateKey(customCAKeyData)
if err != nil {
return nil, nil, nil, fmt.Errorf("error parsing CA Key from the given file name: %v", err)
}
customCACert, err := parsePEMEncodedCert(customCACertData)
if err != nil {
return nil, nil, nil, fmt.Errorf("error parsing CA Cert from the given file name: %v", err)
}
caSecret, caConfigMap = toCASecretAndConfigmap(customCAKey, customCACert, caSecretAndConfigMapName)
} else if config.CAKey != "" || config.CACert != "" {
// if only one of the custom CA Key or Cert is provided
return nil, nil, nil, ErrCAKeyAndCACertReq
}
hasAppSecret := appSecret != nil
hasCASecretAndConfigMap := caSecret != nil && caConfigMap != nil
switch {
case hasAppSecret && hasCASecretAndConfigMap:
return appSecret, caConfigMap, caSecret, nil
case hasAppSecret && !hasCASecretAndConfigMap:
return nil, nil, nil, ErrCANotFound
case !hasAppSecret && hasCASecretAndConfigMap:
// Note: if a custom CA is passed in my the user it takes preference over an already
// generated CA secret and CA configmap that might exist in the cluster
caKey, err := parsePEMEncodedPrivateKey(caSecret.Data[TLSPrivateCAKeyKey])
if err != nil {
return nil, nil, nil, err
}
caCert, err := parsePEMEncodedCert([]byte(caConfigMap.Data[TLSCACertKey]))
if err != nil {
return nil, nil, nil, err
}
key, err := newPrivateKey()
if err != nil {
return nil, nil, nil, err
}
cert, err := newSignedCertificate(config, service, key, caCert, caKey)
if err != nil {
return nil, nil, nil, err
}
appSecret, err := scg.KubeClient.CoreV1().Secrets(ns).Create(toTLSSecret(key, cert, appSecretName))
if err != nil {
return nil, nil, nil, err
}
return appSecret, caConfigMap, caSecret, nil
case !hasAppSecret && !hasCASecretAndConfigMap:
// If no custom CAKey and CACert are provided we have to generate them
caKey, err := newPrivateKey()
if err != nil {
return nil, nil, nil, err
}
caCert, err := newSelfSignedCACertificate(caKey)
if err != nil {
return nil, nil, nil, err
}
caSecret, caConfigMap := toCASecretAndConfigmap(caKey, caCert, caSecretAndConfigMapName)
caSecret, err = scg.KubeClient.CoreV1().Secrets(ns).Create(caSecret)
if err != nil {
return nil, nil, nil, err
}
caConfigMap, err = scg.KubeClient.CoreV1().ConfigMaps(ns).Create(caConfigMap)
if err != nil {
return nil, nil, nil, err
}
key, err := newPrivateKey()
if err != nil {
return nil, nil, nil, err
}
cert, err := newSignedCertificate(config, service, key, caCert, caKey)
if err != nil {
return nil, nil, nil, err
}
appSecret, err := scg.KubeClient.CoreV1().Secrets(ns).Create(toTLSSecret(key, cert, appSecretName))
if err != nil {
return nil, nil, nil, err
}
return appSecret, caConfigMap, caSecret, nil
default:
return nil, nil, nil, ErrInternal
}
}
func verifyConfig(config *CertConfig) error {
if config == nil {
return errors.New("nil CertConfig not allowed")
}
if config.CertName == "" {
return errors.New("empty CertConfig.CertName not allowed")
}
return nil
}
func ToAppSecretName(kind, name, certName string) string {
return strings.ToLower(kind) + "-" + name + "-" + certName
}
func ToCASecretAndConfigMapName(kind, name string) string {
return strings.ToLower(kind) + "-" + name + "-ca"
}
func getAppSecretInCluster(kubeClient kubernetes.Interface, name, namespace string) (*v1.Secret, error) |
// getCASecretAndConfigMapInCluster gets CA secret and configmap of the given name and namespace.
// it only returns both if they are found and nil if both are not found. In the case if only one of them is found,
// then we error out because we expect either both CA secret and configmap exit or not.
//
// NOTE: both the CA secret and configmap have the same name with template `<cr-kind>-<cr-name>-ca` which is what the
// input parameter `name` refers to.
func getCASecretAndConfigMapInCluster(kubeClient kubernetes.Interface, name, namespace string) (*v1.Secret, *v1.ConfigMap, error) {
hasConfigMap := true
cm, err := kubeClient.CoreV1().ConfigMaps(namespace).Get(name, metav1.GetOptions{})
if err != nil && !apiErrors.IsNotFound(err) {
return nil, nil, err
}
if apiErrors.IsNotFound(err) {
hasConfigMap = false
}
hasSecret := true
se, err := kubeClient.CoreV1().Secrets(namespace).Get(name, metav1.GetOptions{})
if err != nil && !apiErrors.IsNotFound(err) {
return nil, nil, err
}
if apiErrors.IsNotFound(err) {
hasSecret = false
}
if hasConfigMap != hasSecret {
// TODO: this case can happen if creating CA configmap succeeds and creating CA secret failed. We need to handle this case properly.
return nil, nil, fmt.Errorf("expect either both ca configmap and secret both exist or not exist, but got hasCAConfigmap==%v and hasCASecret==%v", hasConfigMap, hasSecret)
}
if hasConfigMap == false {
return nil, nil, nil
}
return se, cm, nil
}
func toKindNameNamespace(cr runtime.Object) (string, string, string, error) {
a := meta.NewAccessor()
k, err := a.Kind(cr)
if err != nil {
return "", "", "", err
}
n, err := a.Name(cr)
if err != nil {
return "", "", "", err
}
ns, err := a.Namespace(cr)
if err != nil {
return "", "", "", err
}
return k, n, ns, nil
}
// toTLSSecret returns a client/server "kubernetes.io/tls" secret.
// TODO: add owner ref.
func toTLSSecret(key *rsa.PrivateKey, cert *x509.Certificate, name string) *v1.Secret {
return &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Data: map[string][]byte{
v1.TLSPrivateKeyKey: encodePrivateKeyPEM(key),
v1.TLSCertKey: encodeCertificatePEM(cert),
},
Type: v1.SecretTypeTLS,
}
}
// TODO: add owner ref.
func toCASecretAndConfigmap(key *rsa.PrivateKey, cert *x509.Certificate, name string) (*v1.Secret, *v1.ConfigMap) {
return &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Data: map[string][]byte{
TLSPrivateCAKeyKey: encodePrivateKeyPEM(key),
},
}, &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Data: map[string]string{
TLSCACertKey: string(encodeCertificatePEM(cert)),
},
}
}
| {
se, err := kubeClient.CoreV1().Secrets(namespace).Get(name, metav1.GetOptions{})
if err != nil && !apiErrors.IsNotFound(err) {
return nil, err
}
if apiErrors.IsNotFound(err) {
return nil, nil
}
return se, nil
} | identifier_body |
universal.rs | use crate::{script, Tag, Face, GlyphInfo, Mask, Script};
use crate::buffer::{Buffer, BufferFlags};
use crate::ot::{feature, FeatureFlags};
use crate::plan::{ShapePlan, ShapePlanner};
use crate::unicode::{CharExt, GeneralCategoryExt};
use super::*;
use super::arabic::ArabicShapePlan;
pub const UNIVERSAL_SHAPER: ComplexShaper = ComplexShaper {
collect_features: Some(collect_features),
override_features: None,
create_data: Some(|plan| Box::new(UniversalShapePlan::new(plan))),
preprocess_text: Some(preprocess_text),
postprocess_glyphs: None,
normalization_mode: Some(ShapeNormalizationMode::ComposedDiacriticsNoShortCircuit),
decompose: None,
compose: Some(compose),
setup_masks: Some(setup_masks),
gpos_tag: None,
reorder_marks: None,
zero_width_marks: Some(ZeroWidthMarksMode::ByGdefEarly),
fallback_position: false,
};
pub type Category = u8;
pub mod category {
pub const O: u8 = 0; // OTHER
pub const B: u8 = 1; // BASE
pub const IND: u8 = 3; // BASE_IND
pub const N: u8 = 4; // BASE_NUM
pub const GB: u8 = 5; // BASE_OTHER
pub const CGJ: u8 = 6; // CGJ
// pub const F: u8 = 7; // CONS_FINAL
pub const FM: u8 = 8; // CONS_FINAL_MOD
// pub const M: u8 = 9; // CONS_MED
// pub const CM: u8 = 10; // CONS_MOD
pub const SUB: u8 = 11; // CONS_SUB
pub const H: u8 = 12; // HALANT
pub const HN: u8 = 13; // HALANT_NUM
pub const ZWNJ: u8 = 14; // Zero width non-joiner
pub const ZWJ: u8 = 15; // Zero width joiner
pub const WJ: u8 = 16; // Word joiner
// pub const RSV: u8 = 17; // Reserved characters
pub const R: u8 = 18; // REPHA
pub const S: u8 = 19; // SYM
// pub const SM: u8 = 20; // SYM_MOD
pub const VS: u8 = 21; // VARIATION_SELECTOR
// pub const V: u8 = 36; // VOWEL
// pub const VM: u8 = 40; // VOWEL_MOD
pub const CS: u8 = 43; // CONS_WITH_STACKER
// https://github.com/harfbuzz/harfbuzz/issues/1102
pub const HVM: u8 = 44; // HALANT_OR_VOWEL_MODIFIER
pub const SK: u8 = 48; // SAKOT
pub const FABV: u8 = 24; // CONS_FINAL_ABOVE
pub const FBLW: u8 = 25; // CONS_FINAL_BELOW
pub const FPST: u8 = 26; // CONS_FINAL_POST
pub const MABV: u8 = 27; // CONS_MED_ABOVE
pub const MBLW: u8 = 28; // CONS_MED_BELOW
pub const MPST: u8 = 29; // CONS_MED_POST
pub const MPRE: u8 = 30; // CONS_MED_PRE
pub const CMABV: u8 = 31; // CONS_MOD_ABOVE
pub const CMBLW: u8 = 32; // CONS_MOD_BELOW
pub const VABV: u8 = 33; // VOWEL_ABOVE / VOWEL_ABOVE_BELOW / VOWEL_ABOVE_BELOW_POST / VOWEL_ABOVE_POST
pub const VBLW: u8 = 34; // VOWEL_BELOW / VOWEL_BELOW_POST
pub const VPST: u8 = 35; // VOWEL_POST UIPC = Right
pub const VPRE: u8 = 22; // VOWEL_PRE / VOWEL_PRE_ABOVE / VOWEL_PRE_ABOVE_POST / VOWEL_PRE_POST
pub const VMABV: u8 = 37; // VOWEL_MOD_ABOVE
pub const VMBLW: u8 = 38; // VOWEL_MOD_BELOW
pub const VMPST: u8 = 39; // VOWEL_MOD_POST
pub const VMPRE: u8 = 23; // VOWEL_MOD_PRE
pub const SMABV: u8 = 41; // SYM_MOD_ABOVE
pub const SMBLW: u8 = 42; // SYM_MOD_BELOW
pub const FMABV: u8 = 45; // CONS_FINAL_MOD UIPC = Top
pub const FMBLW: u8 = 46; // CONS_FINAL_MOD UIPC = Bottom
pub const FMPST: u8 = 47; // CONS_FINAL_MOD UIPC = Not_Applicable
}
// These features are applied all at once, before reordering.
const BASIC_FEATURES: &[Tag] = &[
feature::RAKAR_FORMS,
feature::ABOVE_BASE_FORMS,
feature::BELOW_BASE_FORMS,
feature::HALF_FORMS,
feature::POST_BASE_FORMS,
feature::VATTU_VARIANTS,
feature::CONJUNCT_FORMS,
];
const TOPOGRAPHICAL_FEATURES: &[Tag] = &[
feature::ISOLATED_FORMS,
feature::INITIAL_FORMS,
feature::MEDIAL_FORMS_1,
feature::TERMINAL_FORMS_1,
];
// Same order as use_topographical_features.
#[derive(Clone, Copy, PartialEq)]
enum JoiningForm {
Isolated = 0,
Initial,
Medial,
Terminal,
}
// These features are applied all at once, after reordering and clearing syllables.
const OTHER_FEATURES: &[Tag] = &[
feature::ABOVE_BASE_SUBSTITUTIONS,
feature::BELOW_BASE_SUBSTITUTIONS,
feature::HALANT_FORMS,
feature::PRE_BASE_SUBSTITUTIONS,
feature::POST_BASE_SUBSTITUTIONS,
];
impl GlyphInfo {
pub(crate) fn use_category(&self) -> Category {
let v: &[u8; 4] = bytemuck::cast_ref(&self.var2);
v[2]
}
fn set_use_category(&mut self, c: Category) {
let v: &mut [u8; 4] = bytemuck::cast_mut(&mut self.var2);
v[2] = c;
}
fn is_halant_use(&self) -> bool {
matches!(self.use_category(), category::H | category::HVM) && !self.is_ligated()
}
}
struct UniversalShapePlan {
rphf_mask: Mask,
arabic_plan: Option<ArabicShapePlan>,
}
impl UniversalShapePlan {
fn new(plan: &ShapePlan) -> UniversalShapePlan {
let mut arabic_plan = None;
if plan.script.map_or(false, has_arabic_joining) {
arabic_plan = Some(super::arabic::ArabicShapePlan::new(plan));
}
UniversalShapePlan {
rphf_mask: plan.ot_map.one_mask(feature::REPH_FORMS),
arabic_plan,
}
}
}
fn collect_features(planner: &mut ShapePlanner) {
// Do this before any lookups have been applied.
planner.ot_map.add_gsub_pause(Some(setup_syllables));
// Default glyph pre-processing group
planner.ot_map.enable_feature(feature::LOCALIZED_FORMS, FeatureFlags::empty(), 1);
planner.ot_map.enable_feature(feature::GLYPH_COMPOSITION_DECOMPOSITION, FeatureFlags::empty(), 1);
planner.ot_map.enable_feature(feature::NUKTA_FORMS, FeatureFlags::empty(), 1);
planner.ot_map.enable_feature(feature::AKHANDS, FeatureFlags::MANUAL_ZWJ, 1);
// Reordering group
planner.ot_map.add_gsub_pause(Some(crate::ot::clear_substitution_flags));
planner.ot_map.add_feature(feature::REPH_FORMS, FeatureFlags::MANUAL_ZWJ, 1);
planner.ot_map.add_gsub_pause(Some(record_rphf));
planner.ot_map.add_gsub_pause(Some(crate::ot::clear_substitution_flags));
planner.ot_map.enable_feature(feature::PRE_BASE_FORMS, FeatureFlags::MANUAL_ZWJ, 1);
planner.ot_map.add_gsub_pause(Some(record_pref));
// Orthographic unit shaping group
for feature in BASIC_FEATURES {
planner.ot_map.enable_feature(*feature, FeatureFlags::MANUAL_ZWJ, 1);
}
planner.ot_map.add_gsub_pause(Some(reorder));
planner.ot_map.add_gsub_pause(Some(crate::ot::clear_syllables));
// Topographical features
for feature in TOPOGRAPHICAL_FEATURES {
planner.ot_map.add_feature(*feature, FeatureFlags::empty(), 1);
}
planner.ot_map.add_gsub_pause(None);
// Standard typographic presentation
for feature in OTHER_FEATURES {
planner.ot_map.enable_feature(*feature, FeatureFlags::empty(), 1);
}
}
fn setup_syllables(plan: &ShapePlan, _: &Face, buffer: &mut Buffer) {
super::universal_machine::find_syllables(buffer);
foreach_syllable!(buffer, start, end, {
buffer.unsafe_to_break(start, end);
});
setup_rphf_mask(plan, buffer);
setup_topographical_masks(plan, buffer);
}
fn setup_rphf_mask(plan: &ShapePlan, buffer: &mut Buffer) {
let universal_plan = plan.data::<UniversalShapePlan>();
let mask = universal_plan.rphf_mask;
if mask == 0 {
return;
}
let mut start = 0;
let mut end = buffer.next_syllable(0);
while start < buffer.len {
let limit = if buffer.info[start].use_category() == category::R {
1
} else {
core::cmp::min(3, end - start)
};
for i in start..start+limit {
buffer.info[i].mask |= mask;
}
start = end;
end = buffer.next_syllable(start);
}
}
fn setup_topographical_masks(plan: &ShapePlan, buffer: &mut Buffer) {
use super::universal_machine::SyllableType;
let mut masks = [0; 4];
let mut all_masks = 0;
for i in 0..4 {
masks[i] = plan.ot_map.one_mask(TOPOGRAPHICAL_FEATURES[i]);
if masks[i] == plan.ot_map.global_mask() {
masks[i] = 0;
}
all_masks |= masks[i];
}
if all_masks == 0 {
return;
}
let other_masks = !all_masks;
let mut last_start = 0;
let mut last_form = None;
let mut start = 0;
let mut end = buffer.next_syllable(0);
while start < buffer.len {
let syllable = buffer.info[start].syllable() & 0x0F;
if syllable == SyllableType::IndependentCluster as u8 ||
syllable == SyllableType::SymbolCluster as u8 ||
syllable == SyllableType::NonCluster as u8
{
last_form = None;
} else {
let join = last_form == Some(JoiningForm::Terminal) || last_form == Some(JoiningForm::Isolated);
if join {
// Fixup previous syllable's form.
let form = if last_form == Some(JoiningForm::Terminal) {
JoiningForm::Medial
} else {
JoiningForm::Initial
};
for i in last_start..start {
buffer.info[i].mask = (buffer.info[i].mask & other_masks) | masks[form as usize];
}
}
// Form for this syllable.
let form = if join { JoiningForm::Terminal } else { JoiningForm::Isolated };
last_form = Some(form);
for i in start..end {
buffer.info[i].mask = (buffer.info[i].mask & other_masks) | masks[form as usize];
}
}
last_start = start;
start = end;
end = buffer.next_syllable(start);
}
}
fn record_rphf(plan: &ShapePlan, _: &Face, buffer: &mut Buffer) |
fn reorder(_: &ShapePlan, face: &Face, buffer: &mut Buffer) {
insert_dotted_circles(face, buffer);
let mut start = 0;
let mut end = buffer.next_syllable(0);
while start < buffer.len {
reorder_syllable(start, end, buffer);
start = end;
end = buffer.next_syllable(start);
}
}
fn insert_dotted_circles(face: &Face, buffer: &mut Buffer) {
use super::universal_machine::SyllableType;
if buffer.flags.contains(BufferFlags::DO_NOT_INSERT_DOTTED_CIRCLE) {
return;
}
// Note: This loop is extra overhead, but should not be measurable.
// TODO Use a buffer scratch flag to remove the loop.
let has_broken_syllables = buffer.info_slice().iter()
.any(|info| info.syllable() & 0x0F == SyllableType::BrokenCluster as u8);
if !has_broken_syllables {
return;
}
let dottedcircle_glyph = match face.glyph_index(0x25CC) {
Some(g) => g.0 as u32,
None => return,
};
let mut dottedcircle = GlyphInfo {
glyph_id: dottedcircle_glyph,
..GlyphInfo::default()
};
dottedcircle.set_use_category(super::universal_table::get_category(0x25CC));
buffer.clear_output();
buffer.idx = 0;
let mut last_syllable = 0;
while buffer.idx < buffer.len {
let syllable = buffer.cur(0).syllable();
let syllable_type = syllable & 0x0F;
if last_syllable != syllable && syllable_type == SyllableType::BrokenCluster as u8 {
last_syllable = syllable;
let mut ginfo = dottedcircle;
ginfo.cluster = buffer.cur(0).cluster;
ginfo.mask = buffer.cur(0).mask;
ginfo.set_syllable(buffer.cur(0).syllable());
// Insert dottedcircle after possible Repha.
while buffer.idx < buffer.len &&
last_syllable == buffer.cur(0).syllable() &&
buffer.cur(0).use_category() == category::R
{
buffer.next_glyph();
}
buffer.output_info(ginfo);
} else {
buffer.next_glyph();
}
}
buffer.swap_buffers();
}
const fn category_flag(c: Category) -> u32 {
rb_flag(c as u32)
}
const fn category_flag64(c: Category) -> u64 {
rb_flag64(c as u32)
}
const BASE_FLAGS: u64 =
category_flag64(category::FM) |
category_flag64(category::FABV) |
category_flag64(category::FBLW) |
category_flag64(category::FPST) |
category_flag64(category::MABV) |
category_flag64(category::MBLW) |
category_flag64(category::MPST) |
category_flag64(category::MPRE) |
category_flag64(category::VABV) |
category_flag64(category::VBLW) |
category_flag64(category::VPST) |
category_flag64(category::VPRE) |
category_flag64(category::VMABV) |
category_flag64(category::VMBLW) |
category_flag64(category::VMPST) |
category_flag64(category::VMPRE);
fn reorder_syllable(start: usize, end: usize, buffer: &mut Buffer) {
use super::universal_machine::SyllableType;
let syllable_type = (buffer.info[start].syllable() & 0x0F) as u32;
// Only a few syllable types need reordering.
if (rb_flag_unsafe(syllable_type) &
(rb_flag(SyllableType::ViramaTerminatedCluster as u32) |
rb_flag(SyllableType::SakotTerminatedCluster as u32) |
rb_flag(SyllableType::StandardCluster as u32) |
rb_flag(SyllableType::BrokenCluster as u32) |
0)) == 0
{
return;
}
// Move things forward.
if buffer.info[start].use_category() == category::R && end - start > 1 {
// Got a repha. Reorder it towards the end, but before the first post-base glyph.
for i in start+1..end {
let is_post_base_glyph =
(rb_flag64_unsafe(buffer.info[i].use_category() as u32) & BASE_FLAGS) != 0 ||
buffer.info[i].is_halant_use();
if is_post_base_glyph || i == end - 1 {
// If we hit a post-base glyph, move before it; otherwise move to the
// end. Shift things in between backward.
let mut i = i;
if is_post_base_glyph {
i -= 1;
}
buffer.merge_clusters(start, i + 1);
let t = buffer.info[start];
for k in 0..i-start {
buffer.info[k + start] = buffer.info[k + start + 1];
}
buffer.info[i] = t;
break;
}
}
}
// Move things back.
let mut j = start;
for i in start..end {
let flag = rb_flag_unsafe(buffer.info[i].use_category() as u32);
if buffer.info[i].is_halant_use() {
// If we hit a halant, move after it; otherwise move to the beginning, and
// shift things in between forward.
j = i + 1;
} else if (flag & (category_flag(category::VPRE) | category_flag(category::VMPRE))) != 0 &&
buffer.info[i].lig_comp() == 0 && j < i
{
// Only move the first component of a MultipleSubst.
buffer.merge_clusters(j, i + 1);
let t = buffer.info[i];
for k in (0..i-j).rev() {
buffer.info[k + j + 1] = buffer.info[k + j];
}
buffer.info[j] = t;
}
}
}
fn record_pref(_: &ShapePlan, _: &Face, buffer: &mut Buffer) {
let mut start = 0;
let mut end = buffer.next_syllable(0);
while start < buffer.len {
// Mark a substituted pref as VPre, as they behave the same way.
for i in start..end {
if buffer.info[i].is_substituted() {
buffer.info[i].set_use_category(category::VPRE);
break;
}
}
start = end;
end = buffer.next_syllable(start);
}
}
fn has_arabic_joining(script: Script) -> bool {
// List of scripts that have data in arabic-table.
match script {
// Unicode-1.1 additions.
script::ARABIC |
// Unicode-3.0 additions.
script::MONGOLIAN |
script::SYRIAC |
// Unicode-5.0 additions.
script::NKO |
script::PHAGS_PA |
// Unicode-6.0 additions.
script::MANDAIC |
// Unicode-7.0 additions.
script::MANICHAEAN |
script::PSALTER_PAHLAVI |
// Unicode-9.0 additions.
script::ADLAM => true,
_ => false,
}
}
fn preprocess_text(_: &ShapePlan, _: &Face, buffer: &mut Buffer) {
super::vowel_constraints::preprocess_text_vowel_constraints(buffer);
}
fn compose(_: &ShapeNormalizeContext, a: char, b: char) -> Option<char> {
// Avoid recomposing split matras.
if a.general_category().is_mark() {
return None;
}
crate::unicode::compose(a, b)
}
fn setup_masks(plan: &ShapePlan, _: &Face, buffer: &mut Buffer) {
let universal_plan = plan.data::<UniversalShapePlan>();
// Do this before allocating use_category().
if let Some(ref arabic_plan) = universal_plan.arabic_plan {
super::arabic::setup_masks_inner(arabic_plan, plan.script, buffer);
}
// We cannot setup masks here. We save information about characters
// and setup masks later on in a pause-callback.
for info in buffer.info_slice_mut() {
info.set_use_category(super::universal_table::get_category(info.glyph_id));
}
}
| {
let universal_plan = plan.data::<UniversalShapePlan>();
let mask = universal_plan.rphf_mask;
if mask == 0 {
return;
}
let mut start = 0;
let mut end = buffer.next_syllable(0);
while start < buffer.len {
// Mark a substituted repha as USE_R.
for i in start..end {
if buffer.info[i].mask & mask == 0 {
break;
}
if buffer.info[i].is_substituted() {
buffer.info[i].set_use_category(category::R);
break;
}
}
start = end;
end = buffer.next_syllable(start);
}
} | identifier_body |
universal.rs | use crate::{script, Tag, Face, GlyphInfo, Mask, Script};
use crate::buffer::{Buffer, BufferFlags};
use crate::ot::{feature, FeatureFlags};
use crate::plan::{ShapePlan, ShapePlanner};
use crate::unicode::{CharExt, GeneralCategoryExt};
use super::*;
use super::arabic::ArabicShapePlan;
pub const UNIVERSAL_SHAPER: ComplexShaper = ComplexShaper {
collect_features: Some(collect_features),
override_features: None,
create_data: Some(|plan| Box::new(UniversalShapePlan::new(plan))),
preprocess_text: Some(preprocess_text),
postprocess_glyphs: None,
normalization_mode: Some(ShapeNormalizationMode::ComposedDiacriticsNoShortCircuit),
decompose: None,
compose: Some(compose),
setup_masks: Some(setup_masks),
gpos_tag: None,
reorder_marks: None,
zero_width_marks: Some(ZeroWidthMarksMode::ByGdefEarly),
fallback_position: false,
};
pub type Category = u8;
pub mod category {
pub const O: u8 = 0; // OTHER
pub const B: u8 = 1; // BASE
pub const IND: u8 = 3; // BASE_IND
pub const N: u8 = 4; // BASE_NUM
pub const GB: u8 = 5; // BASE_OTHER
pub const CGJ: u8 = 6; // CGJ
// pub const F: u8 = 7; // CONS_FINAL
pub const FM: u8 = 8; // CONS_FINAL_MOD
// pub const M: u8 = 9; // CONS_MED
// pub const CM: u8 = 10; // CONS_MOD
pub const SUB: u8 = 11; // CONS_SUB
pub const H: u8 = 12; // HALANT
pub const HN: u8 = 13; // HALANT_NUM
pub const ZWNJ: u8 = 14; // Zero width non-joiner
pub const ZWJ: u8 = 15; // Zero width joiner
pub const WJ: u8 = 16; // Word joiner
// pub const RSV: u8 = 17; // Reserved characters
pub const R: u8 = 18; // REPHA
pub const S: u8 = 19; // SYM
// pub const SM: u8 = 20; // SYM_MOD
pub const VS: u8 = 21; // VARIATION_SELECTOR
// pub const V: u8 = 36; // VOWEL
// pub const VM: u8 = 40; // VOWEL_MOD
pub const CS: u8 = 43; // CONS_WITH_STACKER
// https://github.com/harfbuzz/harfbuzz/issues/1102
pub const HVM: u8 = 44; // HALANT_OR_VOWEL_MODIFIER
pub const SK: u8 = 48; // SAKOT
pub const FABV: u8 = 24; // CONS_FINAL_ABOVE
pub const FBLW: u8 = 25; // CONS_FINAL_BELOW
pub const FPST: u8 = 26; // CONS_FINAL_POST
pub const MABV: u8 = 27; // CONS_MED_ABOVE
pub const MBLW: u8 = 28; // CONS_MED_BELOW
pub const MPST: u8 = 29; // CONS_MED_POST
pub const MPRE: u8 = 30; // CONS_MED_PRE
pub const CMABV: u8 = 31; // CONS_MOD_ABOVE
pub const CMBLW: u8 = 32; // CONS_MOD_BELOW
pub const VABV: u8 = 33; // VOWEL_ABOVE / VOWEL_ABOVE_BELOW / VOWEL_ABOVE_BELOW_POST / VOWEL_ABOVE_POST
pub const VBLW: u8 = 34; // VOWEL_BELOW / VOWEL_BELOW_POST
pub const VPST: u8 = 35; // VOWEL_POST UIPC = Right
pub const VPRE: u8 = 22; // VOWEL_PRE / VOWEL_PRE_ABOVE / VOWEL_PRE_ABOVE_POST / VOWEL_PRE_POST
pub const VMABV: u8 = 37; // VOWEL_MOD_ABOVE
pub const VMBLW: u8 = 38; // VOWEL_MOD_BELOW
pub const VMPST: u8 = 39; // VOWEL_MOD_POST
pub const VMPRE: u8 = 23; // VOWEL_MOD_PRE
pub const SMABV: u8 = 41; // SYM_MOD_ABOVE
pub const SMBLW: u8 = 42; // SYM_MOD_BELOW
pub const FMABV: u8 = 45; // CONS_FINAL_MOD UIPC = Top
pub const FMBLW: u8 = 46; // CONS_FINAL_MOD UIPC = Bottom
pub const FMPST: u8 = 47; // CONS_FINAL_MOD UIPC = Not_Applicable
}
// These features are applied all at once, before reordering.
const BASIC_FEATURES: &[Tag] = &[
feature::RAKAR_FORMS,
feature::ABOVE_BASE_FORMS,
feature::BELOW_BASE_FORMS,
feature::HALF_FORMS,
feature::POST_BASE_FORMS,
feature::VATTU_VARIANTS,
feature::CONJUNCT_FORMS,
];
const TOPOGRAPHICAL_FEATURES: &[Tag] = &[
feature::ISOLATED_FORMS,
feature::INITIAL_FORMS,
feature::MEDIAL_FORMS_1,
feature::TERMINAL_FORMS_1,
];
// Same order as use_topographical_features.
#[derive(Clone, Copy, PartialEq)]
enum JoiningForm {
Isolated = 0,
Initial,
Medial,
Terminal,
}
// These features are applied all at once, after reordering and clearing syllables.
const OTHER_FEATURES: &[Tag] = &[
feature::ABOVE_BASE_SUBSTITUTIONS,
feature::BELOW_BASE_SUBSTITUTIONS,
feature::HALANT_FORMS,
feature::PRE_BASE_SUBSTITUTIONS,
feature::POST_BASE_SUBSTITUTIONS,
];
impl GlyphInfo {
pub(crate) fn use_category(&self) -> Category {
let v: &[u8; 4] = bytemuck::cast_ref(&self.var2);
v[2]
}
fn set_use_category(&mut self, c: Category) {
let v: &mut [u8; 4] = bytemuck::cast_mut(&mut self.var2);
v[2] = c;
}
fn is_halant_use(&self) -> bool {
matches!(self.use_category(), category::H | category::HVM) && !self.is_ligated()
}
}
struct UniversalShapePlan {
rphf_mask: Mask,
arabic_plan: Option<ArabicShapePlan>,
}
impl UniversalShapePlan {
fn new(plan: &ShapePlan) -> UniversalShapePlan {
let mut arabic_plan = None;
if plan.script.map_or(false, has_arabic_joining) {
arabic_plan = Some(super::arabic::ArabicShapePlan::new(plan));
}
UniversalShapePlan {
rphf_mask: plan.ot_map.one_mask(feature::REPH_FORMS),
arabic_plan,
}
}
}
fn collect_features(planner: &mut ShapePlanner) {
// Do this before any lookups have been applied.
planner.ot_map.add_gsub_pause(Some(setup_syllables));
// Default glyph pre-processing group
planner.ot_map.enable_feature(feature::LOCALIZED_FORMS, FeatureFlags::empty(), 1);
planner.ot_map.enable_feature(feature::GLYPH_COMPOSITION_DECOMPOSITION, FeatureFlags::empty(), 1);
planner.ot_map.enable_feature(feature::NUKTA_FORMS, FeatureFlags::empty(), 1);
planner.ot_map.enable_feature(feature::AKHANDS, FeatureFlags::MANUAL_ZWJ, 1);
// Reordering group
planner.ot_map.add_gsub_pause(Some(crate::ot::clear_substitution_flags));
planner.ot_map.add_feature(feature::REPH_FORMS, FeatureFlags::MANUAL_ZWJ, 1);
planner.ot_map.add_gsub_pause(Some(record_rphf));
planner.ot_map.add_gsub_pause(Some(crate::ot::clear_substitution_flags));
planner.ot_map.enable_feature(feature::PRE_BASE_FORMS, FeatureFlags::MANUAL_ZWJ, 1);
planner.ot_map.add_gsub_pause(Some(record_pref));
// Orthographic unit shaping group
for feature in BASIC_FEATURES {
planner.ot_map.enable_feature(*feature, FeatureFlags::MANUAL_ZWJ, 1);
}
planner.ot_map.add_gsub_pause(Some(reorder));
planner.ot_map.add_gsub_pause(Some(crate::ot::clear_syllables));
// Topographical features
for feature in TOPOGRAPHICAL_FEATURES {
planner.ot_map.add_feature(*feature, FeatureFlags::empty(), 1);
}
planner.ot_map.add_gsub_pause(None);
// Standard typographic presentation
for feature in OTHER_FEATURES {
planner.ot_map.enable_feature(*feature, FeatureFlags::empty(), 1);
}
}
fn setup_syllables(plan: &ShapePlan, _: &Face, buffer: &mut Buffer) {
super::universal_machine::find_syllables(buffer);
foreach_syllable!(buffer, start, end, {
buffer.unsafe_to_break(start, end);
});
setup_rphf_mask(plan, buffer);
setup_topographical_masks(plan, buffer);
}
fn setup_rphf_mask(plan: &ShapePlan, buffer: &mut Buffer) {
let universal_plan = plan.data::<UniversalShapePlan>();
let mask = universal_plan.rphf_mask;
if mask == 0 {
return;
}
let mut start = 0;
let mut end = buffer.next_syllable(0);
while start < buffer.len {
let limit = if buffer.info[start].use_category() == category::R {
1
} else {
core::cmp::min(3, end - start)
};
for i in start..start+limit {
buffer.info[i].mask |= mask;
}
start = end;
end = buffer.next_syllable(start);
}
}
fn setup_topographical_masks(plan: &ShapePlan, buffer: &mut Buffer) {
use super::universal_machine::SyllableType;
let mut masks = [0; 4];
let mut all_masks = 0;
for i in 0..4 {
masks[i] = plan.ot_map.one_mask(TOPOGRAPHICAL_FEATURES[i]);
if masks[i] == plan.ot_map.global_mask() {
masks[i] = 0;
}
all_masks |= masks[i];
}
if all_masks == 0 {
return;
}
let other_masks = !all_masks;
let mut last_start = 0;
let mut last_form = None;
let mut start = 0;
let mut end = buffer.next_syllable(0);
while start < buffer.len {
let syllable = buffer.info[start].syllable() & 0x0F;
if syllable == SyllableType::IndependentCluster as u8 ||
syllable == SyllableType::SymbolCluster as u8 ||
syllable == SyllableType::NonCluster as u8
{
last_form = None;
} else {
let join = last_form == Some(JoiningForm::Terminal) || last_form == Some(JoiningForm::Isolated);
if join {
// Fixup previous syllable's form.
let form = if last_form == Some(JoiningForm::Terminal) {
JoiningForm::Medial
} else {
JoiningForm::Initial
};
for i in last_start..start {
buffer.info[i].mask = (buffer.info[i].mask & other_masks) | masks[form as usize];
}
}
// Form for this syllable.
let form = if join { JoiningForm::Terminal } else { JoiningForm::Isolated };
last_form = Some(form);
for i in start..end {
buffer.info[i].mask = (buffer.info[i].mask & other_masks) | masks[form as usize];
}
}
last_start = start;
start = end;
end = buffer.next_syllable(start);
}
}
fn record_rphf(plan: &ShapePlan, _: &Face, buffer: &mut Buffer) {
let universal_plan = plan.data::<UniversalShapePlan>();
let mask = universal_plan.rphf_mask;
if mask == 0 {
return;
}
let mut start = 0;
let mut end = buffer.next_syllable(0);
while start < buffer.len {
// Mark a substituted repha as USE_R.
for i in start..end {
if buffer.info[i].mask & mask == 0 {
break;
}
if buffer.info[i].is_substituted() {
buffer.info[i].set_use_category(category::R);
break;
}
}
start = end;
end = buffer.next_syllable(start);
}
}
fn reorder(_: &ShapePlan, face: &Face, buffer: &mut Buffer) {
insert_dotted_circles(face, buffer);
let mut start = 0;
let mut end = buffer.next_syllable(0);
while start < buffer.len {
reorder_syllable(start, end, buffer);
start = end;
end = buffer.next_syllable(start);
}
}
fn insert_dotted_circles(face: &Face, buffer: &mut Buffer) {
use super::universal_machine::SyllableType;
if buffer.flags.contains(BufferFlags::DO_NOT_INSERT_DOTTED_CIRCLE) {
return;
}
// Note: This loop is extra overhead, but should not be measurable.
// TODO Use a buffer scratch flag to remove the loop.
let has_broken_syllables = buffer.info_slice().iter()
.any(|info| info.syllable() & 0x0F == SyllableType::BrokenCluster as u8);
if !has_broken_syllables {
return;
}
let dottedcircle_glyph = match face.glyph_index(0x25CC) {
Some(g) => g.0 as u32,
None => return,
};
let mut dottedcircle = GlyphInfo {
glyph_id: dottedcircle_glyph,
..GlyphInfo::default()
};
dottedcircle.set_use_category(super::universal_table::get_category(0x25CC));
buffer.clear_output();
buffer.idx = 0;
let mut last_syllable = 0;
while buffer.idx < buffer.len {
let syllable = buffer.cur(0).syllable();
let syllable_type = syllable & 0x0F;
if last_syllable != syllable && syllable_type == SyllableType::BrokenCluster as u8 {
last_syllable = syllable;
let mut ginfo = dottedcircle;
ginfo.cluster = buffer.cur(0).cluster;
ginfo.mask = buffer.cur(0).mask;
ginfo.set_syllable(buffer.cur(0).syllable());
// Insert dottedcircle after possible Repha.
while buffer.idx < buffer.len &&
last_syllable == buffer.cur(0).syllable() &&
buffer.cur(0).use_category() == category::R
{
buffer.next_glyph();
}
buffer.output_info(ginfo); | buffer.next_glyph();
}
}
buffer.swap_buffers();
}
const fn category_flag(c: Category) -> u32 {
rb_flag(c as u32)
}
const fn category_flag64(c: Category) -> u64 {
rb_flag64(c as u32)
}
const BASE_FLAGS: u64 =
category_flag64(category::FM) |
category_flag64(category::FABV) |
category_flag64(category::FBLW) |
category_flag64(category::FPST) |
category_flag64(category::MABV) |
category_flag64(category::MBLW) |
category_flag64(category::MPST) |
category_flag64(category::MPRE) |
category_flag64(category::VABV) |
category_flag64(category::VBLW) |
category_flag64(category::VPST) |
category_flag64(category::VPRE) |
category_flag64(category::VMABV) |
category_flag64(category::VMBLW) |
category_flag64(category::VMPST) |
category_flag64(category::VMPRE);
fn reorder_syllable(start: usize, end: usize, buffer: &mut Buffer) {
use super::universal_machine::SyllableType;
let syllable_type = (buffer.info[start].syllable() & 0x0F) as u32;
// Only a few syllable types need reordering.
if (rb_flag_unsafe(syllable_type) &
(rb_flag(SyllableType::ViramaTerminatedCluster as u32) |
rb_flag(SyllableType::SakotTerminatedCluster as u32) |
rb_flag(SyllableType::StandardCluster as u32) |
rb_flag(SyllableType::BrokenCluster as u32) |
0)) == 0
{
return;
}
// Move things forward.
if buffer.info[start].use_category() == category::R && end - start > 1 {
// Got a repha. Reorder it towards the end, but before the first post-base glyph.
for i in start+1..end {
let is_post_base_glyph =
(rb_flag64_unsafe(buffer.info[i].use_category() as u32) & BASE_FLAGS) != 0 ||
buffer.info[i].is_halant_use();
if is_post_base_glyph || i == end - 1 {
// If we hit a post-base glyph, move before it; otherwise move to the
// end. Shift things in between backward.
let mut i = i;
if is_post_base_glyph {
i -= 1;
}
buffer.merge_clusters(start, i + 1);
let t = buffer.info[start];
for k in 0..i-start {
buffer.info[k + start] = buffer.info[k + start + 1];
}
buffer.info[i] = t;
break;
}
}
}
// Move things back.
let mut j = start;
for i in start..end {
let flag = rb_flag_unsafe(buffer.info[i].use_category() as u32);
if buffer.info[i].is_halant_use() {
// If we hit a halant, move after it; otherwise move to the beginning, and
// shift things in between forward.
j = i + 1;
} else if (flag & (category_flag(category::VPRE) | category_flag(category::VMPRE))) != 0 &&
buffer.info[i].lig_comp() == 0 && j < i
{
// Only move the first component of a MultipleSubst.
buffer.merge_clusters(j, i + 1);
let t = buffer.info[i];
for k in (0..i-j).rev() {
buffer.info[k + j + 1] = buffer.info[k + j];
}
buffer.info[j] = t;
}
}
}
fn record_pref(_: &ShapePlan, _: &Face, buffer: &mut Buffer) {
let mut start = 0;
let mut end = buffer.next_syllable(0);
while start < buffer.len {
// Mark a substituted pref as VPre, as they behave the same way.
for i in start..end {
if buffer.info[i].is_substituted() {
buffer.info[i].set_use_category(category::VPRE);
break;
}
}
start = end;
end = buffer.next_syllable(start);
}
}
fn has_arabic_joining(script: Script) -> bool {
// List of scripts that have data in arabic-table.
match script {
// Unicode-1.1 additions.
script::ARABIC |
// Unicode-3.0 additions.
script::MONGOLIAN |
script::SYRIAC |
// Unicode-5.0 additions.
script::NKO |
script::PHAGS_PA |
// Unicode-6.0 additions.
script::MANDAIC |
// Unicode-7.0 additions.
script::MANICHAEAN |
script::PSALTER_PAHLAVI |
// Unicode-9.0 additions.
script::ADLAM => true,
_ => false,
}
}
fn preprocess_text(_: &ShapePlan, _: &Face, buffer: &mut Buffer) {
super::vowel_constraints::preprocess_text_vowel_constraints(buffer);
}
fn compose(_: &ShapeNormalizeContext, a: char, b: char) -> Option<char> {
// Avoid recomposing split matras.
if a.general_category().is_mark() {
return None;
}
crate::unicode::compose(a, b)
}
fn setup_masks(plan: &ShapePlan, _: &Face, buffer: &mut Buffer) {
let universal_plan = plan.data::<UniversalShapePlan>();
// Do this before allocating use_category().
if let Some(ref arabic_plan) = universal_plan.arabic_plan {
super::arabic::setup_masks_inner(arabic_plan, plan.script, buffer);
}
// We cannot setup masks here. We save information about characters
// and setup masks later on in a pause-callback.
for info in buffer.info_slice_mut() {
info.set_use_category(super::universal_table::get_category(info.glyph_id));
}
} | } else { | random_line_split |
universal.rs | use crate::{script, Tag, Face, GlyphInfo, Mask, Script};
use crate::buffer::{Buffer, BufferFlags};
use crate::ot::{feature, FeatureFlags};
use crate::plan::{ShapePlan, ShapePlanner};
use crate::unicode::{CharExt, GeneralCategoryExt};
use super::*;
use super::arabic::ArabicShapePlan;
pub const UNIVERSAL_SHAPER: ComplexShaper = ComplexShaper {
collect_features: Some(collect_features),
override_features: None,
create_data: Some(|plan| Box::new(UniversalShapePlan::new(plan))),
preprocess_text: Some(preprocess_text),
postprocess_glyphs: None,
normalization_mode: Some(ShapeNormalizationMode::ComposedDiacriticsNoShortCircuit),
decompose: None,
compose: Some(compose),
setup_masks: Some(setup_masks),
gpos_tag: None,
reorder_marks: None,
zero_width_marks: Some(ZeroWidthMarksMode::ByGdefEarly),
fallback_position: false,
};
pub type Category = u8;
pub mod category {
pub const O: u8 = 0; // OTHER
pub const B: u8 = 1; // BASE
pub const IND: u8 = 3; // BASE_IND
pub const N: u8 = 4; // BASE_NUM
pub const GB: u8 = 5; // BASE_OTHER
pub const CGJ: u8 = 6; // CGJ
// pub const F: u8 = 7; // CONS_FINAL
pub const FM: u8 = 8; // CONS_FINAL_MOD
// pub const M: u8 = 9; // CONS_MED
// pub const CM: u8 = 10; // CONS_MOD
pub const SUB: u8 = 11; // CONS_SUB
pub const H: u8 = 12; // HALANT
pub const HN: u8 = 13; // HALANT_NUM
pub const ZWNJ: u8 = 14; // Zero width non-joiner
pub const ZWJ: u8 = 15; // Zero width joiner
pub const WJ: u8 = 16; // Word joiner
// pub const RSV: u8 = 17; // Reserved characters
pub const R: u8 = 18; // REPHA
pub const S: u8 = 19; // SYM
// pub const SM: u8 = 20; // SYM_MOD
pub const VS: u8 = 21; // VARIATION_SELECTOR
// pub const V: u8 = 36; // VOWEL
// pub const VM: u8 = 40; // VOWEL_MOD
pub const CS: u8 = 43; // CONS_WITH_STACKER
// https://github.com/harfbuzz/harfbuzz/issues/1102
pub const HVM: u8 = 44; // HALANT_OR_VOWEL_MODIFIER
pub const SK: u8 = 48; // SAKOT
pub const FABV: u8 = 24; // CONS_FINAL_ABOVE
pub const FBLW: u8 = 25; // CONS_FINAL_BELOW
pub const FPST: u8 = 26; // CONS_FINAL_POST
pub const MABV: u8 = 27; // CONS_MED_ABOVE
pub const MBLW: u8 = 28; // CONS_MED_BELOW
pub const MPST: u8 = 29; // CONS_MED_POST
pub const MPRE: u8 = 30; // CONS_MED_PRE
pub const CMABV: u8 = 31; // CONS_MOD_ABOVE
pub const CMBLW: u8 = 32; // CONS_MOD_BELOW
pub const VABV: u8 = 33; // VOWEL_ABOVE / VOWEL_ABOVE_BELOW / VOWEL_ABOVE_BELOW_POST / VOWEL_ABOVE_POST
pub const VBLW: u8 = 34; // VOWEL_BELOW / VOWEL_BELOW_POST
pub const VPST: u8 = 35; // VOWEL_POST UIPC = Right
pub const VPRE: u8 = 22; // VOWEL_PRE / VOWEL_PRE_ABOVE / VOWEL_PRE_ABOVE_POST / VOWEL_PRE_POST
pub const VMABV: u8 = 37; // VOWEL_MOD_ABOVE
pub const VMBLW: u8 = 38; // VOWEL_MOD_BELOW
pub const VMPST: u8 = 39; // VOWEL_MOD_POST
pub const VMPRE: u8 = 23; // VOWEL_MOD_PRE
pub const SMABV: u8 = 41; // SYM_MOD_ABOVE
pub const SMBLW: u8 = 42; // SYM_MOD_BELOW
pub const FMABV: u8 = 45; // CONS_FINAL_MOD UIPC = Top
pub const FMBLW: u8 = 46; // CONS_FINAL_MOD UIPC = Bottom
pub const FMPST: u8 = 47; // CONS_FINAL_MOD UIPC = Not_Applicable
}
// These features are applied all at once, before reordering.
const BASIC_FEATURES: &[Tag] = &[
feature::RAKAR_FORMS,
feature::ABOVE_BASE_FORMS,
feature::BELOW_BASE_FORMS,
feature::HALF_FORMS,
feature::POST_BASE_FORMS,
feature::VATTU_VARIANTS,
feature::CONJUNCT_FORMS,
];
const TOPOGRAPHICAL_FEATURES: &[Tag] = &[
feature::ISOLATED_FORMS,
feature::INITIAL_FORMS,
feature::MEDIAL_FORMS_1,
feature::TERMINAL_FORMS_1,
];
// Same order as use_topographical_features.
#[derive(Clone, Copy, PartialEq)]
enum JoiningForm {
Isolated = 0,
Initial,
Medial,
Terminal,
}
// These features are applied all at once, after reordering and clearing syllables.
const OTHER_FEATURES: &[Tag] = &[
feature::ABOVE_BASE_SUBSTITUTIONS,
feature::BELOW_BASE_SUBSTITUTIONS,
feature::HALANT_FORMS,
feature::PRE_BASE_SUBSTITUTIONS,
feature::POST_BASE_SUBSTITUTIONS,
];
impl GlyphInfo {
pub(crate) fn use_category(&self) -> Category {
let v: &[u8; 4] = bytemuck::cast_ref(&self.var2);
v[2]
}
fn set_use_category(&mut self, c: Category) {
let v: &mut [u8; 4] = bytemuck::cast_mut(&mut self.var2);
v[2] = c;
}
fn is_halant_use(&self) -> bool {
matches!(self.use_category(), category::H | category::HVM) && !self.is_ligated()
}
}
struct UniversalShapePlan {
rphf_mask: Mask,
arabic_plan: Option<ArabicShapePlan>,
}
impl UniversalShapePlan {
fn new(plan: &ShapePlan) -> UniversalShapePlan {
let mut arabic_plan = None;
if plan.script.map_or(false, has_arabic_joining) {
arabic_plan = Some(super::arabic::ArabicShapePlan::new(plan));
}
UniversalShapePlan {
rphf_mask: plan.ot_map.one_mask(feature::REPH_FORMS),
arabic_plan,
}
}
}
fn collect_features(planner: &mut ShapePlanner) {
// Do this before any lookups have been applied.
planner.ot_map.add_gsub_pause(Some(setup_syllables));
// Default glyph pre-processing group
planner.ot_map.enable_feature(feature::LOCALIZED_FORMS, FeatureFlags::empty(), 1);
planner.ot_map.enable_feature(feature::GLYPH_COMPOSITION_DECOMPOSITION, FeatureFlags::empty(), 1);
planner.ot_map.enable_feature(feature::NUKTA_FORMS, FeatureFlags::empty(), 1);
planner.ot_map.enable_feature(feature::AKHANDS, FeatureFlags::MANUAL_ZWJ, 1);
// Reordering group
planner.ot_map.add_gsub_pause(Some(crate::ot::clear_substitution_flags));
planner.ot_map.add_feature(feature::REPH_FORMS, FeatureFlags::MANUAL_ZWJ, 1);
planner.ot_map.add_gsub_pause(Some(record_rphf));
planner.ot_map.add_gsub_pause(Some(crate::ot::clear_substitution_flags));
planner.ot_map.enable_feature(feature::PRE_BASE_FORMS, FeatureFlags::MANUAL_ZWJ, 1);
planner.ot_map.add_gsub_pause(Some(record_pref));
// Orthographic unit shaping group
for feature in BASIC_FEATURES {
planner.ot_map.enable_feature(*feature, FeatureFlags::MANUAL_ZWJ, 1);
}
planner.ot_map.add_gsub_pause(Some(reorder));
planner.ot_map.add_gsub_pause(Some(crate::ot::clear_syllables));
// Topographical features
for feature in TOPOGRAPHICAL_FEATURES {
planner.ot_map.add_feature(*feature, FeatureFlags::empty(), 1);
}
planner.ot_map.add_gsub_pause(None);
// Standard typographic presentation
for feature in OTHER_FEATURES {
planner.ot_map.enable_feature(*feature, FeatureFlags::empty(), 1);
}
}
fn setup_syllables(plan: &ShapePlan, _: &Face, buffer: &mut Buffer) {
super::universal_machine::find_syllables(buffer);
foreach_syllable!(buffer, start, end, {
buffer.unsafe_to_break(start, end);
});
setup_rphf_mask(plan, buffer);
setup_topographical_masks(plan, buffer);
}
fn setup_rphf_mask(plan: &ShapePlan, buffer: &mut Buffer) {
let universal_plan = plan.data::<UniversalShapePlan>();
let mask = universal_plan.rphf_mask;
if mask == 0 {
return;
}
let mut start = 0;
let mut end = buffer.next_syllable(0);
while start < buffer.len {
let limit = if buffer.info[start].use_category() == category::R {
1
} else {
core::cmp::min(3, end - start)
};
for i in start..start+limit {
buffer.info[i].mask |= mask;
}
start = end;
end = buffer.next_syllable(start);
}
}
fn setup_topographical_masks(plan: &ShapePlan, buffer: &mut Buffer) {
use super::universal_machine::SyllableType;
let mut masks = [0; 4];
let mut all_masks = 0;
for i in 0..4 {
masks[i] = plan.ot_map.one_mask(TOPOGRAPHICAL_FEATURES[i]);
if masks[i] == plan.ot_map.global_mask() {
masks[i] = 0;
}
all_masks |= masks[i];
}
if all_masks == 0 {
return;
}
let other_masks = !all_masks;
let mut last_start = 0;
let mut last_form = None;
let mut start = 0;
let mut end = buffer.next_syllable(0);
while start < buffer.len {
let syllable = buffer.info[start].syllable() & 0x0F;
if syllable == SyllableType::IndependentCluster as u8 ||
syllable == SyllableType::SymbolCluster as u8 ||
syllable == SyllableType::NonCluster as u8
{
last_form = None;
} else {
let join = last_form == Some(JoiningForm::Terminal) || last_form == Some(JoiningForm::Isolated);
if join {
// Fixup previous syllable's form.
let form = if last_form == Some(JoiningForm::Terminal) {
JoiningForm::Medial
} else {
JoiningForm::Initial
};
for i in last_start..start {
buffer.info[i].mask = (buffer.info[i].mask & other_masks) | masks[form as usize];
}
}
// Form for this syllable.
let form = if join { JoiningForm::Terminal } else { JoiningForm::Isolated };
last_form = Some(form);
for i in start..end {
buffer.info[i].mask = (buffer.info[i].mask & other_masks) | masks[form as usize];
}
}
last_start = start;
start = end;
end = buffer.next_syllable(start);
}
}
fn record_rphf(plan: &ShapePlan, _: &Face, buffer: &mut Buffer) {
let universal_plan = plan.data::<UniversalShapePlan>();
let mask = universal_plan.rphf_mask;
if mask == 0 {
return;
}
let mut start = 0;
let mut end = buffer.next_syllable(0);
while start < buffer.len {
// Mark a substituted repha as USE_R.
for i in start..end {
if buffer.info[i].mask & mask == 0 {
break;
}
if buffer.info[i].is_substituted() {
buffer.info[i].set_use_category(category::R);
break;
}
}
start = end;
end = buffer.next_syllable(start);
}
}
fn reorder(_: &ShapePlan, face: &Face, buffer: &mut Buffer) {
insert_dotted_circles(face, buffer);
let mut start = 0;
let mut end = buffer.next_syllable(0);
while start < buffer.len {
reorder_syllable(start, end, buffer);
start = end;
end = buffer.next_syllable(start);
}
}
fn | (face: &Face, buffer: &mut Buffer) {
use super::universal_machine::SyllableType;
if buffer.flags.contains(BufferFlags::DO_NOT_INSERT_DOTTED_CIRCLE) {
return;
}
// Note: This loop is extra overhead, but should not be measurable.
// TODO Use a buffer scratch flag to remove the loop.
let has_broken_syllables = buffer.info_slice().iter()
.any(|info| info.syllable() & 0x0F == SyllableType::BrokenCluster as u8);
if !has_broken_syllables {
return;
}
let dottedcircle_glyph = match face.glyph_index(0x25CC) {
Some(g) => g.0 as u32,
None => return,
};
let mut dottedcircle = GlyphInfo {
glyph_id: dottedcircle_glyph,
..GlyphInfo::default()
};
dottedcircle.set_use_category(super::universal_table::get_category(0x25CC));
buffer.clear_output();
buffer.idx = 0;
let mut last_syllable = 0;
while buffer.idx < buffer.len {
let syllable = buffer.cur(0).syllable();
let syllable_type = syllable & 0x0F;
if last_syllable != syllable && syllable_type == SyllableType::BrokenCluster as u8 {
last_syllable = syllable;
let mut ginfo = dottedcircle;
ginfo.cluster = buffer.cur(0).cluster;
ginfo.mask = buffer.cur(0).mask;
ginfo.set_syllable(buffer.cur(0).syllable());
// Insert dottedcircle after possible Repha.
while buffer.idx < buffer.len &&
last_syllable == buffer.cur(0).syllable() &&
buffer.cur(0).use_category() == category::R
{
buffer.next_glyph();
}
buffer.output_info(ginfo);
} else {
buffer.next_glyph();
}
}
buffer.swap_buffers();
}
const fn category_flag(c: Category) -> u32 {
rb_flag(c as u32)
}
const fn category_flag64(c: Category) -> u64 {
rb_flag64(c as u32)
}
const BASE_FLAGS: u64 =
category_flag64(category::FM) |
category_flag64(category::FABV) |
category_flag64(category::FBLW) |
category_flag64(category::FPST) |
category_flag64(category::MABV) |
category_flag64(category::MBLW) |
category_flag64(category::MPST) |
category_flag64(category::MPRE) |
category_flag64(category::VABV) |
category_flag64(category::VBLW) |
category_flag64(category::VPST) |
category_flag64(category::VPRE) |
category_flag64(category::VMABV) |
category_flag64(category::VMBLW) |
category_flag64(category::VMPST) |
category_flag64(category::VMPRE);
fn reorder_syllable(start: usize, end: usize, buffer: &mut Buffer) {
use super::universal_machine::SyllableType;
let syllable_type = (buffer.info[start].syllable() & 0x0F) as u32;
// Only a few syllable types need reordering.
if (rb_flag_unsafe(syllable_type) &
(rb_flag(SyllableType::ViramaTerminatedCluster as u32) |
rb_flag(SyllableType::SakotTerminatedCluster as u32) |
rb_flag(SyllableType::StandardCluster as u32) |
rb_flag(SyllableType::BrokenCluster as u32) |
0)) == 0
{
return;
}
// Move things forward.
if buffer.info[start].use_category() == category::R && end - start > 1 {
// Got a repha. Reorder it towards the end, but before the first post-base glyph.
for i in start+1..end {
let is_post_base_glyph =
(rb_flag64_unsafe(buffer.info[i].use_category() as u32) & BASE_FLAGS) != 0 ||
buffer.info[i].is_halant_use();
if is_post_base_glyph || i == end - 1 {
// If we hit a post-base glyph, move before it; otherwise move to the
// end. Shift things in between backward.
let mut i = i;
if is_post_base_glyph {
i -= 1;
}
buffer.merge_clusters(start, i + 1);
let t = buffer.info[start];
for k in 0..i-start {
buffer.info[k + start] = buffer.info[k + start + 1];
}
buffer.info[i] = t;
break;
}
}
}
// Move things back.
let mut j = start;
for i in start..end {
let flag = rb_flag_unsafe(buffer.info[i].use_category() as u32);
if buffer.info[i].is_halant_use() {
// If we hit a halant, move after it; otherwise move to the beginning, and
// shift things in between forward.
j = i + 1;
} else if (flag & (category_flag(category::VPRE) | category_flag(category::VMPRE))) != 0 &&
buffer.info[i].lig_comp() == 0 && j < i
{
// Only move the first component of a MultipleSubst.
buffer.merge_clusters(j, i + 1);
let t = buffer.info[i];
for k in (0..i-j).rev() {
buffer.info[k + j + 1] = buffer.info[k + j];
}
buffer.info[j] = t;
}
}
}
fn record_pref(_: &ShapePlan, _: &Face, buffer: &mut Buffer) {
let mut start = 0;
let mut end = buffer.next_syllable(0);
while start < buffer.len {
// Mark a substituted pref as VPre, as they behave the same way.
for i in start..end {
if buffer.info[i].is_substituted() {
buffer.info[i].set_use_category(category::VPRE);
break;
}
}
start = end;
end = buffer.next_syllable(start);
}
}
fn has_arabic_joining(script: Script) -> bool {
// List of scripts that have data in arabic-table.
match script {
// Unicode-1.1 additions.
script::ARABIC |
// Unicode-3.0 additions.
script::MONGOLIAN |
script::SYRIAC |
// Unicode-5.0 additions.
script::NKO |
script::PHAGS_PA |
// Unicode-6.0 additions.
script::MANDAIC |
// Unicode-7.0 additions.
script::MANICHAEAN |
script::PSALTER_PAHLAVI |
// Unicode-9.0 additions.
script::ADLAM => true,
_ => false,
}
}
fn preprocess_text(_: &ShapePlan, _: &Face, buffer: &mut Buffer) {
super::vowel_constraints::preprocess_text_vowel_constraints(buffer);
}
fn compose(_: &ShapeNormalizeContext, a: char, b: char) -> Option<char> {
// Avoid recomposing split matras.
if a.general_category().is_mark() {
return None;
}
crate::unicode::compose(a, b)
}
fn setup_masks(plan: &ShapePlan, _: &Face, buffer: &mut Buffer) {
let universal_plan = plan.data::<UniversalShapePlan>();
// Do this before allocating use_category().
if let Some(ref arabic_plan) = universal_plan.arabic_plan {
super::arabic::setup_masks_inner(arabic_plan, plan.script, buffer);
}
// We cannot setup masks here. We save information about characters
// and setup masks later on in a pause-callback.
for info in buffer.info_slice_mut() {
info.set_use_category(super::universal_table::get_category(info.glyph_id));
}
}
| insert_dotted_circles | identifier_name |
api_op_CreateScan.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package codegurusecurity
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
"github.com/aws/aws-sdk-go-v2/service/codegurusecurity/types"
smithyendpoints "github.com/aws/smithy-go/endpoints"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/smithy-go/transport/http"
)
// Use to create a scan using code uploaded to an S3 bucket.
func (c *Client) CreateScan(ctx context.Context, params *CreateScanInput, optFns ...func(*Options)) (*CreateScanOutput, error) {
if params == nil {
params = &CreateScanInput{}
}
result, metadata, err := c.invokeOperation(ctx, "CreateScan", params, optFns, c.addOperationCreateScanMiddlewares)
if err != nil {
return nil, err
}
out := result.(*CreateScanOutput)
out.ResultMetadata = metadata
return out, nil
}
type CreateScanInput struct {
// The identifier for an input resource used to create a scan.
//
// This member is required.
ResourceId types.ResourceId
// The unique name that CodeGuru Security uses to track revisions across multiple
// scans of the same resource. Only allowed for a STANDARD scan type. If not
// specified, it will be auto generated.
//
// This member is required.
ScanName *string
// The type of analysis you want CodeGuru Security to perform in the scan, either
// Security or All . The Security type only generates findings related to
// security. The All type generates both security findings and quality findings.
// Defaults to Security type if missing.
AnalysisType types.AnalysisType
// The idempotency token for the request. Amazon CodeGuru Security uses this value
// to prevent the accidental creation of duplicate scans if there are failures and
// retries.
ClientToken *string
// The type of scan, either Standard or Express . Defaults to Standard type if
// missing. Express scans run on limited resources and use a limited set of
// detectors to analyze your code in near-real time. Standard scans have standard
// resource limits and use the full set of detectors to analyze your code.
ScanType types.ScanType
// An array of key-value pairs used to tag a scan. A tag is a custom attribute
// label with two parts:
// - A tag key. For example, CostCenter , Environment , or Secret . Tag keys are
// case sensitive.
// - An optional tag value field. For example, 111122223333 , Production , or a
// team name. Omitting the tag value is the same as using an empty string. Tag
// values are case sensitive.
Tags map[string]string
noSmithyDocumentSerde
}
type CreateScanOutput struct {
// The identifier for the resource object that contains resources that were
// scanned.
//
// This member is required.
ResourceId types.ResourceId
// UUID that identifies the individual scan run.
//
// This member is required.
RunId *string
// The name of the scan.
//
// This member is required.
ScanName *string
// The current state of the scan. Returns either InProgress , Successful , or
// Failed .
//
// This member is required.
ScanState types.ScanState
// The ARN for the scan name.
ScanNameArn *string
// Metadata pertaining to the operation's result.
ResultMetadata middleware.Metadata
noSmithyDocumentSerde
}
func (c *Client) addOperationCreateScanMiddlewares(stack *middleware.Stack, options Options) (err error) {
err = stack.Serialize.Add(&awsRestjson1_serializeOpCreateScan{}, middleware.After)
if err != nil {
return err
}
err = stack.Deserialize.Add(&awsRestjson1_deserializeOpCreateScan{}, middleware.After)
if err != nil {
return err
}
if err = addlegacyEndpointContextSetter(stack, options); err != nil {
return err
}
if err = addSetLoggerMiddleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
return err
}
if err = addResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
return err
}
if err = addRetryMiddlewares(stack, options); err != nil {
return err
}
if err = addHTTPSignerV4Middleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
return err
}
if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
return err
}
if err = addClientUserAgent(stack, options); err != nil {
return err
}
if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = addCreateScanResolveEndpointMiddleware(stack, options); err != nil |
if err = addIdempotencyToken_opCreateScanMiddleware(stack, options); err != nil {
return err
}
if err = addOpCreateScanValidationMiddleware(stack); err != nil {
return err
}
if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateScan(options.Region), middleware.Before); err != nil {
return err
}
if err = awsmiddleware.AddRecursionDetection(stack); err != nil {
return err
}
if err = addRequestIDRetrieverMiddleware(stack); err != nil {
return err
}
if err = addResponseErrorMiddleware(stack); err != nil {
return err
}
if err = addRequestResponseLogging(stack, options); err != nil {
return err
}
if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil {
return err
}
return nil
}
type idempotencyToken_initializeOpCreateScan struct {
tokenProvider IdempotencyTokenProvider
}
func (*idempotencyToken_initializeOpCreateScan) ID() string {
return "OperationIdempotencyTokenAutoFill"
}
func (m *idempotencyToken_initializeOpCreateScan) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (
out middleware.InitializeOutput, metadata middleware.Metadata, err error,
) {
if m.tokenProvider == nil {
return next.HandleInitialize(ctx, in)
}
input, ok := in.Parameters.(*CreateScanInput)
if !ok {
return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateScanInput ")
}
if input.ClientToken == nil {
t, err := m.tokenProvider.GetIdempotencyToken()
if err != nil {
return out, metadata, err
}
input.ClientToken = &t
}
return next.HandleInitialize(ctx, in)
}
func addIdempotencyToken_opCreateScanMiddleware(stack *middleware.Stack, cfg Options) error {
return stack.Initialize.Add(&idempotencyToken_initializeOpCreateScan{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before)
}
func newServiceMetadataMiddleware_opCreateScan(region string) *awsmiddleware.RegisterServiceMetadata {
return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
SigningName: "codeguru-security",
OperationName: "CreateScan",
}
}
type opCreateScanResolveEndpointMiddleware struct {
EndpointResolver EndpointResolverV2
BuiltInResolver builtInParameterResolver
}
func (*opCreateScanResolveEndpointMiddleware) ID() string {
return "ResolveEndpointV2"
}
func (m *opCreateScanResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
out middleware.SerializeOutput, metadata middleware.Metadata, err error,
) {
if awsmiddleware.GetRequiresLegacyEndpoints(ctx) {
return next.HandleSerialize(ctx, in)
}
req, ok := in.Request.(*smithyhttp.Request)
if !ok {
return out, metadata, fmt.Errorf("unknown transport type %T", in.Request)
}
if m.EndpointResolver == nil {
return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil")
}
params := EndpointParameters{}
m.BuiltInResolver.ResolveBuiltIns(¶ms)
var resolvedEndpoint smithyendpoints.Endpoint
resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params)
if err != nil {
return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err)
}
req.URL = &resolvedEndpoint.URI
for k := range resolvedEndpoint.Headers {
req.Header.Set(
k,
resolvedEndpoint.Headers.Get(k),
)
}
authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties)
if err != nil {
var nfe *internalauth.NoAuthenticationSchemesFoundError
if errors.As(err, &nfe) {
// if no auth scheme is found, default to sigv4
signingName := "codeguru-security"
signingRegion := m.BuiltInResolver.(*builtInResolver).Region
ctx = awsmiddleware.SetSigningName(ctx, signingName)
ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
}
var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError
if errors.As(err, &ue) {
return out, metadata, fmt.Errorf(
"This operation requests signer version(s) %v but the client only supports %v",
ue.UnsupportedSchemes,
internalauth.SupportedSchemes,
)
}
}
for _, authScheme := range authSchemes {
switch authScheme.(type) {
case *internalauth.AuthenticationSchemeV4:
v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4)
var signingName, signingRegion string
if v4Scheme.SigningName == nil {
signingName = "codeguru-security"
} else {
signingName = *v4Scheme.SigningName
}
if v4Scheme.SigningRegion == nil {
signingRegion = m.BuiltInResolver.(*builtInResolver).Region
} else {
signingRegion = *v4Scheme.SigningRegion
}
if v4Scheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initialization time.
// Setting this context value will cause the signer to extract it
// and override the value set at client initialization time.
ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding)
}
ctx = awsmiddleware.SetSigningName(ctx, signingName)
ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
break
case *internalauth.AuthenticationSchemeV4A:
v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A)
if v4aScheme.SigningName == nil {
v4aScheme.SigningName = aws.String("codeguru-security")
}
if v4aScheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initialization time.
// Setting this context value will cause the signer to extract it
// and override the value set at client initialization time.
ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding)
}
ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName)
ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0])
break
case *internalauth.AuthenticationSchemeNone:
break
}
}
return next.HandleSerialize(ctx, in)
}
func addCreateScanResolveEndpointMiddleware(stack *middleware.Stack, options Options) error {
return stack.Serialize.Insert(&opCreateScanResolveEndpointMiddleware{
EndpointResolver: options.EndpointResolverV2,
BuiltInResolver: &builtInResolver{
Region: options.Region,
UseDualStack: options.EndpointOptions.UseDualStackEndpoint,
UseFIPS: options.EndpointOptions.UseFIPSEndpoint,
Endpoint: options.BaseEndpoint,
},
}, "ResolveEndpoint", middleware.After)
}
| {
return err
} | conditional_block |
api_op_CreateScan.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package codegurusecurity
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
"github.com/aws/aws-sdk-go-v2/service/codegurusecurity/types"
smithyendpoints "github.com/aws/smithy-go/endpoints"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/smithy-go/transport/http"
)
// Use to create a scan using code uploaded to an S3 bucket.
func (c *Client) CreateScan(ctx context.Context, params *CreateScanInput, optFns ...func(*Options)) (*CreateScanOutput, error) {
if params == nil {
params = &CreateScanInput{}
}
result, metadata, err := c.invokeOperation(ctx, "CreateScan", params, optFns, c.addOperationCreateScanMiddlewares)
if err != nil {
return nil, err
}
out := result.(*CreateScanOutput)
out.ResultMetadata = metadata
return out, nil
}
type CreateScanInput struct {
// The identifier for an input resource used to create a scan.
//
// This member is required.
ResourceId types.ResourceId
// The unique name that CodeGuru Security uses to track revisions across multiple
// scans of the same resource. Only allowed for a STANDARD scan type. If not
// specified, it will be auto generated.
//
// This member is required.
ScanName *string
// The type of analysis you want CodeGuru Security to perform in the scan, either
// Security or All . The Security type only generates findings related to
// security. The All type generates both security findings and quality findings.
// Defaults to Security type if missing.
AnalysisType types.AnalysisType
// The idempotency token for the request. Amazon CodeGuru Security uses this value
// to prevent the accidental creation of duplicate scans if there are failures and
// retries.
ClientToken *string
// The type of scan, either Standard or Express . Defaults to Standard type if
// missing. Express scans run on limited resources and use a limited set of
// detectors to analyze your code in near-real time. Standard scans have standard
// resource limits and use the full set of detectors to analyze your code.
ScanType types.ScanType
// An array of key-value pairs used to tag a scan. A tag is a custom attribute
// label with two parts:
// - A tag key. For example, CostCenter , Environment , or Secret . Tag keys are
// case sensitive.
// - An optional tag value field. For example, 111122223333 , Production , or a
// team name. Omitting the tag value is the same as using an empty string. Tag
// values are case sensitive.
Tags map[string]string
noSmithyDocumentSerde
}
type CreateScanOutput struct {
// The identifier for the resource object that contains resources that were
// scanned.
//
// This member is required.
ResourceId types.ResourceId
// UUID that identifies the individual scan run.
//
// This member is required.
RunId *string
// The name of the scan.
//
// This member is required.
ScanName *string
// The current state of the scan. Returns either InProgress , Successful , or
// Failed .
//
// This member is required.
ScanState types.ScanState
// The ARN for the scan name.
ScanNameArn *string
// Metadata pertaining to the operation's result.
ResultMetadata middleware.Metadata
noSmithyDocumentSerde
}
func (c *Client) | (stack *middleware.Stack, options Options) (err error) {
err = stack.Serialize.Add(&awsRestjson1_serializeOpCreateScan{}, middleware.After)
if err != nil {
return err
}
err = stack.Deserialize.Add(&awsRestjson1_deserializeOpCreateScan{}, middleware.After)
if err != nil {
return err
}
if err = addlegacyEndpointContextSetter(stack, options); err != nil {
return err
}
if err = addSetLoggerMiddleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
return err
}
if err = addResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
return err
}
if err = addRetryMiddlewares(stack, options); err != nil {
return err
}
if err = addHTTPSignerV4Middleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
return err
}
if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
return err
}
if err = addClientUserAgent(stack, options); err != nil {
return err
}
if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = addCreateScanResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = addIdempotencyToken_opCreateScanMiddleware(stack, options); err != nil {
return err
}
if err = addOpCreateScanValidationMiddleware(stack); err != nil {
return err
}
if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateScan(options.Region), middleware.Before); err != nil {
return err
}
if err = awsmiddleware.AddRecursionDetection(stack); err != nil {
return err
}
if err = addRequestIDRetrieverMiddleware(stack); err != nil {
return err
}
if err = addResponseErrorMiddleware(stack); err != nil {
return err
}
if err = addRequestResponseLogging(stack, options); err != nil {
return err
}
if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil {
return err
}
return nil
}
type idempotencyToken_initializeOpCreateScan struct {
tokenProvider IdempotencyTokenProvider
}
func (*idempotencyToken_initializeOpCreateScan) ID() string {
return "OperationIdempotencyTokenAutoFill"
}
func (m *idempotencyToken_initializeOpCreateScan) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (
out middleware.InitializeOutput, metadata middleware.Metadata, err error,
) {
if m.tokenProvider == nil {
return next.HandleInitialize(ctx, in)
}
input, ok := in.Parameters.(*CreateScanInput)
if !ok {
return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateScanInput ")
}
if input.ClientToken == nil {
t, err := m.tokenProvider.GetIdempotencyToken()
if err != nil {
return out, metadata, err
}
input.ClientToken = &t
}
return next.HandleInitialize(ctx, in)
}
func addIdempotencyToken_opCreateScanMiddleware(stack *middleware.Stack, cfg Options) error {
return stack.Initialize.Add(&idempotencyToken_initializeOpCreateScan{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before)
}
func newServiceMetadataMiddleware_opCreateScan(region string) *awsmiddleware.RegisterServiceMetadata {
return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
SigningName: "codeguru-security",
OperationName: "CreateScan",
}
}
type opCreateScanResolveEndpointMiddleware struct {
EndpointResolver EndpointResolverV2
BuiltInResolver builtInParameterResolver
}
func (*opCreateScanResolveEndpointMiddleware) ID() string {
return "ResolveEndpointV2"
}
func (m *opCreateScanResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
out middleware.SerializeOutput, metadata middleware.Metadata, err error,
) {
if awsmiddleware.GetRequiresLegacyEndpoints(ctx) {
return next.HandleSerialize(ctx, in)
}
req, ok := in.Request.(*smithyhttp.Request)
if !ok {
return out, metadata, fmt.Errorf("unknown transport type %T", in.Request)
}
if m.EndpointResolver == nil {
return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil")
}
params := EndpointParameters{}
m.BuiltInResolver.ResolveBuiltIns(¶ms)
var resolvedEndpoint smithyendpoints.Endpoint
resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params)
if err != nil {
return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err)
}
req.URL = &resolvedEndpoint.URI
for k := range resolvedEndpoint.Headers {
req.Header.Set(
k,
resolvedEndpoint.Headers.Get(k),
)
}
authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties)
if err != nil {
var nfe *internalauth.NoAuthenticationSchemesFoundError
if errors.As(err, &nfe) {
// if no auth scheme is found, default to sigv4
signingName := "codeguru-security"
signingRegion := m.BuiltInResolver.(*builtInResolver).Region
ctx = awsmiddleware.SetSigningName(ctx, signingName)
ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
}
var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError
if errors.As(err, &ue) {
return out, metadata, fmt.Errorf(
"This operation requests signer version(s) %v but the client only supports %v",
ue.UnsupportedSchemes,
internalauth.SupportedSchemes,
)
}
}
for _, authScheme := range authSchemes {
switch authScheme.(type) {
case *internalauth.AuthenticationSchemeV4:
v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4)
var signingName, signingRegion string
if v4Scheme.SigningName == nil {
signingName = "codeguru-security"
} else {
signingName = *v4Scheme.SigningName
}
if v4Scheme.SigningRegion == nil {
signingRegion = m.BuiltInResolver.(*builtInResolver).Region
} else {
signingRegion = *v4Scheme.SigningRegion
}
if v4Scheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initialization time.
// Setting this context value will cause the signer to extract it
// and override the value set at client initialization time.
ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding)
}
ctx = awsmiddleware.SetSigningName(ctx, signingName)
ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
break
case *internalauth.AuthenticationSchemeV4A:
v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A)
if v4aScheme.SigningName == nil {
v4aScheme.SigningName = aws.String("codeguru-security")
}
if v4aScheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initialization time.
// Setting this context value will cause the signer to extract it
// and override the value set at client initialization time.
ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding)
}
ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName)
ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0])
break
case *internalauth.AuthenticationSchemeNone:
break
}
}
return next.HandleSerialize(ctx, in)
}
func addCreateScanResolveEndpointMiddleware(stack *middleware.Stack, options Options) error {
return stack.Serialize.Insert(&opCreateScanResolveEndpointMiddleware{
EndpointResolver: options.EndpointResolverV2,
BuiltInResolver: &builtInResolver{
Region: options.Region,
UseDualStack: options.EndpointOptions.UseDualStackEndpoint,
UseFIPS: options.EndpointOptions.UseFIPSEndpoint,
Endpoint: options.BaseEndpoint,
},
}, "ResolveEndpoint", middleware.After)
}
| addOperationCreateScanMiddlewares | identifier_name |
api_op_CreateScan.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package codegurusecurity
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
"github.com/aws/aws-sdk-go-v2/service/codegurusecurity/types"
smithyendpoints "github.com/aws/smithy-go/endpoints"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/smithy-go/transport/http"
)
// Use to create a scan using code uploaded to an S3 bucket.
func (c *Client) CreateScan(ctx context.Context, params *CreateScanInput, optFns ...func(*Options)) (*CreateScanOutput, error) {
if params == nil {
params = &CreateScanInput{}
}
result, metadata, err := c.invokeOperation(ctx, "CreateScan", params, optFns, c.addOperationCreateScanMiddlewares)
if err != nil {
return nil, err
}
out := result.(*CreateScanOutput)
out.ResultMetadata = metadata
return out, nil
}
type CreateScanInput struct {
// The identifier for an input resource used to create a scan.
//
// This member is required.
ResourceId types.ResourceId
// The unique name that CodeGuru Security uses to track revisions across multiple
// scans of the same resource. Only allowed for a STANDARD scan type. If not
// specified, it will be auto generated.
//
// This member is required.
ScanName *string |
// The type of analysis you want CodeGuru Security to perform in the scan, either
// Security or All . The Security type only generates findings related to
// security. The All type generates both security findings and quality findings.
// Defaults to Security type if missing.
AnalysisType types.AnalysisType
// The idempotency token for the request. Amazon CodeGuru Security uses this value
// to prevent the accidental creation of duplicate scans if there are failures and
// retries.
ClientToken *string
// The type of scan, either Standard or Express . Defaults to Standard type if
// missing. Express scans run on limited resources and use a limited set of
// detectors to analyze your code in near-real time. Standard scans have standard
// resource limits and use the full set of detectors to analyze your code.
ScanType types.ScanType
// An array of key-value pairs used to tag a scan. A tag is a custom attribute
// label with two parts:
// - A tag key. For example, CostCenter , Environment , or Secret . Tag keys are
// case sensitive.
// - An optional tag value field. For example, 111122223333 , Production , or a
// team name. Omitting the tag value is the same as using an empty string. Tag
// values are case sensitive.
Tags map[string]string
noSmithyDocumentSerde
}
type CreateScanOutput struct {
// The identifier for the resource object that contains resources that were
// scanned.
//
// This member is required.
ResourceId types.ResourceId
// UUID that identifies the individual scan run.
//
// This member is required.
RunId *string
// The name of the scan.
//
// This member is required.
ScanName *string
// The current state of the scan. Returns either InProgress , Successful , or
// Failed .
//
// This member is required.
ScanState types.ScanState
// The ARN for the scan name.
ScanNameArn *string
// Metadata pertaining to the operation's result.
ResultMetadata middleware.Metadata
noSmithyDocumentSerde
}
func (c *Client) addOperationCreateScanMiddlewares(stack *middleware.Stack, options Options) (err error) {
err = stack.Serialize.Add(&awsRestjson1_serializeOpCreateScan{}, middleware.After)
if err != nil {
return err
}
err = stack.Deserialize.Add(&awsRestjson1_deserializeOpCreateScan{}, middleware.After)
if err != nil {
return err
}
if err = addlegacyEndpointContextSetter(stack, options); err != nil {
return err
}
if err = addSetLoggerMiddleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
return err
}
if err = addResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
return err
}
if err = addRetryMiddlewares(stack, options); err != nil {
return err
}
if err = addHTTPSignerV4Middleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
return err
}
if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
return err
}
if err = addClientUserAgent(stack, options); err != nil {
return err
}
if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = addCreateScanResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = addIdempotencyToken_opCreateScanMiddleware(stack, options); err != nil {
return err
}
if err = addOpCreateScanValidationMiddleware(stack); err != nil {
return err
}
if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateScan(options.Region), middleware.Before); err != nil {
return err
}
if err = awsmiddleware.AddRecursionDetection(stack); err != nil {
return err
}
if err = addRequestIDRetrieverMiddleware(stack); err != nil {
return err
}
if err = addResponseErrorMiddleware(stack); err != nil {
return err
}
if err = addRequestResponseLogging(stack, options); err != nil {
return err
}
if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil {
return err
}
return nil
}
type idempotencyToken_initializeOpCreateScan struct {
tokenProvider IdempotencyTokenProvider
}
func (*idempotencyToken_initializeOpCreateScan) ID() string {
return "OperationIdempotencyTokenAutoFill"
}
func (m *idempotencyToken_initializeOpCreateScan) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (
out middleware.InitializeOutput, metadata middleware.Metadata, err error,
) {
if m.tokenProvider == nil {
return next.HandleInitialize(ctx, in)
}
input, ok := in.Parameters.(*CreateScanInput)
if !ok {
return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateScanInput ")
}
if input.ClientToken == nil {
t, err := m.tokenProvider.GetIdempotencyToken()
if err != nil {
return out, metadata, err
}
input.ClientToken = &t
}
return next.HandleInitialize(ctx, in)
}
func addIdempotencyToken_opCreateScanMiddleware(stack *middleware.Stack, cfg Options) error {
return stack.Initialize.Add(&idempotencyToken_initializeOpCreateScan{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before)
}
func newServiceMetadataMiddleware_opCreateScan(region string) *awsmiddleware.RegisterServiceMetadata {
return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
SigningName: "codeguru-security",
OperationName: "CreateScan",
}
}
type opCreateScanResolveEndpointMiddleware struct {
EndpointResolver EndpointResolverV2
BuiltInResolver builtInParameterResolver
}
func (*opCreateScanResolveEndpointMiddleware) ID() string {
return "ResolveEndpointV2"
}
func (m *opCreateScanResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
out middleware.SerializeOutput, metadata middleware.Metadata, err error,
) {
if awsmiddleware.GetRequiresLegacyEndpoints(ctx) {
return next.HandleSerialize(ctx, in)
}
req, ok := in.Request.(*smithyhttp.Request)
if !ok {
return out, metadata, fmt.Errorf("unknown transport type %T", in.Request)
}
if m.EndpointResolver == nil {
return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil")
}
params := EndpointParameters{}
m.BuiltInResolver.ResolveBuiltIns(¶ms)
var resolvedEndpoint smithyendpoints.Endpoint
resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params)
if err != nil {
return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err)
}
req.URL = &resolvedEndpoint.URI
for k := range resolvedEndpoint.Headers {
req.Header.Set(
k,
resolvedEndpoint.Headers.Get(k),
)
}
authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties)
if err != nil {
var nfe *internalauth.NoAuthenticationSchemesFoundError
if errors.As(err, &nfe) {
// if no auth scheme is found, default to sigv4
signingName := "codeguru-security"
signingRegion := m.BuiltInResolver.(*builtInResolver).Region
ctx = awsmiddleware.SetSigningName(ctx, signingName)
ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
}
var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError
if errors.As(err, &ue) {
return out, metadata, fmt.Errorf(
"This operation requests signer version(s) %v but the client only supports %v",
ue.UnsupportedSchemes,
internalauth.SupportedSchemes,
)
}
}
for _, authScheme := range authSchemes {
switch authScheme.(type) {
case *internalauth.AuthenticationSchemeV4:
v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4)
var signingName, signingRegion string
if v4Scheme.SigningName == nil {
signingName = "codeguru-security"
} else {
signingName = *v4Scheme.SigningName
}
if v4Scheme.SigningRegion == nil {
signingRegion = m.BuiltInResolver.(*builtInResolver).Region
} else {
signingRegion = *v4Scheme.SigningRegion
}
if v4Scheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initialization time.
// Setting this context value will cause the signer to extract it
// and override the value set at client initialization time.
ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding)
}
ctx = awsmiddleware.SetSigningName(ctx, signingName)
ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
break
case *internalauth.AuthenticationSchemeV4A:
v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A)
if v4aScheme.SigningName == nil {
v4aScheme.SigningName = aws.String("codeguru-security")
}
if v4aScheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initialization time.
// Setting this context value will cause the signer to extract it
// and override the value set at client initialization time.
ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding)
}
ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName)
ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0])
break
case *internalauth.AuthenticationSchemeNone:
break
}
}
return next.HandleSerialize(ctx, in)
}
func addCreateScanResolveEndpointMiddleware(stack *middleware.Stack, options Options) error {
return stack.Serialize.Insert(&opCreateScanResolveEndpointMiddleware{
EndpointResolver: options.EndpointResolverV2,
BuiltInResolver: &builtInResolver{
Region: options.Region,
UseDualStack: options.EndpointOptions.UseDualStackEndpoint,
UseFIPS: options.EndpointOptions.UseFIPSEndpoint,
Endpoint: options.BaseEndpoint,
},
}, "ResolveEndpoint", middleware.After)
} | random_line_split | |
api_op_CreateScan.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package codegurusecurity
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
"github.com/aws/aws-sdk-go-v2/service/codegurusecurity/types"
smithyendpoints "github.com/aws/smithy-go/endpoints"
"github.com/aws/smithy-go/middleware"
smithyhttp "github.com/aws/smithy-go/transport/http"
)
// Use to create a scan using code uploaded to an S3 bucket.
func (c *Client) CreateScan(ctx context.Context, params *CreateScanInput, optFns ...func(*Options)) (*CreateScanOutput, error) {
if params == nil {
params = &CreateScanInput{}
}
result, metadata, err := c.invokeOperation(ctx, "CreateScan", params, optFns, c.addOperationCreateScanMiddlewares)
if err != nil {
return nil, err
}
out := result.(*CreateScanOutput)
out.ResultMetadata = metadata
return out, nil
}
type CreateScanInput struct {
// The identifier for an input resource used to create a scan.
//
// This member is required.
ResourceId types.ResourceId
// The unique name that CodeGuru Security uses to track revisions across multiple
// scans of the same resource. Only allowed for a STANDARD scan type. If not
// specified, it will be auto generated.
//
// This member is required.
ScanName *string
// The type of analysis you want CodeGuru Security to perform in the scan, either
// Security or All . The Security type only generates findings related to
// security. The All type generates both security findings and quality findings.
// Defaults to Security type if missing.
AnalysisType types.AnalysisType
// The idempotency token for the request. Amazon CodeGuru Security uses this value
// to prevent the accidental creation of duplicate scans if there are failures and
// retries.
ClientToken *string
// The type of scan, either Standard or Express . Defaults to Standard type if
// missing. Express scans run on limited resources and use a limited set of
// detectors to analyze your code in near-real time. Standard scans have standard
// resource limits and use the full set of detectors to analyze your code.
ScanType types.ScanType
// An array of key-value pairs used to tag a scan. A tag is a custom attribute
// label with two parts:
// - A tag key. For example, CostCenter , Environment , or Secret . Tag keys are
// case sensitive.
// - An optional tag value field. For example, 111122223333 , Production , or a
// team name. Omitting the tag value is the same as using an empty string. Tag
// values are case sensitive.
Tags map[string]string
noSmithyDocumentSerde
}
type CreateScanOutput struct {
// The identifier for the resource object that contains resources that were
// scanned.
//
// This member is required.
ResourceId types.ResourceId
// UUID that identifies the individual scan run.
//
// This member is required.
RunId *string
// The name of the scan.
//
// This member is required.
ScanName *string
// The current state of the scan. Returns either InProgress , Successful , or
// Failed .
//
// This member is required.
ScanState types.ScanState
// The ARN for the scan name.
ScanNameArn *string
// Metadata pertaining to the operation's result.
ResultMetadata middleware.Metadata
noSmithyDocumentSerde
}
func (c *Client) addOperationCreateScanMiddlewares(stack *middleware.Stack, options Options) (err error) {
err = stack.Serialize.Add(&awsRestjson1_serializeOpCreateScan{}, middleware.After)
if err != nil {
return err
}
err = stack.Deserialize.Add(&awsRestjson1_deserializeOpCreateScan{}, middleware.After)
if err != nil {
return err
}
if err = addlegacyEndpointContextSetter(stack, options); err != nil {
return err
}
if err = addSetLoggerMiddleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
return err
}
if err = addResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
return err
}
if err = addRetryMiddlewares(stack, options); err != nil {
return err
}
if err = addHTTPSignerV4Middleware(stack, options); err != nil {
return err
}
if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
return err
}
if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
return err
}
if err = addClientUserAgent(stack, options); err != nil {
return err
}
if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
return err
}
if err = addCreateScanResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = addIdempotencyToken_opCreateScanMiddleware(stack, options); err != nil {
return err
}
if err = addOpCreateScanValidationMiddleware(stack); err != nil {
return err
}
if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateScan(options.Region), middleware.Before); err != nil {
return err
}
if err = awsmiddleware.AddRecursionDetection(stack); err != nil {
return err
}
if err = addRequestIDRetrieverMiddleware(stack); err != nil {
return err
}
if err = addResponseErrorMiddleware(stack); err != nil {
return err
}
if err = addRequestResponseLogging(stack, options); err != nil {
return err
}
if err = addendpointDisableHTTPSMiddleware(stack, options); err != nil {
return err
}
return nil
}
type idempotencyToken_initializeOpCreateScan struct {
tokenProvider IdempotencyTokenProvider
}
func (*idempotencyToken_initializeOpCreateScan) ID() string {
return "OperationIdempotencyTokenAutoFill"
}
func (m *idempotencyToken_initializeOpCreateScan) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (
out middleware.InitializeOutput, metadata middleware.Metadata, err error,
) {
if m.tokenProvider == nil {
return next.HandleInitialize(ctx, in)
}
input, ok := in.Parameters.(*CreateScanInput)
if !ok {
return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateScanInput ")
}
if input.ClientToken == nil {
t, err := m.tokenProvider.GetIdempotencyToken()
if err != nil {
return out, metadata, err
}
input.ClientToken = &t
}
return next.HandleInitialize(ctx, in)
}
func addIdempotencyToken_opCreateScanMiddleware(stack *middleware.Stack, cfg Options) error {
return stack.Initialize.Add(&idempotencyToken_initializeOpCreateScan{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before)
}
func newServiceMetadataMiddleware_opCreateScan(region string) *awsmiddleware.RegisterServiceMetadata {
return &awsmiddleware.RegisterServiceMetadata{
Region: region,
ServiceID: ServiceID,
SigningName: "codeguru-security",
OperationName: "CreateScan",
}
}
type opCreateScanResolveEndpointMiddleware struct {
EndpointResolver EndpointResolverV2
BuiltInResolver builtInParameterResolver
}
func (*opCreateScanResolveEndpointMiddleware) ID() string {
return "ResolveEndpointV2"
}
func (m *opCreateScanResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
out middleware.SerializeOutput, metadata middleware.Metadata, err error,
) {
if awsmiddleware.GetRequiresLegacyEndpoints(ctx) {
return next.HandleSerialize(ctx, in)
}
req, ok := in.Request.(*smithyhttp.Request)
if !ok {
return out, metadata, fmt.Errorf("unknown transport type %T", in.Request)
}
if m.EndpointResolver == nil {
return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil")
}
params := EndpointParameters{}
m.BuiltInResolver.ResolveBuiltIns(¶ms)
var resolvedEndpoint smithyendpoints.Endpoint
resolvedEndpoint, err = m.EndpointResolver.ResolveEndpoint(ctx, params)
if err != nil {
return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err)
}
req.URL = &resolvedEndpoint.URI
for k := range resolvedEndpoint.Headers {
req.Header.Set(
k,
resolvedEndpoint.Headers.Get(k),
)
}
authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties)
if err != nil {
var nfe *internalauth.NoAuthenticationSchemesFoundError
if errors.As(err, &nfe) {
// if no auth scheme is found, default to sigv4
signingName := "codeguru-security"
signingRegion := m.BuiltInResolver.(*builtInResolver).Region
ctx = awsmiddleware.SetSigningName(ctx, signingName)
ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
}
var ue *internalauth.UnSupportedAuthenticationSchemeSpecifiedError
if errors.As(err, &ue) {
return out, metadata, fmt.Errorf(
"This operation requests signer version(s) %v but the client only supports %v",
ue.UnsupportedSchemes,
internalauth.SupportedSchemes,
)
}
}
for _, authScheme := range authSchemes {
switch authScheme.(type) {
case *internalauth.AuthenticationSchemeV4:
v4Scheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4)
var signingName, signingRegion string
if v4Scheme.SigningName == nil {
signingName = "codeguru-security"
} else {
signingName = *v4Scheme.SigningName
}
if v4Scheme.SigningRegion == nil {
signingRegion = m.BuiltInResolver.(*builtInResolver).Region
} else {
signingRegion = *v4Scheme.SigningRegion
}
if v4Scheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initialization time.
// Setting this context value will cause the signer to extract it
// and override the value set at client initialization time.
ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding)
}
ctx = awsmiddleware.SetSigningName(ctx, signingName)
ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion)
break
case *internalauth.AuthenticationSchemeV4A:
v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A)
if v4aScheme.SigningName == nil {
v4aScheme.SigningName = aws.String("codeguru-security")
}
if v4aScheme.DisableDoubleEncoding != nil {
// The signer sets an equivalent value at client initialization time.
// Setting this context value will cause the signer to extract it
// and override the value set at client initialization time.
ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4aScheme.DisableDoubleEncoding)
}
ctx = awsmiddleware.SetSigningName(ctx, *v4aScheme.SigningName)
ctx = awsmiddleware.SetSigningRegion(ctx, v4aScheme.SigningRegionSet[0])
break
case *internalauth.AuthenticationSchemeNone:
break
}
}
return next.HandleSerialize(ctx, in)
}
func addCreateScanResolveEndpointMiddleware(stack *middleware.Stack, options Options) error | {
return stack.Serialize.Insert(&opCreateScanResolveEndpointMiddleware{
EndpointResolver: options.EndpointResolverV2,
BuiltInResolver: &builtInResolver{
Region: options.Region,
UseDualStack: options.EndpointOptions.UseDualStackEndpoint,
UseFIPS: options.EndpointOptions.UseFIPSEndpoint,
Endpoint: options.BaseEndpoint,
},
}, "ResolveEndpoint", middleware.After)
} | identifier_body | |
stocker.py | # Quandl for financial analysis, pandas and numpy for data manipulation
# fbprophet for additive models
import quandl
import pandas as pd
import numpy as np
import fbprophet
# Class for analyzing and (attempting) to predict future prices
# Contains a number of visualizations and analysis methods
class Stocker():
# Initialization requires a ticker symbol
def __init__(self, ticker, exchange='WIKI'):
# Enforce capitalization
ticker = ticker.upper()
# Symbol is used for labeling plots
self.symbol = ticker
# Use Personal Api Key
quandl.ApiConfig.api_key = 'U-m-xTvejNiPHWNa8SzH'
# Retrieval the financial data
try:
stock = quandl.get('%s/%s' % (exchange, ticker))
except Exception as e:
print('Error Retrieving Data.')
print(e)
return
# Set the index to a column called Date
stock = stock.reset_index(level=0)
# Columns required for prophet
stock['ds'] = stock['Date']
if ('Adj. Close' not in stock.columns):
stock['Adj. Close'] = stock['Close']
stock['Adj. Open'] = stock['Open']
stock['y'] = stock['Adj. Close']
stock['Daily Change'] = stock['Adj. Close'] - stock['Adj. Open']
# Data assigned as class attribute
self.stock = stock.copy()
# Minimum and maximum date in range
self.min_date = min(stock['Date'])
self.max_date = max(stock['Date'])
| # Find max and min prices and dates on which they occurred
self.max_price = np.max(self.stock['y'])
self.min_price = np.min(self.stock['y'])
self.min_price_date = self.stock[self.stock['y'] == self.min_price]['Date']
self.min_price_date = self.min_price_date[self.min_price_date.index[0]]
self.max_price_date = self.stock[self.stock['y'] == self.max_price]['Date']
self.max_price_date = self.max_price_date[self.max_price_date.index[0]]
# The starting price (starting with the opening price)
self.starting_price = float(self.stock.loc[0, 'Adj. Open'])
# The most recent price
self.most_recent_price = float(self.stock.loc[self.stock.index[-1], 'y'])
# Whether or not to round dates
self.round_dates = True
# Number of years of data to train on
self.training_years = 3
# Prophet parameters
# Default prior from library
self.changepoint_prior_scale = 0.05
self.weekly_seasonality = False
self.daily_seasonality = False
self.monthly_seasonality = True
self.yearly_seasonality = True
self.changepoints = None
"""
Make sure start and end dates are in the range and can be
converted to pandas datetimes. Returns dates in the correct format
"""
def handle_dates(self, start_date, end_date):
# Default start and end date are the beginning and end of data
if start_date is None:
start_date = self.min_date
if end_date is None:
end_date = self.max_date
try:
# Convert to pandas datetime for indexing dataframe
start_date = pd.to_datetime(start_date)
end_date = pd.to_datetime(end_date)
except Exception as e:
print('Enter valid pandas date format.')
print(e)
return
valid_start = False
valid_end = False
# User will continue to enter dates until valid dates are met
while (not valid_start) & (not valid_end):
valid_end = True
valid_start = True
if end_date < start_date:
print('End Date must be later than start date.')
start_date = pd.to_datetime(input('Enter a new start date: '))
end_date= pd.to_datetime(input('Enter a new end date: '))
valid_end = False
valid_start = False
else:
if end_date > self.max_date:
print('End Date exceeds data range')
end_date= pd.to_datetime(input('Enter a new end date: '))
valid_end = False
if start_date < self.min_date:
print('Start Date is before date range')
start_date = pd.to_datetime(input('Enter a new start date: '))
valid_start = False
return start_date, end_date
"""
Return the dataframe trimmed to the specified range.
"""
def make_df(self, start_date, end_date, df=None):
# Default is to use the object stock data
if not df:
df = self.stock.copy()
start_date, end_date = self.handle_dates(start_date, end_date)
# keep track of whether the start and end dates are in the data
start_in = True
end_in = True
# If user wants to round dates (default behavior)
if self.round_dates:
# Record if start and end date are in df
if (start_date not in list(df['Date'])):
start_in = False
if (end_date not in list(df['Date'])):
end_in = False
# If both are not in dataframe, round both
if (not end_in) & (not start_in):
trim_df = df[(df['Date'] >= start_date) &
(df['Date'] <= end_date)]
else:
# If both are in dataframe, round neither
if (end_in) & (start_in):
trim_df = df[(df['Date'] >= start_date) &
(df['Date'] <= end_date)]
else:
# If only start is missing, round start
if (not start_in):
trim_df = df[(df['Date'] > start_date) &
(df['Date'] <= end_date)]
# If only end is imssing round end
elif (not end_in):
trim_df = df[(df['Date'] >= start_date) &
(df['Date'] < end_date)]
else:
valid_start = False
valid_end = False
while (not valid_start) & (not valid_end):
start_date, end_date = self.handle_dates(start_date, end_date)
# No round dates, if either data not in, print message and return
if (start_date in list(df['Date'])):
valid_start = True
if (end_date in list(df['Date'])):
valid_end = True
# Check to make sure dates are in the data
if (start_date not in list(df['Date'])):
print('Start Date not in data (either out of range or not a trading day.)')
start_date = pd.to_datetime(input(prompt='Enter a new start date: '))
elif (end_date not in list(df['Date'])):
print('End Date not in data (either out of range or not a trading day.)')
end_date = pd.to_datetime(input(prompt='Enter a new end date: ') )
# Dates are not rounded
trim_df = df[(df['Date'] >= start_date) &
(df['Date'] <= end_date.date)]
return trim_df
# Basic Historical Plots and Basic Statistics
def get_stats(self, start_date=None, end_date=None, stats=['Adj. Close']):
if start_date is None:
start_date = self.min_date
if end_date is None:
end_date = self.max_date
stock_plot = self.make_df(start_date, end_date)
ans = []
for i, stat in enumerate(stats):
#stat_min = min(stock_plot[stat])
#stat_max = max(stock_plot[stat])
#stat_avg = np.mean(stock_plot[stat])
#date_stat_min = stock_plot[stock_plot[stat] == stat_min]['Date']
#date_stat_min = date_stat_min[date_stat_min.index[0]]
#date_stat_max = stock_plot[stock_plot[stat] == stat_max]['Date']
#date_stat_max = date_stat_max[date_stat_max.index[0]]
#print('Maximum {} = {:.2f} on {}.'.format(stat, stat_max, date_stat_max))
#print('Minimum {} = {:.2f} on {}.'.format(stat, stat_min, date_stat_min))
#print('Current {} = {:.2f} on {}.\n'.format(stat, self.stock.loc[self.stock.index[-1], stat], self.max_date))
ans.append(self.stock.loc[self.stock.index[-1], stat])
return ans
# Method to linearly interpolate prices on the weekends
def resample(self, dataframe):
# Change the index and resample at daily level
dataframe = dataframe.set_index('ds')
dataframe = dataframe.resample('D')
# Reset the index and interpolate nan values
dataframe = dataframe.reset_index(level=0)
dataframe = dataframe.interpolate()
return dataframe
# Remove weekends from a dataframe
def remove_weekends(self, dataframe):
# Reset index to use ix
dataframe = dataframe.reset_index(drop=True)
weekends = []
# Find all of the weekends
for i, date in enumerate(dataframe['ds']):
if (date.weekday()) == 5 | (date.weekday() == 6):
weekends.append(i)
# Drop the weekends
dataframe = dataframe.drop(weekends, axis=0)
return dataframe
# Calculate and plot profit from buying and holding shares for specified date range
def buy_and_hold(self, start_date=None, end_date=None, nshares=1):
start_date, end_date = self.handle_dates(start_date, end_date)
# Find starting and ending price of stock
start_price = float(self.stock[self.stock['Date'] == start_date]['Adj. Open'])
end_price = float(self.stock.tail(1)['Adj. Close'])
# Make a profit dataframe and calculate profit column
profits = self.make_df(start_date, end_date)
profits['hold_profit'] = nshares * (profits['Adj. Close'] - start_price)
# Total profit
total_hold_profit = nshares * (end_price - start_price)
#print('{} Total buy and hold profit from {} to {} for {} shares = ${:.2f}'.format
# (self.symbol, start_date, end_date, nshares, total_hold_profit))
return total_hold_profit
# Create a prophet model without training
def create_model(self):
# Make the model
model = fbprophet.Prophet(daily_seasonality=self.daily_seasonality,
weekly_seasonality=self.weekly_seasonality,
yearly_seasonality=self.yearly_seasonality,
changepoint_prior_scale=self.changepoint_prior_scale,
changepoints=self.changepoints)
if self.monthly_seasonality:
# Add monthly seasonality
model.add_seasonality(name = 'monthly', period = 30.5, fourier_order = 5)
return model
# Basic prophet model for specified number of days
def create_prophet_model(self, days=1, resample=False):
model = self.create_model()
# Fit on the stock history for self.training_years number of years
stock_history = self.stock[self.stock['Date'] > (self.max_date - pd.DateOffset(years = self.training_years))]
if resample:
stock_history = self.resample(stock_history)
model.fit(stock_history)
# Make and predict for next year with future dataframe
future = model.make_future_dataframe(periods = days, freq='D')
future = model.predict(future)
ans = -1
if days > 0:
# Print the predicted price
print('Predicted Price on {} = ${:.2f}'.format(
future.loc[future.index[-1], 'ds'], future.loc[future.index[-1], 'yhat']))
ans = future.loc[future.index[-1], 'yhat']
return ans | random_line_split | |
stocker.py | # Quandl for financial analysis, pandas and numpy for data manipulation
# fbprophet for additive models
import quandl
import pandas as pd
import numpy as np
import fbprophet
# Class for analyzing and (attempting) to predict future prices
# Contains a number of visualizations and analysis methods
class Stocker():
# Initialization requires a ticker symbol
def __init__(self, ticker, exchange='WIKI'):
# Enforce capitalization
ticker = ticker.upper()
# Symbol is used for labeling plots
self.symbol = ticker
# Use Personal Api Key
quandl.ApiConfig.api_key = 'U-m-xTvejNiPHWNa8SzH'
# Retrieval the financial data
try:
stock = quandl.get('%s/%s' % (exchange, ticker))
except Exception as e:
print('Error Retrieving Data.')
print(e)
return
# Set the index to a column called Date
stock = stock.reset_index(level=0)
# Columns required for prophet
stock['ds'] = stock['Date']
if ('Adj. Close' not in stock.columns):
stock['Adj. Close'] = stock['Close']
stock['Adj. Open'] = stock['Open']
stock['y'] = stock['Adj. Close']
stock['Daily Change'] = stock['Adj. Close'] - stock['Adj. Open']
# Data assigned as class attribute
self.stock = stock.copy()
# Minimum and maximum date in range
self.min_date = min(stock['Date'])
self.max_date = max(stock['Date'])
# Find max and min prices and dates on which they occurred
self.max_price = np.max(self.stock['y'])
self.min_price = np.min(self.stock['y'])
self.min_price_date = self.stock[self.stock['y'] == self.min_price]['Date']
self.min_price_date = self.min_price_date[self.min_price_date.index[0]]
self.max_price_date = self.stock[self.stock['y'] == self.max_price]['Date']
self.max_price_date = self.max_price_date[self.max_price_date.index[0]]
# The starting price (starting with the opening price)
self.starting_price = float(self.stock.loc[0, 'Adj. Open'])
# The most recent price
self.most_recent_price = float(self.stock.loc[self.stock.index[-1], 'y'])
# Whether or not to round dates
self.round_dates = True
# Number of years of data to train on
self.training_years = 3
# Prophet parameters
# Default prior from library
self.changepoint_prior_scale = 0.05
self.weekly_seasonality = False
self.daily_seasonality = False
self.monthly_seasonality = True
self.yearly_seasonality = True
self.changepoints = None
"""
Make sure start and end dates are in the range and can be
converted to pandas datetimes. Returns dates in the correct format
"""
def handle_dates(self, start_date, end_date):
# Default start and end date are the beginning and end of data
if start_date is None:
start_date = self.min_date
if end_date is None:
end_date = self.max_date
try:
# Convert to pandas datetime for indexing dataframe
start_date = pd.to_datetime(start_date)
end_date = pd.to_datetime(end_date)
except Exception as e:
print('Enter valid pandas date format.')
print(e)
return
valid_start = False
valid_end = False
# User will continue to enter dates until valid dates are met
while (not valid_start) & (not valid_end):
valid_end = True
valid_start = True
if end_date < start_date:
print('End Date must be later than start date.')
start_date = pd.to_datetime(input('Enter a new start date: '))
end_date= pd.to_datetime(input('Enter a new end date: '))
valid_end = False
valid_start = False
else:
if end_date > self.max_date:
print('End Date exceeds data range')
end_date= pd.to_datetime(input('Enter a new end date: '))
valid_end = False
if start_date < self.min_date:
print('Start Date is before date range')
start_date = pd.to_datetime(input('Enter a new start date: '))
valid_start = False
return start_date, end_date
"""
Return the dataframe trimmed to the specified range.
"""
def make_df(self, start_date, end_date, df=None):
# Default is to use the object stock data
if not df:
df = self.stock.copy()
start_date, end_date = self.handle_dates(start_date, end_date)
# keep track of whether the start and end dates are in the data
start_in = True
end_in = True
# If user wants to round dates (default behavior)
if self.round_dates:
# Record if start and end date are in df
if (start_date not in list(df['Date'])):
start_in = False
if (end_date not in list(df['Date'])):
end_in = False
# If both are not in dataframe, round both
if (not end_in) & (not start_in):
trim_df = df[(df['Date'] >= start_date) &
(df['Date'] <= end_date)]
else:
# If both are in dataframe, round neither
|
else:
valid_start = False
valid_end = False
while (not valid_start) & (not valid_end):
start_date, end_date = self.handle_dates(start_date, end_date)
# No round dates, if either data not in, print message and return
if (start_date in list(df['Date'])):
valid_start = True
if (end_date in list(df['Date'])):
valid_end = True
# Check to make sure dates are in the data
if (start_date not in list(df['Date'])):
print('Start Date not in data (either out of range or not a trading day.)')
start_date = pd.to_datetime(input(prompt='Enter a new start date: '))
elif (end_date not in list(df['Date'])):
print('End Date not in data (either out of range or not a trading day.)')
end_date = pd.to_datetime(input(prompt='Enter a new end date: ') )
# Dates are not rounded
trim_df = df[(df['Date'] >= start_date) &
(df['Date'] <= end_date.date)]
return trim_df
# Basic Historical Plots and Basic Statistics
def get_stats(self, start_date=None, end_date=None, stats=['Adj. Close']):
if start_date is None:
start_date = self.min_date
if end_date is None:
end_date = self.max_date
stock_plot = self.make_df(start_date, end_date)
ans = []
for i, stat in enumerate(stats):
#stat_min = min(stock_plot[stat])
#stat_max = max(stock_plot[stat])
#stat_avg = np.mean(stock_plot[stat])
#date_stat_min = stock_plot[stock_plot[stat] == stat_min]['Date']
#date_stat_min = date_stat_min[date_stat_min.index[0]]
#date_stat_max = stock_plot[stock_plot[stat] == stat_max]['Date']
#date_stat_max = date_stat_max[date_stat_max.index[0]]
#print('Maximum {} = {:.2f} on {}.'.format(stat, stat_max, date_stat_max))
#print('Minimum {} = {:.2f} on {}.'.format(stat, stat_min, date_stat_min))
#print('Current {} = {:.2f} on {}.\n'.format(stat, self.stock.loc[self.stock.index[-1], stat], self.max_date))
ans.append(self.stock.loc[self.stock.index[-1], stat])
return ans
# Method to linearly interpolate prices on the weekends
def resample(self, dataframe):
# Change the index and resample at daily level
dataframe = dataframe.set_index('ds')
dataframe = dataframe.resample('D')
# Reset the index and interpolate nan values
dataframe = dataframe.reset_index(level=0)
dataframe = dataframe.interpolate()
return dataframe
# Remove weekends from a dataframe
def remove_weekends(self, dataframe):
# Reset index to use ix
dataframe = dataframe.reset_index(drop=True)
weekends = []
# Find all of the weekends
for i, date in enumerate(dataframe['ds']):
if (date.weekday()) == 5 | (date.weekday() == 6):
weekends.append(i)
# Drop the weekends
dataframe = dataframe.drop(weekends, axis=0)
return dataframe
# Calculate and plot profit from buying and holding shares for specified date range
def buy_and_hold(self, start_date=None, end_date=None, nshares=1):
start_date, end_date = self.handle_dates(start_date, end_date)
# Find starting and ending price of stock
start_price = float(self.stock[self.stock['Date'] == start_date]['Adj. Open'])
end_price = float(self.stock.tail(1)['Adj. Close'])
# Make a profit dataframe and calculate profit column
profits = self.make_df(start_date, end_date)
profits['hold_profit'] = nshares * (profits['Adj. Close'] - start_price)
# Total profit
total_hold_profit = nshares * (end_price - start_price)
#print('{} Total buy and hold profit from {} to {} for {} shares = ${:.2f}'.format
# (self.symbol, start_date, end_date, nshares, total_hold_profit))
return total_hold_profit
# Create a prophet model without training
def create_model(self):
# Make the model
model = fbprophet.Prophet(daily_seasonality=self.daily_seasonality,
weekly_seasonality=self.weekly_seasonality,
yearly_seasonality=self.yearly_seasonality,
changepoint_prior_scale=self.changepoint_prior_scale,
changepoints=self.changepoints)
if self.monthly_seasonality:
# Add monthly seasonality
model.add_seasonality(name = 'monthly', period = 30.5, fourier_order = 5)
return model
# Basic prophet model for specified number of days
def create_prophet_model(self, days=1, resample=False):
model = self.create_model()
# Fit on the stock history for self.training_years number of years
stock_history = self.stock[self.stock['Date'] > (self.max_date - pd.DateOffset(years = self.training_years))]
if resample:
stock_history = self.resample(stock_history)
model.fit(stock_history)
# Make and predict for next year with future dataframe
future = model.make_future_dataframe(periods = days, freq='D')
future = model.predict(future)
ans = -1
if days > 0:
# Print the predicted price
print('Predicted Price on {} = ${:.2f}'.format(
future.loc[future.index[-1], 'ds'], future.loc[future.index[-1], 'yhat']))
ans = future.loc[future.index[-1], 'yhat']
return ans
| if (end_in) & (start_in):
trim_df = df[(df['Date'] >= start_date) &
(df['Date'] <= end_date)]
else:
# If only start is missing, round start
if (not start_in):
trim_df = df[(df['Date'] > start_date) &
(df['Date'] <= end_date)]
# If only end is imssing round end
elif (not end_in):
trim_df = df[(df['Date'] >= start_date) &
(df['Date'] < end_date)] | conditional_block |
stocker.py | # Quandl for financial analysis, pandas and numpy for data manipulation
# fbprophet for additive models
import quandl
import pandas as pd
import numpy as np
import fbprophet
# Class for analyzing and (attempting) to predict future prices
# Contains a number of visualizations and analysis methods
class Stocker():
# Initialization requires a ticker symbol
def | (self, ticker, exchange='WIKI'):
# Enforce capitalization
ticker = ticker.upper()
# Symbol is used for labeling plots
self.symbol = ticker
# Use Personal Api Key
quandl.ApiConfig.api_key = 'U-m-xTvejNiPHWNa8SzH'
# Retrieval the financial data
try:
stock = quandl.get('%s/%s' % (exchange, ticker))
except Exception as e:
print('Error Retrieving Data.')
print(e)
return
# Set the index to a column called Date
stock = stock.reset_index(level=0)
# Columns required for prophet
stock['ds'] = stock['Date']
if ('Adj. Close' not in stock.columns):
stock['Adj. Close'] = stock['Close']
stock['Adj. Open'] = stock['Open']
stock['y'] = stock['Adj. Close']
stock['Daily Change'] = stock['Adj. Close'] - stock['Adj. Open']
# Data assigned as class attribute
self.stock = stock.copy()
# Minimum and maximum date in range
self.min_date = min(stock['Date'])
self.max_date = max(stock['Date'])
# Find max and min prices and dates on which they occurred
self.max_price = np.max(self.stock['y'])
self.min_price = np.min(self.stock['y'])
self.min_price_date = self.stock[self.stock['y'] == self.min_price]['Date']
self.min_price_date = self.min_price_date[self.min_price_date.index[0]]
self.max_price_date = self.stock[self.stock['y'] == self.max_price]['Date']
self.max_price_date = self.max_price_date[self.max_price_date.index[0]]
# The starting price (starting with the opening price)
self.starting_price = float(self.stock.loc[0, 'Adj. Open'])
# The most recent price
self.most_recent_price = float(self.stock.loc[self.stock.index[-1], 'y'])
# Whether or not to round dates
self.round_dates = True
# Number of years of data to train on
self.training_years = 3
# Prophet parameters
# Default prior from library
self.changepoint_prior_scale = 0.05
self.weekly_seasonality = False
self.daily_seasonality = False
self.monthly_seasonality = True
self.yearly_seasonality = True
self.changepoints = None
"""
Make sure start and end dates are in the range and can be
converted to pandas datetimes. Returns dates in the correct format
"""
def handle_dates(self, start_date, end_date):
# Default start and end date are the beginning and end of data
if start_date is None:
start_date = self.min_date
if end_date is None:
end_date = self.max_date
try:
# Convert to pandas datetime for indexing dataframe
start_date = pd.to_datetime(start_date)
end_date = pd.to_datetime(end_date)
except Exception as e:
print('Enter valid pandas date format.')
print(e)
return
valid_start = False
valid_end = False
# User will continue to enter dates until valid dates are met
while (not valid_start) & (not valid_end):
valid_end = True
valid_start = True
if end_date < start_date:
print('End Date must be later than start date.')
start_date = pd.to_datetime(input('Enter a new start date: '))
end_date= pd.to_datetime(input('Enter a new end date: '))
valid_end = False
valid_start = False
else:
if end_date > self.max_date:
print('End Date exceeds data range')
end_date= pd.to_datetime(input('Enter a new end date: '))
valid_end = False
if start_date < self.min_date:
print('Start Date is before date range')
start_date = pd.to_datetime(input('Enter a new start date: '))
valid_start = False
return start_date, end_date
"""
Return the dataframe trimmed to the specified range.
"""
def make_df(self, start_date, end_date, df=None):
# Default is to use the object stock data
if not df:
df = self.stock.copy()
start_date, end_date = self.handle_dates(start_date, end_date)
# keep track of whether the start and end dates are in the data
start_in = True
end_in = True
# If user wants to round dates (default behavior)
if self.round_dates:
# Record if start and end date are in df
if (start_date not in list(df['Date'])):
start_in = False
if (end_date not in list(df['Date'])):
end_in = False
# If both are not in dataframe, round both
if (not end_in) & (not start_in):
trim_df = df[(df['Date'] >= start_date) &
(df['Date'] <= end_date)]
else:
# If both are in dataframe, round neither
if (end_in) & (start_in):
trim_df = df[(df['Date'] >= start_date) &
(df['Date'] <= end_date)]
else:
# If only start is missing, round start
if (not start_in):
trim_df = df[(df['Date'] > start_date) &
(df['Date'] <= end_date)]
# If only end is imssing round end
elif (not end_in):
trim_df = df[(df['Date'] >= start_date) &
(df['Date'] < end_date)]
else:
valid_start = False
valid_end = False
while (not valid_start) & (not valid_end):
start_date, end_date = self.handle_dates(start_date, end_date)
# No round dates, if either data not in, print message and return
if (start_date in list(df['Date'])):
valid_start = True
if (end_date in list(df['Date'])):
valid_end = True
# Check to make sure dates are in the data
if (start_date not in list(df['Date'])):
print('Start Date not in data (either out of range or not a trading day.)')
start_date = pd.to_datetime(input(prompt='Enter a new start date: '))
elif (end_date not in list(df['Date'])):
print('End Date not in data (either out of range or not a trading day.)')
end_date = pd.to_datetime(input(prompt='Enter a new end date: ') )
# Dates are not rounded
trim_df = df[(df['Date'] >= start_date) &
(df['Date'] <= end_date.date)]
return trim_df
# Basic Historical Plots and Basic Statistics
def get_stats(self, start_date=None, end_date=None, stats=['Adj. Close']):
if start_date is None:
start_date = self.min_date
if end_date is None:
end_date = self.max_date
stock_plot = self.make_df(start_date, end_date)
ans = []
for i, stat in enumerate(stats):
#stat_min = min(stock_plot[stat])
#stat_max = max(stock_plot[stat])
#stat_avg = np.mean(stock_plot[stat])
#date_stat_min = stock_plot[stock_plot[stat] == stat_min]['Date']
#date_stat_min = date_stat_min[date_stat_min.index[0]]
#date_stat_max = stock_plot[stock_plot[stat] == stat_max]['Date']
#date_stat_max = date_stat_max[date_stat_max.index[0]]
#print('Maximum {} = {:.2f} on {}.'.format(stat, stat_max, date_stat_max))
#print('Minimum {} = {:.2f} on {}.'.format(stat, stat_min, date_stat_min))
#print('Current {} = {:.2f} on {}.\n'.format(stat, self.stock.loc[self.stock.index[-1], stat], self.max_date))
ans.append(self.stock.loc[self.stock.index[-1], stat])
return ans
# Method to linearly interpolate prices on the weekends
def resample(self, dataframe):
# Change the index and resample at daily level
dataframe = dataframe.set_index('ds')
dataframe = dataframe.resample('D')
# Reset the index and interpolate nan values
dataframe = dataframe.reset_index(level=0)
dataframe = dataframe.interpolate()
return dataframe
# Remove weekends from a dataframe
def remove_weekends(self, dataframe):
# Reset index to use ix
dataframe = dataframe.reset_index(drop=True)
weekends = []
# Find all of the weekends
for i, date in enumerate(dataframe['ds']):
if (date.weekday()) == 5 | (date.weekday() == 6):
weekends.append(i)
# Drop the weekends
dataframe = dataframe.drop(weekends, axis=0)
return dataframe
# Calculate and plot profit from buying and holding shares for specified date range
def buy_and_hold(self, start_date=None, end_date=None, nshares=1):
start_date, end_date = self.handle_dates(start_date, end_date)
# Find starting and ending price of stock
start_price = float(self.stock[self.stock['Date'] == start_date]['Adj. Open'])
end_price = float(self.stock.tail(1)['Adj. Close'])
# Make a profit dataframe and calculate profit column
profits = self.make_df(start_date, end_date)
profits['hold_profit'] = nshares * (profits['Adj. Close'] - start_price)
# Total profit
total_hold_profit = nshares * (end_price - start_price)
#print('{} Total buy and hold profit from {} to {} for {} shares = ${:.2f}'.format
# (self.symbol, start_date, end_date, nshares, total_hold_profit))
return total_hold_profit
# Create a prophet model without training
def create_model(self):
# Make the model
model = fbprophet.Prophet(daily_seasonality=self.daily_seasonality,
weekly_seasonality=self.weekly_seasonality,
yearly_seasonality=self.yearly_seasonality,
changepoint_prior_scale=self.changepoint_prior_scale,
changepoints=self.changepoints)
if self.monthly_seasonality:
# Add monthly seasonality
model.add_seasonality(name = 'monthly', period = 30.5, fourier_order = 5)
return model
# Basic prophet model for specified number of days
def create_prophet_model(self, days=1, resample=False):
model = self.create_model()
# Fit on the stock history for self.training_years number of years
stock_history = self.stock[self.stock['Date'] > (self.max_date - pd.DateOffset(years = self.training_years))]
if resample:
stock_history = self.resample(stock_history)
model.fit(stock_history)
# Make and predict for next year with future dataframe
future = model.make_future_dataframe(periods = days, freq='D')
future = model.predict(future)
ans = -1
if days > 0:
# Print the predicted price
print('Predicted Price on {} = ${:.2f}'.format(
future.loc[future.index[-1], 'ds'], future.loc[future.index[-1], 'yhat']))
ans = future.loc[future.index[-1], 'yhat']
return ans
| __init__ | identifier_name |
stocker.py | # Quandl for financial analysis, pandas and numpy for data manipulation
# fbprophet for additive models
import quandl
import pandas as pd
import numpy as np
import fbprophet
# Class for analyzing and (attempting) to predict future prices
# Contains a number of visualizations and analysis methods
class Stocker():
# Initialization requires a ticker symbol
def __init__(self, ticker, exchange='WIKI'):
# Enforce capitalization
ticker = ticker.upper()
# Symbol is used for labeling plots
self.symbol = ticker
# Use Personal Api Key
quandl.ApiConfig.api_key = 'U-m-xTvejNiPHWNa8SzH'
# Retrieval the financial data
try:
stock = quandl.get('%s/%s' % (exchange, ticker))
except Exception as e:
print('Error Retrieving Data.')
print(e)
return
# Set the index to a column called Date
stock = stock.reset_index(level=0)
# Columns required for prophet
stock['ds'] = stock['Date']
if ('Adj. Close' not in stock.columns):
stock['Adj. Close'] = stock['Close']
stock['Adj. Open'] = stock['Open']
stock['y'] = stock['Adj. Close']
stock['Daily Change'] = stock['Adj. Close'] - stock['Adj. Open']
# Data assigned as class attribute
self.stock = stock.copy()
# Minimum and maximum date in range
self.min_date = min(stock['Date'])
self.max_date = max(stock['Date'])
# Find max and min prices and dates on which they occurred
self.max_price = np.max(self.stock['y'])
self.min_price = np.min(self.stock['y'])
self.min_price_date = self.stock[self.stock['y'] == self.min_price]['Date']
self.min_price_date = self.min_price_date[self.min_price_date.index[0]]
self.max_price_date = self.stock[self.stock['y'] == self.max_price]['Date']
self.max_price_date = self.max_price_date[self.max_price_date.index[0]]
# The starting price (starting with the opening price)
self.starting_price = float(self.stock.loc[0, 'Adj. Open'])
# The most recent price
self.most_recent_price = float(self.stock.loc[self.stock.index[-1], 'y'])
# Whether or not to round dates
self.round_dates = True
# Number of years of data to train on
self.training_years = 3
# Prophet parameters
# Default prior from library
self.changepoint_prior_scale = 0.05
self.weekly_seasonality = False
self.daily_seasonality = False
self.monthly_seasonality = True
self.yearly_seasonality = True
self.changepoints = None
"""
Make sure start and end dates are in the range and can be
converted to pandas datetimes. Returns dates in the correct format
"""
def handle_dates(self, start_date, end_date):
# Default start and end date are the beginning and end of data
if start_date is None:
start_date = self.min_date
if end_date is None:
end_date = self.max_date
try:
# Convert to pandas datetime for indexing dataframe
start_date = pd.to_datetime(start_date)
end_date = pd.to_datetime(end_date)
except Exception as e:
print('Enter valid pandas date format.')
print(e)
return
valid_start = False
valid_end = False
# User will continue to enter dates until valid dates are met
while (not valid_start) & (not valid_end):
valid_end = True
valid_start = True
if end_date < start_date:
print('End Date must be later than start date.')
start_date = pd.to_datetime(input('Enter a new start date: '))
end_date= pd.to_datetime(input('Enter a new end date: '))
valid_end = False
valid_start = False
else:
if end_date > self.max_date:
print('End Date exceeds data range')
end_date= pd.to_datetime(input('Enter a new end date: '))
valid_end = False
if start_date < self.min_date:
print('Start Date is before date range')
start_date = pd.to_datetime(input('Enter a new start date: '))
valid_start = False
return start_date, end_date
"""
Return the dataframe trimmed to the specified range.
"""
def make_df(self, start_date, end_date, df=None):
# Default is to use the object stock data
if not df:
df = self.stock.copy()
start_date, end_date = self.handle_dates(start_date, end_date)
# keep track of whether the start and end dates are in the data
start_in = True
end_in = True
# If user wants to round dates (default behavior)
if self.round_dates:
# Record if start and end date are in df
if (start_date not in list(df['Date'])):
start_in = False
if (end_date not in list(df['Date'])):
end_in = False
# If both are not in dataframe, round both
if (not end_in) & (not start_in):
trim_df = df[(df['Date'] >= start_date) &
(df['Date'] <= end_date)]
else:
# If both are in dataframe, round neither
if (end_in) & (start_in):
trim_df = df[(df['Date'] >= start_date) &
(df['Date'] <= end_date)]
else:
# If only start is missing, round start
if (not start_in):
trim_df = df[(df['Date'] > start_date) &
(df['Date'] <= end_date)]
# If only end is imssing round end
elif (not end_in):
trim_df = df[(df['Date'] >= start_date) &
(df['Date'] < end_date)]
else:
valid_start = False
valid_end = False
while (not valid_start) & (not valid_end):
start_date, end_date = self.handle_dates(start_date, end_date)
# No round dates, if either data not in, print message and return
if (start_date in list(df['Date'])):
valid_start = True
if (end_date in list(df['Date'])):
valid_end = True
# Check to make sure dates are in the data
if (start_date not in list(df['Date'])):
print('Start Date not in data (either out of range or not a trading day.)')
start_date = pd.to_datetime(input(prompt='Enter a new start date: '))
elif (end_date not in list(df['Date'])):
print('End Date not in data (either out of range or not a trading day.)')
end_date = pd.to_datetime(input(prompt='Enter a new end date: ') )
# Dates are not rounded
trim_df = df[(df['Date'] >= start_date) &
(df['Date'] <= end_date.date)]
return trim_df
# Basic Historical Plots and Basic Statistics
def get_stats(self, start_date=None, end_date=None, stats=['Adj. Close']):
if start_date is None:
start_date = self.min_date
if end_date is None:
end_date = self.max_date
stock_plot = self.make_df(start_date, end_date)
ans = []
for i, stat in enumerate(stats):
#stat_min = min(stock_plot[stat])
#stat_max = max(stock_plot[stat])
#stat_avg = np.mean(stock_plot[stat])
#date_stat_min = stock_plot[stock_plot[stat] == stat_min]['Date']
#date_stat_min = date_stat_min[date_stat_min.index[0]]
#date_stat_max = stock_plot[stock_plot[stat] == stat_max]['Date']
#date_stat_max = date_stat_max[date_stat_max.index[0]]
#print('Maximum {} = {:.2f} on {}.'.format(stat, stat_max, date_stat_max))
#print('Minimum {} = {:.2f} on {}.'.format(stat, stat_min, date_stat_min))
#print('Current {} = {:.2f} on {}.\n'.format(stat, self.stock.loc[self.stock.index[-1], stat], self.max_date))
ans.append(self.stock.loc[self.stock.index[-1], stat])
return ans
# Method to linearly interpolate prices on the weekends
def resample(self, dataframe):
# Change the index and resample at daily level
dataframe = dataframe.set_index('ds')
dataframe = dataframe.resample('D')
# Reset the index and interpolate nan values
dataframe = dataframe.reset_index(level=0)
dataframe = dataframe.interpolate()
return dataframe
# Remove weekends from a dataframe
def remove_weekends(self, dataframe):
# Reset index to use ix
|
# Calculate and plot profit from buying and holding shares for specified date range
def buy_and_hold(self, start_date=None, end_date=None, nshares=1):
start_date, end_date = self.handle_dates(start_date, end_date)
# Find starting and ending price of stock
start_price = float(self.stock[self.stock['Date'] == start_date]['Adj. Open'])
end_price = float(self.stock.tail(1)['Adj. Close'])
# Make a profit dataframe and calculate profit column
profits = self.make_df(start_date, end_date)
profits['hold_profit'] = nshares * (profits['Adj. Close'] - start_price)
# Total profit
total_hold_profit = nshares * (end_price - start_price)
#print('{} Total buy and hold profit from {} to {} for {} shares = ${:.2f}'.format
# (self.symbol, start_date, end_date, nshares, total_hold_profit))
return total_hold_profit
# Create a prophet model without training
def create_model(self):
# Make the model
model = fbprophet.Prophet(daily_seasonality=self.daily_seasonality,
weekly_seasonality=self.weekly_seasonality,
yearly_seasonality=self.yearly_seasonality,
changepoint_prior_scale=self.changepoint_prior_scale,
changepoints=self.changepoints)
if self.monthly_seasonality:
# Add monthly seasonality
model.add_seasonality(name = 'monthly', period = 30.5, fourier_order = 5)
return model
# Basic prophet model for specified number of days
def create_prophet_model(self, days=1, resample=False):
model = self.create_model()
# Fit on the stock history for self.training_years number of years
stock_history = self.stock[self.stock['Date'] > (self.max_date - pd.DateOffset(years = self.training_years))]
if resample:
stock_history = self.resample(stock_history)
model.fit(stock_history)
# Make and predict for next year with future dataframe
future = model.make_future_dataframe(periods = days, freq='D')
future = model.predict(future)
ans = -1
if days > 0:
# Print the predicted price
print('Predicted Price on {} = ${:.2f}'.format(
future.loc[future.index[-1], 'ds'], future.loc[future.index[-1], 'yhat']))
ans = future.loc[future.index[-1], 'yhat']
return ans
| dataframe = dataframe.reset_index(drop=True)
weekends = []
# Find all of the weekends
for i, date in enumerate(dataframe['ds']):
if (date.weekday()) == 5 | (date.weekday() == 6):
weekends.append(i)
# Drop the weekends
dataframe = dataframe.drop(weekends, axis=0)
return dataframe | identifier_body |
main.go | package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
"github.com/cenkalti/backoff"
"github.com/d4l3k/ricela/chargepoint"
"github.com/d4l3k/ricela/sysmetrics"
"github.com/golang/geo/s2"
"github.com/davecgh/go-spew/spew"
"github.com/jsgoecke/tesla"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/sync/errgroup"
)
var (
bind = flag.String("bind", ":2112", "address to bind to")
standbyPollTime = flag.Duration("standbyPollTime", 1*time.Minute, "polling frequency")
drivePollTime = flag.Duration("drivePollTime", 15*time.Second, "polling frequency")
activePollTime = flag.Duration("activePollTime", 5*time.Second, "polling frequency")
chargePointPollTime = flag.Duration("chargePointPollTime", 5*time.Minute, "polling frequency")
carServerAddr = flag.String("carserver", "http://localhost:27654/diag_vitals", "car server vitals endpoint")
)
const (
StateCharging = "Charging"
StateComplete = "Complete"
)
type Charger interface {
DistanceInMeters(a s2.LatLng) float64
Start(ctx context.Context, r *RiceLa) error
}
type ChargePointCharger struct {
DeviceID int64
LatLng s2.LatLng
}
func (c ChargePointCharger) DistanceInMeters(a s2.LatLng) float64 {
const earthRadius = 6_371_000
angle := c.LatLng.Distance(a)
return earthRadius * angle.Radians()
}
func (c ChargePointCharger) Start(ctx context.Context, r *RiceLa) error {
_, err := r.chargepoint.StartSession(ctx, c.DeviceID)
return err
}
var knownChargers = []Charger{
ChargePointCharger{DeviceID: 1947511, LatLng: s2.LatLngFromDegrees(47.630007, -122.133969)},
}
func main() {
log.SetFlags(log.Flags() | log.Lshortfile)
flag.Parse()
var r RiceLa
if err := r.run(); err != nil {
log.Fatalf("%+v", err)
}
}
type ClimateState struct {
InsideTemp float64 `json:"inside_temp"`
OutsideTemp float64 `json:"outside_temp"`
DriverTempSetting float64 `json:"driver_temp_setting"`
PassengerTempSetting float64 `json:"passenger_temp_setting"`
LeftTempDirection float64 `json:"left_temp_direction"`
RightTempDirection float64 `json:"right_temp_direction"`
IsAutoConditioningOn bool `json:"is_auto_conditioning_on"`
IsFrontDefrosterOn interface{} `json:"is_front_defroster_on"`
IsRearDefrosterOn bool `json:"is_rear_defroster_on"`
FanStatus interface{} `json:"fan_status"`
IsClimateOn bool `json:"is_climate_on"`
MinAvailTemp float64 `json:"min_avail_temp"`
MaxAvailTemp float64 `json:"max_avail_temp"`
SeatHeaterLeft int `json:"seat_heater_left"`
SeatHeaterRight int `json:"seat_heater_right"`
SeatHeaterRearLeft int `json:"seat_heater_rear_left"`
SeatHeaterRearRight int `json:"seat_heater_rear_right"`
SeatHeaterRearCenter int `json:"seat_heater_rear_center"` | SeatHeaterRearLeftBack int `json:"seat_heater_rear_left_back"`
SmartPreconditioning bool `json:"smart_preconditioning"`
}
type VehicleData struct {
UserID int64 `json:"user_id"`
VehicleID int64 `json:"vehicle_id"`
VIN string `json:"vin"`
State string `json:"online"`
ChargeState tesla.ChargeState `json:"charge_state"`
VehicleState tesla.VehicleState `json:"vehicle_state"`
ClimateState ClimateState `json:"climate_state"`
DriveState tesla.DriveState `json:"drive_state"`
}
type VehicleDataResponse struct {
Response VehicleData `json:"response"`
}
func (r *RiceLa) getVehicleData(ctx context.Context, v *tesla.Vehicle) (*VehicleData, error) {
ctx, cancel := context.WithTimeout(ctx, 1*time.Minute)
defer cancel()
log.Printf("Polling %s: %v", v.DisplayName, v.ID)
req, err := http.NewRequestWithContext(ctx, "GET", tesla.BaseURL+"/vehicles/"+strconv.FormatInt(v.ID, 10)+"/vehicle_data", nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+r.client.Token.AccessToken)
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
res, err := r.client.HTTP.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
return nil, errors.Errorf("%s: %s", res.Status, body)
}
out := map[string]interface{}{}
if err := json.Unmarshal(body, &out); err != nil {
return nil, err
}
spew.Dump(out)
count := r.processCounter("tesla", out["response"])
log.Printf("updated %d counters", count)
var resp VehicleDataResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, errors.Wrapf(err, "unmarshalling vehicle_data")
}
return &resp.Response, nil
}
var counterStrs = map[string]float64{
"--": -1,
"NONE": -1,
"PRESENT": 1,
"ENGAGED": 1,
"DISENGAGED": 0,
"LATCHED": 1,
"NOMINAL": 1,
"FAULT": 0,
"ERROR": 0,
"DRIVE": 2,
"PARKED": 1,
"REVERSE": 3,
"NEUTRAL": 4,
"On": 1,
"Off": 0,
"Stopped": 0,
"IDLE": 0,
"ACTIVE": 1,
"on": 1,
"off": 0,
"yes": 1,
"no": 0,
"": -1,
}
func (r *RiceLa) processCounter(key string, v interface{}) int {
switch v := v.(type) {
case map[string]interface{}:
count := 0
for k, v := range v {
key := key + ":" + k
count += r.processCounter(key, v)
}
return count
case float64:
r.setCounter(key, v)
return 1
case int:
r.setCounter(key, float64(v))
return 1
case int64:
r.setCounter(key, float64(v))
return 1
case int32:
r.setCounter(key, float64(v))
return 1
case float32:
r.setCounter(key, float64(v))
return 1
case bool:
if v {
r.setCounter(key, 1)
} else {
r.setCounter(key, 0)
}
return 1
case string:
f, err := strconv.ParseFloat(v, 64)
if err == nil {
r.setCounter(key, f)
return 1
}
f, ok := counterStrs[v]
if ok {
r.setCounter(key, f)
return 1
}
return 0
default:
if v == nil {
r.setCounter(key, 0)
return 1
}
return 0
}
}
func (r *RiceLa) setCounter(key string, v float64) {
r.mu.Lock()
defer r.mu.Unlock()
g, ok := r.mu.gauges[key]
if !ok {
g = promauto.NewGauge(prometheus.GaugeOpts{Name: key})
r.mu.gauges[key] = g
}
g.Set(v)
}
type RiceLa struct {
client *tesla.Client
chargepoint *chargepoint.Client
mu struct {
sync.Mutex
charging bool
gauges map[string]prometheus.Gauge
}
}
func pollTime(data VehicleData) time.Duration {
if !data.VehicleState.Locked && (data.DriveState.ShiftState == nil || data.DriveState.ShiftState == "P" || data.DriveState.ShiftState == "R") && !data.ChargeState.ChargePortDoorOpen {
return *activePollTime
}
if data.DriveState.ShiftState == "D" || data.DriveState.ShiftState == "R" || data.DriveState.ShiftState == "N" || data.ClimateState.IsClimateOn {
return *drivePollTime
}
return *standbyPollTime
}
func (r *RiceLa) startNearbyCharging(ctx context.Context, data tesla.DriveState) error {
log.Println("starting charging")
latlng := s2.LatLngFromDegrees(data.Latitude, data.Longitude)
for _, charger := range knownChargers {
if charger.DistanceInMeters(latlng) < 20 {
return charger.Start(ctx, r)
}
}
return nil
}
func (r *RiceLa) stopCharging(ctx context.Context) error {
log.Println("stop charging")
userStatus, err := r.chargepoint.UserStatus(ctx)
log.Printf("Charge Point user status %+v", userStatus)
if err != nil {
return err
}
for _, station := range userStatus.Charging.Stations {
if err := r.chargepoint.StopSession(ctx, userStatus.Charging.SessionID, station.DeviceID); err != nil {
return err
}
}
return nil
}
func (r *RiceLa) setCharging(charging bool) {
r.mu.Lock()
defer r.mu.Unlock()
r.mu.charging = charging
}
func (r *RiceLa) charging() bool {
r.mu.Lock()
defer r.mu.Unlock()
return r.mu.charging
}
func (r *RiceLa) monitorVehicle(ctx context.Context, v *tesla.Vehicle) error {
var data, prevData *VehicleData
for {
b := backoff.NewExponentialBackOff()
b.MaxElapsedTime = 1 * time.Minute
if err := backoff.Retry(func() error {
var err error
data, err = r.getVehicleData(ctx, v)
if err != nil {
log.Printf("got error polling (likely retrying) %+v", err)
}
return err
}, b); err != nil {
return err
}
pilotCurrent, _ := data.ChargeState.ChargerPilotCurrent.(float64)
if data.ChargeState.ChargingState == StateComplete && pilotCurrent > 1 {
if err := r.stopCharging(ctx); err != nil {
return err
}
}
if prevData != nil && !prevData.ChargeState.ChargePortDoorOpen && data.ChargeState.ChargePortDoorOpen {
if err := r.startNearbyCharging(ctx, data.DriveState); err != nil {
return err
}
}
r.setCharging(data.ChargeState.ChargingState == StateCharging)
prevData = data
select {
case <-ctx.Done():
return nil
case <-time.NewTimer(pollTime(*data)).C:
}
}
}
type Token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
CreatedAt int64 `json:"created_at"`
}
func (r *RiceLa) pollCarServer() error {
res, err := http.Get(*carServerAddr)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return errors.Errorf("%s", res.Status)
}
out := map[string]interface{}{}
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
return err
}
spew.Dump(out)
r.processCounter("carserver", out)
return nil
}
func (r *RiceLa) run() error {
r.mu.gauges = map[string]prometheus.Gauge{}
eg, ctx := errgroup.WithContext(context.Background())
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
tokenJSON := os.Getenv("TESLA_TOKEN_JSON")
var token Token
if err := json.Unmarshal([]byte(tokenJSON), &token); err != nil {
return err
}
var err error
r.client, err = tesla.NewClientWithToken(
&tesla.Auth{
ClientID: os.Getenv("TESLA_CLIENT_ID"),
ClientSecret: os.Getenv("TESLA_CLIENT_SECRET"),
Email: os.Getenv("TESLA_USERNAME"),
Password: os.Getenv("TESLA_PASSWORD"),
}, &tesla.Token{
AccessToken: token.AccessToken,
TokenType: token.TokenType,
ExpiresIn: int(token.ExpiresIn),
Expires: token.CreatedAt + token.ExpiresIn,
})
if err != nil {
log.Printf("%+v", errors.Wrapf(err, "failed to create client"))
}
r.chargepoint = &chargepoint.Client{
Token: os.Getenv("CHARGEPOINT_TOKEN"),
}
if r.client != nil {
log.Printf("Tesla token: %+v", r.client.Token)
eg.Go(func() error {
vehicles, err := r.client.Vehicles()
if err != nil {
return errors.Wrapf(err, "failed to get vehicles")
}
for _, v := range vehicles {
v := v
eg.Go(func() error {
return r.monitorVehicle(ctx, v.Vehicle)
})
}
return nil
})
}
eg.Go(func() error {
return sysmetrics.Monitor(ctx, *drivePollTime)
})
eg.Go(func() error {
for {
sessions, err := r.chargepoint.GetSessions(ctx)
if err != nil {
log.Println("chargpoint stats error", err)
}
if len(sessions) > 0 {
lastSession := sessions[len(sessions)-1]
r.setCounter("chargepoint:latest:total_amount", lastSession.TotalAmount)
r.setCounter("chargepoint:latest:miles_added", lastSession.MilesAdded)
r.setCounter("chargepoint:latest:energy_kwh", lastSession.EnergyKwh)
r.setCounter("chargepoint:latest:power_kw", lastSession.PowerKw)
r.setCounter("chargepoint:latest:latitude", lastSession.Lat)
r.setCounter("chargepoint:latest:longitude", lastSession.Lon)
if lastSession.CurrentCharging == chargepoint.ChargingFullyCharged {
if err := r.stopCharging(ctx); err != nil {
log.Printf("failed to stop charging: %+v", err)
}
}
}
var totalAmount, milesAdded, energyKwh float64
for _, session := range sessions {
totalAmount += session.TotalAmount
milesAdded += session.MilesAdded
energyKwh += session.EnergyKwh
}
r.setCounter("chargepoint:total_amount", totalAmount)
r.setCounter("chargepoint:miles_added", milesAdded)
r.setCounter("chargepoint:energy_kwh", energyKwh)
select {
case <-ctx.Done():
return nil
case <-time.NewTimer(*chargePointPollTime).C:
}
}
})
eg.Go(func() error {
for {
if err := r.pollCarServer(); err != nil {
log.Printf("car server error %+v", err)
}
select {
case <-ctx.Done():
return nil
case <-time.NewTimer(*drivePollTime).C:
}
}
})
s := http.Server{
Addr: *bind,
Handler: mux,
}
eg.Go(func() error {
fmt.Println("Listening...", s.Addr)
return s.ListenAndServe()
})
eg.Go(func() error {
<-ctx.Done()
ctxShutDown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer func() {
cancel()
}()
if err := s.Shutdown(ctxShutDown); err != nil {
log.Fatal(err)
}
return nil
})
return eg.Wait()
} | SeatHeaterRearRightBack int `json:"seat_heater_rear_right_back"` | random_line_split |
main.go | package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
"github.com/cenkalti/backoff"
"github.com/d4l3k/ricela/chargepoint"
"github.com/d4l3k/ricela/sysmetrics"
"github.com/golang/geo/s2"
"github.com/davecgh/go-spew/spew"
"github.com/jsgoecke/tesla"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/sync/errgroup"
)
var (
bind = flag.String("bind", ":2112", "address to bind to")
standbyPollTime = flag.Duration("standbyPollTime", 1*time.Minute, "polling frequency")
drivePollTime = flag.Duration("drivePollTime", 15*time.Second, "polling frequency")
activePollTime = flag.Duration("activePollTime", 5*time.Second, "polling frequency")
chargePointPollTime = flag.Duration("chargePointPollTime", 5*time.Minute, "polling frequency")
carServerAddr = flag.String("carserver", "http://localhost:27654/diag_vitals", "car server vitals endpoint")
)
const (
StateCharging = "Charging"
StateComplete = "Complete"
)
type Charger interface {
DistanceInMeters(a s2.LatLng) float64
Start(ctx context.Context, r *RiceLa) error
}
type ChargePointCharger struct {
DeviceID int64
LatLng s2.LatLng
}
func (c ChargePointCharger) DistanceInMeters(a s2.LatLng) float64 {
const earthRadius = 6_371_000
angle := c.LatLng.Distance(a)
return earthRadius * angle.Radians()
}
func (c ChargePointCharger) Start(ctx context.Context, r *RiceLa) error {
_, err := r.chargepoint.StartSession(ctx, c.DeviceID)
return err
}
var knownChargers = []Charger{
ChargePointCharger{DeviceID: 1947511, LatLng: s2.LatLngFromDegrees(47.630007, -122.133969)},
}
func main() {
log.SetFlags(log.Flags() | log.Lshortfile)
flag.Parse()
var r RiceLa
if err := r.run(); err != nil {
log.Fatalf("%+v", err)
}
}
type ClimateState struct {
InsideTemp float64 `json:"inside_temp"`
OutsideTemp float64 `json:"outside_temp"`
DriverTempSetting float64 `json:"driver_temp_setting"`
PassengerTempSetting float64 `json:"passenger_temp_setting"`
LeftTempDirection float64 `json:"left_temp_direction"`
RightTempDirection float64 `json:"right_temp_direction"`
IsAutoConditioningOn bool `json:"is_auto_conditioning_on"`
IsFrontDefrosterOn interface{} `json:"is_front_defroster_on"`
IsRearDefrosterOn bool `json:"is_rear_defroster_on"`
FanStatus interface{} `json:"fan_status"`
IsClimateOn bool `json:"is_climate_on"`
MinAvailTemp float64 `json:"min_avail_temp"`
MaxAvailTemp float64 `json:"max_avail_temp"`
SeatHeaterLeft int `json:"seat_heater_left"`
SeatHeaterRight int `json:"seat_heater_right"`
SeatHeaterRearLeft int `json:"seat_heater_rear_left"`
SeatHeaterRearRight int `json:"seat_heater_rear_right"`
SeatHeaterRearCenter int `json:"seat_heater_rear_center"`
SeatHeaterRearRightBack int `json:"seat_heater_rear_right_back"`
SeatHeaterRearLeftBack int `json:"seat_heater_rear_left_back"`
SmartPreconditioning bool `json:"smart_preconditioning"`
}
type VehicleData struct {
UserID int64 `json:"user_id"`
VehicleID int64 `json:"vehicle_id"`
VIN string `json:"vin"`
State string `json:"online"`
ChargeState tesla.ChargeState `json:"charge_state"`
VehicleState tesla.VehicleState `json:"vehicle_state"`
ClimateState ClimateState `json:"climate_state"`
DriveState tesla.DriveState `json:"drive_state"`
}
type VehicleDataResponse struct {
Response VehicleData `json:"response"`
}
func (r *RiceLa) getVehicleData(ctx context.Context, v *tesla.Vehicle) (*VehicleData, error) {
ctx, cancel := context.WithTimeout(ctx, 1*time.Minute)
defer cancel()
log.Printf("Polling %s: %v", v.DisplayName, v.ID)
req, err := http.NewRequestWithContext(ctx, "GET", tesla.BaseURL+"/vehicles/"+strconv.FormatInt(v.ID, 10)+"/vehicle_data", nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+r.client.Token.AccessToken)
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
res, err := r.client.HTTP.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
return nil, errors.Errorf("%s: %s", res.Status, body)
}
out := map[string]interface{}{}
if err := json.Unmarshal(body, &out); err != nil {
return nil, err
}
spew.Dump(out)
count := r.processCounter("tesla", out["response"])
log.Printf("updated %d counters", count)
var resp VehicleDataResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, errors.Wrapf(err, "unmarshalling vehicle_data")
}
return &resp.Response, nil
}
var counterStrs = map[string]float64{
"--": -1,
"NONE": -1,
"PRESENT": 1,
"ENGAGED": 1,
"DISENGAGED": 0,
"LATCHED": 1,
"NOMINAL": 1,
"FAULT": 0,
"ERROR": 0,
"DRIVE": 2,
"PARKED": 1,
"REVERSE": 3,
"NEUTRAL": 4,
"On": 1,
"Off": 0,
"Stopped": 0,
"IDLE": 0,
"ACTIVE": 1,
"on": 1,
"off": 0,
"yes": 1,
"no": 0,
"": -1,
}
func (r *RiceLa) processCounter(key string, v interface{}) int {
switch v := v.(type) {
case map[string]interface{}:
count := 0
for k, v := range v {
key := key + ":" + k
count += r.processCounter(key, v)
}
return count
case float64:
r.setCounter(key, v)
return 1
case int:
r.setCounter(key, float64(v))
return 1
case int64:
r.setCounter(key, float64(v))
return 1
case int32:
r.setCounter(key, float64(v))
return 1
case float32:
r.setCounter(key, float64(v))
return 1
case bool:
if v {
r.setCounter(key, 1)
} else {
r.setCounter(key, 0)
}
return 1
case string:
f, err := strconv.ParseFloat(v, 64)
if err == nil {
r.setCounter(key, f)
return 1
}
f, ok := counterStrs[v]
if ok {
r.setCounter(key, f)
return 1
}
return 0
default:
if v == nil {
r.setCounter(key, 0)
return 1
}
return 0
}
}
func (r *RiceLa) setCounter(key string, v float64) {
r.mu.Lock()
defer r.mu.Unlock()
g, ok := r.mu.gauges[key]
if !ok {
g = promauto.NewGauge(prometheus.GaugeOpts{Name: key})
r.mu.gauges[key] = g
}
g.Set(v)
}
type RiceLa struct {
client *tesla.Client
chargepoint *chargepoint.Client
mu struct {
sync.Mutex
charging bool
gauges map[string]prometheus.Gauge
}
}
func pollTime(data VehicleData) time.Duration {
if !data.VehicleState.Locked && (data.DriveState.ShiftState == nil || data.DriveState.ShiftState == "P" || data.DriveState.ShiftState == "R") && !data.ChargeState.ChargePortDoorOpen {
return *activePollTime
}
if data.DriveState.ShiftState == "D" || data.DriveState.ShiftState == "R" || data.DriveState.ShiftState == "N" || data.ClimateState.IsClimateOn {
return *drivePollTime
}
return *standbyPollTime
}
func (r *RiceLa) startNearbyCharging(ctx context.Context, data tesla.DriveState) error {
log.Println("starting charging")
latlng := s2.LatLngFromDegrees(data.Latitude, data.Longitude)
for _, charger := range knownChargers {
if charger.DistanceInMeters(latlng) < 20 {
return charger.Start(ctx, r)
}
}
return nil
}
func (r *RiceLa) stopCharging(ctx context.Context) error {
log.Println("stop charging")
userStatus, err := r.chargepoint.UserStatus(ctx)
log.Printf("Charge Point user status %+v", userStatus)
if err != nil {
return err
}
for _, station := range userStatus.Charging.Stations {
if err := r.chargepoint.StopSession(ctx, userStatus.Charging.SessionID, station.DeviceID); err != nil {
return err
}
}
return nil
}
func (r *RiceLa) setCharging(charging bool) |
func (r *RiceLa) charging() bool {
r.mu.Lock()
defer r.mu.Unlock()
return r.mu.charging
}
func (r *RiceLa) monitorVehicle(ctx context.Context, v *tesla.Vehicle) error {
var data, prevData *VehicleData
for {
b := backoff.NewExponentialBackOff()
b.MaxElapsedTime = 1 * time.Minute
if err := backoff.Retry(func() error {
var err error
data, err = r.getVehicleData(ctx, v)
if err != nil {
log.Printf("got error polling (likely retrying) %+v", err)
}
return err
}, b); err != nil {
return err
}
pilotCurrent, _ := data.ChargeState.ChargerPilotCurrent.(float64)
if data.ChargeState.ChargingState == StateComplete && pilotCurrent > 1 {
if err := r.stopCharging(ctx); err != nil {
return err
}
}
if prevData != nil && !prevData.ChargeState.ChargePortDoorOpen && data.ChargeState.ChargePortDoorOpen {
if err := r.startNearbyCharging(ctx, data.DriveState); err != nil {
return err
}
}
r.setCharging(data.ChargeState.ChargingState == StateCharging)
prevData = data
select {
case <-ctx.Done():
return nil
case <-time.NewTimer(pollTime(*data)).C:
}
}
}
type Token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
CreatedAt int64 `json:"created_at"`
}
func (r *RiceLa) pollCarServer() error {
res, err := http.Get(*carServerAddr)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return errors.Errorf("%s", res.Status)
}
out := map[string]interface{}{}
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
return err
}
spew.Dump(out)
r.processCounter("carserver", out)
return nil
}
func (r *RiceLa) run() error {
r.mu.gauges = map[string]prometheus.Gauge{}
eg, ctx := errgroup.WithContext(context.Background())
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
tokenJSON := os.Getenv("TESLA_TOKEN_JSON")
var token Token
if err := json.Unmarshal([]byte(tokenJSON), &token); err != nil {
return err
}
var err error
r.client, err = tesla.NewClientWithToken(
&tesla.Auth{
ClientID: os.Getenv("TESLA_CLIENT_ID"),
ClientSecret: os.Getenv("TESLA_CLIENT_SECRET"),
Email: os.Getenv("TESLA_USERNAME"),
Password: os.Getenv("TESLA_PASSWORD"),
}, &tesla.Token{
AccessToken: token.AccessToken,
TokenType: token.TokenType,
ExpiresIn: int(token.ExpiresIn),
Expires: token.CreatedAt + token.ExpiresIn,
})
if err != nil {
log.Printf("%+v", errors.Wrapf(err, "failed to create client"))
}
r.chargepoint = &chargepoint.Client{
Token: os.Getenv("CHARGEPOINT_TOKEN"),
}
if r.client != nil {
log.Printf("Tesla token: %+v", r.client.Token)
eg.Go(func() error {
vehicles, err := r.client.Vehicles()
if err != nil {
return errors.Wrapf(err, "failed to get vehicles")
}
for _, v := range vehicles {
v := v
eg.Go(func() error {
return r.monitorVehicle(ctx, v.Vehicle)
})
}
return nil
})
}
eg.Go(func() error {
return sysmetrics.Monitor(ctx, *drivePollTime)
})
eg.Go(func() error {
for {
sessions, err := r.chargepoint.GetSessions(ctx)
if err != nil {
log.Println("chargpoint stats error", err)
}
if len(sessions) > 0 {
lastSession := sessions[len(sessions)-1]
r.setCounter("chargepoint:latest:total_amount", lastSession.TotalAmount)
r.setCounter("chargepoint:latest:miles_added", lastSession.MilesAdded)
r.setCounter("chargepoint:latest:energy_kwh", lastSession.EnergyKwh)
r.setCounter("chargepoint:latest:power_kw", lastSession.PowerKw)
r.setCounter("chargepoint:latest:latitude", lastSession.Lat)
r.setCounter("chargepoint:latest:longitude", lastSession.Lon)
if lastSession.CurrentCharging == chargepoint.ChargingFullyCharged {
if err := r.stopCharging(ctx); err != nil {
log.Printf("failed to stop charging: %+v", err)
}
}
}
var totalAmount, milesAdded, energyKwh float64
for _, session := range sessions {
totalAmount += session.TotalAmount
milesAdded += session.MilesAdded
energyKwh += session.EnergyKwh
}
r.setCounter("chargepoint:total_amount", totalAmount)
r.setCounter("chargepoint:miles_added", milesAdded)
r.setCounter("chargepoint:energy_kwh", energyKwh)
select {
case <-ctx.Done():
return nil
case <-time.NewTimer(*chargePointPollTime).C:
}
}
})
eg.Go(func() error {
for {
if err := r.pollCarServer(); err != nil {
log.Printf("car server error %+v", err)
}
select {
case <-ctx.Done():
return nil
case <-time.NewTimer(*drivePollTime).C:
}
}
})
s := http.Server{
Addr: *bind,
Handler: mux,
}
eg.Go(func() error {
fmt.Println("Listening...", s.Addr)
return s.ListenAndServe()
})
eg.Go(func() error {
<-ctx.Done()
ctxShutDown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer func() {
cancel()
}()
if err := s.Shutdown(ctxShutDown); err != nil {
log.Fatal(err)
}
return nil
})
return eg.Wait()
}
| {
r.mu.Lock()
defer r.mu.Unlock()
r.mu.charging = charging
} | identifier_body |
main.go | package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
"github.com/cenkalti/backoff"
"github.com/d4l3k/ricela/chargepoint"
"github.com/d4l3k/ricela/sysmetrics"
"github.com/golang/geo/s2"
"github.com/davecgh/go-spew/spew"
"github.com/jsgoecke/tesla"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/sync/errgroup"
)
var (
bind = flag.String("bind", ":2112", "address to bind to")
standbyPollTime = flag.Duration("standbyPollTime", 1*time.Minute, "polling frequency")
drivePollTime = flag.Duration("drivePollTime", 15*time.Second, "polling frequency")
activePollTime = flag.Duration("activePollTime", 5*time.Second, "polling frequency")
chargePointPollTime = flag.Duration("chargePointPollTime", 5*time.Minute, "polling frequency")
carServerAddr = flag.String("carserver", "http://localhost:27654/diag_vitals", "car server vitals endpoint")
)
const (
StateCharging = "Charging"
StateComplete = "Complete"
)
type Charger interface {
DistanceInMeters(a s2.LatLng) float64
Start(ctx context.Context, r *RiceLa) error
}
type ChargePointCharger struct {
DeviceID int64
LatLng s2.LatLng
}
func (c ChargePointCharger) DistanceInMeters(a s2.LatLng) float64 {
const earthRadius = 6_371_000
angle := c.LatLng.Distance(a)
return earthRadius * angle.Radians()
}
func (c ChargePointCharger) Start(ctx context.Context, r *RiceLa) error {
_, err := r.chargepoint.StartSession(ctx, c.DeviceID)
return err
}
var knownChargers = []Charger{
ChargePointCharger{DeviceID: 1947511, LatLng: s2.LatLngFromDegrees(47.630007, -122.133969)},
}
func main() {
log.SetFlags(log.Flags() | log.Lshortfile)
flag.Parse()
var r RiceLa
if err := r.run(); err != nil {
log.Fatalf("%+v", err)
}
}
type ClimateState struct {
InsideTemp float64 `json:"inside_temp"`
OutsideTemp float64 `json:"outside_temp"`
DriverTempSetting float64 `json:"driver_temp_setting"`
PassengerTempSetting float64 `json:"passenger_temp_setting"`
LeftTempDirection float64 `json:"left_temp_direction"`
RightTempDirection float64 `json:"right_temp_direction"`
IsAutoConditioningOn bool `json:"is_auto_conditioning_on"`
IsFrontDefrosterOn interface{} `json:"is_front_defroster_on"`
IsRearDefrosterOn bool `json:"is_rear_defroster_on"`
FanStatus interface{} `json:"fan_status"`
IsClimateOn bool `json:"is_climate_on"`
MinAvailTemp float64 `json:"min_avail_temp"`
MaxAvailTemp float64 `json:"max_avail_temp"`
SeatHeaterLeft int `json:"seat_heater_left"`
SeatHeaterRight int `json:"seat_heater_right"`
SeatHeaterRearLeft int `json:"seat_heater_rear_left"`
SeatHeaterRearRight int `json:"seat_heater_rear_right"`
SeatHeaterRearCenter int `json:"seat_heater_rear_center"`
SeatHeaterRearRightBack int `json:"seat_heater_rear_right_back"`
SeatHeaterRearLeftBack int `json:"seat_heater_rear_left_back"`
SmartPreconditioning bool `json:"smart_preconditioning"`
}
type VehicleData struct {
UserID int64 `json:"user_id"`
VehicleID int64 `json:"vehicle_id"`
VIN string `json:"vin"`
State string `json:"online"`
ChargeState tesla.ChargeState `json:"charge_state"`
VehicleState tesla.VehicleState `json:"vehicle_state"`
ClimateState ClimateState `json:"climate_state"`
DriveState tesla.DriveState `json:"drive_state"`
}
type VehicleDataResponse struct {
Response VehicleData `json:"response"`
}
func (r *RiceLa) getVehicleData(ctx context.Context, v *tesla.Vehicle) (*VehicleData, error) {
ctx, cancel := context.WithTimeout(ctx, 1*time.Minute)
defer cancel()
log.Printf("Polling %s: %v", v.DisplayName, v.ID)
req, err := http.NewRequestWithContext(ctx, "GET", tesla.BaseURL+"/vehicles/"+strconv.FormatInt(v.ID, 10)+"/vehicle_data", nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+r.client.Token.AccessToken)
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
res, err := r.client.HTTP.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
return nil, errors.Errorf("%s: %s", res.Status, body)
}
out := map[string]interface{}{}
if err := json.Unmarshal(body, &out); err != nil {
return nil, err
}
spew.Dump(out)
count := r.processCounter("tesla", out["response"])
log.Printf("updated %d counters", count)
var resp VehicleDataResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, errors.Wrapf(err, "unmarshalling vehicle_data")
}
return &resp.Response, nil
}
var counterStrs = map[string]float64{
"--": -1,
"NONE": -1,
"PRESENT": 1,
"ENGAGED": 1,
"DISENGAGED": 0,
"LATCHED": 1,
"NOMINAL": 1,
"FAULT": 0,
"ERROR": 0,
"DRIVE": 2,
"PARKED": 1,
"REVERSE": 3,
"NEUTRAL": 4,
"On": 1,
"Off": 0,
"Stopped": 0,
"IDLE": 0,
"ACTIVE": 1,
"on": 1,
"off": 0,
"yes": 1,
"no": 0,
"": -1,
}
func (r *RiceLa) processCounter(key string, v interface{}) int {
switch v := v.(type) {
case map[string]interface{}:
count := 0
for k, v := range v |
return count
case float64:
r.setCounter(key, v)
return 1
case int:
r.setCounter(key, float64(v))
return 1
case int64:
r.setCounter(key, float64(v))
return 1
case int32:
r.setCounter(key, float64(v))
return 1
case float32:
r.setCounter(key, float64(v))
return 1
case bool:
if v {
r.setCounter(key, 1)
} else {
r.setCounter(key, 0)
}
return 1
case string:
f, err := strconv.ParseFloat(v, 64)
if err == nil {
r.setCounter(key, f)
return 1
}
f, ok := counterStrs[v]
if ok {
r.setCounter(key, f)
return 1
}
return 0
default:
if v == nil {
r.setCounter(key, 0)
return 1
}
return 0
}
}
func (r *RiceLa) setCounter(key string, v float64) {
r.mu.Lock()
defer r.mu.Unlock()
g, ok := r.mu.gauges[key]
if !ok {
g = promauto.NewGauge(prometheus.GaugeOpts{Name: key})
r.mu.gauges[key] = g
}
g.Set(v)
}
type RiceLa struct {
client *tesla.Client
chargepoint *chargepoint.Client
mu struct {
sync.Mutex
charging bool
gauges map[string]prometheus.Gauge
}
}
func pollTime(data VehicleData) time.Duration {
if !data.VehicleState.Locked && (data.DriveState.ShiftState == nil || data.DriveState.ShiftState == "P" || data.DriveState.ShiftState == "R") && !data.ChargeState.ChargePortDoorOpen {
return *activePollTime
}
if data.DriveState.ShiftState == "D" || data.DriveState.ShiftState == "R" || data.DriveState.ShiftState == "N" || data.ClimateState.IsClimateOn {
return *drivePollTime
}
return *standbyPollTime
}
func (r *RiceLa) startNearbyCharging(ctx context.Context, data tesla.DriveState) error {
log.Println("starting charging")
latlng := s2.LatLngFromDegrees(data.Latitude, data.Longitude)
for _, charger := range knownChargers {
if charger.DistanceInMeters(latlng) < 20 {
return charger.Start(ctx, r)
}
}
return nil
}
func (r *RiceLa) stopCharging(ctx context.Context) error {
log.Println("stop charging")
userStatus, err := r.chargepoint.UserStatus(ctx)
log.Printf("Charge Point user status %+v", userStatus)
if err != nil {
return err
}
for _, station := range userStatus.Charging.Stations {
if err := r.chargepoint.StopSession(ctx, userStatus.Charging.SessionID, station.DeviceID); err != nil {
return err
}
}
return nil
}
func (r *RiceLa) setCharging(charging bool) {
r.mu.Lock()
defer r.mu.Unlock()
r.mu.charging = charging
}
func (r *RiceLa) charging() bool {
r.mu.Lock()
defer r.mu.Unlock()
return r.mu.charging
}
func (r *RiceLa) monitorVehicle(ctx context.Context, v *tesla.Vehicle) error {
var data, prevData *VehicleData
for {
b := backoff.NewExponentialBackOff()
b.MaxElapsedTime = 1 * time.Minute
if err := backoff.Retry(func() error {
var err error
data, err = r.getVehicleData(ctx, v)
if err != nil {
log.Printf("got error polling (likely retrying) %+v", err)
}
return err
}, b); err != nil {
return err
}
pilotCurrent, _ := data.ChargeState.ChargerPilotCurrent.(float64)
if data.ChargeState.ChargingState == StateComplete && pilotCurrent > 1 {
if err := r.stopCharging(ctx); err != nil {
return err
}
}
if prevData != nil && !prevData.ChargeState.ChargePortDoorOpen && data.ChargeState.ChargePortDoorOpen {
if err := r.startNearbyCharging(ctx, data.DriveState); err != nil {
return err
}
}
r.setCharging(data.ChargeState.ChargingState == StateCharging)
prevData = data
select {
case <-ctx.Done():
return nil
case <-time.NewTimer(pollTime(*data)).C:
}
}
}
type Token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
CreatedAt int64 `json:"created_at"`
}
func (r *RiceLa) pollCarServer() error {
res, err := http.Get(*carServerAddr)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return errors.Errorf("%s", res.Status)
}
out := map[string]interface{}{}
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
return err
}
spew.Dump(out)
r.processCounter("carserver", out)
return nil
}
func (r *RiceLa) run() error {
r.mu.gauges = map[string]prometheus.Gauge{}
eg, ctx := errgroup.WithContext(context.Background())
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
tokenJSON := os.Getenv("TESLA_TOKEN_JSON")
var token Token
if err := json.Unmarshal([]byte(tokenJSON), &token); err != nil {
return err
}
var err error
r.client, err = tesla.NewClientWithToken(
&tesla.Auth{
ClientID: os.Getenv("TESLA_CLIENT_ID"),
ClientSecret: os.Getenv("TESLA_CLIENT_SECRET"),
Email: os.Getenv("TESLA_USERNAME"),
Password: os.Getenv("TESLA_PASSWORD"),
}, &tesla.Token{
AccessToken: token.AccessToken,
TokenType: token.TokenType,
ExpiresIn: int(token.ExpiresIn),
Expires: token.CreatedAt + token.ExpiresIn,
})
if err != nil {
log.Printf("%+v", errors.Wrapf(err, "failed to create client"))
}
r.chargepoint = &chargepoint.Client{
Token: os.Getenv("CHARGEPOINT_TOKEN"),
}
if r.client != nil {
log.Printf("Tesla token: %+v", r.client.Token)
eg.Go(func() error {
vehicles, err := r.client.Vehicles()
if err != nil {
return errors.Wrapf(err, "failed to get vehicles")
}
for _, v := range vehicles {
v := v
eg.Go(func() error {
return r.monitorVehicle(ctx, v.Vehicle)
})
}
return nil
})
}
eg.Go(func() error {
return sysmetrics.Monitor(ctx, *drivePollTime)
})
eg.Go(func() error {
for {
sessions, err := r.chargepoint.GetSessions(ctx)
if err != nil {
log.Println("chargpoint stats error", err)
}
if len(sessions) > 0 {
lastSession := sessions[len(sessions)-1]
r.setCounter("chargepoint:latest:total_amount", lastSession.TotalAmount)
r.setCounter("chargepoint:latest:miles_added", lastSession.MilesAdded)
r.setCounter("chargepoint:latest:energy_kwh", lastSession.EnergyKwh)
r.setCounter("chargepoint:latest:power_kw", lastSession.PowerKw)
r.setCounter("chargepoint:latest:latitude", lastSession.Lat)
r.setCounter("chargepoint:latest:longitude", lastSession.Lon)
if lastSession.CurrentCharging == chargepoint.ChargingFullyCharged {
if err := r.stopCharging(ctx); err != nil {
log.Printf("failed to stop charging: %+v", err)
}
}
}
var totalAmount, milesAdded, energyKwh float64
for _, session := range sessions {
totalAmount += session.TotalAmount
milesAdded += session.MilesAdded
energyKwh += session.EnergyKwh
}
r.setCounter("chargepoint:total_amount", totalAmount)
r.setCounter("chargepoint:miles_added", milesAdded)
r.setCounter("chargepoint:energy_kwh", energyKwh)
select {
case <-ctx.Done():
return nil
case <-time.NewTimer(*chargePointPollTime).C:
}
}
})
eg.Go(func() error {
for {
if err := r.pollCarServer(); err != nil {
log.Printf("car server error %+v", err)
}
select {
case <-ctx.Done():
return nil
case <-time.NewTimer(*drivePollTime).C:
}
}
})
s := http.Server{
Addr: *bind,
Handler: mux,
}
eg.Go(func() error {
fmt.Println("Listening...", s.Addr)
return s.ListenAndServe()
})
eg.Go(func() error {
<-ctx.Done()
ctxShutDown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer func() {
cancel()
}()
if err := s.Shutdown(ctxShutDown); err != nil {
log.Fatal(err)
}
return nil
})
return eg.Wait()
}
| {
key := key + ":" + k
count += r.processCounter(key, v)
} | conditional_block |
main.go | package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
"github.com/cenkalti/backoff"
"github.com/d4l3k/ricela/chargepoint"
"github.com/d4l3k/ricela/sysmetrics"
"github.com/golang/geo/s2"
"github.com/davecgh/go-spew/spew"
"github.com/jsgoecke/tesla"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/sync/errgroup"
)
var (
bind = flag.String("bind", ":2112", "address to bind to")
standbyPollTime = flag.Duration("standbyPollTime", 1*time.Minute, "polling frequency")
drivePollTime = flag.Duration("drivePollTime", 15*time.Second, "polling frequency")
activePollTime = flag.Duration("activePollTime", 5*time.Second, "polling frequency")
chargePointPollTime = flag.Duration("chargePointPollTime", 5*time.Minute, "polling frequency")
carServerAddr = flag.String("carserver", "http://localhost:27654/diag_vitals", "car server vitals endpoint")
)
const (
StateCharging = "Charging"
StateComplete = "Complete"
)
type Charger interface {
DistanceInMeters(a s2.LatLng) float64
Start(ctx context.Context, r *RiceLa) error
}
type ChargePointCharger struct {
DeviceID int64
LatLng s2.LatLng
}
func (c ChargePointCharger) DistanceInMeters(a s2.LatLng) float64 {
const earthRadius = 6_371_000
angle := c.LatLng.Distance(a)
return earthRadius * angle.Radians()
}
func (c ChargePointCharger) Start(ctx context.Context, r *RiceLa) error {
_, err := r.chargepoint.StartSession(ctx, c.DeviceID)
return err
}
var knownChargers = []Charger{
ChargePointCharger{DeviceID: 1947511, LatLng: s2.LatLngFromDegrees(47.630007, -122.133969)},
}
func main() {
log.SetFlags(log.Flags() | log.Lshortfile)
flag.Parse()
var r RiceLa
if err := r.run(); err != nil {
log.Fatalf("%+v", err)
}
}
type ClimateState struct {
InsideTemp float64 `json:"inside_temp"`
OutsideTemp float64 `json:"outside_temp"`
DriverTempSetting float64 `json:"driver_temp_setting"`
PassengerTempSetting float64 `json:"passenger_temp_setting"`
LeftTempDirection float64 `json:"left_temp_direction"`
RightTempDirection float64 `json:"right_temp_direction"`
IsAutoConditioningOn bool `json:"is_auto_conditioning_on"`
IsFrontDefrosterOn interface{} `json:"is_front_defroster_on"`
IsRearDefrosterOn bool `json:"is_rear_defroster_on"`
FanStatus interface{} `json:"fan_status"`
IsClimateOn bool `json:"is_climate_on"`
MinAvailTemp float64 `json:"min_avail_temp"`
MaxAvailTemp float64 `json:"max_avail_temp"`
SeatHeaterLeft int `json:"seat_heater_left"`
SeatHeaterRight int `json:"seat_heater_right"`
SeatHeaterRearLeft int `json:"seat_heater_rear_left"`
SeatHeaterRearRight int `json:"seat_heater_rear_right"`
SeatHeaterRearCenter int `json:"seat_heater_rear_center"`
SeatHeaterRearRightBack int `json:"seat_heater_rear_right_back"`
SeatHeaterRearLeftBack int `json:"seat_heater_rear_left_back"`
SmartPreconditioning bool `json:"smart_preconditioning"`
}
type VehicleData struct {
UserID int64 `json:"user_id"`
VehicleID int64 `json:"vehicle_id"`
VIN string `json:"vin"`
State string `json:"online"`
ChargeState tesla.ChargeState `json:"charge_state"`
VehicleState tesla.VehicleState `json:"vehicle_state"`
ClimateState ClimateState `json:"climate_state"`
DriveState tesla.DriveState `json:"drive_state"`
}
type VehicleDataResponse struct {
Response VehicleData `json:"response"`
}
func (r *RiceLa) getVehicleData(ctx context.Context, v *tesla.Vehicle) (*VehicleData, error) {
ctx, cancel := context.WithTimeout(ctx, 1*time.Minute)
defer cancel()
log.Printf("Polling %s: %v", v.DisplayName, v.ID)
req, err := http.NewRequestWithContext(ctx, "GET", tesla.BaseURL+"/vehicles/"+strconv.FormatInt(v.ID, 10)+"/vehicle_data", nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+r.client.Token.AccessToken)
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
res, err := r.client.HTTP.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
return nil, errors.Errorf("%s: %s", res.Status, body)
}
out := map[string]interface{}{}
if err := json.Unmarshal(body, &out); err != nil {
return nil, err
}
spew.Dump(out)
count := r.processCounter("tesla", out["response"])
log.Printf("updated %d counters", count)
var resp VehicleDataResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, errors.Wrapf(err, "unmarshalling vehicle_data")
}
return &resp.Response, nil
}
var counterStrs = map[string]float64{
"--": -1,
"NONE": -1,
"PRESENT": 1,
"ENGAGED": 1,
"DISENGAGED": 0,
"LATCHED": 1,
"NOMINAL": 1,
"FAULT": 0,
"ERROR": 0,
"DRIVE": 2,
"PARKED": 1,
"REVERSE": 3,
"NEUTRAL": 4,
"On": 1,
"Off": 0,
"Stopped": 0,
"IDLE": 0,
"ACTIVE": 1,
"on": 1,
"off": 0,
"yes": 1,
"no": 0,
"": -1,
}
func (r *RiceLa) | (key string, v interface{}) int {
switch v := v.(type) {
case map[string]interface{}:
count := 0
for k, v := range v {
key := key + ":" + k
count += r.processCounter(key, v)
}
return count
case float64:
r.setCounter(key, v)
return 1
case int:
r.setCounter(key, float64(v))
return 1
case int64:
r.setCounter(key, float64(v))
return 1
case int32:
r.setCounter(key, float64(v))
return 1
case float32:
r.setCounter(key, float64(v))
return 1
case bool:
if v {
r.setCounter(key, 1)
} else {
r.setCounter(key, 0)
}
return 1
case string:
f, err := strconv.ParseFloat(v, 64)
if err == nil {
r.setCounter(key, f)
return 1
}
f, ok := counterStrs[v]
if ok {
r.setCounter(key, f)
return 1
}
return 0
default:
if v == nil {
r.setCounter(key, 0)
return 1
}
return 0
}
}
func (r *RiceLa) setCounter(key string, v float64) {
r.mu.Lock()
defer r.mu.Unlock()
g, ok := r.mu.gauges[key]
if !ok {
g = promauto.NewGauge(prometheus.GaugeOpts{Name: key})
r.mu.gauges[key] = g
}
g.Set(v)
}
type RiceLa struct {
client *tesla.Client
chargepoint *chargepoint.Client
mu struct {
sync.Mutex
charging bool
gauges map[string]prometheus.Gauge
}
}
func pollTime(data VehicleData) time.Duration {
if !data.VehicleState.Locked && (data.DriveState.ShiftState == nil || data.DriveState.ShiftState == "P" || data.DriveState.ShiftState == "R") && !data.ChargeState.ChargePortDoorOpen {
return *activePollTime
}
if data.DriveState.ShiftState == "D" || data.DriveState.ShiftState == "R" || data.DriveState.ShiftState == "N" || data.ClimateState.IsClimateOn {
return *drivePollTime
}
return *standbyPollTime
}
func (r *RiceLa) startNearbyCharging(ctx context.Context, data tesla.DriveState) error {
log.Println("starting charging")
latlng := s2.LatLngFromDegrees(data.Latitude, data.Longitude)
for _, charger := range knownChargers {
if charger.DistanceInMeters(latlng) < 20 {
return charger.Start(ctx, r)
}
}
return nil
}
func (r *RiceLa) stopCharging(ctx context.Context) error {
log.Println("stop charging")
userStatus, err := r.chargepoint.UserStatus(ctx)
log.Printf("Charge Point user status %+v", userStatus)
if err != nil {
return err
}
for _, station := range userStatus.Charging.Stations {
if err := r.chargepoint.StopSession(ctx, userStatus.Charging.SessionID, station.DeviceID); err != nil {
return err
}
}
return nil
}
func (r *RiceLa) setCharging(charging bool) {
r.mu.Lock()
defer r.mu.Unlock()
r.mu.charging = charging
}
func (r *RiceLa) charging() bool {
r.mu.Lock()
defer r.mu.Unlock()
return r.mu.charging
}
func (r *RiceLa) monitorVehicle(ctx context.Context, v *tesla.Vehicle) error {
var data, prevData *VehicleData
for {
b := backoff.NewExponentialBackOff()
b.MaxElapsedTime = 1 * time.Minute
if err := backoff.Retry(func() error {
var err error
data, err = r.getVehicleData(ctx, v)
if err != nil {
log.Printf("got error polling (likely retrying) %+v", err)
}
return err
}, b); err != nil {
return err
}
pilotCurrent, _ := data.ChargeState.ChargerPilotCurrent.(float64)
if data.ChargeState.ChargingState == StateComplete && pilotCurrent > 1 {
if err := r.stopCharging(ctx); err != nil {
return err
}
}
if prevData != nil && !prevData.ChargeState.ChargePortDoorOpen && data.ChargeState.ChargePortDoorOpen {
if err := r.startNearbyCharging(ctx, data.DriveState); err != nil {
return err
}
}
r.setCharging(data.ChargeState.ChargingState == StateCharging)
prevData = data
select {
case <-ctx.Done():
return nil
case <-time.NewTimer(pollTime(*data)).C:
}
}
}
type Token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
CreatedAt int64 `json:"created_at"`
}
func (r *RiceLa) pollCarServer() error {
res, err := http.Get(*carServerAddr)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return errors.Errorf("%s", res.Status)
}
out := map[string]interface{}{}
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
return err
}
spew.Dump(out)
r.processCounter("carserver", out)
return nil
}
func (r *RiceLa) run() error {
r.mu.gauges = map[string]prometheus.Gauge{}
eg, ctx := errgroup.WithContext(context.Background())
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
tokenJSON := os.Getenv("TESLA_TOKEN_JSON")
var token Token
if err := json.Unmarshal([]byte(tokenJSON), &token); err != nil {
return err
}
var err error
r.client, err = tesla.NewClientWithToken(
&tesla.Auth{
ClientID: os.Getenv("TESLA_CLIENT_ID"),
ClientSecret: os.Getenv("TESLA_CLIENT_SECRET"),
Email: os.Getenv("TESLA_USERNAME"),
Password: os.Getenv("TESLA_PASSWORD"),
}, &tesla.Token{
AccessToken: token.AccessToken,
TokenType: token.TokenType,
ExpiresIn: int(token.ExpiresIn),
Expires: token.CreatedAt + token.ExpiresIn,
})
if err != nil {
log.Printf("%+v", errors.Wrapf(err, "failed to create client"))
}
r.chargepoint = &chargepoint.Client{
Token: os.Getenv("CHARGEPOINT_TOKEN"),
}
if r.client != nil {
log.Printf("Tesla token: %+v", r.client.Token)
eg.Go(func() error {
vehicles, err := r.client.Vehicles()
if err != nil {
return errors.Wrapf(err, "failed to get vehicles")
}
for _, v := range vehicles {
v := v
eg.Go(func() error {
return r.monitorVehicle(ctx, v.Vehicle)
})
}
return nil
})
}
eg.Go(func() error {
return sysmetrics.Monitor(ctx, *drivePollTime)
})
eg.Go(func() error {
for {
sessions, err := r.chargepoint.GetSessions(ctx)
if err != nil {
log.Println("chargpoint stats error", err)
}
if len(sessions) > 0 {
lastSession := sessions[len(sessions)-1]
r.setCounter("chargepoint:latest:total_amount", lastSession.TotalAmount)
r.setCounter("chargepoint:latest:miles_added", lastSession.MilesAdded)
r.setCounter("chargepoint:latest:energy_kwh", lastSession.EnergyKwh)
r.setCounter("chargepoint:latest:power_kw", lastSession.PowerKw)
r.setCounter("chargepoint:latest:latitude", lastSession.Lat)
r.setCounter("chargepoint:latest:longitude", lastSession.Lon)
if lastSession.CurrentCharging == chargepoint.ChargingFullyCharged {
if err := r.stopCharging(ctx); err != nil {
log.Printf("failed to stop charging: %+v", err)
}
}
}
var totalAmount, milesAdded, energyKwh float64
for _, session := range sessions {
totalAmount += session.TotalAmount
milesAdded += session.MilesAdded
energyKwh += session.EnergyKwh
}
r.setCounter("chargepoint:total_amount", totalAmount)
r.setCounter("chargepoint:miles_added", milesAdded)
r.setCounter("chargepoint:energy_kwh", energyKwh)
select {
case <-ctx.Done():
return nil
case <-time.NewTimer(*chargePointPollTime).C:
}
}
})
eg.Go(func() error {
for {
if err := r.pollCarServer(); err != nil {
log.Printf("car server error %+v", err)
}
select {
case <-ctx.Done():
return nil
case <-time.NewTimer(*drivePollTime).C:
}
}
})
s := http.Server{
Addr: *bind,
Handler: mux,
}
eg.Go(func() error {
fmt.Println("Listening...", s.Addr)
return s.ListenAndServe()
})
eg.Go(func() error {
<-ctx.Done()
ctxShutDown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer func() {
cancel()
}()
if err := s.Shutdown(ctxShutDown); err != nil {
log.Fatal(err)
}
return nil
})
return eg.Wait()
}
| processCounter | identifier_name |
norace_test.go | // Copyright 2018 The NATS 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.
// +build !race
package server
import (
"fmt"
"math/rand"
"net"
"sync/atomic"
"testing"
"time"
"github.com/nats-io/go-nats"
)
// IMPORTANT: Tests in this file are not executed when running with the -race flag.
// The test name should be prefixed with TestNoRace so we can run only
// those tests: go test -run=TestNoRace ...
func TestNoRaceAvoidSlowConsumerBigMessages(t *testing.T) {
opts := DefaultOptions() // Use defaults to make sure they avoid pending slow consumer.
s := RunServer(opts)
defer s.Shutdown()
nc1, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer nc1.Close()
nc2, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer nc2.Close()
data := make([]byte, 1024*1024) // 1MB payload
rand.Read(data)
expected := int32(500)
received := int32(0)
done := make(chan bool)
// Create Subscription.
nc1.Subscribe("slow.consumer", func(m *nats.Msg) {
// Just eat it so that we are not measuring
// code time, just delivery.
atomic.AddInt32(&received, 1)
if received >= expected {
done <- true
}
})
// Create Error handler
nc1.SetErrorHandler(func(c *nats.Conn, s *nats.Subscription, err error) {
t.Fatalf("Received an error on the subscription's connection: %v\n", err)
})
nc1.Flush()
for i := 0; i < int(expected); i++ {
nc2.Publish("slow.consumer", data)
}
nc2.Flush()
select {
case <-done:
return
case <-time.After(10 * time.Second):
r := atomic.LoadInt32(&received)
if s.NumSlowConsumers() > 0 {
t.Fatalf("Did not receive all large messages due to slow consumer status: %d of %d", r, expected)
}
t.Fatalf("Failed to receive all large messages: %d of %d\n", r, expected)
}
}
func TestNoRaceRoutedQueueAutoUnsubscribe(t *testing.T) {
optsA, _ := ProcessConfigFile("./configs/seed.conf")
optsA.NoSigs, optsA.NoLog = true, true
srvA := RunServer(optsA)
defer srvA.Shutdown()
srvARouteURL := fmt.Sprintf("nats://%s:%d", optsA.Cluster.Host, srvA.ClusterAddr().Port)
optsB := nextServerOpts(optsA)
optsB.Routes = RoutesFromStr(srvARouteURL)
srvB := RunServer(optsB)
defer srvB.Shutdown()
// Wait for these 2 to connect to each other
checkClusterFormed(t, srvA, srvB)
// Have a client connection to each server
ncA, err := nats.Connect(fmt.Sprintf("nats://%s:%d", optsA.Host, optsA.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer ncA.Close()
ncB, err := nats.Connect(fmt.Sprintf("nats://%s:%d", optsB.Host, optsB.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer ncB.Close()
rbar := int32(0)
barCb := func(m *nats.Msg) {
atomic.AddInt32(&rbar, 1)
}
rbaz := int32(0)
bazCb := func(m *nats.Msg) {
atomic.AddInt32(&rbaz, 1)
}
// Create 125 queue subs with auto-unsubscribe to each server for
// group bar and group baz. So 250 total per queue group.
cons := []*nats.Conn{ncA, ncB}
for _, c := range cons {
for i := 0; i < 125; i++ {
qsub, err := c.QueueSubscribe("foo", "bar", barCb)
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
if err := qsub.AutoUnsubscribe(1); err != nil {
t.Fatalf("Error on auto-unsubscribe: %v", err)
}
qsub, err = c.QueueSubscribe("foo", "baz", bazCb)
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
if err := qsub.AutoUnsubscribe(1); err != nil {
t.Fatalf("Error on auto-unsubscribe: %v", err)
}
}
c.Subscribe("TEST.COMPLETE", func(m *nats.Msg) {})
}
// We coelasce now so for each server we will have all local (250) plus
// two from the remote side for each queue group. We also create one more
// and will wait til each server has 254 subscriptions, that will make sure
// that we have everything setup.
checkFor(t, 10*time.Second, 100*time.Millisecond, func() error {
subsA := srvA.NumSubscriptions()
subsB := srvB.NumSubscriptions()
if subsA != 254 || subsB != 254 {
return fmt.Errorf("Not all subs processed yet: %d and %d", subsA, subsB)
}
return nil
})
expected := int32(250)
// Now send messages from each server
for i := int32(0); i < expected; i++ {
c := cons[i%2]
c.Publish("foo", []byte("Don't Drop Me!"))
}
for _, c := range cons {
c.Flush()
}
checkFor(t, 10*time.Second, 100*time.Millisecond, func() error {
nbar := atomic.LoadInt32(&rbar)
nbaz := atomic.LoadInt32(&rbaz)
if nbar == expected && nbaz == expected {
time.Sleep(500 * time.Millisecond)
return nil
}
return fmt.Errorf("Did not receive all %d queue messages, received %d for 'bar' and %d for 'baz'",
expected, atomic.LoadInt32(&rbar), atomic.LoadInt32(&rbaz))
})
}
func TestNoRaceClosedSlowConsumerWriteDeadline(t *testing.T) {
opts := DefaultOptions()
opts.WriteDeadline = 10 * time.Millisecond // Make very small to trip.
opts.MaxPending = 500 * 1024 * 1024 // Set high so it will not trip here.
s := RunServer(opts)
defer s.Shutdown()
c, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port), 3*time.Second)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer c.Close()
if _, err := c.Write([]byte("CONNECT {}\r\nPING\r\nSUB foo 1\r\n")); err != nil {
t.Fatalf("Error sending protocols to server: %v", err)
}
// Reduce socket buffer to increase reliability of data backing up in the server destined
// for our subscribed client.
c.(*net.TCPConn).SetReadBuffer(128)
url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
sender, err := nats.Connect(url)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer sender.Close()
payload := make([]byte, 1024*1024)
for i := 0; i < 100; i++ {
if err := sender.Publish("foo", payload); err != nil {
t.Fatalf("Error on publish: %v", err)
}
}
// Flush sender connection to ensure that all data has been sent.
if err := sender.Flush(); err != nil {
t.Fatalf("Error on flush: %v", err)
}
// At this point server should have closed connection c.
checkClosedConns(t, s, 1, 2*time.Second)
conns := s.closedClients()
if lc := len(conns); lc != 1 {
t.Fatalf("len(conns) expected to be %d, got %d\n", 1, lc)
}
checkReason(t, conns[0].Reason, SlowConsumerWriteDeadline)
}
func TestNoRaceClosedSlowConsumerPendingBytes(t *testing.T) {
opts := DefaultOptions()
opts.WriteDeadline = 30 * time.Second // Wait for long time so write deadline does not trigger slow consumer.
opts.MaxPending = 1 * 1024 * 1024 // Set to low value (1MB) to allow SC to trip.
s := RunServer(opts)
defer s.Shutdown()
c, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port), 3*time.Second)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer c.Close()
if _, err := c.Write([]byte("CONNECT {}\r\nPING\r\nSUB foo 1\r\n")); err != nil |
// Reduce socket buffer to increase reliability of data backing up in the server destined
// for our subscribed client.
c.(*net.TCPConn).SetReadBuffer(128)
url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
sender, err := nats.Connect(url)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer sender.Close()
payload := make([]byte, 1024*1024)
for i := 0; i < 100; i++ {
if err := sender.Publish("foo", payload); err != nil {
t.Fatalf("Error on publish: %v", err)
}
}
// Flush sender connection to ensure that all data has been sent.
if err := sender.Flush(); err != nil {
t.Fatalf("Error on flush: %v", err)
}
// At this point server should have closed connection c.
checkClosedConns(t, s, 1, 2*time.Second)
conns := s.closedClients()
if lc := len(conns); lc != 1 {
t.Fatalf("len(conns) expected to be %d, got %d\n", 1, lc)
}
checkReason(t, conns[0].Reason, SlowConsumerPendingBytes)
}
func TestNoRaceSlowConsumerPendingBytes(t *testing.T) {
opts := DefaultOptions()
opts.WriteDeadline = 30 * time.Second // Wait for long time so write deadline does not trigger slow consumer.
opts.MaxPending = 1 * 1024 * 1024 // Set to low value (1MB) to allow SC to trip.
s := RunServer(opts)
defer s.Shutdown()
c, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port), 3*time.Second)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer c.Close()
if _, err := c.Write([]byte("CONNECT {}\r\nPING\r\nSUB foo 1\r\n")); err != nil {
t.Fatalf("Error sending protocols to server: %v", err)
}
// Reduce socket buffer to increase reliability of data backing up in the server destined
// for our subscribed client.
c.(*net.TCPConn).SetReadBuffer(128)
url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
sender, err := nats.Connect(url)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer sender.Close()
payload := make([]byte, 1024*1024)
for i := 0; i < 100; i++ {
if err := sender.Publish("foo", payload); err != nil {
t.Fatalf("Error on publish: %v", err)
}
}
// Flush sender connection to ensure that all data has been sent.
if err := sender.Flush(); err != nil {
t.Fatalf("Error on flush: %v", err)
}
// At this point server should have closed connection c.
// On certain platforms, it may take more than one call before
// getting the error.
for i := 0; i < 100; i++ {
if _, err := c.Write([]byte("PUB bar 5\r\nhello\r\n")); err != nil {
// ok
return
}
}
t.Fatal("Connection should have been closed")
}
| {
t.Fatalf("Error sending protocols to server: %v", err)
} | conditional_block |
norace_test.go | // Copyright 2018 The NATS 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.
// +build !race
package server
import (
"fmt"
"math/rand"
"net"
"sync/atomic"
"testing"
"time"
"github.com/nats-io/go-nats"
)
// IMPORTANT: Tests in this file are not executed when running with the -race flag.
// The test name should be prefixed with TestNoRace so we can run only
// those tests: go test -run=TestNoRace ...
func TestNoRaceAvoidSlowConsumerBigMessages(t *testing.T) {
opts := DefaultOptions() // Use defaults to make sure they avoid pending slow consumer.
s := RunServer(opts)
defer s.Shutdown()
nc1, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer nc1.Close()
nc2, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer nc2.Close()
data := make([]byte, 1024*1024) // 1MB payload
rand.Read(data)
expected := int32(500)
received := int32(0)
done := make(chan bool)
// Create Subscription.
nc1.Subscribe("slow.consumer", func(m *nats.Msg) {
// Just eat it so that we are not measuring
// code time, just delivery.
atomic.AddInt32(&received, 1)
if received >= expected {
done <- true
}
})
// Create Error handler
nc1.SetErrorHandler(func(c *nats.Conn, s *nats.Subscription, err error) {
t.Fatalf("Received an error on the subscription's connection: %v\n", err)
})
nc1.Flush()
for i := 0; i < int(expected); i++ {
nc2.Publish("slow.consumer", data)
}
nc2.Flush()
select {
case <-done:
return
case <-time.After(10 * time.Second):
r := atomic.LoadInt32(&received)
if s.NumSlowConsumers() > 0 {
t.Fatalf("Did not receive all large messages due to slow consumer status: %d of %d", r, expected)
}
t.Fatalf("Failed to receive all large messages: %d of %d\n", r, expected)
}
}
func TestNoRaceRoutedQueueAutoUnsubscribe(t *testing.T) {
optsA, _ := ProcessConfigFile("./configs/seed.conf")
optsA.NoSigs, optsA.NoLog = true, true
srvA := RunServer(optsA)
defer srvA.Shutdown()
srvARouteURL := fmt.Sprintf("nats://%s:%d", optsA.Cluster.Host, srvA.ClusterAddr().Port)
optsB := nextServerOpts(optsA)
optsB.Routes = RoutesFromStr(srvARouteURL)
srvB := RunServer(optsB)
defer srvB.Shutdown()
// Wait for these 2 to connect to each other
checkClusterFormed(t, srvA, srvB)
// Have a client connection to each server
ncA, err := nats.Connect(fmt.Sprintf("nats://%s:%d", optsA.Host, optsA.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer ncA.Close()
ncB, err := nats.Connect(fmt.Sprintf("nats://%s:%d", optsB.Host, optsB.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer ncB.Close()
rbar := int32(0)
barCb := func(m *nats.Msg) {
atomic.AddInt32(&rbar, 1)
}
rbaz := int32(0)
bazCb := func(m *nats.Msg) {
atomic.AddInt32(&rbaz, 1)
}
// Create 125 queue subs with auto-unsubscribe to each server for
// group bar and group baz. So 250 total per queue group.
cons := []*nats.Conn{ncA, ncB}
for _, c := range cons {
for i := 0; i < 125; i++ {
qsub, err := c.QueueSubscribe("foo", "bar", barCb)
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
if err := qsub.AutoUnsubscribe(1); err != nil {
t.Fatalf("Error on auto-unsubscribe: %v", err)
}
qsub, err = c.QueueSubscribe("foo", "baz", bazCb)
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
if err := qsub.AutoUnsubscribe(1); err != nil {
t.Fatalf("Error on auto-unsubscribe: %v", err)
}
}
c.Subscribe("TEST.COMPLETE", func(m *nats.Msg) {})
}
// We coelasce now so for each server we will have all local (250) plus
// two from the remote side for each queue group. We also create one more
// and will wait til each server has 254 subscriptions, that will make sure
// that we have everything setup.
checkFor(t, 10*time.Second, 100*time.Millisecond, func() error {
subsA := srvA.NumSubscriptions()
subsB := srvB.NumSubscriptions()
if subsA != 254 || subsB != 254 {
return fmt.Errorf("Not all subs processed yet: %d and %d", subsA, subsB)
}
return nil
})
expected := int32(250)
// Now send messages from each server
for i := int32(0); i < expected; i++ {
c := cons[i%2]
c.Publish("foo", []byte("Don't Drop Me!"))
}
for _, c := range cons {
c.Flush()
}
checkFor(t, 10*time.Second, 100*time.Millisecond, func() error {
nbar := atomic.LoadInt32(&rbar)
nbaz := atomic.LoadInt32(&rbaz)
if nbar == expected && nbaz == expected {
time.Sleep(500 * time.Millisecond)
return nil
}
return fmt.Errorf("Did not receive all %d queue messages, received %d for 'bar' and %d for 'baz'",
expected, atomic.LoadInt32(&rbar), atomic.LoadInt32(&rbaz))
})
}
func | (t *testing.T) {
opts := DefaultOptions()
opts.WriteDeadline = 10 * time.Millisecond // Make very small to trip.
opts.MaxPending = 500 * 1024 * 1024 // Set high so it will not trip here.
s := RunServer(opts)
defer s.Shutdown()
c, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port), 3*time.Second)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer c.Close()
if _, err := c.Write([]byte("CONNECT {}\r\nPING\r\nSUB foo 1\r\n")); err != nil {
t.Fatalf("Error sending protocols to server: %v", err)
}
// Reduce socket buffer to increase reliability of data backing up in the server destined
// for our subscribed client.
c.(*net.TCPConn).SetReadBuffer(128)
url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
sender, err := nats.Connect(url)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer sender.Close()
payload := make([]byte, 1024*1024)
for i := 0; i < 100; i++ {
if err := sender.Publish("foo", payload); err != nil {
t.Fatalf("Error on publish: %v", err)
}
}
// Flush sender connection to ensure that all data has been sent.
if err := sender.Flush(); err != nil {
t.Fatalf("Error on flush: %v", err)
}
// At this point server should have closed connection c.
checkClosedConns(t, s, 1, 2*time.Second)
conns := s.closedClients()
if lc := len(conns); lc != 1 {
t.Fatalf("len(conns) expected to be %d, got %d\n", 1, lc)
}
checkReason(t, conns[0].Reason, SlowConsumerWriteDeadline)
}
func TestNoRaceClosedSlowConsumerPendingBytes(t *testing.T) {
opts := DefaultOptions()
opts.WriteDeadline = 30 * time.Second // Wait for long time so write deadline does not trigger slow consumer.
opts.MaxPending = 1 * 1024 * 1024 // Set to low value (1MB) to allow SC to trip.
s := RunServer(opts)
defer s.Shutdown()
c, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port), 3*time.Second)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer c.Close()
if _, err := c.Write([]byte("CONNECT {}\r\nPING\r\nSUB foo 1\r\n")); err != nil {
t.Fatalf("Error sending protocols to server: %v", err)
}
// Reduce socket buffer to increase reliability of data backing up in the server destined
// for our subscribed client.
c.(*net.TCPConn).SetReadBuffer(128)
url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
sender, err := nats.Connect(url)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer sender.Close()
payload := make([]byte, 1024*1024)
for i := 0; i < 100; i++ {
if err := sender.Publish("foo", payload); err != nil {
t.Fatalf("Error on publish: %v", err)
}
}
// Flush sender connection to ensure that all data has been sent.
if err := sender.Flush(); err != nil {
t.Fatalf("Error on flush: %v", err)
}
// At this point server should have closed connection c.
checkClosedConns(t, s, 1, 2*time.Second)
conns := s.closedClients()
if lc := len(conns); lc != 1 {
t.Fatalf("len(conns) expected to be %d, got %d\n", 1, lc)
}
checkReason(t, conns[0].Reason, SlowConsumerPendingBytes)
}
func TestNoRaceSlowConsumerPendingBytes(t *testing.T) {
opts := DefaultOptions()
opts.WriteDeadline = 30 * time.Second // Wait for long time so write deadline does not trigger slow consumer.
opts.MaxPending = 1 * 1024 * 1024 // Set to low value (1MB) to allow SC to trip.
s := RunServer(opts)
defer s.Shutdown()
c, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port), 3*time.Second)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer c.Close()
if _, err := c.Write([]byte("CONNECT {}\r\nPING\r\nSUB foo 1\r\n")); err != nil {
t.Fatalf("Error sending protocols to server: %v", err)
}
// Reduce socket buffer to increase reliability of data backing up in the server destined
// for our subscribed client.
c.(*net.TCPConn).SetReadBuffer(128)
url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
sender, err := nats.Connect(url)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer sender.Close()
payload := make([]byte, 1024*1024)
for i := 0; i < 100; i++ {
if err := sender.Publish("foo", payload); err != nil {
t.Fatalf("Error on publish: %v", err)
}
}
// Flush sender connection to ensure that all data has been sent.
if err := sender.Flush(); err != nil {
t.Fatalf("Error on flush: %v", err)
}
// At this point server should have closed connection c.
// On certain platforms, it may take more than one call before
// getting the error.
for i := 0; i < 100; i++ {
if _, err := c.Write([]byte("PUB bar 5\r\nhello\r\n")); err != nil {
// ok
return
}
}
t.Fatal("Connection should have been closed")
}
| TestNoRaceClosedSlowConsumerWriteDeadline | identifier_name |
norace_test.go | // Copyright 2018 The NATS 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.
// +build !race
package server
import (
"fmt"
"math/rand"
"net"
"sync/atomic"
"testing"
"time"
"github.com/nats-io/go-nats"
)
// IMPORTANT: Tests in this file are not executed when running with the -race flag.
// The test name should be prefixed with TestNoRace so we can run only
// those tests: go test -run=TestNoRace ...
func TestNoRaceAvoidSlowConsumerBigMessages(t *testing.T) {
opts := DefaultOptions() // Use defaults to make sure they avoid pending slow consumer.
s := RunServer(opts)
defer s.Shutdown()
nc1, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer nc1.Close()
nc2, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer nc2.Close()
data := make([]byte, 1024*1024) // 1MB payload
rand.Read(data)
expected := int32(500)
received := int32(0)
done := make(chan bool)
// Create Subscription.
nc1.Subscribe("slow.consumer", func(m *nats.Msg) {
// Just eat it so that we are not measuring
// code time, just delivery.
atomic.AddInt32(&received, 1)
if received >= expected {
done <- true
}
})
// Create Error handler
nc1.SetErrorHandler(func(c *nats.Conn, s *nats.Subscription, err error) {
t.Fatalf("Received an error on the subscription's connection: %v\n", err)
})
nc1.Flush()
for i := 0; i < int(expected); i++ {
nc2.Publish("slow.consumer", data)
}
nc2.Flush()
select {
case <-done:
return
case <-time.After(10 * time.Second):
r := atomic.LoadInt32(&received)
if s.NumSlowConsumers() > 0 {
t.Fatalf("Did not receive all large messages due to slow consumer status: %d of %d", r, expected)
}
t.Fatalf("Failed to receive all large messages: %d of %d\n", r, expected)
}
}
func TestNoRaceRoutedQueueAutoUnsubscribe(t *testing.T) {
optsA, _ := ProcessConfigFile("./configs/seed.conf")
optsA.NoSigs, optsA.NoLog = true, true
srvA := RunServer(optsA)
defer srvA.Shutdown()
srvARouteURL := fmt.Sprintf("nats://%s:%d", optsA.Cluster.Host, srvA.ClusterAddr().Port)
optsB := nextServerOpts(optsA)
optsB.Routes = RoutesFromStr(srvARouteURL)
srvB := RunServer(optsB)
defer srvB.Shutdown()
// Wait for these 2 to connect to each other
checkClusterFormed(t, srvA, srvB)
// Have a client connection to each server
ncA, err := nats.Connect(fmt.Sprintf("nats://%s:%d", optsA.Host, optsA.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer ncA.Close()
ncB, err := nats.Connect(fmt.Sprintf("nats://%s:%d", optsB.Host, optsB.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer ncB.Close()
rbar := int32(0)
barCb := func(m *nats.Msg) {
atomic.AddInt32(&rbar, 1)
}
rbaz := int32(0)
bazCb := func(m *nats.Msg) {
atomic.AddInt32(&rbaz, 1)
}
// Create 125 queue subs with auto-unsubscribe to each server for
// group bar and group baz. So 250 total per queue group.
cons := []*nats.Conn{ncA, ncB}
for _, c := range cons {
for i := 0; i < 125; i++ {
qsub, err := c.QueueSubscribe("foo", "bar", barCb)
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
if err := qsub.AutoUnsubscribe(1); err != nil {
t.Fatalf("Error on auto-unsubscribe: %v", err)
}
qsub, err = c.QueueSubscribe("foo", "baz", bazCb)
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
if err := qsub.AutoUnsubscribe(1); err != nil {
t.Fatalf("Error on auto-unsubscribe: %v", err)
}
}
c.Subscribe("TEST.COMPLETE", func(m *nats.Msg) {})
}
// We coelasce now so for each server we will have all local (250) plus
// two from the remote side for each queue group. We also create one more
// and will wait til each server has 254 subscriptions, that will make sure
// that we have everything setup.
checkFor(t, 10*time.Second, 100*time.Millisecond, func() error {
subsA := srvA.NumSubscriptions()
subsB := srvB.NumSubscriptions()
if subsA != 254 || subsB != 254 {
return fmt.Errorf("Not all subs processed yet: %d and %d", subsA, subsB)
}
return nil
})
expected := int32(250)
// Now send messages from each server
for i := int32(0); i < expected; i++ {
c := cons[i%2]
c.Publish("foo", []byte("Don't Drop Me!"))
}
for _, c := range cons {
c.Flush()
}
checkFor(t, 10*time.Second, 100*time.Millisecond, func() error {
nbar := atomic.LoadInt32(&rbar)
nbaz := atomic.LoadInt32(&rbaz)
if nbar == expected && nbaz == expected {
time.Sleep(500 * time.Millisecond)
return nil
}
return fmt.Errorf("Did not receive all %d queue messages, received %d for 'bar' and %d for 'baz'",
expected, atomic.LoadInt32(&rbar), atomic.LoadInt32(&rbaz))
})
}
func TestNoRaceClosedSlowConsumerWriteDeadline(t *testing.T) |
func TestNoRaceClosedSlowConsumerPendingBytes(t *testing.T) {
opts := DefaultOptions()
opts.WriteDeadline = 30 * time.Second // Wait for long time so write deadline does not trigger slow consumer.
opts.MaxPending = 1 * 1024 * 1024 // Set to low value (1MB) to allow SC to trip.
s := RunServer(opts)
defer s.Shutdown()
c, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port), 3*time.Second)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer c.Close()
if _, err := c.Write([]byte("CONNECT {}\r\nPING\r\nSUB foo 1\r\n")); err != nil {
t.Fatalf("Error sending protocols to server: %v", err)
}
// Reduce socket buffer to increase reliability of data backing up in the server destined
// for our subscribed client.
c.(*net.TCPConn).SetReadBuffer(128)
url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
sender, err := nats.Connect(url)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer sender.Close()
payload := make([]byte, 1024*1024)
for i := 0; i < 100; i++ {
if err := sender.Publish("foo", payload); err != nil {
t.Fatalf("Error on publish: %v", err)
}
}
// Flush sender connection to ensure that all data has been sent.
if err := sender.Flush(); err != nil {
t.Fatalf("Error on flush: %v", err)
}
// At this point server should have closed connection c.
checkClosedConns(t, s, 1, 2*time.Second)
conns := s.closedClients()
if lc := len(conns); lc != 1 {
t.Fatalf("len(conns) expected to be %d, got %d\n", 1, lc)
}
checkReason(t, conns[0].Reason, SlowConsumerPendingBytes)
}
func TestNoRaceSlowConsumerPendingBytes(t *testing.T) {
opts := DefaultOptions()
opts.WriteDeadline = 30 * time.Second // Wait for long time so write deadline does not trigger slow consumer.
opts.MaxPending = 1 * 1024 * 1024 // Set to low value (1MB) to allow SC to trip.
s := RunServer(opts)
defer s.Shutdown()
c, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port), 3*time.Second)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer c.Close()
if _, err := c.Write([]byte("CONNECT {}\r\nPING\r\nSUB foo 1\r\n")); err != nil {
t.Fatalf("Error sending protocols to server: %v", err)
}
// Reduce socket buffer to increase reliability of data backing up in the server destined
// for our subscribed client.
c.(*net.TCPConn).SetReadBuffer(128)
url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
sender, err := nats.Connect(url)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer sender.Close()
payload := make([]byte, 1024*1024)
for i := 0; i < 100; i++ {
if err := sender.Publish("foo", payload); err != nil {
t.Fatalf("Error on publish: %v", err)
}
}
// Flush sender connection to ensure that all data has been sent.
if err := sender.Flush(); err != nil {
t.Fatalf("Error on flush: %v", err)
}
// At this point server should have closed connection c.
// On certain platforms, it may take more than one call before
// getting the error.
for i := 0; i < 100; i++ {
if _, err := c.Write([]byte("PUB bar 5\r\nhello\r\n")); err != nil {
// ok
return
}
}
t.Fatal("Connection should have been closed")
}
| {
opts := DefaultOptions()
opts.WriteDeadline = 10 * time.Millisecond // Make very small to trip.
opts.MaxPending = 500 * 1024 * 1024 // Set high so it will not trip here.
s := RunServer(opts)
defer s.Shutdown()
c, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port), 3*time.Second)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer c.Close()
if _, err := c.Write([]byte("CONNECT {}\r\nPING\r\nSUB foo 1\r\n")); err != nil {
t.Fatalf("Error sending protocols to server: %v", err)
}
// Reduce socket buffer to increase reliability of data backing up in the server destined
// for our subscribed client.
c.(*net.TCPConn).SetReadBuffer(128)
url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
sender, err := nats.Connect(url)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer sender.Close()
payload := make([]byte, 1024*1024)
for i := 0; i < 100; i++ {
if err := sender.Publish("foo", payload); err != nil {
t.Fatalf("Error on publish: %v", err)
}
}
// Flush sender connection to ensure that all data has been sent.
if err := sender.Flush(); err != nil {
t.Fatalf("Error on flush: %v", err)
}
// At this point server should have closed connection c.
checkClosedConns(t, s, 1, 2*time.Second)
conns := s.closedClients()
if lc := len(conns); lc != 1 {
t.Fatalf("len(conns) expected to be %d, got %d\n", 1, lc)
}
checkReason(t, conns[0].Reason, SlowConsumerWriteDeadline)
} | identifier_body |
norace_test.go | // Copyright 2018 The NATS Authors | // 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.
// +build !race
package server
import (
"fmt"
"math/rand"
"net"
"sync/atomic"
"testing"
"time"
"github.com/nats-io/go-nats"
)
// IMPORTANT: Tests in this file are not executed when running with the -race flag.
// The test name should be prefixed with TestNoRace so we can run only
// those tests: go test -run=TestNoRace ...
func TestNoRaceAvoidSlowConsumerBigMessages(t *testing.T) {
opts := DefaultOptions() // Use defaults to make sure they avoid pending slow consumer.
s := RunServer(opts)
defer s.Shutdown()
nc1, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer nc1.Close()
nc2, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer nc2.Close()
data := make([]byte, 1024*1024) // 1MB payload
rand.Read(data)
expected := int32(500)
received := int32(0)
done := make(chan bool)
// Create Subscription.
nc1.Subscribe("slow.consumer", func(m *nats.Msg) {
// Just eat it so that we are not measuring
// code time, just delivery.
atomic.AddInt32(&received, 1)
if received >= expected {
done <- true
}
})
// Create Error handler
nc1.SetErrorHandler(func(c *nats.Conn, s *nats.Subscription, err error) {
t.Fatalf("Received an error on the subscription's connection: %v\n", err)
})
nc1.Flush()
for i := 0; i < int(expected); i++ {
nc2.Publish("slow.consumer", data)
}
nc2.Flush()
select {
case <-done:
return
case <-time.After(10 * time.Second):
r := atomic.LoadInt32(&received)
if s.NumSlowConsumers() > 0 {
t.Fatalf("Did not receive all large messages due to slow consumer status: %d of %d", r, expected)
}
t.Fatalf("Failed to receive all large messages: %d of %d\n", r, expected)
}
}
func TestNoRaceRoutedQueueAutoUnsubscribe(t *testing.T) {
optsA, _ := ProcessConfigFile("./configs/seed.conf")
optsA.NoSigs, optsA.NoLog = true, true
srvA := RunServer(optsA)
defer srvA.Shutdown()
srvARouteURL := fmt.Sprintf("nats://%s:%d", optsA.Cluster.Host, srvA.ClusterAddr().Port)
optsB := nextServerOpts(optsA)
optsB.Routes = RoutesFromStr(srvARouteURL)
srvB := RunServer(optsB)
defer srvB.Shutdown()
// Wait for these 2 to connect to each other
checkClusterFormed(t, srvA, srvB)
// Have a client connection to each server
ncA, err := nats.Connect(fmt.Sprintf("nats://%s:%d", optsA.Host, optsA.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer ncA.Close()
ncB, err := nats.Connect(fmt.Sprintf("nats://%s:%d", optsB.Host, optsB.Port))
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer ncB.Close()
rbar := int32(0)
barCb := func(m *nats.Msg) {
atomic.AddInt32(&rbar, 1)
}
rbaz := int32(0)
bazCb := func(m *nats.Msg) {
atomic.AddInt32(&rbaz, 1)
}
// Create 125 queue subs with auto-unsubscribe to each server for
// group bar and group baz. So 250 total per queue group.
cons := []*nats.Conn{ncA, ncB}
for _, c := range cons {
for i := 0; i < 125; i++ {
qsub, err := c.QueueSubscribe("foo", "bar", barCb)
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
if err := qsub.AutoUnsubscribe(1); err != nil {
t.Fatalf("Error on auto-unsubscribe: %v", err)
}
qsub, err = c.QueueSubscribe("foo", "baz", bazCb)
if err != nil {
t.Fatalf("Error on subscribe: %v", err)
}
if err := qsub.AutoUnsubscribe(1); err != nil {
t.Fatalf("Error on auto-unsubscribe: %v", err)
}
}
c.Subscribe("TEST.COMPLETE", func(m *nats.Msg) {})
}
// We coelasce now so for each server we will have all local (250) plus
// two from the remote side for each queue group. We also create one more
// and will wait til each server has 254 subscriptions, that will make sure
// that we have everything setup.
checkFor(t, 10*time.Second, 100*time.Millisecond, func() error {
subsA := srvA.NumSubscriptions()
subsB := srvB.NumSubscriptions()
if subsA != 254 || subsB != 254 {
return fmt.Errorf("Not all subs processed yet: %d and %d", subsA, subsB)
}
return nil
})
expected := int32(250)
// Now send messages from each server
for i := int32(0); i < expected; i++ {
c := cons[i%2]
c.Publish("foo", []byte("Don't Drop Me!"))
}
for _, c := range cons {
c.Flush()
}
checkFor(t, 10*time.Second, 100*time.Millisecond, func() error {
nbar := atomic.LoadInt32(&rbar)
nbaz := atomic.LoadInt32(&rbaz)
if nbar == expected && nbaz == expected {
time.Sleep(500 * time.Millisecond)
return nil
}
return fmt.Errorf("Did not receive all %d queue messages, received %d for 'bar' and %d for 'baz'",
expected, atomic.LoadInt32(&rbar), atomic.LoadInt32(&rbaz))
})
}
func TestNoRaceClosedSlowConsumerWriteDeadline(t *testing.T) {
opts := DefaultOptions()
opts.WriteDeadline = 10 * time.Millisecond // Make very small to trip.
opts.MaxPending = 500 * 1024 * 1024 // Set high so it will not trip here.
s := RunServer(opts)
defer s.Shutdown()
c, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port), 3*time.Second)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer c.Close()
if _, err := c.Write([]byte("CONNECT {}\r\nPING\r\nSUB foo 1\r\n")); err != nil {
t.Fatalf("Error sending protocols to server: %v", err)
}
// Reduce socket buffer to increase reliability of data backing up in the server destined
// for our subscribed client.
c.(*net.TCPConn).SetReadBuffer(128)
url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
sender, err := nats.Connect(url)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer sender.Close()
payload := make([]byte, 1024*1024)
for i := 0; i < 100; i++ {
if err := sender.Publish("foo", payload); err != nil {
t.Fatalf("Error on publish: %v", err)
}
}
// Flush sender connection to ensure that all data has been sent.
if err := sender.Flush(); err != nil {
t.Fatalf("Error on flush: %v", err)
}
// At this point server should have closed connection c.
checkClosedConns(t, s, 1, 2*time.Second)
conns := s.closedClients()
if lc := len(conns); lc != 1 {
t.Fatalf("len(conns) expected to be %d, got %d\n", 1, lc)
}
checkReason(t, conns[0].Reason, SlowConsumerWriteDeadline)
}
func TestNoRaceClosedSlowConsumerPendingBytes(t *testing.T) {
opts := DefaultOptions()
opts.WriteDeadline = 30 * time.Second // Wait for long time so write deadline does not trigger slow consumer.
opts.MaxPending = 1 * 1024 * 1024 // Set to low value (1MB) to allow SC to trip.
s := RunServer(opts)
defer s.Shutdown()
c, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port), 3*time.Second)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer c.Close()
if _, err := c.Write([]byte("CONNECT {}\r\nPING\r\nSUB foo 1\r\n")); err != nil {
t.Fatalf("Error sending protocols to server: %v", err)
}
// Reduce socket buffer to increase reliability of data backing up in the server destined
// for our subscribed client.
c.(*net.TCPConn).SetReadBuffer(128)
url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
sender, err := nats.Connect(url)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer sender.Close()
payload := make([]byte, 1024*1024)
for i := 0; i < 100; i++ {
if err := sender.Publish("foo", payload); err != nil {
t.Fatalf("Error on publish: %v", err)
}
}
// Flush sender connection to ensure that all data has been sent.
if err := sender.Flush(); err != nil {
t.Fatalf("Error on flush: %v", err)
}
// At this point server should have closed connection c.
checkClosedConns(t, s, 1, 2*time.Second)
conns := s.closedClients()
if lc := len(conns); lc != 1 {
t.Fatalf("len(conns) expected to be %d, got %d\n", 1, lc)
}
checkReason(t, conns[0].Reason, SlowConsumerPendingBytes)
}
func TestNoRaceSlowConsumerPendingBytes(t *testing.T) {
opts := DefaultOptions()
opts.WriteDeadline = 30 * time.Second // Wait for long time so write deadline does not trigger slow consumer.
opts.MaxPending = 1 * 1024 * 1024 // Set to low value (1MB) to allow SC to trip.
s := RunServer(opts)
defer s.Shutdown()
c, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port), 3*time.Second)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer c.Close()
if _, err := c.Write([]byte("CONNECT {}\r\nPING\r\nSUB foo 1\r\n")); err != nil {
t.Fatalf("Error sending protocols to server: %v", err)
}
// Reduce socket buffer to increase reliability of data backing up in the server destined
// for our subscribed client.
c.(*net.TCPConn).SetReadBuffer(128)
url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
sender, err := nats.Connect(url)
if err != nil {
t.Fatalf("Error on connect: %v", err)
}
defer sender.Close()
payload := make([]byte, 1024*1024)
for i := 0; i < 100; i++ {
if err := sender.Publish("foo", payload); err != nil {
t.Fatalf("Error on publish: %v", err)
}
}
// Flush sender connection to ensure that all data has been sent.
if err := sender.Flush(); err != nil {
t.Fatalf("Error on flush: %v", err)
}
// At this point server should have closed connection c.
// On certain platforms, it may take more than one call before
// getting the error.
for i := 0; i < 100; i++ {
if _, err := c.Write([]byte("PUB bar 5\r\nhello\r\n")); err != nil {
// ok
return
}
}
t.Fatal("Connection should have been closed")
} | // 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
// | random_line_split |
bootstrap.go | /*
* Copyright 2017-2019 Kopano and its licensors
*
* 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.
*
*/
package bootstrap
import (
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"fmt"
"io/ioutil"
"net"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/longsleep/rndm"
"github.com/sirupsen/logrus"
"github.com/libregraph/lico/config"
"github.com/libregraph/lico/encryption"
"github.com/libregraph/lico/identity"
"github.com/libregraph/lico/managers"
oidcProvider "github.com/libregraph/lico/oidc/provider"
"github.com/libregraph/lico/utils"
)
// API types.
type APIType string
const (
APITypeKonnect APIType = "konnect"
APITypeSignin APIType = "signin"
)
// Defaults.
const (
DefaultSigningKeyID = "default"
DefaultSigningKeyBits = 2048
DefaultGuestIdentityManagerName = "guest"
)
// Bootstrap is a data structure to hold configuration required to start
// konnectd.
type Bootstrap interface {
Config() *Config
Managers() *managers.Managers
MakeURIPath(api APIType, subpath string) string
}
// Implementation of the bootstrap interface.
type bootstrap struct {
config *Config
uriBasePath string
managers *managers.Managers
}
// Config returns the bootstap configuration.
func (bs *bootstrap) Config() *Config {
return bs.config
}
// Managers returns bootstrapped identity-managers.
func (bs *bootstrap) Managers() *managers.Managers {
return bs.managers
}
// Boot is the main entry point to bootstrap the service after validating the
// given configuration. The resulting Bootstrap struct can be used to retrieve
// configured identity-managers and their respective http-handlers and config.
//
// This function should be used by consumers which want to embed this project
// as a library.
func Boot(ctx context.Context, settings *Settings, cfg *config.Config) (Bootstrap, error) {
// NOTE(longsleep): Ensure to use same salt length as the hash size.
// See https://www.ietf.org/mail-archive/web/jose/current/msg02901.html for
// reference and https://github.com/golang-jwt/jwt/v4/issues/285 for
// the issue in upstream jwt-go.
for _, alg := range []string{jwt.SigningMethodPS256.Name, jwt.SigningMethodPS384.Name, jwt.SigningMethodPS512.Name} {
sm := jwt.GetSigningMethod(alg)
if signingMethodRSAPSS, ok := sm.(*jwt.SigningMethodRSAPSS); ok {
signingMethodRSAPSS.Options.SaltLength = rsa.PSSSaltLengthEqualsHash
}
}
bs := &bootstrap{
config: &Config{
Config: cfg,
Settings: settings,
},
}
err := bs.initialize(settings)
if err != nil {
return nil, err
}
err = bs.setup(ctx, settings)
if err != nil {
return nil, err
}
return bs, nil
}
// initialize, parsed parameters from commandline with validation and adds them
// to the associated Bootstrap data.
func (bs *bootstrap) initialize(settings *Settings) error {
logger := bs.config.Config.Logger
var err error
if settings.IdentityManager == "" {
return fmt.Errorf("identity-manager argument missing, use one of kc, ldap, cookie, dummy")
}
bs.config.IssuerIdentifierURI, err = url.Parse(settings.Iss)
if err != nil {
return fmt.Errorf("invalid iss value, iss is not a valid URL), %v", err)
} else if settings.Iss == "" {
return fmt.Errorf("missing iss value, did you provide the --iss parameter?")
} else if bs.config.IssuerIdentifierURI.Scheme != "https" {
return fmt.Errorf("invalid iss value, URL must start with https://")
} else if bs.config.IssuerIdentifierURI.Host == "" {
return fmt.Errorf("invalid iss value, URL must have a host")
}
bs.uriBasePath = settings.URIBasePath
bs.config.SignInFormURI, err = url.Parse(settings.SignInURI)
if err != nil {
return fmt.Errorf("invalid sign-in URI, %v", err)
}
bs.config.SignedOutURI, err = url.Parse(settings.SignedOutURI)
if err != nil {
return fmt.Errorf("invalid signed-out URI, %v", err)
}
bs.config.AuthorizationEndpointURI, err = url.Parse(settings.AuthorizationEndpointURI)
if err != nil {
return fmt.Errorf("invalid authorization-endpoint-uri, %v", err)
}
bs.config.EndSessionEndpointURI, err = url.Parse(settings.EndsessionEndpointURI)
if err != nil {
return fmt.Errorf("invalid endsession-endpoint-uri, %v", err)
}
if settings.Insecure {
// NOTE(longsleep): This disable http2 client support. See https://github.com/golang/go/issues/14275 for reasons.
bs.config.TLSClientConfig = utils.InsecureSkipVerifyTLSConfig()
logger.Warnln("insecure mode, TLS client connections are susceptible to man-in-the-middle attacks")
} else {
bs.config.TLSClientConfig = utils.DefaultTLSConfig()
}
for _, trustedProxy := range settings.TrustedProxy {
if ip := net.ParseIP(trustedProxy); ip != nil {
bs.config.Config.TrustedProxyIPs = append(bs.config.Config.TrustedProxyIPs, &ip)
continue
}
if _, ipNet, errParseCIDR := net.ParseCIDR(trustedProxy); errParseCIDR == nil {
bs.config.Config.TrustedProxyNets = append(bs.config.Config.TrustedProxyNets, ipNet)
continue
}
}
if len(bs.config.Config.TrustedProxyIPs) > 0 {
logger.Infoln("trusted proxy IPs", bs.config.Config.TrustedProxyIPs)
}
if len(bs.config.Config.TrustedProxyNets) > 0 {
logger.Infoln("trusted proxy networks", bs.config.Config.TrustedProxyNets)
}
if len(settings.AllowScope) > 0 {
bs.config.Config.AllowedScopes = settings.AllowScope
logger.Infoln("using custom allowed OAuth 2 scopes", bs.config.Config.AllowedScopes)
}
bs.config.Config.AllowClientGuests = settings.AllowClientGuests
if bs.config.Config.AllowClientGuests {
logger.Infoln("client controlled guests are enabled")
}
bs.config.Config.AllowDynamicClientRegistration = settings.AllowDynamicClientRegistration
if bs.config.Config.AllowDynamicClientRegistration {
logger.Infoln("dynamic client registration is enabled")
}
encryptionSecretFn := settings.EncryptionSecretFile
if encryptionSecretFn != "" {
logger.WithField("file", encryptionSecretFn).Infoln("loading encryption secret from file")
bs.config.EncryptionSecret, err = ioutil.ReadFile(encryptionSecretFn)
if err != nil {
return fmt.Errorf("failed to load encryption secret from file: %v", err)
}
if len(bs.config.EncryptionSecret) != encryption.KeySize {
return fmt.Errorf("invalid encryption secret size - must be %d bytes", encryption.KeySize)
}
} else {
logger.Warnf("missing --encryption-secret parameter, using random encyption secret with %d bytes", encryption.KeySize)
bs.config.EncryptionSecret = rndm.GenerateRandomBytes(encryption.KeySize)
}
bs.config.Config.ListenAddr = settings.Listen
bs.config.IdentifierClientDisabled = settings.IdentifierClientDisabled
bs.config.IdentifierClientPath = settings.IdentifierClientPath
bs.config.IdentifierRegistrationConf = settings.IdentifierRegistrationConf
if bs.config.IdentifierRegistrationConf != "" {
bs.config.IdentifierRegistrationConf, _ = filepath.Abs(bs.config.IdentifierRegistrationConf)
if _, errStat := os.Stat(bs.config.IdentifierRegistrationConf); errStat != nil {
return fmt.Errorf("identifier-registration-conf file not found or unable to access: %v", errStat)
}
bs.config.IdentifierAuthoritiesConf = bs.config.IdentifierRegistrationConf
}
bs.config.IdentifierScopesConf = settings.IdentifierScopesConf
if bs.config.IdentifierScopesConf != "" {
bs.config.IdentifierScopesConf, _ = filepath.Abs(bs.config.IdentifierScopesConf)
if _, errStat := os.Stat(bs.config.IdentifierScopesConf); errStat != nil {
return fmt.Errorf("identifier-scopes-conf file not found or unable to access: %v", errStat)
}
}
if settings.IdentifierDefaultBannerLogo != "" {
// Load from file.
b, errRead := ioutil.ReadFile(settings.IdentifierDefaultBannerLogo)
if errRead != nil {
return fmt.Errorf("identifier-default-banner-logo failed to open: %w", errRead)
}
bs.config.IdentifierDefaultBannerLogo = b
}
if settings.IdentifierDefaultSignInPageText != "" {
bs.config.IdentifierDefaultSignInPageText = &settings.IdentifierDefaultSignInPageText
}
if settings.IdentifierDefaultUsernameHintText != "" {
bs.config.IdentifierDefaultUsernameHintText = &settings.IdentifierDefaultUsernameHintText
}
bs.config.IdentifierUILocales = settings.IdentifierUILocales
bs.config.SigningKeyID = settings.SigningKid
bs.config.Signers = make(map[string]crypto.Signer)
bs.config.Validators = make(map[string]crypto.PublicKey)
bs.config.Certificates = make(map[string][]*x509.Certificate)
signingMethodString := settings.SigningMethod
bs.config.SigningMethod = jwt.GetSigningMethod(signingMethodString)
if bs.config.SigningMethod == nil {
return fmt.Errorf("unknown signing method: %s", signingMethodString)
}
signingKeyFns := settings.SigningPrivateKeyFiles
if len(signingKeyFns) > 0 {
first := true
for _, signingKeyFn := range signingKeyFns {
logger.WithField("path", signingKeyFn).Infoln("loading signing key")
err = addSignerWithIDFromFile(signingKeyFn, "", bs)
if err != nil {
return err
}
if first {
// Also add key under the provided id.
first = false
err = addSignerWithIDFromFile(signingKeyFn, bs.config.SigningKeyID, bs)
if err != nil {
return err
}
}
}
} else {
//NOTE(longsleep): remove me - create keypair a random key pair.
sm := jwt.SigningMethodPS256
bs.config.SigningMethod = sm
logger.WithField("alg", sm.Name).Warnf("missing --signing-private-key parameter, using random %d bit signing key", DefaultSigningKeyBits)
signer, _ := rsa.GenerateKey(rand.Reader, DefaultSigningKeyBits)
bs.config.Signers[bs.config.SigningKeyID] = signer
}
// Ensure we have a signer for the things we need.
err = validateSigners(bs)
if err != nil {
return err
}
validationKeysPath := settings.ValidationKeysPath
if validationKeysPath != "" {
logger.WithField("path", validationKeysPath).Infoln("loading validation keys")
err = addValidatorsFromPath(validationKeysPath, bs)
if err != nil {
return err
}
}
bs.config.Config.HTTPTransport = utils.HTTPTransportWithTLSClientConfig(bs.config.TLSClientConfig)
bs.config.AccessTokenDurationSeconds = settings.AccessTokenDurationSeconds
if bs.config.AccessTokenDurationSeconds == 0 {
bs.config.AccessTokenDurationSeconds = 60 * 10 // 10 Minutes
}
bs.config.IDTokenDurationSeconds = settings.IDTokenDurationSeconds
if bs.config.IDTokenDurationSeconds == 0 {
bs.config.IDTokenDurationSeconds = 60 * 60 // 1 Hour
}
bs.config.RefreshTokenDurationSeconds = settings.RefreshTokenDurationSeconds
if bs.config.RefreshTokenDurationSeconds == 0 {
bs.config.RefreshTokenDurationSeconds = 60 * 60 * 24 * 365 * 3 // 3 Years
}
bs.config.DyamicClientSecretDurationSeconds = settings.DyamicClientSecretDurationSeconds
return nil
}
// setup takes care of setting up the managers based on the associated
// Bootstrap's data.
func (bs *bootstrap) setup(ctx context.Context, settings *Settings) error {
managers, err := newManagers(ctx, bs)
if err != nil {
return err
}
bs.managers = managers
identityManager, err := bs.setupIdentity(ctx, settings)
if err != nil {
return err
}
managers.Set("identity", identityManager)
guestManager, err := bs.setupGuest(ctx, identityManager)
if err != nil {
return err
}
managers.Set("guest", guestManager)
oidcProvider, err := bs.setupOIDCProvider(ctx)
if err != nil {
return err
}
managers.Set("oidc", oidcProvider)
managers.Set("handler", oidcProvider) // Use OIDC provider as default HTTP handler.
err = managers.Apply()
if err != nil {
return fmt.Errorf("failed to apply managers: %v", err)
}
// Final steps
err = oidcProvider.InitializeMetadata()
if err != nil {
return fmt.Errorf("failed to initialize provider metadata: %v", err)
}
return nil
}
func (bs *bootstrap) MakeURIPath(api APIType, subpath string) string {
subpath = strings.TrimPrefix(subpath, "/")
uriPath := ""
switch api {
case APITypeKonnect:
uriPath = fmt.Sprintf("%s/konnect/v1/%s", strings.TrimSuffix(bs.uriBasePath, "/"), subpath)
case APITypeSignin:
uriPath = fmt.Sprintf("%s/signin/v1/%s", strings.TrimSuffix(bs.uriBasePath, "/"), subpath)
default:
panic("unknown api type")
}
if subpath == "" {
uriPath = strings.TrimSuffix(uriPath, "/")
}
return uriPath
}
func (bs *bootstrap) MakeURI(api APIType, subpath string) *url.URL {
uriPath := bs.MakeURIPath(api, subpath)
uri, _ := url.Parse(bs.config.IssuerIdentifierURI.String())
uri.Path = uriPath
return uri
}
func (bs *bootstrap) setupIdentity(ctx context.Context, settings *Settings) (identity.Manager, error) {
logger := bs.config.Config.Logger
if settings.IdentityManager == "" {
return nil, fmt.Errorf("identity-manager argument missing")
}
// Identity manager.
identityManagerName := settings.IdentityManager
identityManager, err := getIdentityManagerByName(identityManagerName, bs)
if err != nil |
logger.WithFields(logrus.Fields{
"name": identityManagerName,
"scopes": identityManager.ScopesSupported(nil),
"claims": identityManager.ClaimsSupported(nil),
}).Infoln("identity manager set up")
return identityManager, nil
}
func (bs *bootstrap) setupGuest(ctx context.Context, identityManager identity.Manager) (identity.Manager, error) {
if !bs.config.Config.AllowClientGuests {
return nil, nil
}
var err error
logger := bs.config.Config.Logger
guestManager, err := getIdentityManagerByName(DefaultGuestIdentityManagerName, bs)
if err != nil {
return nil, err
}
if guestManager != nil {
logger.Infoln("identity guest manager set up")
}
return guestManager, nil
}
func (bs *bootstrap) setupOIDCProvider(ctx context.Context) (*oidcProvider.Provider, error) {
var err error
logger := bs.config.Config.Logger
sessionCookiePath, err := getCommonURLPathPrefix(bs.config.AuthorizationEndpointURI.EscapedPath(), bs.config.EndSessionEndpointURI.EscapedPath())
if err != nil {
return nil, fmt.Errorf("failed to find common URL prefix for authorize and endsession: %v", err)
}
var registrationPath = ""
if bs.config.Config.AllowDynamicClientRegistration {
registrationPath = bs.MakeURIPath(APITypeKonnect, "/register")
}
provider, err := oidcProvider.NewProvider(&oidcProvider.Config{
Config: bs.config.Config,
IssuerIdentifier: bs.config.IssuerIdentifierURI.String(),
WellKnownPath: "/.well-known/openid-configuration",
JwksPath: bs.MakeURIPath(APITypeKonnect, "/jwks.json"),
AuthorizationPath: bs.config.AuthorizationEndpointURI.EscapedPath(),
TokenPath: bs.MakeURIPath(APITypeKonnect, "/token"),
UserInfoPath: bs.MakeURIPath(APITypeKonnect, "/userinfo"),
EndSessionPath: bs.config.EndSessionEndpointURI.EscapedPath(),
CheckSessionIframePath: bs.MakeURIPath(APITypeKonnect, "/session/check-session.html"),
RegistrationPath: registrationPath,
BrowserStateCookiePath: bs.MakeURIPath(APITypeKonnect, "/session/"),
BrowserStateCookieName: "__Secure-KKBS", // Kopano-Konnect-Browser-State
SessionCookiePath: sessionCookiePath,
SessionCookieName: "__Secure-KKCS", // Kopano-Konnect-Client-Session
AccessTokenDuration: time.Duration(bs.config.AccessTokenDurationSeconds) * time.Second,
IDTokenDuration: time.Duration(bs.config.IDTokenDurationSeconds) * time.Second,
RefreshTokenDuration: time.Duration(bs.config.RefreshTokenDurationSeconds) * time.Second,
})
if err != nil {
return nil, fmt.Errorf("failed to create provider: %v", err)
}
if bs.config.SigningMethod != nil {
err = provider.SetSigningMethod(bs.config.SigningMethod)
if err != nil {
return nil, fmt.Errorf("failed to set provider signing method: %v", err)
}
}
// All add signers.
for id, signer := range bs.config.Signers {
if id == bs.config.SigningKeyID {
err = provider.SetSigningKey(id, signer)
// Always set default key.
if id != DefaultSigningKeyID {
provider.SetValidationKey(DefaultSigningKeyID, signer.Public())
}
} else {
// Set non default signers as well.
err = provider.SetSigningKey(id, signer)
}
if err != nil {
return nil, err
}
}
// Add all validators.
for id, publicKey := range bs.config.Validators {
err = provider.SetValidationKey(id, publicKey)
if err != nil {
return nil, err
}
}
// Add all certificates.
for id, certificate := range bs.config.Certificates {
err = provider.SetCertificate(id, certificate)
if err != nil {
return nil, err
}
}
sk, ok := provider.GetSigningKey(bs.config.SigningMethod)
if !ok {
return nil, fmt.Errorf("no signing key for selected signing method")
}
if bs.config.SigningKeyID == "" {
// Ensure that there is a default signing Key ID even if none was set.
provider.SetValidationKey(DefaultSigningKeyID, sk.PrivateKey.Public())
}
logger.WithFields(logrus.Fields{
"id": sk.ID,
"method": fmt.Sprintf("%T", sk.SigningMethod),
"alg": sk.SigningMethod.Alg(),
}).Infoln("oidc token signing default set up")
return provider, nil
}
| {
return nil, err
} | conditional_block |
bootstrap.go | /*
* Copyright 2017-2019 Kopano and its licensors
*
* 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.
*
*/
package bootstrap
import (
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"fmt"
"io/ioutil"
"net"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/longsleep/rndm"
"github.com/sirupsen/logrus"
"github.com/libregraph/lico/config"
"github.com/libregraph/lico/encryption"
"github.com/libregraph/lico/identity"
"github.com/libregraph/lico/managers"
oidcProvider "github.com/libregraph/lico/oidc/provider"
"github.com/libregraph/lico/utils"
)
// API types.
type APIType string
const (
APITypeKonnect APIType = "konnect"
APITypeSignin APIType = "signin"
)
// Defaults.
const (
DefaultSigningKeyID = "default"
DefaultSigningKeyBits = 2048
DefaultGuestIdentityManagerName = "guest"
)
// Bootstrap is a data structure to hold configuration required to start
// konnectd.
type Bootstrap interface {
Config() *Config
Managers() *managers.Managers
MakeURIPath(api APIType, subpath string) string
}
// Implementation of the bootstrap interface.
type bootstrap struct {
config *Config
uriBasePath string
managers *managers.Managers
}
| func (bs *bootstrap) Config() *Config {
return bs.config
}
// Managers returns bootstrapped identity-managers.
func (bs *bootstrap) Managers() *managers.Managers {
return bs.managers
}
// Boot is the main entry point to bootstrap the service after validating the
// given configuration. The resulting Bootstrap struct can be used to retrieve
// configured identity-managers and their respective http-handlers and config.
//
// This function should be used by consumers which want to embed this project
// as a library.
func Boot(ctx context.Context, settings *Settings, cfg *config.Config) (Bootstrap, error) {
// NOTE(longsleep): Ensure to use same salt length as the hash size.
// See https://www.ietf.org/mail-archive/web/jose/current/msg02901.html for
// reference and https://github.com/golang-jwt/jwt/v4/issues/285 for
// the issue in upstream jwt-go.
for _, alg := range []string{jwt.SigningMethodPS256.Name, jwt.SigningMethodPS384.Name, jwt.SigningMethodPS512.Name} {
sm := jwt.GetSigningMethod(alg)
if signingMethodRSAPSS, ok := sm.(*jwt.SigningMethodRSAPSS); ok {
signingMethodRSAPSS.Options.SaltLength = rsa.PSSSaltLengthEqualsHash
}
}
bs := &bootstrap{
config: &Config{
Config: cfg,
Settings: settings,
},
}
err := bs.initialize(settings)
if err != nil {
return nil, err
}
err = bs.setup(ctx, settings)
if err != nil {
return nil, err
}
return bs, nil
}
// initialize, parsed parameters from commandline with validation and adds them
// to the associated Bootstrap data.
func (bs *bootstrap) initialize(settings *Settings) error {
logger := bs.config.Config.Logger
var err error
if settings.IdentityManager == "" {
return fmt.Errorf("identity-manager argument missing, use one of kc, ldap, cookie, dummy")
}
bs.config.IssuerIdentifierURI, err = url.Parse(settings.Iss)
if err != nil {
return fmt.Errorf("invalid iss value, iss is not a valid URL), %v", err)
} else if settings.Iss == "" {
return fmt.Errorf("missing iss value, did you provide the --iss parameter?")
} else if bs.config.IssuerIdentifierURI.Scheme != "https" {
return fmt.Errorf("invalid iss value, URL must start with https://")
} else if bs.config.IssuerIdentifierURI.Host == "" {
return fmt.Errorf("invalid iss value, URL must have a host")
}
bs.uriBasePath = settings.URIBasePath
bs.config.SignInFormURI, err = url.Parse(settings.SignInURI)
if err != nil {
return fmt.Errorf("invalid sign-in URI, %v", err)
}
bs.config.SignedOutURI, err = url.Parse(settings.SignedOutURI)
if err != nil {
return fmt.Errorf("invalid signed-out URI, %v", err)
}
bs.config.AuthorizationEndpointURI, err = url.Parse(settings.AuthorizationEndpointURI)
if err != nil {
return fmt.Errorf("invalid authorization-endpoint-uri, %v", err)
}
bs.config.EndSessionEndpointURI, err = url.Parse(settings.EndsessionEndpointURI)
if err != nil {
return fmt.Errorf("invalid endsession-endpoint-uri, %v", err)
}
if settings.Insecure {
// NOTE(longsleep): This disable http2 client support. See https://github.com/golang/go/issues/14275 for reasons.
bs.config.TLSClientConfig = utils.InsecureSkipVerifyTLSConfig()
logger.Warnln("insecure mode, TLS client connections are susceptible to man-in-the-middle attacks")
} else {
bs.config.TLSClientConfig = utils.DefaultTLSConfig()
}
for _, trustedProxy := range settings.TrustedProxy {
if ip := net.ParseIP(trustedProxy); ip != nil {
bs.config.Config.TrustedProxyIPs = append(bs.config.Config.TrustedProxyIPs, &ip)
continue
}
if _, ipNet, errParseCIDR := net.ParseCIDR(trustedProxy); errParseCIDR == nil {
bs.config.Config.TrustedProxyNets = append(bs.config.Config.TrustedProxyNets, ipNet)
continue
}
}
if len(bs.config.Config.TrustedProxyIPs) > 0 {
logger.Infoln("trusted proxy IPs", bs.config.Config.TrustedProxyIPs)
}
if len(bs.config.Config.TrustedProxyNets) > 0 {
logger.Infoln("trusted proxy networks", bs.config.Config.TrustedProxyNets)
}
if len(settings.AllowScope) > 0 {
bs.config.Config.AllowedScopes = settings.AllowScope
logger.Infoln("using custom allowed OAuth 2 scopes", bs.config.Config.AllowedScopes)
}
bs.config.Config.AllowClientGuests = settings.AllowClientGuests
if bs.config.Config.AllowClientGuests {
logger.Infoln("client controlled guests are enabled")
}
bs.config.Config.AllowDynamicClientRegistration = settings.AllowDynamicClientRegistration
if bs.config.Config.AllowDynamicClientRegistration {
logger.Infoln("dynamic client registration is enabled")
}
encryptionSecretFn := settings.EncryptionSecretFile
if encryptionSecretFn != "" {
logger.WithField("file", encryptionSecretFn).Infoln("loading encryption secret from file")
bs.config.EncryptionSecret, err = ioutil.ReadFile(encryptionSecretFn)
if err != nil {
return fmt.Errorf("failed to load encryption secret from file: %v", err)
}
if len(bs.config.EncryptionSecret) != encryption.KeySize {
return fmt.Errorf("invalid encryption secret size - must be %d bytes", encryption.KeySize)
}
} else {
logger.Warnf("missing --encryption-secret parameter, using random encyption secret with %d bytes", encryption.KeySize)
bs.config.EncryptionSecret = rndm.GenerateRandomBytes(encryption.KeySize)
}
bs.config.Config.ListenAddr = settings.Listen
bs.config.IdentifierClientDisabled = settings.IdentifierClientDisabled
bs.config.IdentifierClientPath = settings.IdentifierClientPath
bs.config.IdentifierRegistrationConf = settings.IdentifierRegistrationConf
if bs.config.IdentifierRegistrationConf != "" {
bs.config.IdentifierRegistrationConf, _ = filepath.Abs(bs.config.IdentifierRegistrationConf)
if _, errStat := os.Stat(bs.config.IdentifierRegistrationConf); errStat != nil {
return fmt.Errorf("identifier-registration-conf file not found or unable to access: %v", errStat)
}
bs.config.IdentifierAuthoritiesConf = bs.config.IdentifierRegistrationConf
}
bs.config.IdentifierScopesConf = settings.IdentifierScopesConf
if bs.config.IdentifierScopesConf != "" {
bs.config.IdentifierScopesConf, _ = filepath.Abs(bs.config.IdentifierScopesConf)
if _, errStat := os.Stat(bs.config.IdentifierScopesConf); errStat != nil {
return fmt.Errorf("identifier-scopes-conf file not found or unable to access: %v", errStat)
}
}
if settings.IdentifierDefaultBannerLogo != "" {
// Load from file.
b, errRead := ioutil.ReadFile(settings.IdentifierDefaultBannerLogo)
if errRead != nil {
return fmt.Errorf("identifier-default-banner-logo failed to open: %w", errRead)
}
bs.config.IdentifierDefaultBannerLogo = b
}
if settings.IdentifierDefaultSignInPageText != "" {
bs.config.IdentifierDefaultSignInPageText = &settings.IdentifierDefaultSignInPageText
}
if settings.IdentifierDefaultUsernameHintText != "" {
bs.config.IdentifierDefaultUsernameHintText = &settings.IdentifierDefaultUsernameHintText
}
bs.config.IdentifierUILocales = settings.IdentifierUILocales
bs.config.SigningKeyID = settings.SigningKid
bs.config.Signers = make(map[string]crypto.Signer)
bs.config.Validators = make(map[string]crypto.PublicKey)
bs.config.Certificates = make(map[string][]*x509.Certificate)
signingMethodString := settings.SigningMethod
bs.config.SigningMethod = jwt.GetSigningMethod(signingMethodString)
if bs.config.SigningMethod == nil {
return fmt.Errorf("unknown signing method: %s", signingMethodString)
}
signingKeyFns := settings.SigningPrivateKeyFiles
if len(signingKeyFns) > 0 {
first := true
for _, signingKeyFn := range signingKeyFns {
logger.WithField("path", signingKeyFn).Infoln("loading signing key")
err = addSignerWithIDFromFile(signingKeyFn, "", bs)
if err != nil {
return err
}
if first {
// Also add key under the provided id.
first = false
err = addSignerWithIDFromFile(signingKeyFn, bs.config.SigningKeyID, bs)
if err != nil {
return err
}
}
}
} else {
//NOTE(longsleep): remove me - create keypair a random key pair.
sm := jwt.SigningMethodPS256
bs.config.SigningMethod = sm
logger.WithField("alg", sm.Name).Warnf("missing --signing-private-key parameter, using random %d bit signing key", DefaultSigningKeyBits)
signer, _ := rsa.GenerateKey(rand.Reader, DefaultSigningKeyBits)
bs.config.Signers[bs.config.SigningKeyID] = signer
}
// Ensure we have a signer for the things we need.
err = validateSigners(bs)
if err != nil {
return err
}
validationKeysPath := settings.ValidationKeysPath
if validationKeysPath != "" {
logger.WithField("path", validationKeysPath).Infoln("loading validation keys")
err = addValidatorsFromPath(validationKeysPath, bs)
if err != nil {
return err
}
}
bs.config.Config.HTTPTransport = utils.HTTPTransportWithTLSClientConfig(bs.config.TLSClientConfig)
bs.config.AccessTokenDurationSeconds = settings.AccessTokenDurationSeconds
if bs.config.AccessTokenDurationSeconds == 0 {
bs.config.AccessTokenDurationSeconds = 60 * 10 // 10 Minutes
}
bs.config.IDTokenDurationSeconds = settings.IDTokenDurationSeconds
if bs.config.IDTokenDurationSeconds == 0 {
bs.config.IDTokenDurationSeconds = 60 * 60 // 1 Hour
}
bs.config.RefreshTokenDurationSeconds = settings.RefreshTokenDurationSeconds
if bs.config.RefreshTokenDurationSeconds == 0 {
bs.config.RefreshTokenDurationSeconds = 60 * 60 * 24 * 365 * 3 // 3 Years
}
bs.config.DyamicClientSecretDurationSeconds = settings.DyamicClientSecretDurationSeconds
return nil
}
// setup takes care of setting up the managers based on the associated
// Bootstrap's data.
func (bs *bootstrap) setup(ctx context.Context, settings *Settings) error {
managers, err := newManagers(ctx, bs)
if err != nil {
return err
}
bs.managers = managers
identityManager, err := bs.setupIdentity(ctx, settings)
if err != nil {
return err
}
managers.Set("identity", identityManager)
guestManager, err := bs.setupGuest(ctx, identityManager)
if err != nil {
return err
}
managers.Set("guest", guestManager)
oidcProvider, err := bs.setupOIDCProvider(ctx)
if err != nil {
return err
}
managers.Set("oidc", oidcProvider)
managers.Set("handler", oidcProvider) // Use OIDC provider as default HTTP handler.
err = managers.Apply()
if err != nil {
return fmt.Errorf("failed to apply managers: %v", err)
}
// Final steps
err = oidcProvider.InitializeMetadata()
if err != nil {
return fmt.Errorf("failed to initialize provider metadata: %v", err)
}
return nil
}
func (bs *bootstrap) MakeURIPath(api APIType, subpath string) string {
subpath = strings.TrimPrefix(subpath, "/")
uriPath := ""
switch api {
case APITypeKonnect:
uriPath = fmt.Sprintf("%s/konnect/v1/%s", strings.TrimSuffix(bs.uriBasePath, "/"), subpath)
case APITypeSignin:
uriPath = fmt.Sprintf("%s/signin/v1/%s", strings.TrimSuffix(bs.uriBasePath, "/"), subpath)
default:
panic("unknown api type")
}
if subpath == "" {
uriPath = strings.TrimSuffix(uriPath, "/")
}
return uriPath
}
func (bs *bootstrap) MakeURI(api APIType, subpath string) *url.URL {
uriPath := bs.MakeURIPath(api, subpath)
uri, _ := url.Parse(bs.config.IssuerIdentifierURI.String())
uri.Path = uriPath
return uri
}
func (bs *bootstrap) setupIdentity(ctx context.Context, settings *Settings) (identity.Manager, error) {
logger := bs.config.Config.Logger
if settings.IdentityManager == "" {
return nil, fmt.Errorf("identity-manager argument missing")
}
// Identity manager.
identityManagerName := settings.IdentityManager
identityManager, err := getIdentityManagerByName(identityManagerName, bs)
if err != nil {
return nil, err
}
logger.WithFields(logrus.Fields{
"name": identityManagerName,
"scopes": identityManager.ScopesSupported(nil),
"claims": identityManager.ClaimsSupported(nil),
}).Infoln("identity manager set up")
return identityManager, nil
}
func (bs *bootstrap) setupGuest(ctx context.Context, identityManager identity.Manager) (identity.Manager, error) {
if !bs.config.Config.AllowClientGuests {
return nil, nil
}
var err error
logger := bs.config.Config.Logger
guestManager, err := getIdentityManagerByName(DefaultGuestIdentityManagerName, bs)
if err != nil {
return nil, err
}
if guestManager != nil {
logger.Infoln("identity guest manager set up")
}
return guestManager, nil
}
func (bs *bootstrap) setupOIDCProvider(ctx context.Context) (*oidcProvider.Provider, error) {
var err error
logger := bs.config.Config.Logger
sessionCookiePath, err := getCommonURLPathPrefix(bs.config.AuthorizationEndpointURI.EscapedPath(), bs.config.EndSessionEndpointURI.EscapedPath())
if err != nil {
return nil, fmt.Errorf("failed to find common URL prefix for authorize and endsession: %v", err)
}
var registrationPath = ""
if bs.config.Config.AllowDynamicClientRegistration {
registrationPath = bs.MakeURIPath(APITypeKonnect, "/register")
}
provider, err := oidcProvider.NewProvider(&oidcProvider.Config{
Config: bs.config.Config,
IssuerIdentifier: bs.config.IssuerIdentifierURI.String(),
WellKnownPath: "/.well-known/openid-configuration",
JwksPath: bs.MakeURIPath(APITypeKonnect, "/jwks.json"),
AuthorizationPath: bs.config.AuthorizationEndpointURI.EscapedPath(),
TokenPath: bs.MakeURIPath(APITypeKonnect, "/token"),
UserInfoPath: bs.MakeURIPath(APITypeKonnect, "/userinfo"),
EndSessionPath: bs.config.EndSessionEndpointURI.EscapedPath(),
CheckSessionIframePath: bs.MakeURIPath(APITypeKonnect, "/session/check-session.html"),
RegistrationPath: registrationPath,
BrowserStateCookiePath: bs.MakeURIPath(APITypeKonnect, "/session/"),
BrowserStateCookieName: "__Secure-KKBS", // Kopano-Konnect-Browser-State
SessionCookiePath: sessionCookiePath,
SessionCookieName: "__Secure-KKCS", // Kopano-Konnect-Client-Session
AccessTokenDuration: time.Duration(bs.config.AccessTokenDurationSeconds) * time.Second,
IDTokenDuration: time.Duration(bs.config.IDTokenDurationSeconds) * time.Second,
RefreshTokenDuration: time.Duration(bs.config.RefreshTokenDurationSeconds) * time.Second,
})
if err != nil {
return nil, fmt.Errorf("failed to create provider: %v", err)
}
if bs.config.SigningMethod != nil {
err = provider.SetSigningMethod(bs.config.SigningMethod)
if err != nil {
return nil, fmt.Errorf("failed to set provider signing method: %v", err)
}
}
// All add signers.
for id, signer := range bs.config.Signers {
if id == bs.config.SigningKeyID {
err = provider.SetSigningKey(id, signer)
// Always set default key.
if id != DefaultSigningKeyID {
provider.SetValidationKey(DefaultSigningKeyID, signer.Public())
}
} else {
// Set non default signers as well.
err = provider.SetSigningKey(id, signer)
}
if err != nil {
return nil, err
}
}
// Add all validators.
for id, publicKey := range bs.config.Validators {
err = provider.SetValidationKey(id, publicKey)
if err != nil {
return nil, err
}
}
// Add all certificates.
for id, certificate := range bs.config.Certificates {
err = provider.SetCertificate(id, certificate)
if err != nil {
return nil, err
}
}
sk, ok := provider.GetSigningKey(bs.config.SigningMethod)
if !ok {
return nil, fmt.Errorf("no signing key for selected signing method")
}
if bs.config.SigningKeyID == "" {
// Ensure that there is a default signing Key ID even if none was set.
provider.SetValidationKey(DefaultSigningKeyID, sk.PrivateKey.Public())
}
logger.WithFields(logrus.Fields{
"id": sk.ID,
"method": fmt.Sprintf("%T", sk.SigningMethod),
"alg": sk.SigningMethod.Alg(),
}).Infoln("oidc token signing default set up")
return provider, nil
} | // Config returns the bootstap configuration. | random_line_split |
bootstrap.go | /*
* Copyright 2017-2019 Kopano and its licensors
*
* 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.
*
*/
package bootstrap
import (
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"fmt"
"io/ioutil"
"net"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/longsleep/rndm"
"github.com/sirupsen/logrus"
"github.com/libregraph/lico/config"
"github.com/libregraph/lico/encryption"
"github.com/libregraph/lico/identity"
"github.com/libregraph/lico/managers"
oidcProvider "github.com/libregraph/lico/oidc/provider"
"github.com/libregraph/lico/utils"
)
// API types.
type APIType string
const (
APITypeKonnect APIType = "konnect"
APITypeSignin APIType = "signin"
)
// Defaults.
const (
DefaultSigningKeyID = "default"
DefaultSigningKeyBits = 2048
DefaultGuestIdentityManagerName = "guest"
)
// Bootstrap is a data structure to hold configuration required to start
// konnectd.
type Bootstrap interface {
Config() *Config
Managers() *managers.Managers
MakeURIPath(api APIType, subpath string) string
}
// Implementation of the bootstrap interface.
type bootstrap struct {
config *Config
uriBasePath string
managers *managers.Managers
}
// Config returns the bootstap configuration.
func (bs *bootstrap) Config() *Config {
return bs.config
}
// Managers returns bootstrapped identity-managers.
func (bs *bootstrap) Managers() *managers.Managers {
return bs.managers
}
// Boot is the main entry point to bootstrap the service after validating the
// given configuration. The resulting Bootstrap struct can be used to retrieve
// configured identity-managers and their respective http-handlers and config.
//
// This function should be used by consumers which want to embed this project
// as a library.
func Boot(ctx context.Context, settings *Settings, cfg *config.Config) (Bootstrap, error) |
// initialize, parsed parameters from commandline with validation and adds them
// to the associated Bootstrap data.
func (bs *bootstrap) initialize(settings *Settings) error {
logger := bs.config.Config.Logger
var err error
if settings.IdentityManager == "" {
return fmt.Errorf("identity-manager argument missing, use one of kc, ldap, cookie, dummy")
}
bs.config.IssuerIdentifierURI, err = url.Parse(settings.Iss)
if err != nil {
return fmt.Errorf("invalid iss value, iss is not a valid URL), %v", err)
} else if settings.Iss == "" {
return fmt.Errorf("missing iss value, did you provide the --iss parameter?")
} else if bs.config.IssuerIdentifierURI.Scheme != "https" {
return fmt.Errorf("invalid iss value, URL must start with https://")
} else if bs.config.IssuerIdentifierURI.Host == "" {
return fmt.Errorf("invalid iss value, URL must have a host")
}
bs.uriBasePath = settings.URIBasePath
bs.config.SignInFormURI, err = url.Parse(settings.SignInURI)
if err != nil {
return fmt.Errorf("invalid sign-in URI, %v", err)
}
bs.config.SignedOutURI, err = url.Parse(settings.SignedOutURI)
if err != nil {
return fmt.Errorf("invalid signed-out URI, %v", err)
}
bs.config.AuthorizationEndpointURI, err = url.Parse(settings.AuthorizationEndpointURI)
if err != nil {
return fmt.Errorf("invalid authorization-endpoint-uri, %v", err)
}
bs.config.EndSessionEndpointURI, err = url.Parse(settings.EndsessionEndpointURI)
if err != nil {
return fmt.Errorf("invalid endsession-endpoint-uri, %v", err)
}
if settings.Insecure {
// NOTE(longsleep): This disable http2 client support. See https://github.com/golang/go/issues/14275 for reasons.
bs.config.TLSClientConfig = utils.InsecureSkipVerifyTLSConfig()
logger.Warnln("insecure mode, TLS client connections are susceptible to man-in-the-middle attacks")
} else {
bs.config.TLSClientConfig = utils.DefaultTLSConfig()
}
for _, trustedProxy := range settings.TrustedProxy {
if ip := net.ParseIP(trustedProxy); ip != nil {
bs.config.Config.TrustedProxyIPs = append(bs.config.Config.TrustedProxyIPs, &ip)
continue
}
if _, ipNet, errParseCIDR := net.ParseCIDR(trustedProxy); errParseCIDR == nil {
bs.config.Config.TrustedProxyNets = append(bs.config.Config.TrustedProxyNets, ipNet)
continue
}
}
if len(bs.config.Config.TrustedProxyIPs) > 0 {
logger.Infoln("trusted proxy IPs", bs.config.Config.TrustedProxyIPs)
}
if len(bs.config.Config.TrustedProxyNets) > 0 {
logger.Infoln("trusted proxy networks", bs.config.Config.TrustedProxyNets)
}
if len(settings.AllowScope) > 0 {
bs.config.Config.AllowedScopes = settings.AllowScope
logger.Infoln("using custom allowed OAuth 2 scopes", bs.config.Config.AllowedScopes)
}
bs.config.Config.AllowClientGuests = settings.AllowClientGuests
if bs.config.Config.AllowClientGuests {
logger.Infoln("client controlled guests are enabled")
}
bs.config.Config.AllowDynamicClientRegistration = settings.AllowDynamicClientRegistration
if bs.config.Config.AllowDynamicClientRegistration {
logger.Infoln("dynamic client registration is enabled")
}
encryptionSecretFn := settings.EncryptionSecretFile
if encryptionSecretFn != "" {
logger.WithField("file", encryptionSecretFn).Infoln("loading encryption secret from file")
bs.config.EncryptionSecret, err = ioutil.ReadFile(encryptionSecretFn)
if err != nil {
return fmt.Errorf("failed to load encryption secret from file: %v", err)
}
if len(bs.config.EncryptionSecret) != encryption.KeySize {
return fmt.Errorf("invalid encryption secret size - must be %d bytes", encryption.KeySize)
}
} else {
logger.Warnf("missing --encryption-secret parameter, using random encyption secret with %d bytes", encryption.KeySize)
bs.config.EncryptionSecret = rndm.GenerateRandomBytes(encryption.KeySize)
}
bs.config.Config.ListenAddr = settings.Listen
bs.config.IdentifierClientDisabled = settings.IdentifierClientDisabled
bs.config.IdentifierClientPath = settings.IdentifierClientPath
bs.config.IdentifierRegistrationConf = settings.IdentifierRegistrationConf
if bs.config.IdentifierRegistrationConf != "" {
bs.config.IdentifierRegistrationConf, _ = filepath.Abs(bs.config.IdentifierRegistrationConf)
if _, errStat := os.Stat(bs.config.IdentifierRegistrationConf); errStat != nil {
return fmt.Errorf("identifier-registration-conf file not found or unable to access: %v", errStat)
}
bs.config.IdentifierAuthoritiesConf = bs.config.IdentifierRegistrationConf
}
bs.config.IdentifierScopesConf = settings.IdentifierScopesConf
if bs.config.IdentifierScopesConf != "" {
bs.config.IdentifierScopesConf, _ = filepath.Abs(bs.config.IdentifierScopesConf)
if _, errStat := os.Stat(bs.config.IdentifierScopesConf); errStat != nil {
return fmt.Errorf("identifier-scopes-conf file not found or unable to access: %v", errStat)
}
}
if settings.IdentifierDefaultBannerLogo != "" {
// Load from file.
b, errRead := ioutil.ReadFile(settings.IdentifierDefaultBannerLogo)
if errRead != nil {
return fmt.Errorf("identifier-default-banner-logo failed to open: %w", errRead)
}
bs.config.IdentifierDefaultBannerLogo = b
}
if settings.IdentifierDefaultSignInPageText != "" {
bs.config.IdentifierDefaultSignInPageText = &settings.IdentifierDefaultSignInPageText
}
if settings.IdentifierDefaultUsernameHintText != "" {
bs.config.IdentifierDefaultUsernameHintText = &settings.IdentifierDefaultUsernameHintText
}
bs.config.IdentifierUILocales = settings.IdentifierUILocales
bs.config.SigningKeyID = settings.SigningKid
bs.config.Signers = make(map[string]crypto.Signer)
bs.config.Validators = make(map[string]crypto.PublicKey)
bs.config.Certificates = make(map[string][]*x509.Certificate)
signingMethodString := settings.SigningMethod
bs.config.SigningMethod = jwt.GetSigningMethod(signingMethodString)
if bs.config.SigningMethod == nil {
return fmt.Errorf("unknown signing method: %s", signingMethodString)
}
signingKeyFns := settings.SigningPrivateKeyFiles
if len(signingKeyFns) > 0 {
first := true
for _, signingKeyFn := range signingKeyFns {
logger.WithField("path", signingKeyFn).Infoln("loading signing key")
err = addSignerWithIDFromFile(signingKeyFn, "", bs)
if err != nil {
return err
}
if first {
// Also add key under the provided id.
first = false
err = addSignerWithIDFromFile(signingKeyFn, bs.config.SigningKeyID, bs)
if err != nil {
return err
}
}
}
} else {
//NOTE(longsleep): remove me - create keypair a random key pair.
sm := jwt.SigningMethodPS256
bs.config.SigningMethod = sm
logger.WithField("alg", sm.Name).Warnf("missing --signing-private-key parameter, using random %d bit signing key", DefaultSigningKeyBits)
signer, _ := rsa.GenerateKey(rand.Reader, DefaultSigningKeyBits)
bs.config.Signers[bs.config.SigningKeyID] = signer
}
// Ensure we have a signer for the things we need.
err = validateSigners(bs)
if err != nil {
return err
}
validationKeysPath := settings.ValidationKeysPath
if validationKeysPath != "" {
logger.WithField("path", validationKeysPath).Infoln("loading validation keys")
err = addValidatorsFromPath(validationKeysPath, bs)
if err != nil {
return err
}
}
bs.config.Config.HTTPTransport = utils.HTTPTransportWithTLSClientConfig(bs.config.TLSClientConfig)
bs.config.AccessTokenDurationSeconds = settings.AccessTokenDurationSeconds
if bs.config.AccessTokenDurationSeconds == 0 {
bs.config.AccessTokenDurationSeconds = 60 * 10 // 10 Minutes
}
bs.config.IDTokenDurationSeconds = settings.IDTokenDurationSeconds
if bs.config.IDTokenDurationSeconds == 0 {
bs.config.IDTokenDurationSeconds = 60 * 60 // 1 Hour
}
bs.config.RefreshTokenDurationSeconds = settings.RefreshTokenDurationSeconds
if bs.config.RefreshTokenDurationSeconds == 0 {
bs.config.RefreshTokenDurationSeconds = 60 * 60 * 24 * 365 * 3 // 3 Years
}
bs.config.DyamicClientSecretDurationSeconds = settings.DyamicClientSecretDurationSeconds
return nil
}
// setup takes care of setting up the managers based on the associated
// Bootstrap's data.
func (bs *bootstrap) setup(ctx context.Context, settings *Settings) error {
managers, err := newManagers(ctx, bs)
if err != nil {
return err
}
bs.managers = managers
identityManager, err := bs.setupIdentity(ctx, settings)
if err != nil {
return err
}
managers.Set("identity", identityManager)
guestManager, err := bs.setupGuest(ctx, identityManager)
if err != nil {
return err
}
managers.Set("guest", guestManager)
oidcProvider, err := bs.setupOIDCProvider(ctx)
if err != nil {
return err
}
managers.Set("oidc", oidcProvider)
managers.Set("handler", oidcProvider) // Use OIDC provider as default HTTP handler.
err = managers.Apply()
if err != nil {
return fmt.Errorf("failed to apply managers: %v", err)
}
// Final steps
err = oidcProvider.InitializeMetadata()
if err != nil {
return fmt.Errorf("failed to initialize provider metadata: %v", err)
}
return nil
}
func (bs *bootstrap) MakeURIPath(api APIType, subpath string) string {
subpath = strings.TrimPrefix(subpath, "/")
uriPath := ""
switch api {
case APITypeKonnect:
uriPath = fmt.Sprintf("%s/konnect/v1/%s", strings.TrimSuffix(bs.uriBasePath, "/"), subpath)
case APITypeSignin:
uriPath = fmt.Sprintf("%s/signin/v1/%s", strings.TrimSuffix(bs.uriBasePath, "/"), subpath)
default:
panic("unknown api type")
}
if subpath == "" {
uriPath = strings.TrimSuffix(uriPath, "/")
}
return uriPath
}
func (bs *bootstrap) MakeURI(api APIType, subpath string) *url.URL {
uriPath := bs.MakeURIPath(api, subpath)
uri, _ := url.Parse(bs.config.IssuerIdentifierURI.String())
uri.Path = uriPath
return uri
}
func (bs *bootstrap) setupIdentity(ctx context.Context, settings *Settings) (identity.Manager, error) {
logger := bs.config.Config.Logger
if settings.IdentityManager == "" {
return nil, fmt.Errorf("identity-manager argument missing")
}
// Identity manager.
identityManagerName := settings.IdentityManager
identityManager, err := getIdentityManagerByName(identityManagerName, bs)
if err != nil {
return nil, err
}
logger.WithFields(logrus.Fields{
"name": identityManagerName,
"scopes": identityManager.ScopesSupported(nil),
"claims": identityManager.ClaimsSupported(nil),
}).Infoln("identity manager set up")
return identityManager, nil
}
func (bs *bootstrap) setupGuest(ctx context.Context, identityManager identity.Manager) (identity.Manager, error) {
if !bs.config.Config.AllowClientGuests {
return nil, nil
}
var err error
logger := bs.config.Config.Logger
guestManager, err := getIdentityManagerByName(DefaultGuestIdentityManagerName, bs)
if err != nil {
return nil, err
}
if guestManager != nil {
logger.Infoln("identity guest manager set up")
}
return guestManager, nil
}
func (bs *bootstrap) setupOIDCProvider(ctx context.Context) (*oidcProvider.Provider, error) {
var err error
logger := bs.config.Config.Logger
sessionCookiePath, err := getCommonURLPathPrefix(bs.config.AuthorizationEndpointURI.EscapedPath(), bs.config.EndSessionEndpointURI.EscapedPath())
if err != nil {
return nil, fmt.Errorf("failed to find common URL prefix for authorize and endsession: %v", err)
}
var registrationPath = ""
if bs.config.Config.AllowDynamicClientRegistration {
registrationPath = bs.MakeURIPath(APITypeKonnect, "/register")
}
provider, err := oidcProvider.NewProvider(&oidcProvider.Config{
Config: bs.config.Config,
IssuerIdentifier: bs.config.IssuerIdentifierURI.String(),
WellKnownPath: "/.well-known/openid-configuration",
JwksPath: bs.MakeURIPath(APITypeKonnect, "/jwks.json"),
AuthorizationPath: bs.config.AuthorizationEndpointURI.EscapedPath(),
TokenPath: bs.MakeURIPath(APITypeKonnect, "/token"),
UserInfoPath: bs.MakeURIPath(APITypeKonnect, "/userinfo"),
EndSessionPath: bs.config.EndSessionEndpointURI.EscapedPath(),
CheckSessionIframePath: bs.MakeURIPath(APITypeKonnect, "/session/check-session.html"),
RegistrationPath: registrationPath,
BrowserStateCookiePath: bs.MakeURIPath(APITypeKonnect, "/session/"),
BrowserStateCookieName: "__Secure-KKBS", // Kopano-Konnect-Browser-State
SessionCookiePath: sessionCookiePath,
SessionCookieName: "__Secure-KKCS", // Kopano-Konnect-Client-Session
AccessTokenDuration: time.Duration(bs.config.AccessTokenDurationSeconds) * time.Second,
IDTokenDuration: time.Duration(bs.config.IDTokenDurationSeconds) * time.Second,
RefreshTokenDuration: time.Duration(bs.config.RefreshTokenDurationSeconds) * time.Second,
})
if err != nil {
return nil, fmt.Errorf("failed to create provider: %v", err)
}
if bs.config.SigningMethod != nil {
err = provider.SetSigningMethod(bs.config.SigningMethod)
if err != nil {
return nil, fmt.Errorf("failed to set provider signing method: %v", err)
}
}
// All add signers.
for id, signer := range bs.config.Signers {
if id == bs.config.SigningKeyID {
err = provider.SetSigningKey(id, signer)
// Always set default key.
if id != DefaultSigningKeyID {
provider.SetValidationKey(DefaultSigningKeyID, signer.Public())
}
} else {
// Set non default signers as well.
err = provider.SetSigningKey(id, signer)
}
if err != nil {
return nil, err
}
}
// Add all validators.
for id, publicKey := range bs.config.Validators {
err = provider.SetValidationKey(id, publicKey)
if err != nil {
return nil, err
}
}
// Add all certificates.
for id, certificate := range bs.config.Certificates {
err = provider.SetCertificate(id, certificate)
if err != nil {
return nil, err
}
}
sk, ok := provider.GetSigningKey(bs.config.SigningMethod)
if !ok {
return nil, fmt.Errorf("no signing key for selected signing method")
}
if bs.config.SigningKeyID == "" {
// Ensure that there is a default signing Key ID even if none was set.
provider.SetValidationKey(DefaultSigningKeyID, sk.PrivateKey.Public())
}
logger.WithFields(logrus.Fields{
"id": sk.ID,
"method": fmt.Sprintf("%T", sk.SigningMethod),
"alg": sk.SigningMethod.Alg(),
}).Infoln("oidc token signing default set up")
return provider, nil
}
| {
// NOTE(longsleep): Ensure to use same salt length as the hash size.
// See https://www.ietf.org/mail-archive/web/jose/current/msg02901.html for
// reference and https://github.com/golang-jwt/jwt/v4/issues/285 for
// the issue in upstream jwt-go.
for _, alg := range []string{jwt.SigningMethodPS256.Name, jwt.SigningMethodPS384.Name, jwt.SigningMethodPS512.Name} {
sm := jwt.GetSigningMethod(alg)
if signingMethodRSAPSS, ok := sm.(*jwt.SigningMethodRSAPSS); ok {
signingMethodRSAPSS.Options.SaltLength = rsa.PSSSaltLengthEqualsHash
}
}
bs := &bootstrap{
config: &Config{
Config: cfg,
Settings: settings,
},
}
err := bs.initialize(settings)
if err != nil {
return nil, err
}
err = bs.setup(ctx, settings)
if err != nil {
return nil, err
}
return bs, nil
} | identifier_body |
bootstrap.go | /*
* Copyright 2017-2019 Kopano and its licensors
*
* 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.
*
*/
package bootstrap
import (
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"fmt"
"io/ioutil"
"net"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/longsleep/rndm"
"github.com/sirupsen/logrus"
"github.com/libregraph/lico/config"
"github.com/libregraph/lico/encryption"
"github.com/libregraph/lico/identity"
"github.com/libregraph/lico/managers"
oidcProvider "github.com/libregraph/lico/oidc/provider"
"github.com/libregraph/lico/utils"
)
// API types.
type APIType string
const (
APITypeKonnect APIType = "konnect"
APITypeSignin APIType = "signin"
)
// Defaults.
const (
DefaultSigningKeyID = "default"
DefaultSigningKeyBits = 2048
DefaultGuestIdentityManagerName = "guest"
)
// Bootstrap is a data structure to hold configuration required to start
// konnectd.
type Bootstrap interface {
Config() *Config
Managers() *managers.Managers
MakeURIPath(api APIType, subpath string) string
}
// Implementation of the bootstrap interface.
type bootstrap struct {
config *Config
uriBasePath string
managers *managers.Managers
}
// Config returns the bootstap configuration.
func (bs *bootstrap) Config() *Config {
return bs.config
}
// Managers returns bootstrapped identity-managers.
func (bs *bootstrap) Managers() *managers.Managers {
return bs.managers
}
// Boot is the main entry point to bootstrap the service after validating the
// given configuration. The resulting Bootstrap struct can be used to retrieve
// configured identity-managers and their respective http-handlers and config.
//
// This function should be used by consumers which want to embed this project
// as a library.
func Boot(ctx context.Context, settings *Settings, cfg *config.Config) (Bootstrap, error) {
// NOTE(longsleep): Ensure to use same salt length as the hash size.
// See https://www.ietf.org/mail-archive/web/jose/current/msg02901.html for
// reference and https://github.com/golang-jwt/jwt/v4/issues/285 for
// the issue in upstream jwt-go.
for _, alg := range []string{jwt.SigningMethodPS256.Name, jwt.SigningMethodPS384.Name, jwt.SigningMethodPS512.Name} {
sm := jwt.GetSigningMethod(alg)
if signingMethodRSAPSS, ok := sm.(*jwt.SigningMethodRSAPSS); ok {
signingMethodRSAPSS.Options.SaltLength = rsa.PSSSaltLengthEqualsHash
}
}
bs := &bootstrap{
config: &Config{
Config: cfg,
Settings: settings,
},
}
err := bs.initialize(settings)
if err != nil {
return nil, err
}
err = bs.setup(ctx, settings)
if err != nil {
return nil, err
}
return bs, nil
}
// initialize, parsed parameters from commandline with validation and adds them
// to the associated Bootstrap data.
func (bs *bootstrap) initialize(settings *Settings) error {
logger := bs.config.Config.Logger
var err error
if settings.IdentityManager == "" {
return fmt.Errorf("identity-manager argument missing, use one of kc, ldap, cookie, dummy")
}
bs.config.IssuerIdentifierURI, err = url.Parse(settings.Iss)
if err != nil {
return fmt.Errorf("invalid iss value, iss is not a valid URL), %v", err)
} else if settings.Iss == "" {
return fmt.Errorf("missing iss value, did you provide the --iss parameter?")
} else if bs.config.IssuerIdentifierURI.Scheme != "https" {
return fmt.Errorf("invalid iss value, URL must start with https://")
} else if bs.config.IssuerIdentifierURI.Host == "" {
return fmt.Errorf("invalid iss value, URL must have a host")
}
bs.uriBasePath = settings.URIBasePath
bs.config.SignInFormURI, err = url.Parse(settings.SignInURI)
if err != nil {
return fmt.Errorf("invalid sign-in URI, %v", err)
}
bs.config.SignedOutURI, err = url.Parse(settings.SignedOutURI)
if err != nil {
return fmt.Errorf("invalid signed-out URI, %v", err)
}
bs.config.AuthorizationEndpointURI, err = url.Parse(settings.AuthorizationEndpointURI)
if err != nil {
return fmt.Errorf("invalid authorization-endpoint-uri, %v", err)
}
bs.config.EndSessionEndpointURI, err = url.Parse(settings.EndsessionEndpointURI)
if err != nil {
return fmt.Errorf("invalid endsession-endpoint-uri, %v", err)
}
if settings.Insecure {
// NOTE(longsleep): This disable http2 client support. See https://github.com/golang/go/issues/14275 for reasons.
bs.config.TLSClientConfig = utils.InsecureSkipVerifyTLSConfig()
logger.Warnln("insecure mode, TLS client connections are susceptible to man-in-the-middle attacks")
} else {
bs.config.TLSClientConfig = utils.DefaultTLSConfig()
}
for _, trustedProxy := range settings.TrustedProxy {
if ip := net.ParseIP(trustedProxy); ip != nil {
bs.config.Config.TrustedProxyIPs = append(bs.config.Config.TrustedProxyIPs, &ip)
continue
}
if _, ipNet, errParseCIDR := net.ParseCIDR(trustedProxy); errParseCIDR == nil {
bs.config.Config.TrustedProxyNets = append(bs.config.Config.TrustedProxyNets, ipNet)
continue
}
}
if len(bs.config.Config.TrustedProxyIPs) > 0 {
logger.Infoln("trusted proxy IPs", bs.config.Config.TrustedProxyIPs)
}
if len(bs.config.Config.TrustedProxyNets) > 0 {
logger.Infoln("trusted proxy networks", bs.config.Config.TrustedProxyNets)
}
if len(settings.AllowScope) > 0 {
bs.config.Config.AllowedScopes = settings.AllowScope
logger.Infoln("using custom allowed OAuth 2 scopes", bs.config.Config.AllowedScopes)
}
bs.config.Config.AllowClientGuests = settings.AllowClientGuests
if bs.config.Config.AllowClientGuests {
logger.Infoln("client controlled guests are enabled")
}
bs.config.Config.AllowDynamicClientRegistration = settings.AllowDynamicClientRegistration
if bs.config.Config.AllowDynamicClientRegistration {
logger.Infoln("dynamic client registration is enabled")
}
encryptionSecretFn := settings.EncryptionSecretFile
if encryptionSecretFn != "" {
logger.WithField("file", encryptionSecretFn).Infoln("loading encryption secret from file")
bs.config.EncryptionSecret, err = ioutil.ReadFile(encryptionSecretFn)
if err != nil {
return fmt.Errorf("failed to load encryption secret from file: %v", err)
}
if len(bs.config.EncryptionSecret) != encryption.KeySize {
return fmt.Errorf("invalid encryption secret size - must be %d bytes", encryption.KeySize)
}
} else {
logger.Warnf("missing --encryption-secret parameter, using random encyption secret with %d bytes", encryption.KeySize)
bs.config.EncryptionSecret = rndm.GenerateRandomBytes(encryption.KeySize)
}
bs.config.Config.ListenAddr = settings.Listen
bs.config.IdentifierClientDisabled = settings.IdentifierClientDisabled
bs.config.IdentifierClientPath = settings.IdentifierClientPath
bs.config.IdentifierRegistrationConf = settings.IdentifierRegistrationConf
if bs.config.IdentifierRegistrationConf != "" {
bs.config.IdentifierRegistrationConf, _ = filepath.Abs(bs.config.IdentifierRegistrationConf)
if _, errStat := os.Stat(bs.config.IdentifierRegistrationConf); errStat != nil {
return fmt.Errorf("identifier-registration-conf file not found or unable to access: %v", errStat)
}
bs.config.IdentifierAuthoritiesConf = bs.config.IdentifierRegistrationConf
}
bs.config.IdentifierScopesConf = settings.IdentifierScopesConf
if bs.config.IdentifierScopesConf != "" {
bs.config.IdentifierScopesConf, _ = filepath.Abs(bs.config.IdentifierScopesConf)
if _, errStat := os.Stat(bs.config.IdentifierScopesConf); errStat != nil {
return fmt.Errorf("identifier-scopes-conf file not found or unable to access: %v", errStat)
}
}
if settings.IdentifierDefaultBannerLogo != "" {
// Load from file.
b, errRead := ioutil.ReadFile(settings.IdentifierDefaultBannerLogo)
if errRead != nil {
return fmt.Errorf("identifier-default-banner-logo failed to open: %w", errRead)
}
bs.config.IdentifierDefaultBannerLogo = b
}
if settings.IdentifierDefaultSignInPageText != "" {
bs.config.IdentifierDefaultSignInPageText = &settings.IdentifierDefaultSignInPageText
}
if settings.IdentifierDefaultUsernameHintText != "" {
bs.config.IdentifierDefaultUsernameHintText = &settings.IdentifierDefaultUsernameHintText
}
bs.config.IdentifierUILocales = settings.IdentifierUILocales
bs.config.SigningKeyID = settings.SigningKid
bs.config.Signers = make(map[string]crypto.Signer)
bs.config.Validators = make(map[string]crypto.PublicKey)
bs.config.Certificates = make(map[string][]*x509.Certificate)
signingMethodString := settings.SigningMethod
bs.config.SigningMethod = jwt.GetSigningMethod(signingMethodString)
if bs.config.SigningMethod == nil {
return fmt.Errorf("unknown signing method: %s", signingMethodString)
}
signingKeyFns := settings.SigningPrivateKeyFiles
if len(signingKeyFns) > 0 {
first := true
for _, signingKeyFn := range signingKeyFns {
logger.WithField("path", signingKeyFn).Infoln("loading signing key")
err = addSignerWithIDFromFile(signingKeyFn, "", bs)
if err != nil {
return err
}
if first {
// Also add key under the provided id.
first = false
err = addSignerWithIDFromFile(signingKeyFn, bs.config.SigningKeyID, bs)
if err != nil {
return err
}
}
}
} else {
//NOTE(longsleep): remove me - create keypair a random key pair.
sm := jwt.SigningMethodPS256
bs.config.SigningMethod = sm
logger.WithField("alg", sm.Name).Warnf("missing --signing-private-key parameter, using random %d bit signing key", DefaultSigningKeyBits)
signer, _ := rsa.GenerateKey(rand.Reader, DefaultSigningKeyBits)
bs.config.Signers[bs.config.SigningKeyID] = signer
}
// Ensure we have a signer for the things we need.
err = validateSigners(bs)
if err != nil {
return err
}
validationKeysPath := settings.ValidationKeysPath
if validationKeysPath != "" {
logger.WithField("path", validationKeysPath).Infoln("loading validation keys")
err = addValidatorsFromPath(validationKeysPath, bs)
if err != nil {
return err
}
}
bs.config.Config.HTTPTransport = utils.HTTPTransportWithTLSClientConfig(bs.config.TLSClientConfig)
bs.config.AccessTokenDurationSeconds = settings.AccessTokenDurationSeconds
if bs.config.AccessTokenDurationSeconds == 0 {
bs.config.AccessTokenDurationSeconds = 60 * 10 // 10 Minutes
}
bs.config.IDTokenDurationSeconds = settings.IDTokenDurationSeconds
if bs.config.IDTokenDurationSeconds == 0 {
bs.config.IDTokenDurationSeconds = 60 * 60 // 1 Hour
}
bs.config.RefreshTokenDurationSeconds = settings.RefreshTokenDurationSeconds
if bs.config.RefreshTokenDurationSeconds == 0 {
bs.config.RefreshTokenDurationSeconds = 60 * 60 * 24 * 365 * 3 // 3 Years
}
bs.config.DyamicClientSecretDurationSeconds = settings.DyamicClientSecretDurationSeconds
return nil
}
// setup takes care of setting up the managers based on the associated
// Bootstrap's data.
func (bs *bootstrap) setup(ctx context.Context, settings *Settings) error {
managers, err := newManagers(ctx, bs)
if err != nil {
return err
}
bs.managers = managers
identityManager, err := bs.setupIdentity(ctx, settings)
if err != nil {
return err
}
managers.Set("identity", identityManager)
guestManager, err := bs.setupGuest(ctx, identityManager)
if err != nil {
return err
}
managers.Set("guest", guestManager)
oidcProvider, err := bs.setupOIDCProvider(ctx)
if err != nil {
return err
}
managers.Set("oidc", oidcProvider)
managers.Set("handler", oidcProvider) // Use OIDC provider as default HTTP handler.
err = managers.Apply()
if err != nil {
return fmt.Errorf("failed to apply managers: %v", err)
}
// Final steps
err = oidcProvider.InitializeMetadata()
if err != nil {
return fmt.Errorf("failed to initialize provider metadata: %v", err)
}
return nil
}
func (bs *bootstrap) MakeURIPath(api APIType, subpath string) string {
subpath = strings.TrimPrefix(subpath, "/")
uriPath := ""
switch api {
case APITypeKonnect:
uriPath = fmt.Sprintf("%s/konnect/v1/%s", strings.TrimSuffix(bs.uriBasePath, "/"), subpath)
case APITypeSignin:
uriPath = fmt.Sprintf("%s/signin/v1/%s", strings.TrimSuffix(bs.uriBasePath, "/"), subpath)
default:
panic("unknown api type")
}
if subpath == "" {
uriPath = strings.TrimSuffix(uriPath, "/")
}
return uriPath
}
func (bs *bootstrap) MakeURI(api APIType, subpath string) *url.URL {
uriPath := bs.MakeURIPath(api, subpath)
uri, _ := url.Parse(bs.config.IssuerIdentifierURI.String())
uri.Path = uriPath
return uri
}
func (bs *bootstrap) setupIdentity(ctx context.Context, settings *Settings) (identity.Manager, error) {
logger := bs.config.Config.Logger
if settings.IdentityManager == "" {
return nil, fmt.Errorf("identity-manager argument missing")
}
// Identity manager.
identityManagerName := settings.IdentityManager
identityManager, err := getIdentityManagerByName(identityManagerName, bs)
if err != nil {
return nil, err
}
logger.WithFields(logrus.Fields{
"name": identityManagerName,
"scopes": identityManager.ScopesSupported(nil),
"claims": identityManager.ClaimsSupported(nil),
}).Infoln("identity manager set up")
return identityManager, nil
}
func (bs *bootstrap) | (ctx context.Context, identityManager identity.Manager) (identity.Manager, error) {
if !bs.config.Config.AllowClientGuests {
return nil, nil
}
var err error
logger := bs.config.Config.Logger
guestManager, err := getIdentityManagerByName(DefaultGuestIdentityManagerName, bs)
if err != nil {
return nil, err
}
if guestManager != nil {
logger.Infoln("identity guest manager set up")
}
return guestManager, nil
}
func (bs *bootstrap) setupOIDCProvider(ctx context.Context) (*oidcProvider.Provider, error) {
var err error
logger := bs.config.Config.Logger
sessionCookiePath, err := getCommonURLPathPrefix(bs.config.AuthorizationEndpointURI.EscapedPath(), bs.config.EndSessionEndpointURI.EscapedPath())
if err != nil {
return nil, fmt.Errorf("failed to find common URL prefix for authorize and endsession: %v", err)
}
var registrationPath = ""
if bs.config.Config.AllowDynamicClientRegistration {
registrationPath = bs.MakeURIPath(APITypeKonnect, "/register")
}
provider, err := oidcProvider.NewProvider(&oidcProvider.Config{
Config: bs.config.Config,
IssuerIdentifier: bs.config.IssuerIdentifierURI.String(),
WellKnownPath: "/.well-known/openid-configuration",
JwksPath: bs.MakeURIPath(APITypeKonnect, "/jwks.json"),
AuthorizationPath: bs.config.AuthorizationEndpointURI.EscapedPath(),
TokenPath: bs.MakeURIPath(APITypeKonnect, "/token"),
UserInfoPath: bs.MakeURIPath(APITypeKonnect, "/userinfo"),
EndSessionPath: bs.config.EndSessionEndpointURI.EscapedPath(),
CheckSessionIframePath: bs.MakeURIPath(APITypeKonnect, "/session/check-session.html"),
RegistrationPath: registrationPath,
BrowserStateCookiePath: bs.MakeURIPath(APITypeKonnect, "/session/"),
BrowserStateCookieName: "__Secure-KKBS", // Kopano-Konnect-Browser-State
SessionCookiePath: sessionCookiePath,
SessionCookieName: "__Secure-KKCS", // Kopano-Konnect-Client-Session
AccessTokenDuration: time.Duration(bs.config.AccessTokenDurationSeconds) * time.Second,
IDTokenDuration: time.Duration(bs.config.IDTokenDurationSeconds) * time.Second,
RefreshTokenDuration: time.Duration(bs.config.RefreshTokenDurationSeconds) * time.Second,
})
if err != nil {
return nil, fmt.Errorf("failed to create provider: %v", err)
}
if bs.config.SigningMethod != nil {
err = provider.SetSigningMethod(bs.config.SigningMethod)
if err != nil {
return nil, fmt.Errorf("failed to set provider signing method: %v", err)
}
}
// All add signers.
for id, signer := range bs.config.Signers {
if id == bs.config.SigningKeyID {
err = provider.SetSigningKey(id, signer)
// Always set default key.
if id != DefaultSigningKeyID {
provider.SetValidationKey(DefaultSigningKeyID, signer.Public())
}
} else {
// Set non default signers as well.
err = provider.SetSigningKey(id, signer)
}
if err != nil {
return nil, err
}
}
// Add all validators.
for id, publicKey := range bs.config.Validators {
err = provider.SetValidationKey(id, publicKey)
if err != nil {
return nil, err
}
}
// Add all certificates.
for id, certificate := range bs.config.Certificates {
err = provider.SetCertificate(id, certificate)
if err != nil {
return nil, err
}
}
sk, ok := provider.GetSigningKey(bs.config.SigningMethod)
if !ok {
return nil, fmt.Errorf("no signing key for selected signing method")
}
if bs.config.SigningKeyID == "" {
// Ensure that there is a default signing Key ID even if none was set.
provider.SetValidationKey(DefaultSigningKeyID, sk.PrivateKey.Public())
}
logger.WithFields(logrus.Fields{
"id": sk.ID,
"method": fmt.Sprintf("%T", sk.SigningMethod),
"alg": sk.SigningMethod.Alg(),
}).Infoln("oidc token signing default set up")
return provider, nil
}
| setupGuest | identifier_name |
source.rs | //! Utils for extracting, inspecting or transforming source code
#![allow(clippy::module_name_repetitions)]
use crate::line_span;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LintContext};
use rustc_span::hygiene;
use rustc_span::{BytePos, Pos, Span, SyntaxContext};
use std::borrow::Cow;
/// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
/// Also takes an `Option<String>` which can be put inside the braces.
pub fn expr_block<'a, T: LintContext>(
cx: &T,
expr: &Expr<'_>,
option: Option<String>,
default: &'a str,
indent_relative_to: Option<Span>,
) -> Cow<'a, str> {
let code = snippet_block(cx, expr.span, default, indent_relative_to);
let string = option.unwrap_or_default();
if expr.span.from_expansion() {
Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
} else if let ExprKind::Block(_, _) = expr.kind {
Cow::Owned(format!("{}{}", code, string))
} else if string.is_empty() {
Cow::Owned(format!("{{ {} }}", code))
} else {
Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
}
}
/// Returns a new Span that extends the original Span to the first non-whitespace char of the first
/// line.
///
/// ```rust,ignore
/// let x = ();
/// // ^^
/// // will be converted to
/// let x = ();
/// // ^^^^^^^^^^
/// ```
pub fn first_line_of_span<T: LintContext>(cx: &T, span: Span) -> Span {
first_char_in_first_line(cx, span).map_or(span, |first_char_pos| span.with_lo(first_char_pos))
}
fn first_char_in_first_line<T: LintContext>(cx: &T, span: Span) -> Option<BytePos> {
let line_span = line_span(cx, span);
snippet_opt(cx, line_span).and_then(|snip| {
snip.find(|c: char| !c.is_whitespace())
.map(|pos| line_span.lo() + BytePos::from_usize(pos))
})
}
/// Returns the indentation of the line of a span
///
/// ```rust,ignore
/// let x = ();
/// // ^^ -- will return 0
/// let x = ();
/// // ^^ -- will return 4
/// ```
pub fn indent_of<T: LintContext>(cx: &T, span: Span) -> Option<usize> {
snippet_opt(cx, line_span(cx, span)).and_then(|snip| snip.find(|c: char| !c.is_whitespace()))
}
/// Gets a snippet of the indentation of the line of a span
pub fn snippet_indent<T: LintContext>(cx: &T, span: Span) -> Option<String> {
snippet_opt(cx, line_span(cx, span)).map(|mut s| {
let len = s.len() - s.trim_start().len();
s.truncate(len);
s
})
}
// If the snippet is empty, it's an attribute that was inserted during macro
// expansion and we want to ignore those, because they could come from external
// sources that the user has no control over.
// For some reason these attributes don't have any expansion info on them, so
// we have to check it this way until there is a better way.
pub fn is_present_in_source<T: LintContext>(cx: &T, span: Span) -> bool {
if let Some(snippet) = snippet_opt(cx, span) {
if snippet.is_empty() {
return false;
}
}
true
}
/// Returns the positon just before rarrow
///
/// ```rust,ignore
/// fn into(self) -> () {}
/// ^
/// // in case of unformatted code
/// fn into2(self)-> () {}
/// ^
/// fn into3(self) -> () {}
/// ^
/// ```
pub fn position_before_rarrow(s: &str) -> Option<usize> {
s.rfind("->").map(|rpos| {
let mut rpos = rpos;
let chars: Vec<char> = s.chars().collect();
while rpos > 1 {
if let Some(c) = chars.get(rpos - 1) {
if c.is_whitespace() {
rpos -= 1;
continue;
}
}
break;
}
rpos
})
}
/// Reindent a multiline string with possibility of ignoring the first line.
#[allow(clippy::needless_pass_by_value)]
pub fn reindent_multiline(s: Cow<'_, str>, ignore_first: bool, indent: Option<usize>) -> Cow<'_, str> {
let s_space = reindent_multiline_inner(&s, ignore_first, indent, ' ');
let s_tab = reindent_multiline_inner(&s_space, ignore_first, indent, '\t');
reindent_multiline_inner(&s_tab, ignore_first, indent, ' ').into()
}
fn reindent_multiline_inner(s: &str, ignore_first: bool, indent: Option<usize>, ch: char) -> String {
let x = s
.lines()
.skip(usize::from(ignore_first))
.filter_map(|l| {
if l.is_empty() {
None
} else {
// ignore empty lines
Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
}
})
.min()
.unwrap_or(0);
let indent = indent.unwrap_or(0);
s.lines()
.enumerate()
.map(|(i, l)| {
if (ignore_first && i == 0) || l.is_empty() {
l.to_owned()
} else if x > indent | else {
" ".repeat(indent - x) + l
}
})
.collect::<Vec<String>>()
.join("\n")
}
/// Converts a span to a code snippet if available, otherwise returns the default.
///
/// This is useful if you want to provide suggestions for your lint or more generally, if you want
/// to convert a given `Span` to a `str`. To create suggestions consider using
/// [`snippet_with_applicability`] to ensure that the applicability stays correct.
///
/// # Example
/// ```rust,ignore
/// // Given two spans one for `value` and one for the `init` expression.
/// let value = Vec::new();
/// // ^^^^^ ^^^^^^^^^^
/// // span1 span2
///
/// // The snipped call would return the corresponding code snippet
/// snippet(cx, span1, "..") // -> "value"
/// snippet(cx, span2, "..") // -> "Vec::new()"
/// ```
pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
}
/// Same as [`snippet`], but it adapts the applicability level by following rules:
///
/// - Applicability level `Unspecified` will never be changed.
/// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
/// - If the default value is used and the applicability level is `MachineApplicable`, change it to
/// `HasPlaceholders`
pub fn snippet_with_applicability<'a, T: LintContext>(
cx: &T,
span: Span,
default: &'a str,
applicability: &mut Applicability,
) -> Cow<'a, str> {
if *applicability != Applicability::Unspecified && span.from_expansion() {
*applicability = Applicability::MaybeIncorrect;
}
snippet_opt(cx, span).map_or_else(
|| {
if *applicability == Applicability::MachineApplicable {
*applicability = Applicability::HasPlaceholders;
}
Cow::Borrowed(default)
},
From::from,
)
}
/// Same as `snippet`, but should only be used when it's clear that the input span is
/// not a macro argument.
pub fn snippet_with_macro_callsite<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
snippet(cx, span.source_callsite(), default)
}
/// Converts a span to a code snippet. Returns `None` if not available.
pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
cx.sess().source_map().span_to_snippet(span).ok()
}
/// Converts a span (from a block) to a code snippet if available, otherwise use default.
///
/// This trims the code of indentation, except for the first line. Use it for blocks or block-like
/// things which need to be printed as such.
///
/// The `indent_relative_to` arg can be used, to provide a span, where the indentation of the
/// resulting snippet of the given span.
///
/// # Example
///
/// ```rust,ignore
/// snippet_block(cx, block.span, "..", None)
/// // where, `block` is the block of the if expr
/// if x {
/// y;
/// }
/// // will return the snippet
/// {
/// y;
/// }
/// ```
///
/// ```rust,ignore
/// snippet_block(cx, block.span, "..", Some(if_expr.span))
/// // where, `block` is the block of the if expr
/// if x {
/// y;
/// }
/// // will return the snippet
/// {
/// y;
/// } // aligned with `if`
/// ```
/// Note that the first line of the snippet always has 0 indentation.
pub fn snippet_block<'a, T: LintContext>(
cx: &T,
span: Span,
default: &'a str,
indent_relative_to: Option<Span>,
) -> Cow<'a, str> {
let snip = snippet(cx, span, default);
let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
reindent_multiline(snip, true, indent)
}
/// Same as `snippet_block`, but adapts the applicability level by the rules of
/// `snippet_with_applicability`.
pub fn snippet_block_with_applicability<'a, T: LintContext>(
cx: &T,
span: Span,
default: &'a str,
indent_relative_to: Option<Span>,
applicability: &mut Applicability,
) -> Cow<'a, str> {
let snip = snippet_with_applicability(cx, span, default, applicability);
let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
reindent_multiline(snip, true, indent)
}
/// Same as `snippet_with_applicability`, but first walks the span up to the given context. This
/// will result in the macro call, rather then the expansion, if the span is from a child context.
/// If the span is not from a child context, it will be used directly instead.
///
/// e.g. Given the expression `&vec![]`, getting a snippet from the span for `vec![]` as a HIR node
/// would result in `box []`. If given the context of the address of expression, this function will
/// correctly get a snippet of `vec![]`.
///
/// This will also return whether or not the snippet is a macro call.
pub fn snippet_with_context(
cx: &LateContext<'_>,
span: Span,
outer: SyntaxContext,
default: &'a str,
applicability: &mut Applicability,
) -> (Cow<'a, str>, bool) {
let (span, is_macro_call) = walk_span_to_context(span, outer).map_or_else(
|| {
// The span is from a macro argument, and the outer context is the macro using the argument
if *applicability != Applicability::Unspecified {
*applicability = Applicability::MaybeIncorrect;
}
// TODO: get the argument span.
(span, false)
},
|outer_span| (outer_span, span.ctxt() != outer),
);
(
snippet_with_applicability(cx, span, default, applicability),
is_macro_call,
)
}
/// Walks the span up to the target context, thereby returning the macro call site if the span is
/// inside a macro expansion, or the original span if it is not. Note this will return `None` in the
/// case of the span being in a macro expansion, but the target context is from expanding a macro
/// argument.
///
/// Given the following
///
/// ```rust,ignore
/// macro_rules! m { ($e:expr) => { f($e) }; }
/// g(m!(0))
/// ```
///
/// If called with a span of the call to `f` and a context of the call to `g` this will return a
/// span containing `m!(0)`. However, if called with a span of the literal `0` this will give a span
/// containing `0` as the context is the same as the outer context.
///
/// This will traverse through multiple macro calls. Given the following:
///
/// ```rust,ignore
/// macro_rules! m { ($e:expr) => { n!($e, 0) }; }
/// macro_rules! n { ($e:expr, $f:expr) => { f($e, $f) }; }
/// g(m!(0))
/// ```
///
/// If called with a span of the call to `f` and a context of the call to `g` this will return a
/// span containing `m!(0)`.
pub fn walk_span_to_context(span: Span, outer: SyntaxContext) -> Option<Span> {
let outer_span = hygiene::walk_chain(span, outer);
(outer_span.ctxt() == outer).then(|| outer_span)
}
/// Removes block comments from the given `Vec` of lines.
///
/// # Examples
///
/// ```rust,ignore
/// without_block_comments(vec!["/*", "foo", "*/"]);
/// // => vec![]
///
/// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
/// // => vec!["bar"]
/// ```
pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
let mut without = vec![];
let mut nest_level = 0;
for line in lines {
if line.contains("/*") {
nest_level += 1;
continue;
} else if line.contains("*/") {
nest_level -= 1;
continue;
}
if nest_level == 0 {
without.push(line);
}
}
without
}
#[cfg(test)]
mod test {
use super::{reindent_multiline, without_block_comments};
#[test]
fn test_reindent_multiline_single_line() {
assert_eq!("", reindent_multiline("".into(), false, None));
assert_eq!("...", reindent_multiline("...".into(), false, None));
assert_eq!("...", reindent_multiline(" ...".into(), false, None));
assert_eq!("...", reindent_multiline("\t...".into(), false, None));
assert_eq!("...", reindent_multiline("\t\t...".into(), false, None));
}
#[test]
#[rustfmt::skip]
fn test_reindent_multiline_block() {
assert_eq!("\
if x {
y
} else {
z
}", reindent_multiline(" if x {
y
} else {
z
}".into(), false, None));
assert_eq!("\
if x {
\ty
} else {
\tz
}", reindent_multiline(" if x {
\ty
} else {
\tz
}".into(), false, None));
}
#[test]
#[rustfmt::skip]
fn test_reindent_multiline_empty_line() {
assert_eq!("\
if x {
y
} else {
z
}", reindent_multiline(" if x {
y
} else {
z
}".into(), false, None));
}
#[test]
#[rustfmt::skip]
fn test_reindent_multiline_lines_deeper() {
assert_eq!("\
if x {
y
} else {
z
}", reindent_multiline("\
if x {
y
} else {
z
}".into(), true, Some(8)));
}
#[test]
fn test_without_block_comments_lines_without_block_comments() {
let result = without_block_comments(vec!["/*", "", "*/"]);
println!("result: {:?}", result);
assert!(result.is_empty());
let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
let result = without_block_comments(vec!["/* rust", "", "*/"]);
assert!(result.is_empty());
let result = without_block_comments(vec!["/* one-line comment */"]);
assert!(result.is_empty());
let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
assert!(result.is_empty());
let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
assert!(result.is_empty());
let result = without_block_comments(vec!["foo", "bar", "baz"]);
assert_eq!(result, vec!["foo", "bar", "baz"]);
}
}
| {
l.split_at(x - indent).1.to_owned()
} | conditional_block |
source.rs | //! Utils for extracting, inspecting or transforming source code
#![allow(clippy::module_name_repetitions)]
use crate::line_span;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LintContext};
use rustc_span::hygiene;
use rustc_span::{BytePos, Pos, Span, SyntaxContext};
use std::borrow::Cow;
/// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
/// Also takes an `Option<String>` which can be put inside the braces.
pub fn expr_block<'a, T: LintContext>(
cx: &T,
expr: &Expr<'_>,
option: Option<String>,
default: &'a str,
indent_relative_to: Option<Span>,
) -> Cow<'a, str> {
let code = snippet_block(cx, expr.span, default, indent_relative_to);
let string = option.unwrap_or_default();
if expr.span.from_expansion() {
Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
} else if let ExprKind::Block(_, _) = expr.kind {
Cow::Owned(format!("{}{}", code, string))
} else if string.is_empty() {
Cow::Owned(format!("{{ {} }}", code))
} else {
Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
}
}
/// Returns a new Span that extends the original Span to the first non-whitespace char of the first
/// line.
///
/// ```rust,ignore
/// let x = ();
/// // ^^
/// // will be converted to
/// let x = ();
/// // ^^^^^^^^^^
/// ```
pub fn first_line_of_span<T: LintContext>(cx: &T, span: Span) -> Span {
first_char_in_first_line(cx, span).map_or(span, |first_char_pos| span.with_lo(first_char_pos))
}
fn first_char_in_first_line<T: LintContext>(cx: &T, span: Span) -> Option<BytePos> {
let line_span = line_span(cx, span);
snippet_opt(cx, line_span).and_then(|snip| {
snip.find(|c: char| !c.is_whitespace())
.map(|pos| line_span.lo() + BytePos::from_usize(pos))
})
}
/// Returns the indentation of the line of a span
///
/// ```rust,ignore
/// let x = ();
/// // ^^ -- will return 0
/// let x = ();
/// // ^^ -- will return 4
/// ```
pub fn indent_of<T: LintContext>(cx: &T, span: Span) -> Option<usize> {
snippet_opt(cx, line_span(cx, span)).and_then(|snip| snip.find(|c: char| !c.is_whitespace()))
}
/// Gets a snippet of the indentation of the line of a span
pub fn snippet_indent<T: LintContext>(cx: &T, span: Span) -> Option<String> {
snippet_opt(cx, line_span(cx, span)).map(|mut s| {
let len = s.len() - s.trim_start().len();
s.truncate(len);
s
})
}
// If the snippet is empty, it's an attribute that was inserted during macro
// expansion and we want to ignore those, because they could come from external
// sources that the user has no control over.
// For some reason these attributes don't have any expansion info on them, so
// we have to check it this way until there is a better way.
pub fn is_present_in_source<T: LintContext>(cx: &T, span: Span) -> bool {
if let Some(snippet) = snippet_opt(cx, span) {
if snippet.is_empty() {
return false;
}
}
true
}
/// Returns the positon just before rarrow
///
/// ```rust,ignore
/// fn into(self) -> () {}
/// ^
/// // in case of unformatted code
/// fn into2(self)-> () {}
/// ^
/// fn into3(self) -> () {}
/// ^
/// ```
pub fn position_before_rarrow(s: &str) -> Option<usize> {
s.rfind("->").map(|rpos| {
let mut rpos = rpos;
let chars: Vec<char> = s.chars().collect();
while rpos > 1 {
if let Some(c) = chars.get(rpos - 1) {
if c.is_whitespace() {
rpos -= 1;
continue;
}
}
break;
}
rpos
})
}
/// Reindent a multiline string with possibility of ignoring the first line.
#[allow(clippy::needless_pass_by_value)]
pub fn reindent_multiline(s: Cow<'_, str>, ignore_first: bool, indent: Option<usize>) -> Cow<'_, str> {
let s_space = reindent_multiline_inner(&s, ignore_first, indent, ' ');
let s_tab = reindent_multiline_inner(&s_space, ignore_first, indent, '\t');
reindent_multiline_inner(&s_tab, ignore_first, indent, ' ').into()
}
fn reindent_multiline_inner(s: &str, ignore_first: bool, indent: Option<usize>, ch: char) -> String {
let x = s
.lines()
.skip(usize::from(ignore_first))
.filter_map(|l| {
if l.is_empty() {
None
} else {
// ignore empty lines
Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
}
})
.min()
.unwrap_or(0);
let indent = indent.unwrap_or(0);
s.lines()
.enumerate()
.map(|(i, l)| {
if (ignore_first && i == 0) || l.is_empty() {
l.to_owned()
} else if x > indent {
l.split_at(x - indent).1.to_owned()
} else {
" ".repeat(indent - x) + l
}
})
.collect::<Vec<String>>()
.join("\n") | /// Converts a span to a code snippet if available, otherwise returns the default.
///
/// This is useful if you want to provide suggestions for your lint or more generally, if you want
/// to convert a given `Span` to a `str`. To create suggestions consider using
/// [`snippet_with_applicability`] to ensure that the applicability stays correct.
///
/// # Example
/// ```rust,ignore
/// // Given two spans one for `value` and one for the `init` expression.
/// let value = Vec::new();
/// // ^^^^^ ^^^^^^^^^^
/// // span1 span2
///
/// // The snipped call would return the corresponding code snippet
/// snippet(cx, span1, "..") // -> "value"
/// snippet(cx, span2, "..") // -> "Vec::new()"
/// ```
pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
}
/// Same as [`snippet`], but it adapts the applicability level by following rules:
///
/// - Applicability level `Unspecified` will never be changed.
/// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
/// - If the default value is used and the applicability level is `MachineApplicable`, change it to
/// `HasPlaceholders`
pub fn snippet_with_applicability<'a, T: LintContext>(
cx: &T,
span: Span,
default: &'a str,
applicability: &mut Applicability,
) -> Cow<'a, str> {
if *applicability != Applicability::Unspecified && span.from_expansion() {
*applicability = Applicability::MaybeIncorrect;
}
snippet_opt(cx, span).map_or_else(
|| {
if *applicability == Applicability::MachineApplicable {
*applicability = Applicability::HasPlaceholders;
}
Cow::Borrowed(default)
},
From::from,
)
}
/// Same as `snippet`, but should only be used when it's clear that the input span is
/// not a macro argument.
pub fn snippet_with_macro_callsite<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
snippet(cx, span.source_callsite(), default)
}
/// Converts a span to a code snippet. Returns `None` if not available.
pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
cx.sess().source_map().span_to_snippet(span).ok()
}
/// Converts a span (from a block) to a code snippet if available, otherwise use default.
///
/// This trims the code of indentation, except for the first line. Use it for blocks or block-like
/// things which need to be printed as such.
///
/// The `indent_relative_to` arg can be used, to provide a span, where the indentation of the
/// resulting snippet of the given span.
///
/// # Example
///
/// ```rust,ignore
/// snippet_block(cx, block.span, "..", None)
/// // where, `block` is the block of the if expr
/// if x {
/// y;
/// }
/// // will return the snippet
/// {
/// y;
/// }
/// ```
///
/// ```rust,ignore
/// snippet_block(cx, block.span, "..", Some(if_expr.span))
/// // where, `block` is the block of the if expr
/// if x {
/// y;
/// }
/// // will return the snippet
/// {
/// y;
/// } // aligned with `if`
/// ```
/// Note that the first line of the snippet always has 0 indentation.
pub fn snippet_block<'a, T: LintContext>(
cx: &T,
span: Span,
default: &'a str,
indent_relative_to: Option<Span>,
) -> Cow<'a, str> {
let snip = snippet(cx, span, default);
let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
reindent_multiline(snip, true, indent)
}
/// Same as `snippet_block`, but adapts the applicability level by the rules of
/// `snippet_with_applicability`.
pub fn snippet_block_with_applicability<'a, T: LintContext>(
cx: &T,
span: Span,
default: &'a str,
indent_relative_to: Option<Span>,
applicability: &mut Applicability,
) -> Cow<'a, str> {
let snip = snippet_with_applicability(cx, span, default, applicability);
let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
reindent_multiline(snip, true, indent)
}
/// Same as `snippet_with_applicability`, but first walks the span up to the given context. This
/// will result in the macro call, rather then the expansion, if the span is from a child context.
/// If the span is not from a child context, it will be used directly instead.
///
/// e.g. Given the expression `&vec![]`, getting a snippet from the span for `vec![]` as a HIR node
/// would result in `box []`. If given the context of the address of expression, this function will
/// correctly get a snippet of `vec![]`.
///
/// This will also return whether or not the snippet is a macro call.
pub fn snippet_with_context(
cx: &LateContext<'_>,
span: Span,
outer: SyntaxContext,
default: &'a str,
applicability: &mut Applicability,
) -> (Cow<'a, str>, bool) {
let (span, is_macro_call) = walk_span_to_context(span, outer).map_or_else(
|| {
// The span is from a macro argument, and the outer context is the macro using the argument
if *applicability != Applicability::Unspecified {
*applicability = Applicability::MaybeIncorrect;
}
// TODO: get the argument span.
(span, false)
},
|outer_span| (outer_span, span.ctxt() != outer),
);
(
snippet_with_applicability(cx, span, default, applicability),
is_macro_call,
)
}
/// Walks the span up to the target context, thereby returning the macro call site if the span is
/// inside a macro expansion, or the original span if it is not. Note this will return `None` in the
/// case of the span being in a macro expansion, but the target context is from expanding a macro
/// argument.
///
/// Given the following
///
/// ```rust,ignore
/// macro_rules! m { ($e:expr) => { f($e) }; }
/// g(m!(0))
/// ```
///
/// If called with a span of the call to `f` and a context of the call to `g` this will return a
/// span containing `m!(0)`. However, if called with a span of the literal `0` this will give a span
/// containing `0` as the context is the same as the outer context.
///
/// This will traverse through multiple macro calls. Given the following:
///
/// ```rust,ignore
/// macro_rules! m { ($e:expr) => { n!($e, 0) }; }
/// macro_rules! n { ($e:expr, $f:expr) => { f($e, $f) }; }
/// g(m!(0))
/// ```
///
/// If called with a span of the call to `f` and a context of the call to `g` this will return a
/// span containing `m!(0)`.
pub fn walk_span_to_context(span: Span, outer: SyntaxContext) -> Option<Span> {
let outer_span = hygiene::walk_chain(span, outer);
(outer_span.ctxt() == outer).then(|| outer_span)
}
/// Removes block comments from the given `Vec` of lines.
///
/// # Examples
///
/// ```rust,ignore
/// without_block_comments(vec!["/*", "foo", "*/"]);
/// // => vec![]
///
/// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
/// // => vec!["bar"]
/// ```
pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
let mut without = vec![];
let mut nest_level = 0;
for line in lines {
if line.contains("/*") {
nest_level += 1;
continue;
} else if line.contains("*/") {
nest_level -= 1;
continue;
}
if nest_level == 0 {
without.push(line);
}
}
without
}
#[cfg(test)]
mod test {
use super::{reindent_multiline, without_block_comments};
#[test]
fn test_reindent_multiline_single_line() {
assert_eq!("", reindent_multiline("".into(), false, None));
assert_eq!("...", reindent_multiline("...".into(), false, None));
assert_eq!("...", reindent_multiline(" ...".into(), false, None));
assert_eq!("...", reindent_multiline("\t...".into(), false, None));
assert_eq!("...", reindent_multiline("\t\t...".into(), false, None));
}
#[test]
#[rustfmt::skip]
fn test_reindent_multiline_block() {
assert_eq!("\
if x {
y
} else {
z
}", reindent_multiline(" if x {
y
} else {
z
}".into(), false, None));
assert_eq!("\
if x {
\ty
} else {
\tz
}", reindent_multiline(" if x {
\ty
} else {
\tz
}".into(), false, None));
}
#[test]
#[rustfmt::skip]
fn test_reindent_multiline_empty_line() {
assert_eq!("\
if x {
y
} else {
z
}", reindent_multiline(" if x {
y
} else {
z
}".into(), false, None));
}
#[test]
#[rustfmt::skip]
fn test_reindent_multiline_lines_deeper() {
assert_eq!("\
if x {
y
} else {
z
}", reindent_multiline("\
if x {
y
} else {
z
}".into(), true, Some(8)));
}
#[test]
fn test_without_block_comments_lines_without_block_comments() {
let result = without_block_comments(vec!["/*", "", "*/"]);
println!("result: {:?}", result);
assert!(result.is_empty());
let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
let result = without_block_comments(vec!["/* rust", "", "*/"]);
assert!(result.is_empty());
let result = without_block_comments(vec!["/* one-line comment */"]);
assert!(result.is_empty());
let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
assert!(result.is_empty());
let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
assert!(result.is_empty());
let result = without_block_comments(vec!["foo", "bar", "baz"]);
assert_eq!(result, vec!["foo", "bar", "baz"]);
}
} | }
| random_line_split |
source.rs | //! Utils for extracting, inspecting or transforming source code
#![allow(clippy::module_name_repetitions)]
use crate::line_span;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LintContext};
use rustc_span::hygiene;
use rustc_span::{BytePos, Pos, Span, SyntaxContext};
use std::borrow::Cow;
/// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
/// Also takes an `Option<String>` which can be put inside the braces.
pub fn | <'a, T: LintContext>(
cx: &T,
expr: &Expr<'_>,
option: Option<String>,
default: &'a str,
indent_relative_to: Option<Span>,
) -> Cow<'a, str> {
let code = snippet_block(cx, expr.span, default, indent_relative_to);
let string = option.unwrap_or_default();
if expr.span.from_expansion() {
Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
} else if let ExprKind::Block(_, _) = expr.kind {
Cow::Owned(format!("{}{}", code, string))
} else if string.is_empty() {
Cow::Owned(format!("{{ {} }}", code))
} else {
Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
}
}
/// Returns a new Span that extends the original Span to the first non-whitespace char of the first
/// line.
///
/// ```rust,ignore
/// let x = ();
/// // ^^
/// // will be converted to
/// let x = ();
/// // ^^^^^^^^^^
/// ```
pub fn first_line_of_span<T: LintContext>(cx: &T, span: Span) -> Span {
first_char_in_first_line(cx, span).map_or(span, |first_char_pos| span.with_lo(first_char_pos))
}
fn first_char_in_first_line<T: LintContext>(cx: &T, span: Span) -> Option<BytePos> {
let line_span = line_span(cx, span);
snippet_opt(cx, line_span).and_then(|snip| {
snip.find(|c: char| !c.is_whitespace())
.map(|pos| line_span.lo() + BytePos::from_usize(pos))
})
}
/// Returns the indentation of the line of a span
///
/// ```rust,ignore
/// let x = ();
/// // ^^ -- will return 0
/// let x = ();
/// // ^^ -- will return 4
/// ```
pub fn indent_of<T: LintContext>(cx: &T, span: Span) -> Option<usize> {
snippet_opt(cx, line_span(cx, span)).and_then(|snip| snip.find(|c: char| !c.is_whitespace()))
}
/// Gets a snippet of the indentation of the line of a span
pub fn snippet_indent<T: LintContext>(cx: &T, span: Span) -> Option<String> {
snippet_opt(cx, line_span(cx, span)).map(|mut s| {
let len = s.len() - s.trim_start().len();
s.truncate(len);
s
})
}
// If the snippet is empty, it's an attribute that was inserted during macro
// expansion and we want to ignore those, because they could come from external
// sources that the user has no control over.
// For some reason these attributes don't have any expansion info on them, so
// we have to check it this way until there is a better way.
pub fn is_present_in_source<T: LintContext>(cx: &T, span: Span) -> bool {
if let Some(snippet) = snippet_opt(cx, span) {
if snippet.is_empty() {
return false;
}
}
true
}
/// Returns the positon just before rarrow
///
/// ```rust,ignore
/// fn into(self) -> () {}
/// ^
/// // in case of unformatted code
/// fn into2(self)-> () {}
/// ^
/// fn into3(self) -> () {}
/// ^
/// ```
pub fn position_before_rarrow(s: &str) -> Option<usize> {
s.rfind("->").map(|rpos| {
let mut rpos = rpos;
let chars: Vec<char> = s.chars().collect();
while rpos > 1 {
if let Some(c) = chars.get(rpos - 1) {
if c.is_whitespace() {
rpos -= 1;
continue;
}
}
break;
}
rpos
})
}
/// Reindent a multiline string with possibility of ignoring the first line.
#[allow(clippy::needless_pass_by_value)]
pub fn reindent_multiline(s: Cow<'_, str>, ignore_first: bool, indent: Option<usize>) -> Cow<'_, str> {
let s_space = reindent_multiline_inner(&s, ignore_first, indent, ' ');
let s_tab = reindent_multiline_inner(&s_space, ignore_first, indent, '\t');
reindent_multiline_inner(&s_tab, ignore_first, indent, ' ').into()
}
fn reindent_multiline_inner(s: &str, ignore_first: bool, indent: Option<usize>, ch: char) -> String {
let x = s
.lines()
.skip(usize::from(ignore_first))
.filter_map(|l| {
if l.is_empty() {
None
} else {
// ignore empty lines
Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
}
})
.min()
.unwrap_or(0);
let indent = indent.unwrap_or(0);
s.lines()
.enumerate()
.map(|(i, l)| {
if (ignore_first && i == 0) || l.is_empty() {
l.to_owned()
} else if x > indent {
l.split_at(x - indent).1.to_owned()
} else {
" ".repeat(indent - x) + l
}
})
.collect::<Vec<String>>()
.join("\n")
}
/// Converts a span to a code snippet if available, otherwise returns the default.
///
/// This is useful if you want to provide suggestions for your lint or more generally, if you want
/// to convert a given `Span` to a `str`. To create suggestions consider using
/// [`snippet_with_applicability`] to ensure that the applicability stays correct.
///
/// # Example
/// ```rust,ignore
/// // Given two spans one for `value` and one for the `init` expression.
/// let value = Vec::new();
/// // ^^^^^ ^^^^^^^^^^
/// // span1 span2
///
/// // The snipped call would return the corresponding code snippet
/// snippet(cx, span1, "..") // -> "value"
/// snippet(cx, span2, "..") // -> "Vec::new()"
/// ```
pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
}
/// Same as [`snippet`], but it adapts the applicability level by following rules:
///
/// - Applicability level `Unspecified` will never be changed.
/// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
/// - If the default value is used and the applicability level is `MachineApplicable`, change it to
/// `HasPlaceholders`
pub fn snippet_with_applicability<'a, T: LintContext>(
cx: &T,
span: Span,
default: &'a str,
applicability: &mut Applicability,
) -> Cow<'a, str> {
if *applicability != Applicability::Unspecified && span.from_expansion() {
*applicability = Applicability::MaybeIncorrect;
}
snippet_opt(cx, span).map_or_else(
|| {
if *applicability == Applicability::MachineApplicable {
*applicability = Applicability::HasPlaceholders;
}
Cow::Borrowed(default)
},
From::from,
)
}
/// Same as `snippet`, but should only be used when it's clear that the input span is
/// not a macro argument.
pub fn snippet_with_macro_callsite<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
snippet(cx, span.source_callsite(), default)
}
/// Converts a span to a code snippet. Returns `None` if not available.
pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
cx.sess().source_map().span_to_snippet(span).ok()
}
/// Converts a span (from a block) to a code snippet if available, otherwise use default.
///
/// This trims the code of indentation, except for the first line. Use it for blocks or block-like
/// things which need to be printed as such.
///
/// The `indent_relative_to` arg can be used, to provide a span, where the indentation of the
/// resulting snippet of the given span.
///
/// # Example
///
/// ```rust,ignore
/// snippet_block(cx, block.span, "..", None)
/// // where, `block` is the block of the if expr
/// if x {
/// y;
/// }
/// // will return the snippet
/// {
/// y;
/// }
/// ```
///
/// ```rust,ignore
/// snippet_block(cx, block.span, "..", Some(if_expr.span))
/// // where, `block` is the block of the if expr
/// if x {
/// y;
/// }
/// // will return the snippet
/// {
/// y;
/// } // aligned with `if`
/// ```
/// Note that the first line of the snippet always has 0 indentation.
pub fn snippet_block<'a, T: LintContext>(
cx: &T,
span: Span,
default: &'a str,
indent_relative_to: Option<Span>,
) -> Cow<'a, str> {
let snip = snippet(cx, span, default);
let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
reindent_multiline(snip, true, indent)
}
/// Same as `snippet_block`, but adapts the applicability level by the rules of
/// `snippet_with_applicability`.
pub fn snippet_block_with_applicability<'a, T: LintContext>(
cx: &T,
span: Span,
default: &'a str,
indent_relative_to: Option<Span>,
applicability: &mut Applicability,
) -> Cow<'a, str> {
let snip = snippet_with_applicability(cx, span, default, applicability);
let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
reindent_multiline(snip, true, indent)
}
/// Same as `snippet_with_applicability`, but first walks the span up to the given context. This
/// will result in the macro call, rather then the expansion, if the span is from a child context.
/// If the span is not from a child context, it will be used directly instead.
///
/// e.g. Given the expression `&vec![]`, getting a snippet from the span for `vec![]` as a HIR node
/// would result in `box []`. If given the context of the address of expression, this function will
/// correctly get a snippet of `vec![]`.
///
/// This will also return whether or not the snippet is a macro call.
pub fn snippet_with_context(
cx: &LateContext<'_>,
span: Span,
outer: SyntaxContext,
default: &'a str,
applicability: &mut Applicability,
) -> (Cow<'a, str>, bool) {
let (span, is_macro_call) = walk_span_to_context(span, outer).map_or_else(
|| {
// The span is from a macro argument, and the outer context is the macro using the argument
if *applicability != Applicability::Unspecified {
*applicability = Applicability::MaybeIncorrect;
}
// TODO: get the argument span.
(span, false)
},
|outer_span| (outer_span, span.ctxt() != outer),
);
(
snippet_with_applicability(cx, span, default, applicability),
is_macro_call,
)
}
/// Walks the span up to the target context, thereby returning the macro call site if the span is
/// inside a macro expansion, or the original span if it is not. Note this will return `None` in the
/// case of the span being in a macro expansion, but the target context is from expanding a macro
/// argument.
///
/// Given the following
///
/// ```rust,ignore
/// macro_rules! m { ($e:expr) => { f($e) }; }
/// g(m!(0))
/// ```
///
/// If called with a span of the call to `f` and a context of the call to `g` this will return a
/// span containing `m!(0)`. However, if called with a span of the literal `0` this will give a span
/// containing `0` as the context is the same as the outer context.
///
/// This will traverse through multiple macro calls. Given the following:
///
/// ```rust,ignore
/// macro_rules! m { ($e:expr) => { n!($e, 0) }; }
/// macro_rules! n { ($e:expr, $f:expr) => { f($e, $f) }; }
/// g(m!(0))
/// ```
///
/// If called with a span of the call to `f` and a context of the call to `g` this will return a
/// span containing `m!(0)`.
pub fn walk_span_to_context(span: Span, outer: SyntaxContext) -> Option<Span> {
let outer_span = hygiene::walk_chain(span, outer);
(outer_span.ctxt() == outer).then(|| outer_span)
}
/// Removes block comments from the given `Vec` of lines.
///
/// # Examples
///
/// ```rust,ignore
/// without_block_comments(vec!["/*", "foo", "*/"]);
/// // => vec![]
///
/// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
/// // => vec!["bar"]
/// ```
pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
let mut without = vec![];
let mut nest_level = 0;
for line in lines {
if line.contains("/*") {
nest_level += 1;
continue;
} else if line.contains("*/") {
nest_level -= 1;
continue;
}
if nest_level == 0 {
without.push(line);
}
}
without
}
#[cfg(test)]
mod test {
use super::{reindent_multiline, without_block_comments};
#[test]
fn test_reindent_multiline_single_line() {
assert_eq!("", reindent_multiline("".into(), false, None));
assert_eq!("...", reindent_multiline("...".into(), false, None));
assert_eq!("...", reindent_multiline(" ...".into(), false, None));
assert_eq!("...", reindent_multiline("\t...".into(), false, None));
assert_eq!("...", reindent_multiline("\t\t...".into(), false, None));
}
#[test]
#[rustfmt::skip]
fn test_reindent_multiline_block() {
assert_eq!("\
if x {
y
} else {
z
}", reindent_multiline(" if x {
y
} else {
z
}".into(), false, None));
assert_eq!("\
if x {
\ty
} else {
\tz
}", reindent_multiline(" if x {
\ty
} else {
\tz
}".into(), false, None));
}
#[test]
#[rustfmt::skip]
fn test_reindent_multiline_empty_line() {
assert_eq!("\
if x {
y
} else {
z
}", reindent_multiline(" if x {
y
} else {
z
}".into(), false, None));
}
#[test]
#[rustfmt::skip]
fn test_reindent_multiline_lines_deeper() {
assert_eq!("\
if x {
y
} else {
z
}", reindent_multiline("\
if x {
y
} else {
z
}".into(), true, Some(8)));
}
#[test]
fn test_without_block_comments_lines_without_block_comments() {
let result = without_block_comments(vec!["/*", "", "*/"]);
println!("result: {:?}", result);
assert!(result.is_empty());
let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
let result = without_block_comments(vec!["/* rust", "", "*/"]);
assert!(result.is_empty());
let result = without_block_comments(vec!["/* one-line comment */"]);
assert!(result.is_empty());
let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
assert!(result.is_empty());
let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
assert!(result.is_empty());
let result = without_block_comments(vec!["foo", "bar", "baz"]);
assert_eq!(result, vec!["foo", "bar", "baz"]);
}
}
| expr_block | identifier_name |
source.rs | //! Utils for extracting, inspecting or transforming source code
#![allow(clippy::module_name_repetitions)]
use crate::line_span;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LintContext};
use rustc_span::hygiene;
use rustc_span::{BytePos, Pos, Span, SyntaxContext};
use std::borrow::Cow;
/// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
/// Also takes an `Option<String>` which can be put inside the braces.
pub fn expr_block<'a, T: LintContext>(
cx: &T,
expr: &Expr<'_>,
option: Option<String>,
default: &'a str,
indent_relative_to: Option<Span>,
) -> Cow<'a, str> {
let code = snippet_block(cx, expr.span, default, indent_relative_to);
let string = option.unwrap_or_default();
if expr.span.from_expansion() {
Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
} else if let ExprKind::Block(_, _) = expr.kind {
Cow::Owned(format!("{}{}", code, string))
} else if string.is_empty() {
Cow::Owned(format!("{{ {} }}", code))
} else {
Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
}
}
/// Returns a new Span that extends the original Span to the first non-whitespace char of the first
/// line.
///
/// ```rust,ignore
/// let x = ();
/// // ^^
/// // will be converted to
/// let x = ();
/// // ^^^^^^^^^^
/// ```
pub fn first_line_of_span<T: LintContext>(cx: &T, span: Span) -> Span {
first_char_in_first_line(cx, span).map_or(span, |first_char_pos| span.with_lo(first_char_pos))
}
fn first_char_in_first_line<T: LintContext>(cx: &T, span: Span) -> Option<BytePos> {
let line_span = line_span(cx, span);
snippet_opt(cx, line_span).and_then(|snip| {
snip.find(|c: char| !c.is_whitespace())
.map(|pos| line_span.lo() + BytePos::from_usize(pos))
})
}
/// Returns the indentation of the line of a span
///
/// ```rust,ignore
/// let x = ();
/// // ^^ -- will return 0
/// let x = ();
/// // ^^ -- will return 4
/// ```
pub fn indent_of<T: LintContext>(cx: &T, span: Span) -> Option<usize> {
snippet_opt(cx, line_span(cx, span)).and_then(|snip| snip.find(|c: char| !c.is_whitespace()))
}
/// Gets a snippet of the indentation of the line of a span
pub fn snippet_indent<T: LintContext>(cx: &T, span: Span) -> Option<String> {
snippet_opt(cx, line_span(cx, span)).map(|mut s| {
let len = s.len() - s.trim_start().len();
s.truncate(len);
s
})
}
// If the snippet is empty, it's an attribute that was inserted during macro
// expansion and we want to ignore those, because they could come from external
// sources that the user has no control over.
// For some reason these attributes don't have any expansion info on them, so
// we have to check it this way until there is a better way.
pub fn is_present_in_source<T: LintContext>(cx: &T, span: Span) -> bool {
if let Some(snippet) = snippet_opt(cx, span) {
if snippet.is_empty() {
return false;
}
}
true
}
/// Returns the positon just before rarrow
///
/// ```rust,ignore
/// fn into(self) -> () {}
/// ^
/// // in case of unformatted code
/// fn into2(self)-> () {}
/// ^
/// fn into3(self) -> () {}
/// ^
/// ```
pub fn position_before_rarrow(s: &str) -> Option<usize> {
s.rfind("->").map(|rpos| {
let mut rpos = rpos;
let chars: Vec<char> = s.chars().collect();
while rpos > 1 {
if let Some(c) = chars.get(rpos - 1) {
if c.is_whitespace() {
rpos -= 1;
continue;
}
}
break;
}
rpos
})
}
/// Reindent a multiline string with possibility of ignoring the first line.
#[allow(clippy::needless_pass_by_value)]
pub fn reindent_multiline(s: Cow<'_, str>, ignore_first: bool, indent: Option<usize>) -> Cow<'_, str> {
let s_space = reindent_multiline_inner(&s, ignore_first, indent, ' ');
let s_tab = reindent_multiline_inner(&s_space, ignore_first, indent, '\t');
reindent_multiline_inner(&s_tab, ignore_first, indent, ' ').into()
}
fn reindent_multiline_inner(s: &str, ignore_first: bool, indent: Option<usize>, ch: char) -> String {
let x = s
.lines()
.skip(usize::from(ignore_first))
.filter_map(|l| {
if l.is_empty() {
None
} else {
// ignore empty lines
Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
}
})
.min()
.unwrap_or(0);
let indent = indent.unwrap_or(0);
s.lines()
.enumerate()
.map(|(i, l)| {
if (ignore_first && i == 0) || l.is_empty() {
l.to_owned()
} else if x > indent {
l.split_at(x - indent).1.to_owned()
} else {
" ".repeat(indent - x) + l
}
})
.collect::<Vec<String>>()
.join("\n")
}
/// Converts a span to a code snippet if available, otherwise returns the default.
///
/// This is useful if you want to provide suggestions for your lint or more generally, if you want
/// to convert a given `Span` to a `str`. To create suggestions consider using
/// [`snippet_with_applicability`] to ensure that the applicability stays correct.
///
/// # Example
/// ```rust,ignore
/// // Given two spans one for `value` and one for the `init` expression.
/// let value = Vec::new();
/// // ^^^^^ ^^^^^^^^^^
/// // span1 span2
///
/// // The snipped call would return the corresponding code snippet
/// snippet(cx, span1, "..") // -> "value"
/// snippet(cx, span2, "..") // -> "Vec::new()"
/// ```
pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
}
/// Same as [`snippet`], but it adapts the applicability level by following rules:
///
/// - Applicability level `Unspecified` will never be changed.
/// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
/// - If the default value is used and the applicability level is `MachineApplicable`, change it to
/// `HasPlaceholders`
pub fn snippet_with_applicability<'a, T: LintContext>(
cx: &T,
span: Span,
default: &'a str,
applicability: &mut Applicability,
) -> Cow<'a, str> |
/// Same as `snippet`, but should only be used when it's clear that the input span is
/// not a macro argument.
pub fn snippet_with_macro_callsite<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
snippet(cx, span.source_callsite(), default)
}
/// Converts a span to a code snippet. Returns `None` if not available.
pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
cx.sess().source_map().span_to_snippet(span).ok()
}
/// Converts a span (from a block) to a code snippet if available, otherwise use default.
///
/// This trims the code of indentation, except for the first line. Use it for blocks or block-like
/// things which need to be printed as such.
///
/// The `indent_relative_to` arg can be used, to provide a span, where the indentation of the
/// resulting snippet of the given span.
///
/// # Example
///
/// ```rust,ignore
/// snippet_block(cx, block.span, "..", None)
/// // where, `block` is the block of the if expr
/// if x {
/// y;
/// }
/// // will return the snippet
/// {
/// y;
/// }
/// ```
///
/// ```rust,ignore
/// snippet_block(cx, block.span, "..", Some(if_expr.span))
/// // where, `block` is the block of the if expr
/// if x {
/// y;
/// }
/// // will return the snippet
/// {
/// y;
/// } // aligned with `if`
/// ```
/// Note that the first line of the snippet always has 0 indentation.
pub fn snippet_block<'a, T: LintContext>(
cx: &T,
span: Span,
default: &'a str,
indent_relative_to: Option<Span>,
) -> Cow<'a, str> {
let snip = snippet(cx, span, default);
let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
reindent_multiline(snip, true, indent)
}
/// Same as `snippet_block`, but adapts the applicability level by the rules of
/// `snippet_with_applicability`.
pub fn snippet_block_with_applicability<'a, T: LintContext>(
cx: &T,
span: Span,
default: &'a str,
indent_relative_to: Option<Span>,
applicability: &mut Applicability,
) -> Cow<'a, str> {
let snip = snippet_with_applicability(cx, span, default, applicability);
let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
reindent_multiline(snip, true, indent)
}
/// Same as `snippet_with_applicability`, but first walks the span up to the given context. This
/// will result in the macro call, rather then the expansion, if the span is from a child context.
/// If the span is not from a child context, it will be used directly instead.
///
/// e.g. Given the expression `&vec![]`, getting a snippet from the span for `vec![]` as a HIR node
/// would result in `box []`. If given the context of the address of expression, this function will
/// correctly get a snippet of `vec![]`.
///
/// This will also return whether or not the snippet is a macro call.
pub fn snippet_with_context(
cx: &LateContext<'_>,
span: Span,
outer: SyntaxContext,
default: &'a str,
applicability: &mut Applicability,
) -> (Cow<'a, str>, bool) {
let (span, is_macro_call) = walk_span_to_context(span, outer).map_or_else(
|| {
// The span is from a macro argument, and the outer context is the macro using the argument
if *applicability != Applicability::Unspecified {
*applicability = Applicability::MaybeIncorrect;
}
// TODO: get the argument span.
(span, false)
},
|outer_span| (outer_span, span.ctxt() != outer),
);
(
snippet_with_applicability(cx, span, default, applicability),
is_macro_call,
)
}
/// Walks the span up to the target context, thereby returning the macro call site if the span is
/// inside a macro expansion, or the original span if it is not. Note this will return `None` in the
/// case of the span being in a macro expansion, but the target context is from expanding a macro
/// argument.
///
/// Given the following
///
/// ```rust,ignore
/// macro_rules! m { ($e:expr) => { f($e) }; }
/// g(m!(0))
/// ```
///
/// If called with a span of the call to `f` and a context of the call to `g` this will return a
/// span containing `m!(0)`. However, if called with a span of the literal `0` this will give a span
/// containing `0` as the context is the same as the outer context.
///
/// This will traverse through multiple macro calls. Given the following:
///
/// ```rust,ignore
/// macro_rules! m { ($e:expr) => { n!($e, 0) }; }
/// macro_rules! n { ($e:expr, $f:expr) => { f($e, $f) }; }
/// g(m!(0))
/// ```
///
/// If called with a span of the call to `f` and a context of the call to `g` this will return a
/// span containing `m!(0)`.
pub fn walk_span_to_context(span: Span, outer: SyntaxContext) -> Option<Span> {
let outer_span = hygiene::walk_chain(span, outer);
(outer_span.ctxt() == outer).then(|| outer_span)
}
/// Removes block comments from the given `Vec` of lines.
///
/// # Examples
///
/// ```rust,ignore
/// without_block_comments(vec!["/*", "foo", "*/"]);
/// // => vec![]
///
/// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
/// // => vec!["bar"]
/// ```
pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
let mut without = vec![];
let mut nest_level = 0;
for line in lines {
if line.contains("/*") {
nest_level += 1;
continue;
} else if line.contains("*/") {
nest_level -= 1;
continue;
}
if nest_level == 0 {
without.push(line);
}
}
without
}
#[cfg(test)]
mod test {
use super::{reindent_multiline, without_block_comments};
#[test]
fn test_reindent_multiline_single_line() {
assert_eq!("", reindent_multiline("".into(), false, None));
assert_eq!("...", reindent_multiline("...".into(), false, None));
assert_eq!("...", reindent_multiline(" ...".into(), false, None));
assert_eq!("...", reindent_multiline("\t...".into(), false, None));
assert_eq!("...", reindent_multiline("\t\t...".into(), false, None));
}
#[test]
#[rustfmt::skip]
fn test_reindent_multiline_block() {
assert_eq!("\
if x {
y
} else {
z
}", reindent_multiline(" if x {
y
} else {
z
}".into(), false, None));
assert_eq!("\
if x {
\ty
} else {
\tz
}", reindent_multiline(" if x {
\ty
} else {
\tz
}".into(), false, None));
}
#[test]
#[rustfmt::skip]
fn test_reindent_multiline_empty_line() {
assert_eq!("\
if x {
y
} else {
z
}", reindent_multiline(" if x {
y
} else {
z
}".into(), false, None));
}
#[test]
#[rustfmt::skip]
fn test_reindent_multiline_lines_deeper() {
assert_eq!("\
if x {
y
} else {
z
}", reindent_multiline("\
if x {
y
} else {
z
}".into(), true, Some(8)));
}
#[test]
fn test_without_block_comments_lines_without_block_comments() {
let result = without_block_comments(vec!["/*", "", "*/"]);
println!("result: {:?}", result);
assert!(result.is_empty());
let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
let result = without_block_comments(vec!["/* rust", "", "*/"]);
assert!(result.is_empty());
let result = without_block_comments(vec!["/* one-line comment */"]);
assert!(result.is_empty());
let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
assert!(result.is_empty());
let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
assert!(result.is_empty());
let result = without_block_comments(vec!["foo", "bar", "baz"]);
assert_eq!(result, vec!["foo", "bar", "baz"]);
}
}
| {
if *applicability != Applicability::Unspecified && span.from_expansion() {
*applicability = Applicability::MaybeIncorrect;
}
snippet_opt(cx, span).map_or_else(
|| {
if *applicability == Applicability::MachineApplicable {
*applicability = Applicability::HasPlaceholders;
}
Cow::Borrowed(default)
},
From::from,
)
} | identifier_body |
ogre_unit.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''Simple Python-Ogre application functions.
Derived from SampleFramework, reimplemented as a toolkit for agile prototyping or succinct unit-testing. Assemble an application from the functions.
'''
__author__ = 'Ethan Kennerly'
import ogre.renderer.OGRE as ogre
import ogre.io.OIS as OIS
import code_util
def getPluginPath():
"""Return the absolute path to a valid plugins.cfg file.
Copied from sf_OIS.py"""
import sys
import os
import os.path
paths = [os.path.join(os.getcwd(), 'plugins.cfg'),
'/etc/OGRE/plugins.cfg',
os.path.join(os.path.dirname(os.path.abspath(__file__)),
'plugins.cfg')]
for path in paths:
if os.path.exists(path):
return path
sys.stderr.write("\n"
"** Warning: Unable to locate a suitable plugins.cfg file.\n"
"** Warning: Please check your ogre installation and copy a\n"
"** Warning: working plugins.cfg file to the current directory.\n\n")
raise ogre.Exception(0, "can't locate the 'plugins.cfg' file", "")
def setup_resources(resources_path = 'resources.cfg'):
'''Load resources, such as from 'resources.cfg'.'''
config = ogre.ConfigFile()
config.load(resources_path)
section_iter = config.getSectionIterator()
while section_iter.hasMoreElements():
section_name = section_iter.peekNextKey()
settings = section_iter.getNext()
for item in settings:
ogre.ResourceGroupManager.getSingleton().addResourceLocation(item.value, item.key, section_name)
def setup_root(plugins_path = getPluginPath(),
resources_path = 'resources.cfg'):
'''Return new root, sceneManager.'''
root = ogre.Root(plugins_path)
root.setFrameSmoothingPeriod(5.0)
setup_resources(resources_path)
sceneManager = root.createSceneManager(ogre.ST_GENERIC,"ExampleSMInstance")
return root, sceneManager
def initialise_null_render(plugins_path = getPluginPath()):
'Prepare to null renderer and return ogre root.'
ogre_root = ogre.Root(plugins_path)
rend_list = ogre_root.getAvailableRenderers()
ogre_root.setRenderSystem(rend_list[-1])
ogre_root.getRenderSystem()._initRenderTargets()
ogre_root.initialise(False)
return ogre_root
def setup_null_root(plugins_path = getPluginPath(),
resources_path = 'resources.cfg'):
'''Return root, sceneManager. Suitable for unit test without entity, camera, light.
>>> logManager, logListener = quiet_log()
>>> root, sceneManager = setup_null_root()
>>> assert root
>>> assert sceneManager
>>> for i in range(10):
... if not renderOneFrame(root): print False
>>> del sceneManager, root
>>> del logManager, logListener
'''
root = initialise_null_render(plugins_path)
setup_resources(resources_path)
sceneManager = root.createSceneManager(ogre.ST_GENERIC,"ExampleSMInstance")
return root, sceneManager
def setup_viewport(root, sceneManager):
'''Create render window and viewport from user selection, and return renderWindow and camera.'''
renderWindow = configure(root)
if not renderWindow:
return None
camera = sceneManager.createCamera('Camera')
viewport = renderWindow.addViewport(camera)
return renderWindow, camera
def configure(ogre_root):
"""This shows the config dialog and returns the renderWindow."""
user_confirmation = ogre_root.showConfigDialog()
if user_confirmation:
return ogre_root.initialise(True, "OGRE Render Window")
else:
return None
def setup_unittest():
'''With tiny render window and resources. Return root and sceneManager.
>>> logManager, logListener = quiet_log()
>>> root, sceneManager, renderWindow, camera = setup_unittest()
>>> assert root
>>> assert sceneManager
>>> assert renderWindow
>>> assert camera
>>> del sceneManager, root, renderWindow, camera
>>> del logManager, logListener
'''
root, sceneManager = setup_null_root()
renderWindow = root.createRenderWindow('test', 4, 3, False)
camera = sceneManager.createCamera('Camera')
ogre.ResourceGroupManager.getSingleton().initialiseAllResourceGroups()
return root, sceneManager, renderWindow, camera
def setup():
'''Set up minimal Ogre application and return root and sceneManager.
>>> logManager, logListener = quiet_log()
# TODO: Doctest crashes, although external call to setup works!
#>>> root, sceneManager, renderWindow, camera = setup()
#>>> assert root
#>>> assert sceneManager
#>>> assert renderWindow
#>>> assert camera
#>>> application = setup_quiet_application(setup_unittest)
#>>> for i in range(10):
#... print i,
#... if not renderOneFrame(root): print False
#0 1 2 3 4 5 6 7 8 9
#>>> sceneManager.clearScene()
#>>> del renderWindow
#>>> del camera
#>>> del sceneManager
#>>> del root
>>> del logManager, logListener
'''
root, sceneManager = setup_root()
renderWindow, camera = setup_viewport(root, sceneManager)
ogre.TextureManager.getSingleton().setDefaultNumMipmaps(5)
ogre.ResourceGroupManager.getSingleton().initialiseAllResourceGroups()
return root, sceneManager, renderWindow, camera
def run(root, sceneManager, renderWindow, camera):
'''Construct and render.'''
root, sceneManager, renderWindow, camera = setup()
if root and sceneManager:
root.startRendering()
def renderOneFrame(ogre_root):
'Render a frame. Return False if closed. Useful for unit test.'
ogre.WindowEventUtilities().messagePump()
return ogre_root.renderOneFrame()
# For applications that do not have logListener attribute.
logListener = None
logManager = None
| class quiet_logListener_class(ogre.LogListener):
def messageLogged(self, message, level, debug, logName):
'''Called by Ogre instead of logging.'''
pass
#print message
def quiet_log():
'''Replace log with quiet version. Useful for unit test.
Return logManager and logListener, which must destructed AFTER root.
>>> logManager, logListener = quiet_log()
>>> root, sceneManager, renderWindow, camera = setup_unittest()
Gotcha: If you encounter 'R6025 Pure virtual function call' error within a class, then write destructor to destroy root before logManager and logListener. http://www.indiegamer.com/archives/t-3533.html
>>> del root
>>> del sceneManager, renderWindow, camera
>>> del logManager, logListener
Derived from examples:
http://www.ogre3d.org/phpBB2addons/viewtopic.php?p=10887&sid=ce193664e1d3d7c4af509e6f4e2718c6
http://wiki.python-ogre.org/index.php/ChangeLog
'''
logManager = ogre.LogManager()
log = ogre.LogManager.getSingletonPtr().createLog(
'quiet.log', True, False, True)
logListener = quiet_logListener_class()
log.addListener(logListener)
return logManager, logListener
class application_class(object):
'''Minimal Ogre application, which needs reference to root.
>>> application = setup_quiet_application(setup_unittest)
>>> for i in range(10):
... print i,
... if not renderOneFrame(application.root): print False
0 1 2 3 4 5 6 7 8 9
>>> assert application
'''
def __init__(self):
self.root = None
self.sceneManager = None
self.renderWindow = None
self.camera = None
# For quiet_log
self.logManager = None
self.logListener = None
def __del__(self):
del self.sceneManager
del self.root
del self.renderWindow
del self.camera
# Must delete root before logManager and logListener
del self.logListener
del self.logManager
def setup_quiet_application(setup_function = setup, application = None):
'''Return a minimal, application with logging disabled.
>>> application = setup_quiet_application(setup_unittest)
Alternatively try to make an application be quiet.
>>> application = application_class()
>>> application = setup_quiet_application(setup_unittest, application)
'''
if not application:
application = application_class()
if hasattr(application, 'logManager') \
and hasattr(application, 'logListener'):
if quiet_logListener_class != type(application.logListener):
application.logManager, application.logListener = quiet_log()
else:
global logListener, logManager
logManager, logListener = quiet_log()
application.root, application.sceneManager, application.renderWindow, application.camera = setup_function()
return application
def setup_unittest_application(application = None):
'''Convenience function to avoid accessing namespace.
>>> application = setup_unittest_application()
>>> del application
Try to setup an existing application quietly.
>>> application = application_class()
>>> application = setup_unittest_application(application)
'''
return setup_quiet_application(setup_unittest, application)
def setup_unittest_sample_framework_application(application):
'''Setup a unit test for SampleFramework, by assigning camera and renderWindow.
>>> import ogre.renderer.OGRE.sf_OIS as sf
>>> application = sf.Application()
>>> application = setup_unittest_sample_framework_application(application)
>>> application.sceneManager.clearScene()
>>> del application
'''
application = setup_quiet_application(setup_unittest, application)
if hasattr(application, 'camera') and not application.camera:
if application.sceneManager.hasCamera('Camera'):
application.camera = application.sceneManager.getCamera('Camera')
elif hasattr(application, '_createCamera'):
application._createCamera()
if hasattr(application, '_createViewports'):
#print '--- createScene'
application._createViewports()
if hasattr(application, '_createScene'):
#print '--- createScene'
application._createScene()
if hasattr(application, 'frameListener'):
if hasattr(application, '_createFrameListener'):
#print '--- createFrameListener'
application._createFrameListener()
return application
def go(application):
'''Convenience for an application.'''
if hasattr(application, 'go'):
application.go()
else:
run(application.root, application.sceneManager, application.renderWindow, application.camera)
if __name__ == '__main__':
import code_util
code_util.test(__file__) | random_line_split | |
ogre_unit.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''Simple Python-Ogre application functions.
Derived from SampleFramework, reimplemented as a toolkit for agile prototyping or succinct unit-testing. Assemble an application from the functions.
'''
__author__ = 'Ethan Kennerly'
import ogre.renderer.OGRE as ogre
import ogre.io.OIS as OIS
import code_util
def | ():
"""Return the absolute path to a valid plugins.cfg file.
Copied from sf_OIS.py"""
import sys
import os
import os.path
paths = [os.path.join(os.getcwd(), 'plugins.cfg'),
'/etc/OGRE/plugins.cfg',
os.path.join(os.path.dirname(os.path.abspath(__file__)),
'plugins.cfg')]
for path in paths:
if os.path.exists(path):
return path
sys.stderr.write("\n"
"** Warning: Unable to locate a suitable plugins.cfg file.\n"
"** Warning: Please check your ogre installation and copy a\n"
"** Warning: working plugins.cfg file to the current directory.\n\n")
raise ogre.Exception(0, "can't locate the 'plugins.cfg' file", "")
def setup_resources(resources_path = 'resources.cfg'):
'''Load resources, such as from 'resources.cfg'.'''
config = ogre.ConfigFile()
config.load(resources_path)
section_iter = config.getSectionIterator()
while section_iter.hasMoreElements():
section_name = section_iter.peekNextKey()
settings = section_iter.getNext()
for item in settings:
ogre.ResourceGroupManager.getSingleton().addResourceLocation(item.value, item.key, section_name)
def setup_root(plugins_path = getPluginPath(),
resources_path = 'resources.cfg'):
'''Return new root, sceneManager.'''
root = ogre.Root(plugins_path)
root.setFrameSmoothingPeriod(5.0)
setup_resources(resources_path)
sceneManager = root.createSceneManager(ogre.ST_GENERIC,"ExampleSMInstance")
return root, sceneManager
def initialise_null_render(plugins_path = getPluginPath()):
'Prepare to null renderer and return ogre root.'
ogre_root = ogre.Root(plugins_path)
rend_list = ogre_root.getAvailableRenderers()
ogre_root.setRenderSystem(rend_list[-1])
ogre_root.getRenderSystem()._initRenderTargets()
ogre_root.initialise(False)
return ogre_root
def setup_null_root(plugins_path = getPluginPath(),
resources_path = 'resources.cfg'):
'''Return root, sceneManager. Suitable for unit test without entity, camera, light.
>>> logManager, logListener = quiet_log()
>>> root, sceneManager = setup_null_root()
>>> assert root
>>> assert sceneManager
>>> for i in range(10):
... if not renderOneFrame(root): print False
>>> del sceneManager, root
>>> del logManager, logListener
'''
root = initialise_null_render(plugins_path)
setup_resources(resources_path)
sceneManager = root.createSceneManager(ogre.ST_GENERIC,"ExampleSMInstance")
return root, sceneManager
def setup_viewport(root, sceneManager):
'''Create render window and viewport from user selection, and return renderWindow and camera.'''
renderWindow = configure(root)
if not renderWindow:
return None
camera = sceneManager.createCamera('Camera')
viewport = renderWindow.addViewport(camera)
return renderWindow, camera
def configure(ogre_root):
"""This shows the config dialog and returns the renderWindow."""
user_confirmation = ogre_root.showConfigDialog()
if user_confirmation:
return ogre_root.initialise(True, "OGRE Render Window")
else:
return None
def setup_unittest():
'''With tiny render window and resources. Return root and sceneManager.
>>> logManager, logListener = quiet_log()
>>> root, sceneManager, renderWindow, camera = setup_unittest()
>>> assert root
>>> assert sceneManager
>>> assert renderWindow
>>> assert camera
>>> del sceneManager, root, renderWindow, camera
>>> del logManager, logListener
'''
root, sceneManager = setup_null_root()
renderWindow = root.createRenderWindow('test', 4, 3, False)
camera = sceneManager.createCamera('Camera')
ogre.ResourceGroupManager.getSingleton().initialiseAllResourceGroups()
return root, sceneManager, renderWindow, camera
def setup():
'''Set up minimal Ogre application and return root and sceneManager.
>>> logManager, logListener = quiet_log()
# TODO: Doctest crashes, although external call to setup works!
#>>> root, sceneManager, renderWindow, camera = setup()
#>>> assert root
#>>> assert sceneManager
#>>> assert renderWindow
#>>> assert camera
#>>> application = setup_quiet_application(setup_unittest)
#>>> for i in range(10):
#... print i,
#... if not renderOneFrame(root): print False
#0 1 2 3 4 5 6 7 8 9
#>>> sceneManager.clearScene()
#>>> del renderWindow
#>>> del camera
#>>> del sceneManager
#>>> del root
>>> del logManager, logListener
'''
root, sceneManager = setup_root()
renderWindow, camera = setup_viewport(root, sceneManager)
ogre.TextureManager.getSingleton().setDefaultNumMipmaps(5)
ogre.ResourceGroupManager.getSingleton().initialiseAllResourceGroups()
return root, sceneManager, renderWindow, camera
def run(root, sceneManager, renderWindow, camera):
'''Construct and render.'''
root, sceneManager, renderWindow, camera = setup()
if root and sceneManager:
root.startRendering()
def renderOneFrame(ogre_root):
'Render a frame. Return False if closed. Useful for unit test.'
ogre.WindowEventUtilities().messagePump()
return ogre_root.renderOneFrame()
# For applications that do not have logListener attribute.
logListener = None
logManager = None
class quiet_logListener_class(ogre.LogListener):
def messageLogged(self, message, level, debug, logName):
'''Called by Ogre instead of logging.'''
pass
#print message
def quiet_log():
'''Replace log with quiet version. Useful for unit test.
Return logManager and logListener, which must destructed AFTER root.
>>> logManager, logListener = quiet_log()
>>> root, sceneManager, renderWindow, camera = setup_unittest()
Gotcha: If you encounter 'R6025 Pure virtual function call' error within a class, then write destructor to destroy root before logManager and logListener. http://www.indiegamer.com/archives/t-3533.html
>>> del root
>>> del sceneManager, renderWindow, camera
>>> del logManager, logListener
Derived from examples:
http://www.ogre3d.org/phpBB2addons/viewtopic.php?p=10887&sid=ce193664e1d3d7c4af509e6f4e2718c6
http://wiki.python-ogre.org/index.php/ChangeLog
'''
logManager = ogre.LogManager()
log = ogre.LogManager.getSingletonPtr().createLog(
'quiet.log', True, False, True)
logListener = quiet_logListener_class()
log.addListener(logListener)
return logManager, logListener
class application_class(object):
'''Minimal Ogre application, which needs reference to root.
>>> application = setup_quiet_application(setup_unittest)
>>> for i in range(10):
... print i,
... if not renderOneFrame(application.root): print False
0 1 2 3 4 5 6 7 8 9
>>> assert application
'''
def __init__(self):
self.root = None
self.sceneManager = None
self.renderWindow = None
self.camera = None
# For quiet_log
self.logManager = None
self.logListener = None
def __del__(self):
del self.sceneManager
del self.root
del self.renderWindow
del self.camera
# Must delete root before logManager and logListener
del self.logListener
del self.logManager
def setup_quiet_application(setup_function = setup, application = None):
'''Return a minimal, application with logging disabled.
>>> application = setup_quiet_application(setup_unittest)
Alternatively try to make an application be quiet.
>>> application = application_class()
>>> application = setup_quiet_application(setup_unittest, application)
'''
if not application:
application = application_class()
if hasattr(application, 'logManager') \
and hasattr(application, 'logListener'):
if quiet_logListener_class != type(application.logListener):
application.logManager, application.logListener = quiet_log()
else:
global logListener, logManager
logManager, logListener = quiet_log()
application.root, application.sceneManager, application.renderWindow, application.camera = setup_function()
return application
def setup_unittest_application(application = None):
'''Convenience function to avoid accessing namespace.
>>> application = setup_unittest_application()
>>> del application
Try to setup an existing application quietly.
>>> application = application_class()
>>> application = setup_unittest_application(application)
'''
return setup_quiet_application(setup_unittest, application)
def setup_unittest_sample_framework_application(application):
'''Setup a unit test for SampleFramework, by assigning camera and renderWindow.
>>> import ogre.renderer.OGRE.sf_OIS as sf
>>> application = sf.Application()
>>> application = setup_unittest_sample_framework_application(application)
>>> application.sceneManager.clearScene()
>>> del application
'''
application = setup_quiet_application(setup_unittest, application)
if hasattr(application, 'camera') and not application.camera:
if application.sceneManager.hasCamera('Camera'):
application.camera = application.sceneManager.getCamera('Camera')
elif hasattr(application, '_createCamera'):
application._createCamera()
if hasattr(application, '_createViewports'):
#print '--- createScene'
application._createViewports()
if hasattr(application, '_createScene'):
#print '--- createScene'
application._createScene()
if hasattr(application, 'frameListener'):
if hasattr(application, '_createFrameListener'):
#print '--- createFrameListener'
application._createFrameListener()
return application
def go(application):
'''Convenience for an application.'''
if hasattr(application, 'go'):
application.go()
else:
run(application.root, application.sceneManager, application.renderWindow, application.camera)
if __name__ == '__main__':
import code_util
code_util.test(__file__)
| getPluginPath | identifier_name |
ogre_unit.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''Simple Python-Ogre application functions.
Derived from SampleFramework, reimplemented as a toolkit for agile prototyping or succinct unit-testing. Assemble an application from the functions.
'''
__author__ = 'Ethan Kennerly'
import ogre.renderer.OGRE as ogre
import ogre.io.OIS as OIS
import code_util
def getPluginPath():
"""Return the absolute path to a valid plugins.cfg file.
Copied from sf_OIS.py"""
import sys
import os
import os.path
paths = [os.path.join(os.getcwd(), 'plugins.cfg'),
'/etc/OGRE/plugins.cfg',
os.path.join(os.path.dirname(os.path.abspath(__file__)),
'plugins.cfg')]
for path in paths:
if os.path.exists(path):
return path
sys.stderr.write("\n"
"** Warning: Unable to locate a suitable plugins.cfg file.\n"
"** Warning: Please check your ogre installation and copy a\n"
"** Warning: working plugins.cfg file to the current directory.\n\n")
raise ogre.Exception(0, "can't locate the 'plugins.cfg' file", "")
def setup_resources(resources_path = 'resources.cfg'):
|
def setup_root(plugins_path = getPluginPath(),
resources_path = 'resources.cfg'):
'''Return new root, sceneManager.'''
root = ogre.Root(plugins_path)
root.setFrameSmoothingPeriod(5.0)
setup_resources(resources_path)
sceneManager = root.createSceneManager(ogre.ST_GENERIC,"ExampleSMInstance")
return root, sceneManager
def initialise_null_render(plugins_path = getPluginPath()):
'Prepare to null renderer and return ogre root.'
ogre_root = ogre.Root(plugins_path)
rend_list = ogre_root.getAvailableRenderers()
ogre_root.setRenderSystem(rend_list[-1])
ogre_root.getRenderSystem()._initRenderTargets()
ogre_root.initialise(False)
return ogre_root
def setup_null_root(plugins_path = getPluginPath(),
resources_path = 'resources.cfg'):
'''Return root, sceneManager. Suitable for unit test without entity, camera, light.
>>> logManager, logListener = quiet_log()
>>> root, sceneManager = setup_null_root()
>>> assert root
>>> assert sceneManager
>>> for i in range(10):
... if not renderOneFrame(root): print False
>>> del sceneManager, root
>>> del logManager, logListener
'''
root = initialise_null_render(plugins_path)
setup_resources(resources_path)
sceneManager = root.createSceneManager(ogre.ST_GENERIC,"ExampleSMInstance")
return root, sceneManager
def setup_viewport(root, sceneManager):
'''Create render window and viewport from user selection, and return renderWindow and camera.'''
renderWindow = configure(root)
if not renderWindow:
return None
camera = sceneManager.createCamera('Camera')
viewport = renderWindow.addViewport(camera)
return renderWindow, camera
def configure(ogre_root):
"""This shows the config dialog and returns the renderWindow."""
user_confirmation = ogre_root.showConfigDialog()
if user_confirmation:
return ogre_root.initialise(True, "OGRE Render Window")
else:
return None
def setup_unittest():
'''With tiny render window and resources. Return root and sceneManager.
>>> logManager, logListener = quiet_log()
>>> root, sceneManager, renderWindow, camera = setup_unittest()
>>> assert root
>>> assert sceneManager
>>> assert renderWindow
>>> assert camera
>>> del sceneManager, root, renderWindow, camera
>>> del logManager, logListener
'''
root, sceneManager = setup_null_root()
renderWindow = root.createRenderWindow('test', 4, 3, False)
camera = sceneManager.createCamera('Camera')
ogre.ResourceGroupManager.getSingleton().initialiseAllResourceGroups()
return root, sceneManager, renderWindow, camera
def setup():
'''Set up minimal Ogre application and return root and sceneManager.
>>> logManager, logListener = quiet_log()
# TODO: Doctest crashes, although external call to setup works!
#>>> root, sceneManager, renderWindow, camera = setup()
#>>> assert root
#>>> assert sceneManager
#>>> assert renderWindow
#>>> assert camera
#>>> application = setup_quiet_application(setup_unittest)
#>>> for i in range(10):
#... print i,
#... if not renderOneFrame(root): print False
#0 1 2 3 4 5 6 7 8 9
#>>> sceneManager.clearScene()
#>>> del renderWindow
#>>> del camera
#>>> del sceneManager
#>>> del root
>>> del logManager, logListener
'''
root, sceneManager = setup_root()
renderWindow, camera = setup_viewport(root, sceneManager)
ogre.TextureManager.getSingleton().setDefaultNumMipmaps(5)
ogre.ResourceGroupManager.getSingleton().initialiseAllResourceGroups()
return root, sceneManager, renderWindow, camera
def run(root, sceneManager, renderWindow, camera):
'''Construct and render.'''
root, sceneManager, renderWindow, camera = setup()
if root and sceneManager:
root.startRendering()
def renderOneFrame(ogre_root):
'Render a frame. Return False if closed. Useful for unit test.'
ogre.WindowEventUtilities().messagePump()
return ogre_root.renderOneFrame()
# For applications that do not have logListener attribute.
logListener = None
logManager = None
class quiet_logListener_class(ogre.LogListener):
def messageLogged(self, message, level, debug, logName):
'''Called by Ogre instead of logging.'''
pass
#print message
def quiet_log():
'''Replace log with quiet version. Useful for unit test.
Return logManager and logListener, which must destructed AFTER root.
>>> logManager, logListener = quiet_log()
>>> root, sceneManager, renderWindow, camera = setup_unittest()
Gotcha: If you encounter 'R6025 Pure virtual function call' error within a class, then write destructor to destroy root before logManager and logListener. http://www.indiegamer.com/archives/t-3533.html
>>> del root
>>> del sceneManager, renderWindow, camera
>>> del logManager, logListener
Derived from examples:
http://www.ogre3d.org/phpBB2addons/viewtopic.php?p=10887&sid=ce193664e1d3d7c4af509e6f4e2718c6
http://wiki.python-ogre.org/index.php/ChangeLog
'''
logManager = ogre.LogManager()
log = ogre.LogManager.getSingletonPtr().createLog(
'quiet.log', True, False, True)
logListener = quiet_logListener_class()
log.addListener(logListener)
return logManager, logListener
class application_class(object):
'''Minimal Ogre application, which needs reference to root.
>>> application = setup_quiet_application(setup_unittest)
>>> for i in range(10):
... print i,
... if not renderOneFrame(application.root): print False
0 1 2 3 4 5 6 7 8 9
>>> assert application
'''
def __init__(self):
self.root = None
self.sceneManager = None
self.renderWindow = None
self.camera = None
# For quiet_log
self.logManager = None
self.logListener = None
def __del__(self):
del self.sceneManager
del self.root
del self.renderWindow
del self.camera
# Must delete root before logManager and logListener
del self.logListener
del self.logManager
def setup_quiet_application(setup_function = setup, application = None):
'''Return a minimal, application with logging disabled.
>>> application = setup_quiet_application(setup_unittest)
Alternatively try to make an application be quiet.
>>> application = application_class()
>>> application = setup_quiet_application(setup_unittest, application)
'''
if not application:
application = application_class()
if hasattr(application, 'logManager') \
and hasattr(application, 'logListener'):
if quiet_logListener_class != type(application.logListener):
application.logManager, application.logListener = quiet_log()
else:
global logListener, logManager
logManager, logListener = quiet_log()
application.root, application.sceneManager, application.renderWindow, application.camera = setup_function()
return application
def setup_unittest_application(application = None):
'''Convenience function to avoid accessing namespace.
>>> application = setup_unittest_application()
>>> del application
Try to setup an existing application quietly.
>>> application = application_class()
>>> application = setup_unittest_application(application)
'''
return setup_quiet_application(setup_unittest, application)
def setup_unittest_sample_framework_application(application):
'''Setup a unit test for SampleFramework, by assigning camera and renderWindow.
>>> import ogre.renderer.OGRE.sf_OIS as sf
>>> application = sf.Application()
>>> application = setup_unittest_sample_framework_application(application)
>>> application.sceneManager.clearScene()
>>> del application
'''
application = setup_quiet_application(setup_unittest, application)
if hasattr(application, 'camera') and not application.camera:
if application.sceneManager.hasCamera('Camera'):
application.camera = application.sceneManager.getCamera('Camera')
elif hasattr(application, '_createCamera'):
application._createCamera()
if hasattr(application, '_createViewports'):
#print '--- createScene'
application._createViewports()
if hasattr(application, '_createScene'):
#print '--- createScene'
application._createScene()
if hasattr(application, 'frameListener'):
if hasattr(application, '_createFrameListener'):
#print '--- createFrameListener'
application._createFrameListener()
return application
def go(application):
'''Convenience for an application.'''
if hasattr(application, 'go'):
application.go()
else:
run(application.root, application.sceneManager, application.renderWindow, application.camera)
if __name__ == '__main__':
import code_util
code_util.test(__file__)
| '''Load resources, such as from 'resources.cfg'.'''
config = ogre.ConfigFile()
config.load(resources_path)
section_iter = config.getSectionIterator()
while section_iter.hasMoreElements():
section_name = section_iter.peekNextKey()
settings = section_iter.getNext()
for item in settings:
ogre.ResourceGroupManager.getSingleton().addResourceLocation(item.value, item.key, section_name) | identifier_body |
ogre_unit.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''Simple Python-Ogre application functions.
Derived from SampleFramework, reimplemented as a toolkit for agile prototyping or succinct unit-testing. Assemble an application from the functions.
'''
__author__ = 'Ethan Kennerly'
import ogre.renderer.OGRE as ogre
import ogre.io.OIS as OIS
import code_util
def getPluginPath():
"""Return the absolute path to a valid plugins.cfg file.
Copied from sf_OIS.py"""
import sys
import os
import os.path
paths = [os.path.join(os.getcwd(), 'plugins.cfg'),
'/etc/OGRE/plugins.cfg',
os.path.join(os.path.dirname(os.path.abspath(__file__)),
'plugins.cfg')]
for path in paths:
|
sys.stderr.write("\n"
"** Warning: Unable to locate a suitable plugins.cfg file.\n"
"** Warning: Please check your ogre installation and copy a\n"
"** Warning: working plugins.cfg file to the current directory.\n\n")
raise ogre.Exception(0, "can't locate the 'plugins.cfg' file", "")
def setup_resources(resources_path = 'resources.cfg'):
'''Load resources, such as from 'resources.cfg'.'''
config = ogre.ConfigFile()
config.load(resources_path)
section_iter = config.getSectionIterator()
while section_iter.hasMoreElements():
section_name = section_iter.peekNextKey()
settings = section_iter.getNext()
for item in settings:
ogre.ResourceGroupManager.getSingleton().addResourceLocation(item.value, item.key, section_name)
def setup_root(plugins_path = getPluginPath(),
resources_path = 'resources.cfg'):
'''Return new root, sceneManager.'''
root = ogre.Root(plugins_path)
root.setFrameSmoothingPeriod(5.0)
setup_resources(resources_path)
sceneManager = root.createSceneManager(ogre.ST_GENERIC,"ExampleSMInstance")
return root, sceneManager
def initialise_null_render(plugins_path = getPluginPath()):
'Prepare to null renderer and return ogre root.'
ogre_root = ogre.Root(plugins_path)
rend_list = ogre_root.getAvailableRenderers()
ogre_root.setRenderSystem(rend_list[-1])
ogre_root.getRenderSystem()._initRenderTargets()
ogre_root.initialise(False)
return ogre_root
def setup_null_root(plugins_path = getPluginPath(),
resources_path = 'resources.cfg'):
'''Return root, sceneManager. Suitable for unit test without entity, camera, light.
>>> logManager, logListener = quiet_log()
>>> root, sceneManager = setup_null_root()
>>> assert root
>>> assert sceneManager
>>> for i in range(10):
... if not renderOneFrame(root): print False
>>> del sceneManager, root
>>> del logManager, logListener
'''
root = initialise_null_render(plugins_path)
setup_resources(resources_path)
sceneManager = root.createSceneManager(ogre.ST_GENERIC,"ExampleSMInstance")
return root, sceneManager
def setup_viewport(root, sceneManager):
'''Create render window and viewport from user selection, and return renderWindow and camera.'''
renderWindow = configure(root)
if not renderWindow:
return None
camera = sceneManager.createCamera('Camera')
viewport = renderWindow.addViewport(camera)
return renderWindow, camera
def configure(ogre_root):
"""This shows the config dialog and returns the renderWindow."""
user_confirmation = ogre_root.showConfigDialog()
if user_confirmation:
return ogre_root.initialise(True, "OGRE Render Window")
else:
return None
def setup_unittest():
'''With tiny render window and resources. Return root and sceneManager.
>>> logManager, logListener = quiet_log()
>>> root, sceneManager, renderWindow, camera = setup_unittest()
>>> assert root
>>> assert sceneManager
>>> assert renderWindow
>>> assert camera
>>> del sceneManager, root, renderWindow, camera
>>> del logManager, logListener
'''
root, sceneManager = setup_null_root()
renderWindow = root.createRenderWindow('test', 4, 3, False)
camera = sceneManager.createCamera('Camera')
ogre.ResourceGroupManager.getSingleton().initialiseAllResourceGroups()
return root, sceneManager, renderWindow, camera
def setup():
'''Set up minimal Ogre application and return root and sceneManager.
>>> logManager, logListener = quiet_log()
# TODO: Doctest crashes, although external call to setup works!
#>>> root, sceneManager, renderWindow, camera = setup()
#>>> assert root
#>>> assert sceneManager
#>>> assert renderWindow
#>>> assert camera
#>>> application = setup_quiet_application(setup_unittest)
#>>> for i in range(10):
#... print i,
#... if not renderOneFrame(root): print False
#0 1 2 3 4 5 6 7 8 9
#>>> sceneManager.clearScene()
#>>> del renderWindow
#>>> del camera
#>>> del sceneManager
#>>> del root
>>> del logManager, logListener
'''
root, sceneManager = setup_root()
renderWindow, camera = setup_viewport(root, sceneManager)
ogre.TextureManager.getSingleton().setDefaultNumMipmaps(5)
ogre.ResourceGroupManager.getSingleton().initialiseAllResourceGroups()
return root, sceneManager, renderWindow, camera
def run(root, sceneManager, renderWindow, camera):
'''Construct and render.'''
root, sceneManager, renderWindow, camera = setup()
if root and sceneManager:
root.startRendering()
def renderOneFrame(ogre_root):
'Render a frame. Return False if closed. Useful for unit test.'
ogre.WindowEventUtilities().messagePump()
return ogre_root.renderOneFrame()
# For applications that do not have logListener attribute.
logListener = None
logManager = None
class quiet_logListener_class(ogre.LogListener):
def messageLogged(self, message, level, debug, logName):
'''Called by Ogre instead of logging.'''
pass
#print message
def quiet_log():
'''Replace log with quiet version. Useful for unit test.
Return logManager and logListener, which must destructed AFTER root.
>>> logManager, logListener = quiet_log()
>>> root, sceneManager, renderWindow, camera = setup_unittest()
Gotcha: If you encounter 'R6025 Pure virtual function call' error within a class, then write destructor to destroy root before logManager and logListener. http://www.indiegamer.com/archives/t-3533.html
>>> del root
>>> del sceneManager, renderWindow, camera
>>> del logManager, logListener
Derived from examples:
http://www.ogre3d.org/phpBB2addons/viewtopic.php?p=10887&sid=ce193664e1d3d7c4af509e6f4e2718c6
http://wiki.python-ogre.org/index.php/ChangeLog
'''
logManager = ogre.LogManager()
log = ogre.LogManager.getSingletonPtr().createLog(
'quiet.log', True, False, True)
logListener = quiet_logListener_class()
log.addListener(logListener)
return logManager, logListener
class application_class(object):
'''Minimal Ogre application, which needs reference to root.
>>> application = setup_quiet_application(setup_unittest)
>>> for i in range(10):
... print i,
... if not renderOneFrame(application.root): print False
0 1 2 3 4 5 6 7 8 9
>>> assert application
'''
def __init__(self):
self.root = None
self.sceneManager = None
self.renderWindow = None
self.camera = None
# For quiet_log
self.logManager = None
self.logListener = None
def __del__(self):
del self.sceneManager
del self.root
del self.renderWindow
del self.camera
# Must delete root before logManager and logListener
del self.logListener
del self.logManager
def setup_quiet_application(setup_function = setup, application = None):
'''Return a minimal, application with logging disabled.
>>> application = setup_quiet_application(setup_unittest)
Alternatively try to make an application be quiet.
>>> application = application_class()
>>> application = setup_quiet_application(setup_unittest, application)
'''
if not application:
application = application_class()
if hasattr(application, 'logManager') \
and hasattr(application, 'logListener'):
if quiet_logListener_class != type(application.logListener):
application.logManager, application.logListener = quiet_log()
else:
global logListener, logManager
logManager, logListener = quiet_log()
application.root, application.sceneManager, application.renderWindow, application.camera = setup_function()
return application
def setup_unittest_application(application = None):
'''Convenience function to avoid accessing namespace.
>>> application = setup_unittest_application()
>>> del application
Try to setup an existing application quietly.
>>> application = application_class()
>>> application = setup_unittest_application(application)
'''
return setup_quiet_application(setup_unittest, application)
def setup_unittest_sample_framework_application(application):
'''Setup a unit test for SampleFramework, by assigning camera and renderWindow.
>>> import ogre.renderer.OGRE.sf_OIS as sf
>>> application = sf.Application()
>>> application = setup_unittest_sample_framework_application(application)
>>> application.sceneManager.clearScene()
>>> del application
'''
application = setup_quiet_application(setup_unittest, application)
if hasattr(application, 'camera') and not application.camera:
if application.sceneManager.hasCamera('Camera'):
application.camera = application.sceneManager.getCamera('Camera')
elif hasattr(application, '_createCamera'):
application._createCamera()
if hasattr(application, '_createViewports'):
#print '--- createScene'
application._createViewports()
if hasattr(application, '_createScene'):
#print '--- createScene'
application._createScene()
if hasattr(application, 'frameListener'):
if hasattr(application, '_createFrameListener'):
#print '--- createFrameListener'
application._createFrameListener()
return application
def go(application):
'''Convenience for an application.'''
if hasattr(application, 'go'):
application.go()
else:
run(application.root, application.sceneManager, application.renderWindow, application.camera)
if __name__ == '__main__':
import code_util
code_util.test(__file__)
| if os.path.exists(path):
return path | conditional_block |
data_loader.py | # coding:utf-8
#
#
import os
import sox
import math
import json
import torch
import numpy as np
import soundfile as sf
from tempfile import NamedTemporaryFile
from .adding_reverb import ReverbAugmentor
from torch.utils.data import Dataset, Sampler, DistributedSampler, DataLoader
def load_audio(path):
sound, sample_rate = sf.read(path, dtype='int16')
sound = sound.astype('float32') / 32767 # normalize audio
if len(sound.shape) > 1:
if sound.shape[1] == 1:
sound = sound.squeeze()
else:
sound = sound.mean(axis=1) # multiple channels, average
return sound
class AudioParser(object):
def parse_transcript(self, transcript_path):
"""
:param transcript_path: Path where transcript is stored from the manifest file
:return: Transcript in training/testing format
"""
raise NotImplementedError
def parse_audio(self, audio_path):
"""
:param audio_path: Path where audio is stored from the manifest file
:return: Audio in training/testing format
"""
raise NotImplementedError
class NoiseInjection(object):
def __init__(self,
path=None,
sample_rate=16000,
noise_levels=(0, 0.5)):
"""
Adds noise to an input signal with specific SNR. Higher the noise level, the more noise added.
Modified code from https://github.com/willfrey/audio/blob/master/torchaudio/transforms.py
"""
if not os.path.exists(path):
print("Directory doesn't exist: {}".format(path))
raise IOError
# self.paths = path is not None and librosa.util.find_files(path)
with open(path) as f:
self.paths = f.readlines()
self.sample_rate = sample_rate
self.noise_levels = noise_levels
def inject_noise(self, data):
noise_info_dic = json.loads(np.random.choice(self.paths))
noise_path = noise_info_dic['audio_filepath']
noise_level = np.random.uniform(*self.noise_levels)
return self.inject_noise_sample(data, noise_path, noise_level)
def inject_noise_sample(self, data, noise_path, noise_level):
# noise_len = get_audio_length(noise_path)
noise_len = sox.file_info.duration(noise_path)
data_len = len(data) / self.sample_rate
noise_start = np.random.rand() * (noise_len - data_len)
noise_end = noise_start + data_len
noise_dst = audio_with_sox(noise_path, self.sample_rate, noise_start, noise_end)
if len(data) != len(noise_dst):
data += 0
else:
|
return data
class SpectrogramParser(AudioParser):
def __init__(self,
audio_conf,
speed_volume_perturb=False,
reverberation=False):
"""
Parses audio file into spectrogram with optional normalization and various augmentations
:param audio_conf: Dictionary containing the sample rate, window and the window length/stride in seconds
:param normalize(default False): Apply standard mean and deviation normalization to audio tensor
:param speed_volume_perturb(default False): Apply random tempo and gain perturbations
:param spec_augment(default False): Apply simple spectral augmentation to mel spectograms
"""
super(SpectrogramParser, self).__init__()
self.sample_rate = audio_conf['sample_rate']
self.speed_volume_perturb = speed_volume_perturb
self.reverberation = reverberation
self.noiseInjector = NoiseInjection(audio_conf['noise_dir'], self.sample_rate,
audio_conf['noise_levels']) if audio_conf.get(
'noise_dir') is not None else None
self.noise_prob = audio_conf.get('noise_prob')
self.reverb_prob = audio_conf.get('reverb_prob')
self.reverb = ReverbAugmentor(min_distance=3, max_distance=5)
def parse_audio(self, audio_path):
# os.system("cp {} {}/wav".format(audio_path, os.getcwd()))
if self.speed_volume_perturb:
y = load_randomly_augmented_audio(audio_path, self.sample_rate)
# sf.write('wav/aaaa_{}'.format(os.path.basename(audio_path)), y, self.sample_rate)
else:
y = load_audio(audio_path)
if self.reverberation:
add_reverb = np.random.binomial(1, self.reverb_prob)
if add_reverb:
y = self.reverb.add_reverb(y)
# sf.write('wav/bbbb_{}'.format(os.path.basename(audio_path)), y, self.sample_rate)
if self.noiseInjector:
add_noise = np.random.binomial(1, self.noise_prob)
if add_noise:
y = self.noiseInjector.inject_noise(y)
# sf.write('wav/cccc_{}'.format(os.path.basename(audio_path)), y, self.sample_rate)
y = torch.FloatTensor(y)
return y
def parse_transcript(self, transcript_path):
raise NotImplementedError
class SpectrogramDataset(Dataset, SpectrogramParser):
def __init__(self,
audio_conf,
manifest_filepath,
labels,
word_form,
speed_volume_perturb=False,
reverberation=False,
min_durations=0.0,
max_durations=60.0):
"""
Dataset that loads tensors via a csv containing file paths to audio files and transcripts separated by
a comma. Each new line is a different sample. Example below:
/path/to/audio.wav,/path/to/audio.txt
...
:param audio_conf: Dictionary containing the sample rate
:param manifest_filepath: Path to manifest csv as describe above
:param labels: list containing all the possible characters to map to
:param normalize: Apply standard mean and deviation normalization to audio tensor
:param speed_volume_perturb(default False): Apply random tempo and gain perturbations
:param spec_augment(default False): Apply simple spectral augmentation to mel spectograms
"""
self.word_form_fict = {"sinogram": "text", "pinyin": "pinyin", "english": "fully_pinyin"}
with open(manifest_filepath) as f:
ids = f.readlines()
ids = [i for i in ids if min_durations < float(json.loads(i)['duration']) <= max_durations]
self.ids = sorted(ids, key=lambda x: float(json.loads(x)['duration']), reverse=True)
self.size = len(ids)
self.word_form = word_form
self.labels_map = dict([(labels[i], i) for i in range(len(labels))])
super(SpectrogramDataset, self).__init__(audio_conf, speed_volume_perturb, reverberation)
def __getitem__(self, index):
sample = json.loads(self.ids[index])
# print("sample: {}".format(sample['duration']))
audio_path, transcripts = sample['audio_filepath'], sample[self.word_form_fict[self.word_form]]
raw_data = self.parse_audio(audio_path)
transcript_id = self.parse_transcript(transcripts)
return raw_data, transcript_id
def parse_transcript(self, transcript):
if self.word_form == 'pinyin':
transcript_id = [self.label_numerical(x) for x in transcript.split(' ')]
elif self.word_form == 'sinogram' or self.word_form == 'english':
transcript_id = list(filter(None, [self.labels_map.get(x) for x in list(transcript)]))
else:
raise ValueError('wrong word form: {}'.format(self.word_form))
return transcript_id
def __len__(self):
return self.size
def label_numerical(self, x):
if self.labels_map.get(x) is not None:
return self.labels_map.get(x)
else:
return self.labels_map.get('.')
def _collate_fn(batch):
def func(p):
return p[0].size(0)
batch = sorted(batch, key=lambda sample: sample[0].size(0), reverse=True)
longest_sample = max(batch, key=func)[0]
minibatch_size = len(batch)
max_seqlength = longest_sample.size(0)
inputs = torch.zeros(minibatch_size, max_seqlength)
input_percentages = torch.FloatTensor(minibatch_size)
target_sizes = torch.IntTensor(minibatch_size)
targets = []
for x in range(minibatch_size):
sample = batch[x]
tensor = sample[0]
target = sample[1]
seq_length = tensor.size(0)
inputs[x].narrow(0, 0, seq_length).copy_(tensor)
input_percentages[x] = seq_length / float(max_seqlength)
target_sizes[x] = len(target)
targets.extend(target)
targets = torch.IntTensor(targets)
return inputs, targets, input_percentages, target_sizes
class AudioDataLoader(DataLoader):
def __init__(self, *args, **kwargs):
"""
Creates a data loader for AudioDatasets.
"""
super(AudioDataLoader, self).__init__(*args, **kwargs)
self.collate_fn = _collate_fn
class DSRandomSampler(Sampler):
"""
Implementation of a Random Sampler for sampling the dataset.
Added to ensure we reset the start index when an epoch is finished.
This is essential since we support saving/loading state during an epoch.
"""
def __init__(self, dataset, batch_size=1, start_index=0):
super().__init__(data_source=dataset)
self.dataset = dataset
self.start_index = start_index
self.batch_size = batch_size
ids = list(range(len(self.dataset)))
self.bins = [ids[i:i + self.batch_size] for i in range(0, len(ids), self.batch_size)]
def __iter__(self):
# deterministically shuffle based on epoch
g = torch.Generator()
g.manual_seed(self.epoch)
indices = (
torch.randperm(len(self.bins) - self.start_index, generator=g)
.add(self.start_index)
.tolist()
)
for x in indices:
batch_ids = self.bins[x]
np.random.shuffle(batch_ids)
yield batch_ids
def __len__(self):
return len(self.bins) - self.start_index
def set_epoch(self, epoch):
self.epoch = epoch
def reset_training_step(self, training_step):
self.start_index = training_step
class DSDistributedSampler(DistributedSampler):
"""
Overrides the DistributedSampler to ensure we reset the start index when an epoch is finished.
This is essential since we support saving/loading state during an epoch.
"""
def __init__(self, dataset, num_replicas=None, rank=None, start_index=0, batch_size=1):
super().__init__(dataset=dataset, num_replicas=num_replicas, rank=rank)
self.start_index = start_index
self.batch_size = batch_size
ids = list(range(len(dataset)))
self.bins = [ids[i:i + self.batch_size] for i in range(0, len(ids), self.batch_size)]
self.num_samples = int(
math.ceil(float(len(self.bins) - self.start_index) / self.num_replicas)
)
self.total_size = self.num_samples * self.num_replicas
def __iter__(self):
# deterministically shuffle based on epoch
g = torch.Generator()
g.manual_seed(self.epoch)
indices = (
torch.randperm(len(self.bins) - self.start_index, generator=g)
.add(self.start_index)
.tolist()
)
# print("self.bins : {}".format(self.bins))
indices = sorted(indices, reverse=False)
# print("indices : {}".format(indices))
# add extra samples to make it evenly divisible
indices += indices[: (self.total_size - len(indices))]
assert len(indices) == self.total_size
# subsample
indices = indices[self.rank: self.total_size: self.num_replicas]
assert len(indices) == self.num_samples
for x in indices:
batch_ids = self.bins[x]
np.random.shuffle(batch_ids)
yield batch_ids
def __len__(self):
return self.num_samples
def reset_training_step(self, training_step):
self.start_index = training_step
self.num_samples = int(
math.ceil(float(len(self.bins) - self.start_index) / self.num_replicas)
)
self.total_size = self.num_samples * self.num_replicas
def audio_with_sox(path, sample_rate, start_time, end_time):
"""
crop and resample the recording with sox and loads it.
"""
try:
with NamedTemporaryFile(suffix=".wav") as tar_file:
tar_filename = tar_file.name
sox_params = "sox \"{}\" -r {} -c 1 -b 16 -e si {} trim {} ={} >/dev/null 2>&1".format(path, sample_rate,
tar_filename,
start_time,
end_time)
os.system(sox_params)
y = load_audio(tar_filename)
except Exception as E:
y = load_audio(path)
return y
def augment_audio_with_sox(path, sample_rate, tempo, gain):
"""
Changes tempo and gain of the recording with sox and loads it.
"""
try:
with NamedTemporaryFile(suffix=".wav") as augmented_file:
augmented_filename = augmented_file.name
sox_augment_params = ["tempo", "{:.3f}".format(tempo), "gain", "{:.3f}".format(gain)]
sox_params = "sox \"{}\" -r {} -c 1 -b 16 -e si {} {} >/dev/null 2>&1".format(path, sample_rate,
augmented_filename,
" ".join(sox_augment_params))
os.system(sox_params)
y = load_audio(augmented_filename)
except Exception as E:
y = load_audio(path)
return y
def load_randomly_augmented_audio(path, sample_rate=16000, tempo_range=(0.85, 1.15),
gain_range=(-6, 8)):
"""
Picks tempo and gain uniformly, applies it to the utterance by using sox utility.
Returns the augmented utterance.
"""
low_tempo, high_tempo = tempo_range
tempo_value = np.random.uniform(low=low_tempo, high=high_tempo)
low_gain, high_gain = gain_range
gain_value = np.random.uniform(low=low_gain, high=high_gain)
audio = augment_audio_with_sox(path=path, sample_rate=sample_rate,
tempo=tempo_value, gain=gain_value)
return audio
| noise_energy = np.sqrt(noise_dst.dot(noise_dst) / noise_dst.size)
data_energy = np.sqrt(data.dot(data) / data.size)
data += noise_level * noise_dst * data_energy / noise_energy | conditional_block |
data_loader.py | # coding:utf-8
#
#
import os
import sox
import math
import json
import torch
import numpy as np
import soundfile as sf
from tempfile import NamedTemporaryFile
from .adding_reverb import ReverbAugmentor
from torch.utils.data import Dataset, Sampler, DistributedSampler, DataLoader
def load_audio(path):
sound, sample_rate = sf.read(path, dtype='int16')
sound = sound.astype('float32') / 32767 # normalize audio
if len(sound.shape) > 1:
if sound.shape[1] == 1:
sound = sound.squeeze()
else:
sound = sound.mean(axis=1) # multiple channels, average
return sound
class AudioParser(object):
def parse_transcript(self, transcript_path):
"""
:param transcript_path: Path where transcript is stored from the manifest file
:return: Transcript in training/testing format
"""
raise NotImplementedError
def parse_audio(self, audio_path):
"""
:param audio_path: Path where audio is stored from the manifest file
:return: Audio in training/testing format
"""
raise NotImplementedError
class NoiseInjection(object):
def __init__(self,
path=None,
sample_rate=16000,
noise_levels=(0, 0.5)):
"""
Adds noise to an input signal with specific SNR. Higher the noise level, the more noise added.
Modified code from https://github.com/willfrey/audio/blob/master/torchaudio/transforms.py
"""
if not os.path.exists(path):
print("Directory doesn't exist: {}".format(path))
raise IOError
# self.paths = path is not None and librosa.util.find_files(path)
with open(path) as f:
self.paths = f.readlines()
self.sample_rate = sample_rate
self.noise_levels = noise_levels
def inject_noise(self, data):
noise_info_dic = json.loads(np.random.choice(self.paths))
noise_path = noise_info_dic['audio_filepath']
noise_level = np.random.uniform(*self.noise_levels)
return self.inject_noise_sample(data, noise_path, noise_level)
def inject_noise_sample(self, data, noise_path, noise_level):
# noise_len = get_audio_length(noise_path)
noise_len = sox.file_info.duration(noise_path)
data_len = len(data) / self.sample_rate
noise_start = np.random.rand() * (noise_len - data_len)
noise_end = noise_start + data_len
noise_dst = audio_with_sox(noise_path, self.sample_rate, noise_start, noise_end)
if len(data) != len(noise_dst):
data += 0
else:
noise_energy = np.sqrt(noise_dst.dot(noise_dst) / noise_dst.size)
data_energy = np.sqrt(data.dot(data) / data.size)
data += noise_level * noise_dst * data_energy / noise_energy
return data
class SpectrogramParser(AudioParser):
def __init__(self,
audio_conf,
speed_volume_perturb=False,
reverberation=False):
"""
Parses audio file into spectrogram with optional normalization and various augmentations
:param audio_conf: Dictionary containing the sample rate, window and the window length/stride in seconds
:param normalize(default False): Apply standard mean and deviation normalization to audio tensor
:param speed_volume_perturb(default False): Apply random tempo and gain perturbations
:param spec_augment(default False): Apply simple spectral augmentation to mel spectograms
"""
super(SpectrogramParser, self).__init__()
self.sample_rate = audio_conf['sample_rate']
self.speed_volume_perturb = speed_volume_perturb
self.reverberation = reverberation
self.noiseInjector = NoiseInjection(audio_conf['noise_dir'], self.sample_rate,
audio_conf['noise_levels']) if audio_conf.get(
'noise_dir') is not None else None
self.noise_prob = audio_conf.get('noise_prob')
self.reverb_prob = audio_conf.get('reverb_prob')
self.reverb = ReverbAugmentor(min_distance=3, max_distance=5)
def parse_audio(self, audio_path):
# os.system("cp {} {}/wav".format(audio_path, os.getcwd()))
if self.speed_volume_perturb:
y = load_randomly_augmented_audio(audio_path, self.sample_rate)
# sf.write('wav/aaaa_{}'.format(os.path.basename(audio_path)), y, self.sample_rate)
else:
y = load_audio(audio_path)
if self.reverberation:
add_reverb = np.random.binomial(1, self.reverb_prob)
if add_reverb:
y = self.reverb.add_reverb(y)
# sf.write('wav/bbbb_{}'.format(os.path.basename(audio_path)), y, self.sample_rate)
if self.noiseInjector:
add_noise = np.random.binomial(1, self.noise_prob)
if add_noise:
y = self.noiseInjector.inject_noise(y)
# sf.write('wav/cccc_{}'.format(os.path.basename(audio_path)), y, self.sample_rate)
y = torch.FloatTensor(y)
return y
def parse_transcript(self, transcript_path):
raise NotImplementedError
class SpectrogramDataset(Dataset, SpectrogramParser):
def __init__(self,
audio_conf,
manifest_filepath,
labels,
word_form,
speed_volume_perturb=False,
reverberation=False,
min_durations=0.0,
max_durations=60.0):
"""
Dataset that loads tensors via a csv containing file paths to audio files and transcripts separated by
a comma. Each new line is a different sample. Example below:
/path/to/audio.wav,/path/to/audio.txt
...
:param audio_conf: Dictionary containing the sample rate
:param manifest_filepath: Path to manifest csv as describe above
:param labels: list containing all the possible characters to map to
:param normalize: Apply standard mean and deviation normalization to audio tensor
:param speed_volume_perturb(default False): Apply random tempo and gain perturbations
:param spec_augment(default False): Apply simple spectral augmentation to mel spectograms
"""
self.word_form_fict = {"sinogram": "text", "pinyin": "pinyin", "english": "fully_pinyin"}
with open(manifest_filepath) as f:
ids = f.readlines()
ids = [i for i in ids if min_durations < float(json.loads(i)['duration']) <= max_durations]
self.ids = sorted(ids, key=lambda x: float(json.loads(x)['duration']), reverse=True)
self.size = len(ids)
self.word_form = word_form
self.labels_map = dict([(labels[i], i) for i in range(len(labels))])
super(SpectrogramDataset, self).__init__(audio_conf, speed_volume_perturb, reverberation)
def __getitem__(self, index):
sample = json.loads(self.ids[index])
# print("sample: {}".format(sample['duration']))
audio_path, transcripts = sample['audio_filepath'], sample[self.word_form_fict[self.word_form]]
raw_data = self.parse_audio(audio_path)
transcript_id = self.parse_transcript(transcripts)
return raw_data, transcript_id
def parse_transcript(self, transcript):
if self.word_form == 'pinyin':
transcript_id = [self.label_numerical(x) for x in transcript.split(' ')]
elif self.word_form == 'sinogram' or self.word_form == 'english':
transcript_id = list(filter(None, [self.labels_map.get(x) for x in list(transcript)]))
else:
raise ValueError('wrong word form: {}'.format(self.word_form))
return transcript_id
def __len__(self):
return self.size
def label_numerical(self, x):
if self.labels_map.get(x) is not None:
return self.labels_map.get(x)
else:
return self.labels_map.get('.')
def _collate_fn(batch):
def func(p):
return p[0].size(0)
batch = sorted(batch, key=lambda sample: sample[0].size(0), reverse=True)
longest_sample = max(batch, key=func)[0]
minibatch_size = len(batch)
max_seqlength = longest_sample.size(0)
inputs = torch.zeros(minibatch_size, max_seqlength)
input_percentages = torch.FloatTensor(minibatch_size)
target_sizes = torch.IntTensor(minibatch_size)
targets = []
for x in range(minibatch_size):
sample = batch[x]
tensor = sample[0]
target = sample[1]
seq_length = tensor.size(0)
inputs[x].narrow(0, 0, seq_length).copy_(tensor)
input_percentages[x] = seq_length / float(max_seqlength)
target_sizes[x] = len(target)
targets.extend(target)
targets = torch.IntTensor(targets)
return inputs, targets, input_percentages, target_sizes
class AudioDataLoader(DataLoader):
def __init__(self, *args, **kwargs):
"""
Creates a data loader for AudioDatasets.
"""
super(AudioDataLoader, self).__init__(*args, **kwargs)
self.collate_fn = _collate_fn
class DSRandomSampler(Sampler):
"""
Implementation of a Random Sampler for sampling the dataset.
Added to ensure we reset the start index when an epoch is finished.
This is essential since we support saving/loading state during an epoch.
"""
def __init__(self, dataset, batch_size=1, start_index=0):
super().__init__(data_source=dataset)
self.dataset = dataset
self.start_index = start_index
self.batch_size = batch_size
ids = list(range(len(self.dataset)))
self.bins = [ids[i:i + self.batch_size] for i in range(0, len(ids), self.batch_size)]
def __iter__(self):
# deterministically shuffle based on epoch
g = torch.Generator()
g.manual_seed(self.epoch)
indices = (
torch.randperm(len(self.bins) - self.start_index, generator=g)
.add(self.start_index)
.tolist()
)
for x in indices:
batch_ids = self.bins[x]
np.random.shuffle(batch_ids)
yield batch_ids
def __len__(self):
return len(self.bins) - self.start_index
def set_epoch(self, epoch):
self.epoch = epoch
def reset_training_step(self, training_step):
self.start_index = training_step
class DSDistributedSampler(DistributedSampler):
"""
Overrides the DistributedSampler to ensure we reset the start index when an epoch is finished.
This is essential since we support saving/loading state during an epoch.
"""
def __init__(self, dataset, num_replicas=None, rank=None, start_index=0, batch_size=1):
super().__init__(dataset=dataset, num_replicas=num_replicas, rank=rank)
self.start_index = start_index
self.batch_size = batch_size
ids = list(range(len(dataset)))
self.bins = [ids[i:i + self.batch_size] for i in range(0, len(ids), self.batch_size)]
self.num_samples = int(
math.ceil(float(len(self.bins) - self.start_index) / self.num_replicas)
)
self.total_size = self.num_samples * self.num_replicas
def __iter__(self):
# deterministically shuffle based on epoch
g = torch.Generator()
g.manual_seed(self.epoch)
indices = (
torch.randperm(len(self.bins) - self.start_index, generator=g)
.add(self.start_index)
.tolist()
)
# print("self.bins : {}".format(self.bins))
indices = sorted(indices, reverse=False)
# print("indices : {}".format(indices))
# add extra samples to make it evenly divisible
indices += indices[: (self.total_size - len(indices))]
assert len(indices) == self.total_size
# subsample
indices = indices[self.rank: self.total_size: self.num_replicas]
assert len(indices) == self.num_samples
for x in indices:
batch_ids = self.bins[x]
np.random.shuffle(batch_ids)
yield batch_ids
def __len__(self):
return self.num_samples
def reset_training_step(self, training_step):
self.start_index = training_step
self.num_samples = int(
math.ceil(float(len(self.bins) - self.start_index) / self.num_replicas)
)
self.total_size = self.num_samples * self.num_replicas
def audio_with_sox(path, sample_rate, start_time, end_time):
"""
crop and resample the recording with sox and loads it.
"""
try:
with NamedTemporaryFile(suffix=".wav") as tar_file:
tar_filename = tar_file.name
sox_params = "sox \"{}\" -r {} -c 1 -b 16 -e si {} trim {} ={} >/dev/null 2>&1".format(path, sample_rate,
tar_filename,
start_time,
end_time)
os.system(sox_params)
y = load_audio(tar_filename)
except Exception as E:
y = load_audio(path)
return y
def augment_audio_with_sox(path, sample_rate, tempo, gain):
"""
Changes tempo and gain of the recording with sox and loads it.
"""
try:
with NamedTemporaryFile(suffix=".wav") as augmented_file:
augmented_filename = augmented_file.name
sox_augment_params = ["tempo", "{:.3f}".format(tempo), "gain", "{:.3f}".format(gain)]
sox_params = "sox \"{}\" -r {} -c 1 -b 16 -e si {} {} >/dev/null 2>&1".format(path, sample_rate,
augmented_filename,
" ".join(sox_augment_params))
os.system(sox_params)
y = load_audio(augmented_filename)
except Exception as E:
y = load_audio(path)
return y
def load_randomly_augmented_audio(path, sample_rate=16000, tempo_range=(0.85, 1.15),
gain_range=(-6, 8)):
| """
Picks tempo and gain uniformly, applies it to the utterance by using sox utility.
Returns the augmented utterance.
"""
low_tempo, high_tempo = tempo_range
tempo_value = np.random.uniform(low=low_tempo, high=high_tempo)
low_gain, high_gain = gain_range
gain_value = np.random.uniform(low=low_gain, high=high_gain)
audio = augment_audio_with_sox(path=path, sample_rate=sample_rate,
tempo=tempo_value, gain=gain_value)
return audio | identifier_body | |
data_loader.py | # coding:utf-8
#
#
import os
import sox
import math
import json
import torch
import numpy as np
import soundfile as sf
from tempfile import NamedTemporaryFile
from .adding_reverb import ReverbAugmentor
from torch.utils.data import Dataset, Sampler, DistributedSampler, DataLoader
def load_audio(path):
sound, sample_rate = sf.read(path, dtype='int16')
sound = sound.astype('float32') / 32767 # normalize audio
if len(sound.shape) > 1:
if sound.shape[1] == 1:
sound = sound.squeeze()
else:
sound = sound.mean(axis=1) # multiple channels, average
return sound
class AudioParser(object):
def parse_transcript(self, transcript_path):
"""
:param transcript_path: Path where transcript is stored from the manifest file
:return: Transcript in training/testing format
"""
raise NotImplementedError
def parse_audio(self, audio_path):
"""
:param audio_path: Path where audio is stored from the manifest file
:return: Audio in training/testing format
"""
raise NotImplementedError
class NoiseInjection(object):
def __init__(self,
path=None,
sample_rate=16000,
noise_levels=(0, 0.5)):
"""
Adds noise to an input signal with specific SNR. Higher the noise level, the more noise added.
Modified code from https://github.com/willfrey/audio/blob/master/torchaudio/transforms.py
"""
if not os.path.exists(path):
print("Directory doesn't exist: {}".format(path))
raise IOError
# self.paths = path is not None and librosa.util.find_files(path)
with open(path) as f:
self.paths = f.readlines()
self.sample_rate = sample_rate
self.noise_levels = noise_levels
def inject_noise(self, data):
noise_info_dic = json.loads(np.random.choice(self.paths))
noise_path = noise_info_dic['audio_filepath']
noise_level = np.random.uniform(*self.noise_levels)
return self.inject_noise_sample(data, noise_path, noise_level)
def inject_noise_sample(self, data, noise_path, noise_level):
# noise_len = get_audio_length(noise_path)
noise_len = sox.file_info.duration(noise_path)
data_len = len(data) / self.sample_rate
noise_start = np.random.rand() * (noise_len - data_len)
noise_end = noise_start + data_len
noise_dst = audio_with_sox(noise_path, self.sample_rate, noise_start, noise_end)
if len(data) != len(noise_dst):
data += 0
else:
noise_energy = np.sqrt(noise_dst.dot(noise_dst) / noise_dst.size)
data_energy = np.sqrt(data.dot(data) / data.size)
data += noise_level * noise_dst * data_energy / noise_energy
return data
class SpectrogramParser(AudioParser):
def __init__(self,
audio_conf,
speed_volume_perturb=False,
reverberation=False):
"""
Parses audio file into spectrogram with optional normalization and various augmentations
:param audio_conf: Dictionary containing the sample rate, window and the window length/stride in seconds
:param normalize(default False): Apply standard mean and deviation normalization to audio tensor
:param speed_volume_perturb(default False): Apply random tempo and gain perturbations
:param spec_augment(default False): Apply simple spectral augmentation to mel spectograms
"""
super(SpectrogramParser, self).__init__()
self.sample_rate = audio_conf['sample_rate']
self.speed_volume_perturb = speed_volume_perturb
self.reverberation = reverberation
self.noiseInjector = NoiseInjection(audio_conf['noise_dir'], self.sample_rate,
audio_conf['noise_levels']) if audio_conf.get(
'noise_dir') is not None else None
self.noise_prob = audio_conf.get('noise_prob')
self.reverb_prob = audio_conf.get('reverb_prob')
self.reverb = ReverbAugmentor(min_distance=3, max_distance=5)
def parse_audio(self, audio_path):
# os.system("cp {} {}/wav".format(audio_path, os.getcwd()))
if self.speed_volume_perturb:
y = load_randomly_augmented_audio(audio_path, self.sample_rate)
# sf.write('wav/aaaa_{}'.format(os.path.basename(audio_path)), y, self.sample_rate)
else:
y = load_audio(audio_path)
if self.reverberation:
add_reverb = np.random.binomial(1, self.reverb_prob)
if add_reverb:
y = self.reverb.add_reverb(y)
# sf.write('wav/bbbb_{}'.format(os.path.basename(audio_path)), y, self.sample_rate)
if self.noiseInjector:
add_noise = np.random.binomial(1, self.noise_prob)
if add_noise:
y = self.noiseInjector.inject_noise(y)
# sf.write('wav/cccc_{}'.format(os.path.basename(audio_path)), y, self.sample_rate)
y = torch.FloatTensor(y)
return y
def | (self, transcript_path):
raise NotImplementedError
class SpectrogramDataset(Dataset, SpectrogramParser):
def __init__(self,
audio_conf,
manifest_filepath,
labels,
word_form,
speed_volume_perturb=False,
reverberation=False,
min_durations=0.0,
max_durations=60.0):
"""
Dataset that loads tensors via a csv containing file paths to audio files and transcripts separated by
a comma. Each new line is a different sample. Example below:
/path/to/audio.wav,/path/to/audio.txt
...
:param audio_conf: Dictionary containing the sample rate
:param manifest_filepath: Path to manifest csv as describe above
:param labels: list containing all the possible characters to map to
:param normalize: Apply standard mean and deviation normalization to audio tensor
:param speed_volume_perturb(default False): Apply random tempo and gain perturbations
:param spec_augment(default False): Apply simple spectral augmentation to mel spectograms
"""
self.word_form_fict = {"sinogram": "text", "pinyin": "pinyin", "english": "fully_pinyin"}
with open(manifest_filepath) as f:
ids = f.readlines()
ids = [i for i in ids if min_durations < float(json.loads(i)['duration']) <= max_durations]
self.ids = sorted(ids, key=lambda x: float(json.loads(x)['duration']), reverse=True)
self.size = len(ids)
self.word_form = word_form
self.labels_map = dict([(labels[i], i) for i in range(len(labels))])
super(SpectrogramDataset, self).__init__(audio_conf, speed_volume_perturb, reverberation)
def __getitem__(self, index):
sample = json.loads(self.ids[index])
# print("sample: {}".format(sample['duration']))
audio_path, transcripts = sample['audio_filepath'], sample[self.word_form_fict[self.word_form]]
raw_data = self.parse_audio(audio_path)
transcript_id = self.parse_transcript(transcripts)
return raw_data, transcript_id
def parse_transcript(self, transcript):
if self.word_form == 'pinyin':
transcript_id = [self.label_numerical(x) for x in transcript.split(' ')]
elif self.word_form == 'sinogram' or self.word_form == 'english':
transcript_id = list(filter(None, [self.labels_map.get(x) for x in list(transcript)]))
else:
raise ValueError('wrong word form: {}'.format(self.word_form))
return transcript_id
def __len__(self):
return self.size
def label_numerical(self, x):
if self.labels_map.get(x) is not None:
return self.labels_map.get(x)
else:
return self.labels_map.get('.')
def _collate_fn(batch):
def func(p):
return p[0].size(0)
batch = sorted(batch, key=lambda sample: sample[0].size(0), reverse=True)
longest_sample = max(batch, key=func)[0]
minibatch_size = len(batch)
max_seqlength = longest_sample.size(0)
inputs = torch.zeros(minibatch_size, max_seqlength)
input_percentages = torch.FloatTensor(minibatch_size)
target_sizes = torch.IntTensor(minibatch_size)
targets = []
for x in range(minibatch_size):
sample = batch[x]
tensor = sample[0]
target = sample[1]
seq_length = tensor.size(0)
inputs[x].narrow(0, 0, seq_length).copy_(tensor)
input_percentages[x] = seq_length / float(max_seqlength)
target_sizes[x] = len(target)
targets.extend(target)
targets = torch.IntTensor(targets)
return inputs, targets, input_percentages, target_sizes
class AudioDataLoader(DataLoader):
def __init__(self, *args, **kwargs):
"""
Creates a data loader for AudioDatasets.
"""
super(AudioDataLoader, self).__init__(*args, **kwargs)
self.collate_fn = _collate_fn
class DSRandomSampler(Sampler):
"""
Implementation of a Random Sampler for sampling the dataset.
Added to ensure we reset the start index when an epoch is finished.
This is essential since we support saving/loading state during an epoch.
"""
def __init__(self, dataset, batch_size=1, start_index=0):
super().__init__(data_source=dataset)
self.dataset = dataset
self.start_index = start_index
self.batch_size = batch_size
ids = list(range(len(self.dataset)))
self.bins = [ids[i:i + self.batch_size] for i in range(0, len(ids), self.batch_size)]
def __iter__(self):
# deterministically shuffle based on epoch
g = torch.Generator()
g.manual_seed(self.epoch)
indices = (
torch.randperm(len(self.bins) - self.start_index, generator=g)
.add(self.start_index)
.tolist()
)
for x in indices:
batch_ids = self.bins[x]
np.random.shuffle(batch_ids)
yield batch_ids
def __len__(self):
return len(self.bins) - self.start_index
def set_epoch(self, epoch):
self.epoch = epoch
def reset_training_step(self, training_step):
self.start_index = training_step
class DSDistributedSampler(DistributedSampler):
"""
Overrides the DistributedSampler to ensure we reset the start index when an epoch is finished.
This is essential since we support saving/loading state during an epoch.
"""
def __init__(self, dataset, num_replicas=None, rank=None, start_index=0, batch_size=1):
super().__init__(dataset=dataset, num_replicas=num_replicas, rank=rank)
self.start_index = start_index
self.batch_size = batch_size
ids = list(range(len(dataset)))
self.bins = [ids[i:i + self.batch_size] for i in range(0, len(ids), self.batch_size)]
self.num_samples = int(
math.ceil(float(len(self.bins) - self.start_index) / self.num_replicas)
)
self.total_size = self.num_samples * self.num_replicas
def __iter__(self):
# deterministically shuffle based on epoch
g = torch.Generator()
g.manual_seed(self.epoch)
indices = (
torch.randperm(len(self.bins) - self.start_index, generator=g)
.add(self.start_index)
.tolist()
)
# print("self.bins : {}".format(self.bins))
indices = sorted(indices, reverse=False)
# print("indices : {}".format(indices))
# add extra samples to make it evenly divisible
indices += indices[: (self.total_size - len(indices))]
assert len(indices) == self.total_size
# subsample
indices = indices[self.rank: self.total_size: self.num_replicas]
assert len(indices) == self.num_samples
for x in indices:
batch_ids = self.bins[x]
np.random.shuffle(batch_ids)
yield batch_ids
def __len__(self):
return self.num_samples
def reset_training_step(self, training_step):
self.start_index = training_step
self.num_samples = int(
math.ceil(float(len(self.bins) - self.start_index) / self.num_replicas)
)
self.total_size = self.num_samples * self.num_replicas
def audio_with_sox(path, sample_rate, start_time, end_time):
"""
crop and resample the recording with sox and loads it.
"""
try:
with NamedTemporaryFile(suffix=".wav") as tar_file:
tar_filename = tar_file.name
sox_params = "sox \"{}\" -r {} -c 1 -b 16 -e si {} trim {} ={} >/dev/null 2>&1".format(path, sample_rate,
tar_filename,
start_time,
end_time)
os.system(sox_params)
y = load_audio(tar_filename)
except Exception as E:
y = load_audio(path)
return y
def augment_audio_with_sox(path, sample_rate, tempo, gain):
"""
Changes tempo and gain of the recording with sox and loads it.
"""
try:
with NamedTemporaryFile(suffix=".wav") as augmented_file:
augmented_filename = augmented_file.name
sox_augment_params = ["tempo", "{:.3f}".format(tempo), "gain", "{:.3f}".format(gain)]
sox_params = "sox \"{}\" -r {} -c 1 -b 16 -e si {} {} >/dev/null 2>&1".format(path, sample_rate,
augmented_filename,
" ".join(sox_augment_params))
os.system(sox_params)
y = load_audio(augmented_filename)
except Exception as E:
y = load_audio(path)
return y
def load_randomly_augmented_audio(path, sample_rate=16000, tempo_range=(0.85, 1.15),
gain_range=(-6, 8)):
"""
Picks tempo and gain uniformly, applies it to the utterance by using sox utility.
Returns the augmented utterance.
"""
low_tempo, high_tempo = tempo_range
tempo_value = np.random.uniform(low=low_tempo, high=high_tempo)
low_gain, high_gain = gain_range
gain_value = np.random.uniform(low=low_gain, high=high_gain)
audio = augment_audio_with_sox(path=path, sample_rate=sample_rate,
tempo=tempo_value, gain=gain_value)
return audio
| parse_transcript | identifier_name |
data_loader.py | # coding:utf-8
#
#
import os
import sox
import math
import json
import torch
import numpy as np
import soundfile as sf
from tempfile import NamedTemporaryFile
from .adding_reverb import ReverbAugmentor
from torch.utils.data import Dataset, Sampler, DistributedSampler, DataLoader
def load_audio(path):
sound, sample_rate = sf.read(path, dtype='int16')
sound = sound.astype('float32') / 32767 # normalize audio
if len(sound.shape) > 1:
if sound.shape[1] == 1:
sound = sound.squeeze()
else:
sound = sound.mean(axis=1) # multiple channels, average
return sound
class AudioParser(object):
def parse_transcript(self, transcript_path):
"""
:param transcript_path: Path where transcript is stored from the manifest file
:return: Transcript in training/testing format
"""
raise NotImplementedError
def parse_audio(self, audio_path):
"""
:param audio_path: Path where audio is stored from the manifest file
:return: Audio in training/testing format
"""
raise NotImplementedError
class NoiseInjection(object):
def __init__(self,
path=None,
sample_rate=16000,
noise_levels=(0, 0.5)):
"""
Adds noise to an input signal with specific SNR. Higher the noise level, the more noise added.
Modified code from https://github.com/willfrey/audio/blob/master/torchaudio/transforms.py
"""
if not os.path.exists(path):
print("Directory doesn't exist: {}".format(path))
raise IOError
# self.paths = path is not None and librosa.util.find_files(path)
with open(path) as f:
self.paths = f.readlines()
self.sample_rate = sample_rate
self.noise_levels = noise_levels
def inject_noise(self, data):
noise_info_dic = json.loads(np.random.choice(self.paths))
noise_path = noise_info_dic['audio_filepath']
noise_level = np.random.uniform(*self.noise_levels)
return self.inject_noise_sample(data, noise_path, noise_level)
def inject_noise_sample(self, data, noise_path, noise_level):
# noise_len = get_audio_length(noise_path)
noise_len = sox.file_info.duration(noise_path)
data_len = len(data) / self.sample_rate
noise_start = np.random.rand() * (noise_len - data_len)
noise_end = noise_start + data_len
noise_dst = audio_with_sox(noise_path, self.sample_rate, noise_start, noise_end)
if len(data) != len(noise_dst):
data += 0
else:
noise_energy = np.sqrt(noise_dst.dot(noise_dst) / noise_dst.size)
data_energy = np.sqrt(data.dot(data) / data.size)
data += noise_level * noise_dst * data_energy / noise_energy
return data
class SpectrogramParser(AudioParser):
def __init__(self,
audio_conf,
speed_volume_perturb=False,
reverberation=False):
"""
Parses audio file into spectrogram with optional normalization and various augmentations
:param audio_conf: Dictionary containing the sample rate, window and the window length/stride in seconds
:param normalize(default False): Apply standard mean and deviation normalization to audio tensor
:param speed_volume_perturb(default False): Apply random tempo and gain perturbations
:param spec_augment(default False): Apply simple spectral augmentation to mel spectograms
"""
super(SpectrogramParser, self).__init__()
self.sample_rate = audio_conf['sample_rate']
self.speed_volume_perturb = speed_volume_perturb
self.reverberation = reverberation
self.noiseInjector = NoiseInjection(audio_conf['noise_dir'], self.sample_rate,
audio_conf['noise_levels']) if audio_conf.get(
'noise_dir') is not None else None
self.noise_prob = audio_conf.get('noise_prob')
self.reverb_prob = audio_conf.get('reverb_prob')
self.reverb = ReverbAugmentor(min_distance=3, max_distance=5)
def parse_audio(self, audio_path):
# os.system("cp {} {}/wav".format(audio_path, os.getcwd()))
if self.speed_volume_perturb: | add_reverb = np.random.binomial(1, self.reverb_prob)
if add_reverb:
y = self.reverb.add_reverb(y)
# sf.write('wav/bbbb_{}'.format(os.path.basename(audio_path)), y, self.sample_rate)
if self.noiseInjector:
add_noise = np.random.binomial(1, self.noise_prob)
if add_noise:
y = self.noiseInjector.inject_noise(y)
# sf.write('wav/cccc_{}'.format(os.path.basename(audio_path)), y, self.sample_rate)
y = torch.FloatTensor(y)
return y
def parse_transcript(self, transcript_path):
raise NotImplementedError
class SpectrogramDataset(Dataset, SpectrogramParser):
def __init__(self,
audio_conf,
manifest_filepath,
labels,
word_form,
speed_volume_perturb=False,
reverberation=False,
min_durations=0.0,
max_durations=60.0):
"""
Dataset that loads tensors via a csv containing file paths to audio files and transcripts separated by
a comma. Each new line is a different sample. Example below:
/path/to/audio.wav,/path/to/audio.txt
...
:param audio_conf: Dictionary containing the sample rate
:param manifest_filepath: Path to manifest csv as describe above
:param labels: list containing all the possible characters to map to
:param normalize: Apply standard mean and deviation normalization to audio tensor
:param speed_volume_perturb(default False): Apply random tempo and gain perturbations
:param spec_augment(default False): Apply simple spectral augmentation to mel spectograms
"""
self.word_form_fict = {"sinogram": "text", "pinyin": "pinyin", "english": "fully_pinyin"}
with open(manifest_filepath) as f:
ids = f.readlines()
ids = [i for i in ids if min_durations < float(json.loads(i)['duration']) <= max_durations]
self.ids = sorted(ids, key=lambda x: float(json.loads(x)['duration']), reverse=True)
self.size = len(ids)
self.word_form = word_form
self.labels_map = dict([(labels[i], i) for i in range(len(labels))])
super(SpectrogramDataset, self).__init__(audio_conf, speed_volume_perturb, reverberation)
def __getitem__(self, index):
sample = json.loads(self.ids[index])
# print("sample: {}".format(sample['duration']))
audio_path, transcripts = sample['audio_filepath'], sample[self.word_form_fict[self.word_form]]
raw_data = self.parse_audio(audio_path)
transcript_id = self.parse_transcript(transcripts)
return raw_data, transcript_id
def parse_transcript(self, transcript):
if self.word_form == 'pinyin':
transcript_id = [self.label_numerical(x) for x in transcript.split(' ')]
elif self.word_form == 'sinogram' or self.word_form == 'english':
transcript_id = list(filter(None, [self.labels_map.get(x) for x in list(transcript)]))
else:
raise ValueError('wrong word form: {}'.format(self.word_form))
return transcript_id
def __len__(self):
return self.size
def label_numerical(self, x):
if self.labels_map.get(x) is not None:
return self.labels_map.get(x)
else:
return self.labels_map.get('.')
def _collate_fn(batch):
def func(p):
return p[0].size(0)
batch = sorted(batch, key=lambda sample: sample[0].size(0), reverse=True)
longest_sample = max(batch, key=func)[0]
minibatch_size = len(batch)
max_seqlength = longest_sample.size(0)
inputs = torch.zeros(minibatch_size, max_seqlength)
input_percentages = torch.FloatTensor(minibatch_size)
target_sizes = torch.IntTensor(minibatch_size)
targets = []
for x in range(minibatch_size):
sample = batch[x]
tensor = sample[0]
target = sample[1]
seq_length = tensor.size(0)
inputs[x].narrow(0, 0, seq_length).copy_(tensor)
input_percentages[x] = seq_length / float(max_seqlength)
target_sizes[x] = len(target)
targets.extend(target)
targets = torch.IntTensor(targets)
return inputs, targets, input_percentages, target_sizes
class AudioDataLoader(DataLoader):
def __init__(self, *args, **kwargs):
"""
Creates a data loader for AudioDatasets.
"""
super(AudioDataLoader, self).__init__(*args, **kwargs)
self.collate_fn = _collate_fn
class DSRandomSampler(Sampler):
"""
Implementation of a Random Sampler for sampling the dataset.
Added to ensure we reset the start index when an epoch is finished.
This is essential since we support saving/loading state during an epoch.
"""
def __init__(self, dataset, batch_size=1, start_index=0):
super().__init__(data_source=dataset)
self.dataset = dataset
self.start_index = start_index
self.batch_size = batch_size
ids = list(range(len(self.dataset)))
self.bins = [ids[i:i + self.batch_size] for i in range(0, len(ids), self.batch_size)]
def __iter__(self):
# deterministically shuffle based on epoch
g = torch.Generator()
g.manual_seed(self.epoch)
indices = (
torch.randperm(len(self.bins) - self.start_index, generator=g)
.add(self.start_index)
.tolist()
)
for x in indices:
batch_ids = self.bins[x]
np.random.shuffle(batch_ids)
yield batch_ids
def __len__(self):
return len(self.bins) - self.start_index
def set_epoch(self, epoch):
self.epoch = epoch
def reset_training_step(self, training_step):
self.start_index = training_step
class DSDistributedSampler(DistributedSampler):
"""
Overrides the DistributedSampler to ensure we reset the start index when an epoch is finished.
This is essential since we support saving/loading state during an epoch.
"""
def __init__(self, dataset, num_replicas=None, rank=None, start_index=0, batch_size=1):
super().__init__(dataset=dataset, num_replicas=num_replicas, rank=rank)
self.start_index = start_index
self.batch_size = batch_size
ids = list(range(len(dataset)))
self.bins = [ids[i:i + self.batch_size] for i in range(0, len(ids), self.batch_size)]
self.num_samples = int(
math.ceil(float(len(self.bins) - self.start_index) / self.num_replicas)
)
self.total_size = self.num_samples * self.num_replicas
def __iter__(self):
# deterministically shuffle based on epoch
g = torch.Generator()
g.manual_seed(self.epoch)
indices = (
torch.randperm(len(self.bins) - self.start_index, generator=g)
.add(self.start_index)
.tolist()
)
# print("self.bins : {}".format(self.bins))
indices = sorted(indices, reverse=False)
# print("indices : {}".format(indices))
# add extra samples to make it evenly divisible
indices += indices[: (self.total_size - len(indices))]
assert len(indices) == self.total_size
# subsample
indices = indices[self.rank: self.total_size: self.num_replicas]
assert len(indices) == self.num_samples
for x in indices:
batch_ids = self.bins[x]
np.random.shuffle(batch_ids)
yield batch_ids
def __len__(self):
return self.num_samples
def reset_training_step(self, training_step):
self.start_index = training_step
self.num_samples = int(
math.ceil(float(len(self.bins) - self.start_index) / self.num_replicas)
)
self.total_size = self.num_samples * self.num_replicas
def audio_with_sox(path, sample_rate, start_time, end_time):
"""
crop and resample the recording with sox and loads it.
"""
try:
with NamedTemporaryFile(suffix=".wav") as tar_file:
tar_filename = tar_file.name
sox_params = "sox \"{}\" -r {} -c 1 -b 16 -e si {} trim {} ={} >/dev/null 2>&1".format(path, sample_rate,
tar_filename,
start_time,
end_time)
os.system(sox_params)
y = load_audio(tar_filename)
except Exception as E:
y = load_audio(path)
return y
def augment_audio_with_sox(path, sample_rate, tempo, gain):
"""
Changes tempo and gain of the recording with sox and loads it.
"""
try:
with NamedTemporaryFile(suffix=".wav") as augmented_file:
augmented_filename = augmented_file.name
sox_augment_params = ["tempo", "{:.3f}".format(tempo), "gain", "{:.3f}".format(gain)]
sox_params = "sox \"{}\" -r {} -c 1 -b 16 -e si {} {} >/dev/null 2>&1".format(path, sample_rate,
augmented_filename,
" ".join(sox_augment_params))
os.system(sox_params)
y = load_audio(augmented_filename)
except Exception as E:
y = load_audio(path)
return y
def load_randomly_augmented_audio(path, sample_rate=16000, tempo_range=(0.85, 1.15),
gain_range=(-6, 8)):
"""
Picks tempo and gain uniformly, applies it to the utterance by using sox utility.
Returns the augmented utterance.
"""
low_tempo, high_tempo = tempo_range
tempo_value = np.random.uniform(low=low_tempo, high=high_tempo)
low_gain, high_gain = gain_range
gain_value = np.random.uniform(low=low_gain, high=high_gain)
audio = augment_audio_with_sox(path=path, sample_rate=sample_rate,
tempo=tempo_value, gain=gain_value)
return audio | y = load_randomly_augmented_audio(audio_path, self.sample_rate)
# sf.write('wav/aaaa_{}'.format(os.path.basename(audio_path)), y, self.sample_rate)
else:
y = load_audio(audio_path)
if self.reverberation: | random_line_split |
IMMA2nc1.py | # -*- coding: utf-8 -*-
# Purpose: Python module for processing and saving IMMA1 to netCDF 4
# same shortnames are used as the IMMA1 data, please refere to IMMA1 documentation for more details
# IMMA1 documentation is at https://rda.ucar.edu/datasets/ds548.0/#!docs
# History: developed by Zhankun Wang between Oct 2016 and May 2017 for the BEDI ICOADS project
# (c) NOAA National Centers for Environmental Information
# contact: zhankun.wang@noaa.gov
import uuid
import time
import netCDF4
import numpy as np
import os
import jdutil
# change the path to where the program and documents are saved. one level above
fpath_default = '/nodc/projects/tsg/zwang/ICOADS/codes'
# change to where the python codes saved
os.chdir(fpath_default)
time_fmt = "%Y-%m-%dT%H:%M:%SZ"
att_doc = 2
if att_doc == 1:
f = open('%sTables_ICOADS.csv' %fpath_default, 'r')
lines = f.readlines()
lines = [x.rstrip("\r\n") for x in lines]
f.close()
No = [x.split(',')[0] for x in lines]
length = [x.split(',')[1] for x in lines]
abbr = [x.split(',')[2].upper() for x in lines]
longname = [x.split(',')[3] for x in lines]
min_values = [x.split(',')[4] for x in lines]
max_values = [x.split(',')[5] for x in lines]
units = [x.split(',')[6] for x in lines]
comments = [x.split(',')[7:] for x in lines]
elif att_doc == 2:
f = open('%sicoads_dsv.csv' %fpath_default, 'r')
lines = f.readlines()
lines = [x.rstrip("\r\n") for x in lines]
lines = [x.rstrip("\xa0") for x in lines]
f.close()
ancillary = [x.split(',')[1] for x in lines]
names = [x.split(',')[2] for x in lines]
units = [x.split(',')[5] for x in lines]
min_values = [x.split(',')[6] for x in lines]
max_values = [x.split(',')[7] for x in lines]
longname = [x.split(',')[9] for x in lines]
flagvalues = [x.split(',')[10] for x in lines]
# flagvalues = [x.replace(' ',',') for x in flagvalues]
flagmeanings = [x.split(',')[17] for x in lines]
standardname = [x.split(',')[18] for x in lines]
scaledtype = [x.split(',')[16] for x in lines]
comments = [x.split(',')[19] for x in lines]
keywords_list = [x.split(',')[22] for x in lines]
abbr = [x.split('-')[0] for x in names]
abbr_e = [x.split('-')[1] if '-' in x else x for x in names]
flagvalues = [x if 'blank' not in x else '' for x in flagvalues]
else:
print('Error: No proper variable attributes document is found!')
parameters = {}
attachment = {}
atta_list = [0,1,5,6,7,8,9,95,96,97,98,99]
attachment['00'] = 'CORE'
parameters['00'] = ('YR','MO','DY','HR','LAT','LON','IM','ATTC','TI','LI','DS','VS','NID','II','ID','C1','DI','D','WI','W','VI','VV','WW','W1','SLP','A','PPP','IT','AT','WBTI','WBT','DPTI','DPT','SI','SST','N','NH','CL','HI','H','CM','CH','WD','WP','WH','SD','SP','SH')
attachment['01'] = 'ICOADS ATTACHMENT'
parameters['01'] = ('BSI','B10','B1','DCK','SID','PT','DUPS','DUPC','TC','PB','WX','SX','C2','SQZ','SQA','AQZ','AQA','UQZ','UQA','VQZ','VQA','PQZ','PQA','DQZ','DQA','ND','SF','AF','UF','VF','PF','RF','ZNC','WNC','BNC','XNC','YNC','PNC','ANC','GNC','DNC','SNC','CNC','ENC','FNC','TNC','QCE','LZ','QCZ')
attachment['05'] = 'IMMT-5/FM13 ATTACHMENT'
parameters['05'] = ('OS','OP','FM','IMMV','IX','W2','WMI','SD2','SP2','SH2','IS','ES','RS','IC1','IC2','IC3','IC4','IC5','IR','RRR','TR','NU','QCI','QI1','QI2','QI3','QI4','QI5','QI6','QI7','QI8','QI9','QI10','QI11','QI12','QI13','QI14','QI15','QI16','QI17','QI18','QI19','QI20','QI21','HDG','COG','SOG','SLL','SLHH','RWD','RWS','QI22','QI23','QI24','QI25','QI26','QI27','QI28','QI29','RH','RHI','AWSI','IMONO')
attachment['06'] = 'MODEL QUALITY CONTROL ATTACHMENT'
parameters['06'] = ('CCCC','BUID','FBSRC','BMP','BSWU','SWU','BSWV','SWV','BSAT','BSRH','SRH','BSST','MST','MSH','BY','BM','BD','BH','BFL')
attachment['07'] = 'SHIP METADATA ATTACHMENT'
parameters['07'] = ('MDS','C1M','OPM','KOV','COR','TOB','TOT','EOT','LOT','TOH','EOH','SIM','LOV','DOS','HOP','HOT','HOB','HOA','SMF','SME','SMV')
attachment['08'] = 'NEAR-SURFACE OCEANOGRAPHIC DATA ATTACHMENT'
parameters['08'] = ('OTV','OTZ','OSV','OSZ','OOV','OOZ','OPV','OPZ','OSIV','OSIZ','ONV','ONZ','OPHV','OPHZ','OCV','OCZ','OAV','OAZ','OPCV','OPCZ','ODV','ODZ','PUID')
attachment['09'] = 'EDITED CLOUD REPORT ATTACHMENT'
parameters['09'] = ('CCE','WWE','NE','NHE','HE','CLE','CME','CHE','AM','AH','UM','UH','SBI','SA','RI')
attachment['95'] = 'REANALYSES QC/FEEDBACK ATTACHMENT'
parameters['95'] = ('ICNR','FNR','DPRO','DPRP','UFR','MFGR','MFGSR','MAR','MASR','BCR','ARCR','CDR','ASIR')
attachment['96'] = 'ICOADS VALUE-ADDED DATABASE ATTACHMENT'
parameters['96'] = ('ICNI','FNI','JVAD','VAD','IVAU1','JVAU1','VAU1','IVAU2','JVAU2','VAU2','IVAU3','JVAU3','VAU3','VQC','ARCI','CDI','ASII')
attachment['97'] = 'ERROR ATTACHMENT'
parameters['97'] = ('ICNE','FNE','CEF','ERRD','ARCE','CDE','ASIE')
attachment['98'] = 'UNIQUE ID ATTACHMENT'
parameters['98'] = ('UID','RN1','RN2','RN3','RSA','IRF')
attachment['99'] = 'SUPPLEMENTAL DATA ATTACHMENT'
parameters['99'] = ('ATTE','SUPD')
def get_var_att(var):
idx = abbr.index(var)
if att_doc == 1:
att = {'abbr':var,'longname':longname[idx],'min_v':min_values[idx],'max_v': max_values[idx],'unit':units[idx], 'comment': comments[idx]}
elif att_doc == 2:
att = {'abbr':var,'ancillary':ancillary[idx],'standardname':standardname[idx],'scaledtype':scaledtype[idx],'longname':longname[idx],'min_v':min_values[idx],'max_v': max_values[idx],'unit':units[idx], 'comment': comments[idx], 'flagvalues': flagvalues[idx], 'flagmeanings':flagmeanings[idx]}
else:
print('Error: No attribute document found.')
return att
def get_ancillary(anc_QC, check_list):
var = anc_QC.split(';')
var = [x.split('-')[0].strip() for x in var]
var = [x for x in var if x in check_list ]
return ' '.join(var)
def getParameters(i):
return parameters["%02d" % i]
def save(out_file,data, **kwargs):
def duration(seconds):
t= []
for dm in (60, 60, 24, 7):
seconds, m = divmod(seconds, dm)
t.append(m)
t.append(seconds)
return ''.join('%d%s' % (num, unit)
for num, unit in zip(t[::-1], 'W DT H M S'.split())
if num)
def get_keywords(data):
keywords = []
for var in data.data.keys():
if var in abbr:
idx = abbr.index(var)
if len(keywords_list[idx])>0:
keywords.append(keywords_list[idx])
# print var, keywords_list[idx]
keywords = list(set(keywords))
keywords = ['Earth Science > %s' %x for x in keywords]
keywords = ', '.join(keywords)
return keywords
def Add_gattrs(ff):
lon_min = min(data['LON'])
lon_max = max(data['LON'])
lat_min = min(data['LAT'])
lat_max = max(data['LAT'])
start_time = min(data.data['Julian'])
end_time = max(data.data['Julian'])
dur_time = (end_time-start_time)*24.0*3600.0
start_time = jdutil.jd_to_datetime(start_time)
start_time_s = "%s-%02d-%02dT%02d:%02d:%02dZ" %(start_time.year,start_time.month,start_time.day,start_time.hour,start_time.minute,start_time.second)
end_time = jdutil.jd_to_datetime(end_time)
end_time_s = "%s-%02d-%02dT%02d:%02d:%02dZ" %(end_time.year,end_time.month,end_time.day,end_time.hour,end_time.minute,end_time.second)
version = out_file.split('_')[1]
#start_time_s = time.strftime(time_fmt,time.gmtime(float(start_time)))
#end_time_s = time.strftime(time_fmt,time.gmtime(float(end_time)))
ff.ncei_template_version = "NCEI_NetCDF_Point_Template_v2.0"
ff.featureType = "point"
ff.title = "International Comprehensive Ocean-Atmosphere Data Set (ICOADS) %s data collected from %s to %s." %(version, start_time_s, end_time_s)
ff.summary = "This file contains ICOADS %s data in netCDF4 format collected from %s to %s. The International Comprehensive Ocean-Atmosphere Data Set (ICOADS) offers surface marine data spanning the past three centuries, and simple gridded monthly summary products for 2-degree latitude x 2-degree longitude boxes back to 1800 (and 1degreex1degree boxes since 1960)--these data and products are freely distributed worldwide. As it contains observations from many different observing systems encompassing the evolution of measurement technology over hundreds of years, ICOADS is probably the most complete and heterogeneous collection of surface marine data in existence." %(version, start_time_s, end_time_s)
ff.keywords = get_keywords(data);
ff.Conventions = "CF-1.6, ACDD-1.3"
ff.id = out_file.split('.nc')[0].replace('IMMA1','ICOADS')
ff.naming_authority = "gov.noaa.ncei"
#ff.source = "http://rda.ucar.edu/data/ds548.0/imma1_r3.0.0/%s.tar" %out_file.split('-')[0]
ff.source = "%s.gz" %out_file.split('.nc')[0]
ff.processing_level = "Restructured from IMMA1 format to NetCDF4 format."
ff.acknowledgement = "Conversion of ICOADS data from IMMA1 to netCDF format by NCEI is supported by the NOAA Big Earth Data Initiative (BEDI)."
ff.license = "These data may be redistributed and used without restriction."
ff.standard_name_vocabulary = "CF Standard Name Table v31"
ff.date_created = time.strftime(time_fmt,time.gmtime())
ff.creator_name = "NCEI"
ff.creator_email = "ncei.info@noaa.gov"
ff.creator_url = "https://www.ncei.noaa.gov/"
ff.institution = "National Centers for Environmental Information (NCEI), NOAA"
ff.project = "International Comprehensive Ocean-Atmosphere Data Set (ICOADS) Project"
ff.publisher_name = "NCEI"
ff.publisher_email = "ncei.info@noaa.gov"
ff.publisher_url = "https://www.ncei.noaa.gov/"
ff.geospatial_bounds = "POLYGON ((%.4f %.4f,%.4f %.4f,%.4f %.4f,%.4f %.4f,%.4f %.4f))" %(lon_min,lat_min,lon_min,lat_max,lon_max,lat_max,lon_max,lat_min,lon_min,lat_min)
ff.geospatial_bounds_crs = "EPSG:4326"
ff.geospatial_lat_min = float("%.4f" %(lat_min))
ff.geospatial_lat_max = float("%.4f" %(lat_max))
ff.geospatial_lon_min = float("%.4f" %(lon_min))
ff.geospatial_lon_max = float("%.4f" %(lon_max))
ff.geospatial_lat_units = "degrees_north"
ff.geospatial_lon_units = "degrees_east"
ff.time_coverage_start = start_time_s
ff.time_coverage_end = end_time_s
ff.time_coverage_duration = 'P' + duration(dur_time)
ff.time_coverage_resolution = "vary"
ff.uuid = str(uuid.uuid4())
ff.sea_name = "World-Wide Distribution"
ff.creator_type = "group"
ff.creator_institution = "NOAA National Centers for Environmental Information (NCEI)"
ff.publisher_type = "institution"
ff.publisher_institution = "NOAA National Centers for Environmental Information (NCEI)"
ff.program = ""
ff.contributor_name = "Zhankun Wang; ICOADS team"
ff.contributor_role = "ICOADS Data Conversion to NetCDF; ICOADS IMMA1 Data Provider"
ff.date_modified = time.strftime(time_fmt,time.gmtime())
ff.date_issued = time.strftime(time_fmt,time.gmtime())
ff.date_metadata_modified = time.strftime(time_fmt,time.gmtime())
ff.product_version = "ICOADS %s netCDF4" %version
ff.keywords_vocabulary = "Global Change Master Directory (GCMD) 2015. GCMD Keywords, Version 8.1."
ff.cdm_data_type = 'Point'
#ff.metadata_link = 'http://rda.ucar.edu/datasets/ds548.0/#!docs'
ff.metadata_link = ''
if len(set(data.data['IM'])) == 1:
ff.IMMA_Version = str(data.data['IM'][0])
else:
|
if len(set(data.data['RN1'])) == 1:
ff.Release_Number_Primary = str(data.data['RN1'][0])
else:
print('%s: check Release_Number_Primary' %out_file)
if len(set(data.data['RN2'])) == 1:
ff.Release_Number_Secondary = str(data.data['RN2'][0])
else:
print('%s: check Release_Number_Secondary' %out_file)
if len(set(data.data['RN3'])) == 1:
ff.Release_Number_Tertiary = str(data.data['RN3'][0])
else:
print('%s: check Release_Number_Tertiary' %out_file)
if len(set(data.data['RSA'])) == 1:
ff.Release_status_indicator = str(data.data['RSA'][0])
else:
print('%s: check RSA' %out_file)
#ff.comment = ""
ff.references = 'http://rda.ucar.edu/datasets/ds548.0/docs/R3.0-citation.pdf'
ff.history = time.strftime(time_fmt,time.gmtime()) + ": Converted from IMMA1 format to netCDF4 format by Z.W. "
fpath = kwargs.get('fpath')
if fpath is None:
fpath = fpath_default
#ftxt = open("%s%s.txt" %(fpath,out_file[0:-3]), 'w')
#ftxt.write('Saving to %s ...\n' %out_file);
ff = netCDF4.Dataset(fpath + out_file.replace('IMMA1','ICOADS'), 'w', format='NETCDF4')
Add_gattrs(ff)
ff.createDimension('obs',len(data.data['YR']))
'''
# save time in Julian Days
timein = ff.createVariable('time','f8',('obs',),zlib=True,complevel=4)
timein.long_name = "time"
timein.standard_name = "time"
timein.units = "days since -4713-1-1 12:0:0 "
timein.calendar = "julian"
timein.axis = "T"
timein.comment = "Julian days since noon on January 1, 4713 BC. Missing values of date (DD in date) are replaced by 0 and missing values in HR are filled with 0.0 in this calculation. See actural values in date, HR for reference."
timein[:] = data.data['Julian'][:]
'''
# save time in Julian Days since the beginning of ICOADS data: 1662-10-15 12:00:00
timein = ff.createVariable('time','f8',('obs',),zlib=True,complevel=4)
timein.long_name = "time"
timein.standard_name = "time"
timein.units = "days since 1662-10-15 12:00:00"
timein.calendar = "julian"
timein.axis = "T"
timein.comment = "Julian days since the beginning of the ICOADS record, which is 1662-10-15 12:00:00. Missing values of date (DD in date) are replaced by 0 and missing values in HR are filled with 0.0 in this calculation. See actual values in date, HR for reference."
timein[:] = data.data['Julian1'][:]
# save date in YYYYMMDD
ff.createDimension('DATE_len',len(data.data['DATE'][0]))
date = ff.createVariable('date','S1',('obs','DATE_len',),zlib=True,complevel=4)
date.long_name = "date in YYYYMMDD"
#date.valid_min = '16000101'
#date.valid_max = '20241231'
date.format = 'YYYYMMDD'
#date.axis = "T"
date.comment = "YYYY: four digital year, MM: two digital month and DD: two digital date. Missing values of DD have been filled with 99."
date[:] = [netCDF4.stringtochar(np.array(x)) for x in data.data['DATE']]
#print data.data['YR']
crsout = ff.createVariable('crs','i')
crsout.grid_mapping_name = "latitude_longitude"
crsout.epsg_code = "EPSG:4326"
crsout.semi_major_axis = 6378137.0
crsout.inverse_flattening = 298.257223563
#crsout.comment = ''
dim_list = []
dim_dir = []
exclusives = ['YR','MO','DY','SUPD','IM','ATTC','ATTE','RN1','RN2','RN3','RSA']
'''
exclusives_2 = ['CDE','CDI','YR','MO','DY','SUPD','IM','ATTC','ATTE','RN1','RN2','RN3','RSA','ICNR','FNR','DPRO','DPRP','UFR','MFGR','MFGSR','MAR','MASR','BCR','ARCR','CDR','ASIR']
for atta in atta_list:
var_list = getParameters(atta)
for var in var_list:
if var in exclusives_2:
pass
else:
print var
att = get_var_att(var)
if 'flagvalues' in att:
if len(att['flagvalues']) > 0:
print var, att['flagvalues'], att['flagmeanings']
foo = att['flagvalues'].split(' ')
foo_m = att['flagmeanings'].split(' ')
for x,y in zip(foo,foo_m): print('%s: %s' %(x,y))
'''
for atta in atta_list:
var_list = getParameters(atta)
for var in var_list:
if var in data.data.keys():
if var in exclusives:
pass
else:
start = time.time()
#ftxt.write('%s start at %s. ' %(var,time.strftime(time_fmt,time.gmtime())));
index = [i for i, x in enumerate(data.data[var]) if x is not None]
# print var,data[var],index[0],data.data[var][index[0]]
if type(data.data[var][index[0]]) is int:
dataout = ff.createVariable(var,'i2',('obs',),fill_value = -99,zlib=True,complevel=4)
#dataout = ff.createVariable(var,'f4',('obs',),zlib=True,complevel=4)
dataout[index] = [data.data[var][idx] for idx in index]
elif type(data.data[var][index[0]]) is float:
if var == 'LAT':
dataout = ff.createVariable('lat','f4',('obs',),zlib=True,complevel=4)
elif var == 'LON':
dataout = ff.createVariable('lon','f4',('obs',),zlib=True,complevel=4)
else:
dataout = ff.createVariable(var,'f4',('obs',),fill_value = float(-9999),zlib=True,complevel=4)
dataout[index] = [data.data[var][idx] for idx in index]
elif type(data.data[var][index[0]]) is str:
#print var
if var == 'SUPD':
#ll = max([len(x) if x is not None else 0 for x in data.data[var] ])
#data.data[var] = [x.ljust(ll) if x is not None else None for x in data.data[var]]
pass
else:
ll = len(data.data[var][index[0]])
if ll not in dim_list:
ff.createDimension('%s_len' %var,ll)
dataout = ff.createVariable(var,'S1',('obs','%s_len' %var,),zlib=True,complevel=4)
dim_list.append(ll)
dim_dir.append(var)
else:
idx = dim_list.index(ll)
dataout = ff.createVariable(var,'S1',('obs','%s_len' %dim_dir[idx],),zlib=True,complevel=4)
dataout[index] = [netCDF4.stringtochar(np.array(data.data[var][idx])) for idx in index]
else:
print var, type(data.data[var][index[0]])
att = get_var_att(var)
if 'standardname' in att:
if len(att['standardname']) >0: dataout.standard_name = att['standardname']
dataout.long_name = att['longname'] if len(att['longname']) > 0 else ""
if len(att['unit']) > 0: dataout.units = att['unit']
if len(att['min_v']) > 0:
if 'int' in att['scaledtype']:
dataout.valid_min = np.int16(att['min_v'])
elif 'double' in att['scaledtype']:
dataout.valid_min = float(att['min_v'])
else:
dataout.valid_min = float(att['min_v'])
if len(att['max_v']) > 0:
if 'int' in att['scaledtype']:
dataout.valid_max = np.int16(att['max_v'])
elif 'double' in att['scaledtype']:
dataout.valid_max = float(att['max_v'])
else:
dataout.valid_max = float(att['max_v'])
if var == 'LAT': dataout.axis = 'Y'
if var == 'LON': dataout.axis = 'X'
#if len(att['min_v']) > 0:
# dataout.scale_factor = 1.
# dataout.add_offset = 0.
if 'flagvalues' in att:
if len(att['flagvalues']) >0:
foo = att['flagvalues'].split(' ')
dataout.flag_values = [np.int16(x) for x in foo]
if len(att['flagmeanings']) >0: dataout.flag_meanings = att['flagmeanings']
if var != 'LAT' and var != 'LON':
dataout.coordinates = "time lat lon"
dataout.grid_mapping = "crs"
dataout.cell_methods = "time: point"
if len(att['comment']) > 0: dataout.comment = att['comment']
if len(get_ancillary(att['ancillary'],data.data.keys())) > 0: dataout.ancillary_variables = get_ancillary(att['ancillary'],data.data.keys())
end = time.time()
#print var, end-start
#ftxt.write('Time used = %s sec\n' %(end-start));
#dataout.standard_name = "sea_surface_temperature"
#dataout.long_name = "Sea surface temperature"
#dataout.units = "degree_Celsius"
#ftxt.write('Done with %s' %out_file)
ff.close()
#ftxt.close()
| print('%s: check IMMA version' %out_file) | conditional_block |
IMMA2nc1.py | # -*- coding: utf-8 -*-
# Purpose: Python module for processing and saving IMMA1 to netCDF 4
# same shortnames are used as the IMMA1 data, please refere to IMMA1 documentation for more details
# IMMA1 documentation is at https://rda.ucar.edu/datasets/ds548.0/#!docs
# History: developed by Zhankun Wang between Oct 2016 and May 2017 for the BEDI ICOADS project
# (c) NOAA National Centers for Environmental Information
# contact: zhankun.wang@noaa.gov
import uuid
import time
import netCDF4
import numpy as np
import os
import jdutil
# change the path to where the program and documents are saved. one level above
fpath_default = '/nodc/projects/tsg/zwang/ICOADS/codes'
# change to where the python codes saved
os.chdir(fpath_default)
time_fmt = "%Y-%m-%dT%H:%M:%SZ"
att_doc = 2
if att_doc == 1:
f = open('%sTables_ICOADS.csv' %fpath_default, 'r')
lines = f.readlines()
lines = [x.rstrip("\r\n") for x in lines]
f.close()
No = [x.split(',')[0] for x in lines]
length = [x.split(',')[1] for x in lines]
abbr = [x.split(',')[2].upper() for x in lines]
longname = [x.split(',')[3] for x in lines]
min_values = [x.split(',')[4] for x in lines]
max_values = [x.split(',')[5] for x in lines]
units = [x.split(',')[6] for x in lines]
comments = [x.split(',')[7:] for x in lines]
elif att_doc == 2:
f = open('%sicoads_dsv.csv' %fpath_default, 'r')
lines = f.readlines()
lines = [x.rstrip("\r\n") for x in lines]
lines = [x.rstrip("\xa0") for x in lines]
f.close()
ancillary = [x.split(',')[1] for x in lines]
names = [x.split(',')[2] for x in lines]
units = [x.split(',')[5] for x in lines]
min_values = [x.split(',')[6] for x in lines]
max_values = [x.split(',')[7] for x in lines]
longname = [x.split(',')[9] for x in lines]
flagvalues = [x.split(',')[10] for x in lines]
# flagvalues = [x.replace(' ',',') for x in flagvalues]
flagmeanings = [x.split(',')[17] for x in lines]
standardname = [x.split(',')[18] for x in lines]
scaledtype = [x.split(',')[16] for x in lines]
comments = [x.split(',')[19] for x in lines]
keywords_list = [x.split(',')[22] for x in lines]
abbr = [x.split('-')[0] for x in names]
abbr_e = [x.split('-')[1] if '-' in x else x for x in names]
flagvalues = [x if 'blank' not in x else '' for x in flagvalues]
else:
print('Error: No proper variable attributes document is found!')
parameters = {}
attachment = {}
atta_list = [0,1,5,6,7,8,9,95,96,97,98,99]
attachment['00'] = 'CORE'
parameters['00'] = ('YR','MO','DY','HR','LAT','LON','IM','ATTC','TI','LI','DS','VS','NID','II','ID','C1','DI','D','WI','W','VI','VV','WW','W1','SLP','A','PPP','IT','AT','WBTI','WBT','DPTI','DPT','SI','SST','N','NH','CL','HI','H','CM','CH','WD','WP','WH','SD','SP','SH')
attachment['01'] = 'ICOADS ATTACHMENT'
parameters['01'] = ('BSI','B10','B1','DCK','SID','PT','DUPS','DUPC','TC','PB','WX','SX','C2','SQZ','SQA','AQZ','AQA','UQZ','UQA','VQZ','VQA','PQZ','PQA','DQZ','DQA','ND','SF','AF','UF','VF','PF','RF','ZNC','WNC','BNC','XNC','YNC','PNC','ANC','GNC','DNC','SNC','CNC','ENC','FNC','TNC','QCE','LZ','QCZ')
attachment['05'] = 'IMMT-5/FM13 ATTACHMENT'
parameters['05'] = ('OS','OP','FM','IMMV','IX','W2','WMI','SD2','SP2','SH2','IS','ES','RS','IC1','IC2','IC3','IC4','IC5','IR','RRR','TR','NU','QCI','QI1','QI2','QI3','QI4','QI5','QI6','QI7','QI8','QI9','QI10','QI11','QI12','QI13','QI14','QI15','QI16','QI17','QI18','QI19','QI20','QI21','HDG','COG','SOG','SLL','SLHH','RWD','RWS','QI22','QI23','QI24','QI25','QI26','QI27','QI28','QI29','RH','RHI','AWSI','IMONO')
attachment['06'] = 'MODEL QUALITY CONTROL ATTACHMENT'
parameters['06'] = ('CCCC','BUID','FBSRC','BMP','BSWU','SWU','BSWV','SWV','BSAT','BSRH','SRH','BSST','MST','MSH','BY','BM','BD','BH','BFL')
attachment['07'] = 'SHIP METADATA ATTACHMENT'
parameters['07'] = ('MDS','C1M','OPM','KOV','COR','TOB','TOT','EOT','LOT','TOH','EOH','SIM','LOV','DOS','HOP','HOT','HOB','HOA','SMF','SME','SMV')
attachment['08'] = 'NEAR-SURFACE OCEANOGRAPHIC DATA ATTACHMENT'
parameters['08'] = ('OTV','OTZ','OSV','OSZ','OOV','OOZ','OPV','OPZ','OSIV','OSIZ','ONV','ONZ','OPHV','OPHZ','OCV','OCZ','OAV','OAZ','OPCV','OPCZ','ODV','ODZ','PUID')
attachment['09'] = 'EDITED CLOUD REPORT ATTACHMENT'
parameters['09'] = ('CCE','WWE','NE','NHE','HE','CLE','CME','CHE','AM','AH','UM','UH','SBI','SA','RI')
attachment['95'] = 'REANALYSES QC/FEEDBACK ATTACHMENT'
parameters['95'] = ('ICNR','FNR','DPRO','DPRP','UFR','MFGR','MFGSR','MAR','MASR','BCR','ARCR','CDR','ASIR')
attachment['96'] = 'ICOADS VALUE-ADDED DATABASE ATTACHMENT'
parameters['96'] = ('ICNI','FNI','JVAD','VAD','IVAU1','JVAU1','VAU1','IVAU2','JVAU2','VAU2','IVAU3','JVAU3','VAU3','VQC','ARCI','CDI','ASII')
attachment['97'] = 'ERROR ATTACHMENT'
parameters['97'] = ('ICNE','FNE','CEF','ERRD','ARCE','CDE','ASIE')
attachment['98'] = 'UNIQUE ID ATTACHMENT'
parameters['98'] = ('UID','RN1','RN2','RN3','RSA','IRF')
attachment['99'] = 'SUPPLEMENTAL DATA ATTACHMENT'
parameters['99'] = ('ATTE','SUPD')
def get_var_att(var):
idx = abbr.index(var)
if att_doc == 1:
att = {'abbr':var,'longname':longname[idx],'min_v':min_values[idx],'max_v': max_values[idx],'unit':units[idx], 'comment': comments[idx]}
elif att_doc == 2:
att = {'abbr':var,'ancillary':ancillary[idx],'standardname':standardname[idx],'scaledtype':scaledtype[idx],'longname':longname[idx],'min_v':min_values[idx],'max_v': max_values[idx],'unit':units[idx], 'comment': comments[idx], 'flagvalues': flagvalues[idx], 'flagmeanings':flagmeanings[idx]}
else:
print('Error: No attribute document found.')
return att
def get_ancillary(anc_QC, check_list):
var = anc_QC.split(';')
var = [x.split('-')[0].strip() for x in var]
var = [x for x in var if x in check_list ]
return ' '.join(var)
def getParameters(i):
return parameters["%02d" % i]
def | (out_file,data, **kwargs):
def duration(seconds):
t= []
for dm in (60, 60, 24, 7):
seconds, m = divmod(seconds, dm)
t.append(m)
t.append(seconds)
return ''.join('%d%s' % (num, unit)
for num, unit in zip(t[::-1], 'W DT H M S'.split())
if num)
def get_keywords(data):
keywords = []
for var in data.data.keys():
if var in abbr:
idx = abbr.index(var)
if len(keywords_list[idx])>0:
keywords.append(keywords_list[idx])
# print var, keywords_list[idx]
keywords = list(set(keywords))
keywords = ['Earth Science > %s' %x for x in keywords]
keywords = ', '.join(keywords)
return keywords
def Add_gattrs(ff):
lon_min = min(data['LON'])
lon_max = max(data['LON'])
lat_min = min(data['LAT'])
lat_max = max(data['LAT'])
start_time = min(data.data['Julian'])
end_time = max(data.data['Julian'])
dur_time = (end_time-start_time)*24.0*3600.0
start_time = jdutil.jd_to_datetime(start_time)
start_time_s = "%s-%02d-%02dT%02d:%02d:%02dZ" %(start_time.year,start_time.month,start_time.day,start_time.hour,start_time.minute,start_time.second)
end_time = jdutil.jd_to_datetime(end_time)
end_time_s = "%s-%02d-%02dT%02d:%02d:%02dZ" %(end_time.year,end_time.month,end_time.day,end_time.hour,end_time.minute,end_time.second)
version = out_file.split('_')[1]
#start_time_s = time.strftime(time_fmt,time.gmtime(float(start_time)))
#end_time_s = time.strftime(time_fmt,time.gmtime(float(end_time)))
ff.ncei_template_version = "NCEI_NetCDF_Point_Template_v2.0"
ff.featureType = "point"
ff.title = "International Comprehensive Ocean-Atmosphere Data Set (ICOADS) %s data collected from %s to %s." %(version, start_time_s, end_time_s)
ff.summary = "This file contains ICOADS %s data in netCDF4 format collected from %s to %s. The International Comprehensive Ocean-Atmosphere Data Set (ICOADS) offers surface marine data spanning the past three centuries, and simple gridded monthly summary products for 2-degree latitude x 2-degree longitude boxes back to 1800 (and 1degreex1degree boxes since 1960)--these data and products are freely distributed worldwide. As it contains observations from many different observing systems encompassing the evolution of measurement technology over hundreds of years, ICOADS is probably the most complete and heterogeneous collection of surface marine data in existence." %(version, start_time_s, end_time_s)
ff.keywords = get_keywords(data);
ff.Conventions = "CF-1.6, ACDD-1.3"
ff.id = out_file.split('.nc')[0].replace('IMMA1','ICOADS')
ff.naming_authority = "gov.noaa.ncei"
#ff.source = "http://rda.ucar.edu/data/ds548.0/imma1_r3.0.0/%s.tar" %out_file.split('-')[0]
ff.source = "%s.gz" %out_file.split('.nc')[0]
ff.processing_level = "Restructured from IMMA1 format to NetCDF4 format."
ff.acknowledgement = "Conversion of ICOADS data from IMMA1 to netCDF format by NCEI is supported by the NOAA Big Earth Data Initiative (BEDI)."
ff.license = "These data may be redistributed and used without restriction."
ff.standard_name_vocabulary = "CF Standard Name Table v31"
ff.date_created = time.strftime(time_fmt,time.gmtime())
ff.creator_name = "NCEI"
ff.creator_email = "ncei.info@noaa.gov"
ff.creator_url = "https://www.ncei.noaa.gov/"
ff.institution = "National Centers for Environmental Information (NCEI), NOAA"
ff.project = "International Comprehensive Ocean-Atmosphere Data Set (ICOADS) Project"
ff.publisher_name = "NCEI"
ff.publisher_email = "ncei.info@noaa.gov"
ff.publisher_url = "https://www.ncei.noaa.gov/"
ff.geospatial_bounds = "POLYGON ((%.4f %.4f,%.4f %.4f,%.4f %.4f,%.4f %.4f,%.4f %.4f))" %(lon_min,lat_min,lon_min,lat_max,lon_max,lat_max,lon_max,lat_min,lon_min,lat_min)
ff.geospatial_bounds_crs = "EPSG:4326"
ff.geospatial_lat_min = float("%.4f" %(lat_min))
ff.geospatial_lat_max = float("%.4f" %(lat_max))
ff.geospatial_lon_min = float("%.4f" %(lon_min))
ff.geospatial_lon_max = float("%.4f" %(lon_max))
ff.geospatial_lat_units = "degrees_north"
ff.geospatial_lon_units = "degrees_east"
ff.time_coverage_start = start_time_s
ff.time_coverage_end = end_time_s
ff.time_coverage_duration = 'P' + duration(dur_time)
ff.time_coverage_resolution = "vary"
ff.uuid = str(uuid.uuid4())
ff.sea_name = "World-Wide Distribution"
ff.creator_type = "group"
ff.creator_institution = "NOAA National Centers for Environmental Information (NCEI)"
ff.publisher_type = "institution"
ff.publisher_institution = "NOAA National Centers for Environmental Information (NCEI)"
ff.program = ""
ff.contributor_name = "Zhankun Wang; ICOADS team"
ff.contributor_role = "ICOADS Data Conversion to NetCDF; ICOADS IMMA1 Data Provider"
ff.date_modified = time.strftime(time_fmt,time.gmtime())
ff.date_issued = time.strftime(time_fmt,time.gmtime())
ff.date_metadata_modified = time.strftime(time_fmt,time.gmtime())
ff.product_version = "ICOADS %s netCDF4" %version
ff.keywords_vocabulary = "Global Change Master Directory (GCMD) 2015. GCMD Keywords, Version 8.1."
ff.cdm_data_type = 'Point'
#ff.metadata_link = 'http://rda.ucar.edu/datasets/ds548.0/#!docs'
ff.metadata_link = ''
if len(set(data.data['IM'])) == 1:
ff.IMMA_Version = str(data.data['IM'][0])
else:
print('%s: check IMMA version' %out_file)
if len(set(data.data['RN1'])) == 1:
ff.Release_Number_Primary = str(data.data['RN1'][0])
else:
print('%s: check Release_Number_Primary' %out_file)
if len(set(data.data['RN2'])) == 1:
ff.Release_Number_Secondary = str(data.data['RN2'][0])
else:
print('%s: check Release_Number_Secondary' %out_file)
if len(set(data.data['RN3'])) == 1:
ff.Release_Number_Tertiary = str(data.data['RN3'][0])
else:
print('%s: check Release_Number_Tertiary' %out_file)
if len(set(data.data['RSA'])) == 1:
ff.Release_status_indicator = str(data.data['RSA'][0])
else:
print('%s: check RSA' %out_file)
#ff.comment = ""
ff.references = 'http://rda.ucar.edu/datasets/ds548.0/docs/R3.0-citation.pdf'
ff.history = time.strftime(time_fmt,time.gmtime()) + ": Converted from IMMA1 format to netCDF4 format by Z.W. "
fpath = kwargs.get('fpath')
if fpath is None:
fpath = fpath_default
#ftxt = open("%s%s.txt" %(fpath,out_file[0:-3]), 'w')
#ftxt.write('Saving to %s ...\n' %out_file);
ff = netCDF4.Dataset(fpath + out_file.replace('IMMA1','ICOADS'), 'w', format='NETCDF4')
Add_gattrs(ff)
ff.createDimension('obs',len(data.data['YR']))
'''
# save time in Julian Days
timein = ff.createVariable('time','f8',('obs',),zlib=True,complevel=4)
timein.long_name = "time"
timein.standard_name = "time"
timein.units = "days since -4713-1-1 12:0:0 "
timein.calendar = "julian"
timein.axis = "T"
timein.comment = "Julian days since noon on January 1, 4713 BC. Missing values of date (DD in date) are replaced by 0 and missing values in HR are filled with 0.0 in this calculation. See actural values in date, HR for reference."
timein[:] = data.data['Julian'][:]
'''
# save time in Julian Days since the beginning of ICOADS data: 1662-10-15 12:00:00
timein = ff.createVariable('time','f8',('obs',),zlib=True,complevel=4)
timein.long_name = "time"
timein.standard_name = "time"
timein.units = "days since 1662-10-15 12:00:00"
timein.calendar = "julian"
timein.axis = "T"
timein.comment = "Julian days since the beginning of the ICOADS record, which is 1662-10-15 12:00:00. Missing values of date (DD in date) are replaced by 0 and missing values in HR are filled with 0.0 in this calculation. See actual values in date, HR for reference."
timein[:] = data.data['Julian1'][:]
# save date in YYYYMMDD
ff.createDimension('DATE_len',len(data.data['DATE'][0]))
date = ff.createVariable('date','S1',('obs','DATE_len',),zlib=True,complevel=4)
date.long_name = "date in YYYYMMDD"
#date.valid_min = '16000101'
#date.valid_max = '20241231'
date.format = 'YYYYMMDD'
#date.axis = "T"
date.comment = "YYYY: four digital year, MM: two digital month and DD: two digital date. Missing values of DD have been filled with 99."
date[:] = [netCDF4.stringtochar(np.array(x)) for x in data.data['DATE']]
#print data.data['YR']
crsout = ff.createVariable('crs','i')
crsout.grid_mapping_name = "latitude_longitude"
crsout.epsg_code = "EPSG:4326"
crsout.semi_major_axis = 6378137.0
crsout.inverse_flattening = 298.257223563
#crsout.comment = ''
dim_list = []
dim_dir = []
exclusives = ['YR','MO','DY','SUPD','IM','ATTC','ATTE','RN1','RN2','RN3','RSA']
'''
exclusives_2 = ['CDE','CDI','YR','MO','DY','SUPD','IM','ATTC','ATTE','RN1','RN2','RN3','RSA','ICNR','FNR','DPRO','DPRP','UFR','MFGR','MFGSR','MAR','MASR','BCR','ARCR','CDR','ASIR']
for atta in atta_list:
var_list = getParameters(atta)
for var in var_list:
if var in exclusives_2:
pass
else:
print var
att = get_var_att(var)
if 'flagvalues' in att:
if len(att['flagvalues']) > 0:
print var, att['flagvalues'], att['flagmeanings']
foo = att['flagvalues'].split(' ')
foo_m = att['flagmeanings'].split(' ')
for x,y in zip(foo,foo_m): print('%s: %s' %(x,y))
'''
for atta in atta_list:
var_list = getParameters(atta)
for var in var_list:
if var in data.data.keys():
if var in exclusives:
pass
else:
start = time.time()
#ftxt.write('%s start at %s. ' %(var,time.strftime(time_fmt,time.gmtime())));
index = [i for i, x in enumerate(data.data[var]) if x is not None]
# print var,data[var],index[0],data.data[var][index[0]]
if type(data.data[var][index[0]]) is int:
dataout = ff.createVariable(var,'i2',('obs',),fill_value = -99,zlib=True,complevel=4)
#dataout = ff.createVariable(var,'f4',('obs',),zlib=True,complevel=4)
dataout[index] = [data.data[var][idx] for idx in index]
elif type(data.data[var][index[0]]) is float:
if var == 'LAT':
dataout = ff.createVariable('lat','f4',('obs',),zlib=True,complevel=4)
elif var == 'LON':
dataout = ff.createVariable('lon','f4',('obs',),zlib=True,complevel=4)
else:
dataout = ff.createVariable(var,'f4',('obs',),fill_value = float(-9999),zlib=True,complevel=4)
dataout[index] = [data.data[var][idx] for idx in index]
elif type(data.data[var][index[0]]) is str:
#print var
if var == 'SUPD':
#ll = max([len(x) if x is not None else 0 for x in data.data[var] ])
#data.data[var] = [x.ljust(ll) if x is not None else None for x in data.data[var]]
pass
else:
ll = len(data.data[var][index[0]])
if ll not in dim_list:
ff.createDimension('%s_len' %var,ll)
dataout = ff.createVariable(var,'S1',('obs','%s_len' %var,),zlib=True,complevel=4)
dim_list.append(ll)
dim_dir.append(var)
else:
idx = dim_list.index(ll)
dataout = ff.createVariable(var,'S1',('obs','%s_len' %dim_dir[idx],),zlib=True,complevel=4)
dataout[index] = [netCDF4.stringtochar(np.array(data.data[var][idx])) for idx in index]
else:
print var, type(data.data[var][index[0]])
att = get_var_att(var)
if 'standardname' in att:
if len(att['standardname']) >0: dataout.standard_name = att['standardname']
dataout.long_name = att['longname'] if len(att['longname']) > 0 else ""
if len(att['unit']) > 0: dataout.units = att['unit']
if len(att['min_v']) > 0:
if 'int' in att['scaledtype']:
dataout.valid_min = np.int16(att['min_v'])
elif 'double' in att['scaledtype']:
dataout.valid_min = float(att['min_v'])
else:
dataout.valid_min = float(att['min_v'])
if len(att['max_v']) > 0:
if 'int' in att['scaledtype']:
dataout.valid_max = np.int16(att['max_v'])
elif 'double' in att['scaledtype']:
dataout.valid_max = float(att['max_v'])
else:
dataout.valid_max = float(att['max_v'])
if var == 'LAT': dataout.axis = 'Y'
if var == 'LON': dataout.axis = 'X'
#if len(att['min_v']) > 0:
# dataout.scale_factor = 1.
# dataout.add_offset = 0.
if 'flagvalues' in att:
if len(att['flagvalues']) >0:
foo = att['flagvalues'].split(' ')
dataout.flag_values = [np.int16(x) for x in foo]
if len(att['flagmeanings']) >0: dataout.flag_meanings = att['flagmeanings']
if var != 'LAT' and var != 'LON':
dataout.coordinates = "time lat lon"
dataout.grid_mapping = "crs"
dataout.cell_methods = "time: point"
if len(att['comment']) > 0: dataout.comment = att['comment']
if len(get_ancillary(att['ancillary'],data.data.keys())) > 0: dataout.ancillary_variables = get_ancillary(att['ancillary'],data.data.keys())
end = time.time()
#print var, end-start
#ftxt.write('Time used = %s sec\n' %(end-start));
#dataout.standard_name = "sea_surface_temperature"
#dataout.long_name = "Sea surface temperature"
#dataout.units = "degree_Celsius"
#ftxt.write('Done with %s' %out_file)
ff.close()
#ftxt.close()
| save | identifier_name |
IMMA2nc1.py | # -*- coding: utf-8 -*-
# Purpose: Python module for processing and saving IMMA1 to netCDF 4
# same shortnames are used as the IMMA1 data, please refere to IMMA1 documentation for more details
# IMMA1 documentation is at https://rda.ucar.edu/datasets/ds548.0/#!docs
# History: developed by Zhankun Wang between Oct 2016 and May 2017 for the BEDI ICOADS project
# (c) NOAA National Centers for Environmental Information
# contact: zhankun.wang@noaa.gov
import uuid
import time
import netCDF4
import numpy as np
import os
import jdutil
# change the path to where the program and documents are saved. one level above
fpath_default = '/nodc/projects/tsg/zwang/ICOADS/codes'
# change to where the python codes saved
os.chdir(fpath_default)
time_fmt = "%Y-%m-%dT%H:%M:%SZ"
att_doc = 2
if att_doc == 1:
f = open('%sTables_ICOADS.csv' %fpath_default, 'r')
lines = f.readlines()
lines = [x.rstrip("\r\n") for x in lines]
f.close()
No = [x.split(',')[0] for x in lines]
length = [x.split(',')[1] for x in lines]
abbr = [x.split(',')[2].upper() for x in lines]
longname = [x.split(',')[3] for x in lines]
min_values = [x.split(',')[4] for x in lines]
max_values = [x.split(',')[5] for x in lines]
units = [x.split(',')[6] for x in lines]
comments = [x.split(',')[7:] for x in lines]
elif att_doc == 2:
f = open('%sicoads_dsv.csv' %fpath_default, 'r')
lines = f.readlines()
lines = [x.rstrip("\r\n") for x in lines]
lines = [x.rstrip("\xa0") for x in lines]
f.close()
ancillary = [x.split(',')[1] for x in lines]
names = [x.split(',')[2] for x in lines]
units = [x.split(',')[5] for x in lines]
min_values = [x.split(',')[6] for x in lines]
max_values = [x.split(',')[7] for x in lines]
longname = [x.split(',')[9] for x in lines]
flagvalues = [x.split(',')[10] for x in lines]
# flagvalues = [x.replace(' ',',') for x in flagvalues]
flagmeanings = [x.split(',')[17] for x in lines]
standardname = [x.split(',')[18] for x in lines]
scaledtype = [x.split(',')[16] for x in lines]
comments = [x.split(',')[19] for x in lines]
keywords_list = [x.split(',')[22] for x in lines]
abbr = [x.split('-')[0] for x in names]
abbr_e = [x.split('-')[1] if '-' in x else x for x in names]
flagvalues = [x if 'blank' not in x else '' for x in flagvalues]
else:
print('Error: No proper variable attributes document is found!')
parameters = {}
attachment = {}
atta_list = [0,1,5,6,7,8,9,95,96,97,98,99]
attachment['00'] = 'CORE'
parameters['00'] = ('YR','MO','DY','HR','LAT','LON','IM','ATTC','TI','LI','DS','VS','NID','II','ID','C1','DI','D','WI','W','VI','VV','WW','W1','SLP','A','PPP','IT','AT','WBTI','WBT','DPTI','DPT','SI','SST','N','NH','CL','HI','H','CM','CH','WD','WP','WH','SD','SP','SH')
attachment['01'] = 'ICOADS ATTACHMENT'
parameters['01'] = ('BSI','B10','B1','DCK','SID','PT','DUPS','DUPC','TC','PB','WX','SX','C2','SQZ','SQA','AQZ','AQA','UQZ','UQA','VQZ','VQA','PQZ','PQA','DQZ','DQA','ND','SF','AF','UF','VF','PF','RF','ZNC','WNC','BNC','XNC','YNC','PNC','ANC','GNC','DNC','SNC','CNC','ENC','FNC','TNC','QCE','LZ','QCZ')
attachment['05'] = 'IMMT-5/FM13 ATTACHMENT'
parameters['05'] = ('OS','OP','FM','IMMV','IX','W2','WMI','SD2','SP2','SH2','IS','ES','RS','IC1','IC2','IC3','IC4','IC5','IR','RRR','TR','NU','QCI','QI1','QI2','QI3','QI4','QI5','QI6','QI7','QI8','QI9','QI10','QI11','QI12','QI13','QI14','QI15','QI16','QI17','QI18','QI19','QI20','QI21','HDG','COG','SOG','SLL','SLHH','RWD','RWS','QI22','QI23','QI24','QI25','QI26','QI27','QI28','QI29','RH','RHI','AWSI','IMONO')
attachment['06'] = 'MODEL QUALITY CONTROL ATTACHMENT'
parameters['06'] = ('CCCC','BUID','FBSRC','BMP','BSWU','SWU','BSWV','SWV','BSAT','BSRH','SRH','BSST','MST','MSH','BY','BM','BD','BH','BFL')
attachment['07'] = 'SHIP METADATA ATTACHMENT'
parameters['07'] = ('MDS','C1M','OPM','KOV','COR','TOB','TOT','EOT','LOT','TOH','EOH','SIM','LOV','DOS','HOP','HOT','HOB','HOA','SMF','SME','SMV')
attachment['08'] = 'NEAR-SURFACE OCEANOGRAPHIC DATA ATTACHMENT'
parameters['08'] = ('OTV','OTZ','OSV','OSZ','OOV','OOZ','OPV','OPZ','OSIV','OSIZ','ONV','ONZ','OPHV','OPHZ','OCV','OCZ','OAV','OAZ','OPCV','OPCZ','ODV','ODZ','PUID')
attachment['09'] = 'EDITED CLOUD REPORT ATTACHMENT'
parameters['09'] = ('CCE','WWE','NE','NHE','HE','CLE','CME','CHE','AM','AH','UM','UH','SBI','SA','RI')
attachment['95'] = 'REANALYSES QC/FEEDBACK ATTACHMENT'
parameters['95'] = ('ICNR','FNR','DPRO','DPRP','UFR','MFGR','MFGSR','MAR','MASR','BCR','ARCR','CDR','ASIR')
attachment['96'] = 'ICOADS VALUE-ADDED DATABASE ATTACHMENT'
parameters['96'] = ('ICNI','FNI','JVAD','VAD','IVAU1','JVAU1','VAU1','IVAU2','JVAU2','VAU2','IVAU3','JVAU3','VAU3','VQC','ARCI','CDI','ASII')
attachment['97'] = 'ERROR ATTACHMENT'
parameters['97'] = ('ICNE','FNE','CEF','ERRD','ARCE','CDE','ASIE')
attachment['98'] = 'UNIQUE ID ATTACHMENT'
parameters['98'] = ('UID','RN1','RN2','RN3','RSA','IRF')
attachment['99'] = 'SUPPLEMENTAL DATA ATTACHMENT'
parameters['99'] = ('ATTE','SUPD')
def get_var_att(var):
idx = abbr.index(var)
if att_doc == 1:
att = {'abbr':var,'longname':longname[idx],'min_v':min_values[idx],'max_v': max_values[idx],'unit':units[idx], 'comment': comments[idx]}
elif att_doc == 2:
att = {'abbr':var,'ancillary':ancillary[idx],'standardname':standardname[idx],'scaledtype':scaledtype[idx],'longname':longname[idx],'min_v':min_values[idx],'max_v': max_values[idx],'unit':units[idx], 'comment': comments[idx], 'flagvalues': flagvalues[idx], 'flagmeanings':flagmeanings[idx]}
else:
print('Error: No attribute document found.')
return att
def get_ancillary(anc_QC, check_list):
var = anc_QC.split(';')
var = [x.split('-')[0].strip() for x in var]
var = [x for x in var if x in check_list ]
return ' '.join(var)
def getParameters(i):
return parameters["%02d" % i]
def save(out_file,data, **kwargs):
| def duration(seconds):
t= []
for dm in (60, 60, 24, 7):
seconds, m = divmod(seconds, dm)
t.append(m)
t.append(seconds)
return ''.join('%d%s' % (num, unit)
for num, unit in zip(t[::-1], 'W DT H M S'.split())
if num)
def get_keywords(data):
keywords = []
for var in data.data.keys():
if var in abbr:
idx = abbr.index(var)
if len(keywords_list[idx])>0:
keywords.append(keywords_list[idx])
# print var, keywords_list[idx]
keywords = list(set(keywords))
keywords = ['Earth Science > %s' %x for x in keywords]
keywords = ', '.join(keywords)
return keywords
def Add_gattrs(ff):
lon_min = min(data['LON'])
lon_max = max(data['LON'])
lat_min = min(data['LAT'])
lat_max = max(data['LAT'])
start_time = min(data.data['Julian'])
end_time = max(data.data['Julian'])
dur_time = (end_time-start_time)*24.0*3600.0
start_time = jdutil.jd_to_datetime(start_time)
start_time_s = "%s-%02d-%02dT%02d:%02d:%02dZ" %(start_time.year,start_time.month,start_time.day,start_time.hour,start_time.minute,start_time.second)
end_time = jdutil.jd_to_datetime(end_time)
end_time_s = "%s-%02d-%02dT%02d:%02d:%02dZ" %(end_time.year,end_time.month,end_time.day,end_time.hour,end_time.minute,end_time.second)
version = out_file.split('_')[1]
#start_time_s = time.strftime(time_fmt,time.gmtime(float(start_time)))
#end_time_s = time.strftime(time_fmt,time.gmtime(float(end_time)))
ff.ncei_template_version = "NCEI_NetCDF_Point_Template_v2.0"
ff.featureType = "point"
ff.title = "International Comprehensive Ocean-Atmosphere Data Set (ICOADS) %s data collected from %s to %s." %(version, start_time_s, end_time_s)
ff.summary = "This file contains ICOADS %s data in netCDF4 format collected from %s to %s. The International Comprehensive Ocean-Atmosphere Data Set (ICOADS) offers surface marine data spanning the past three centuries, and simple gridded monthly summary products for 2-degree latitude x 2-degree longitude boxes back to 1800 (and 1degreex1degree boxes since 1960)--these data and products are freely distributed worldwide. As it contains observations from many different observing systems encompassing the evolution of measurement technology over hundreds of years, ICOADS is probably the most complete and heterogeneous collection of surface marine data in existence." %(version, start_time_s, end_time_s)
ff.keywords = get_keywords(data);
ff.Conventions = "CF-1.6, ACDD-1.3"
ff.id = out_file.split('.nc')[0].replace('IMMA1','ICOADS')
ff.naming_authority = "gov.noaa.ncei"
#ff.source = "http://rda.ucar.edu/data/ds548.0/imma1_r3.0.0/%s.tar" %out_file.split('-')[0]
ff.source = "%s.gz" %out_file.split('.nc')[0]
ff.processing_level = "Restructured from IMMA1 format to NetCDF4 format."
ff.acknowledgement = "Conversion of ICOADS data from IMMA1 to netCDF format by NCEI is supported by the NOAA Big Earth Data Initiative (BEDI)."
ff.license = "These data may be redistributed and used without restriction."
ff.standard_name_vocabulary = "CF Standard Name Table v31"
ff.date_created = time.strftime(time_fmt,time.gmtime())
ff.creator_name = "NCEI"
ff.creator_email = "ncei.info@noaa.gov"
ff.creator_url = "https://www.ncei.noaa.gov/"
ff.institution = "National Centers for Environmental Information (NCEI), NOAA"
ff.project = "International Comprehensive Ocean-Atmosphere Data Set (ICOADS) Project"
ff.publisher_name = "NCEI"
ff.publisher_email = "ncei.info@noaa.gov"
ff.publisher_url = "https://www.ncei.noaa.gov/"
ff.geospatial_bounds = "POLYGON ((%.4f %.4f,%.4f %.4f,%.4f %.4f,%.4f %.4f,%.4f %.4f))" %(lon_min,lat_min,lon_min,lat_max,lon_max,lat_max,lon_max,lat_min,lon_min,lat_min)
ff.geospatial_bounds_crs = "EPSG:4326"
ff.geospatial_lat_min = float("%.4f" %(lat_min))
ff.geospatial_lat_max = float("%.4f" %(lat_max))
ff.geospatial_lon_min = float("%.4f" %(lon_min))
ff.geospatial_lon_max = float("%.4f" %(lon_max))
ff.geospatial_lat_units = "degrees_north"
ff.geospatial_lon_units = "degrees_east"
ff.time_coverage_start = start_time_s
ff.time_coverage_end = end_time_s
ff.time_coverage_duration = 'P' + duration(dur_time)
ff.time_coverage_resolution = "vary"
ff.uuid = str(uuid.uuid4())
ff.sea_name = "World-Wide Distribution"
ff.creator_type = "group"
ff.creator_institution = "NOAA National Centers for Environmental Information (NCEI)"
ff.publisher_type = "institution"
ff.publisher_institution = "NOAA National Centers for Environmental Information (NCEI)"
ff.program = ""
ff.contributor_name = "Zhankun Wang; ICOADS team"
ff.contributor_role = "ICOADS Data Conversion to NetCDF; ICOADS IMMA1 Data Provider"
ff.date_modified = time.strftime(time_fmt,time.gmtime())
ff.date_issued = time.strftime(time_fmt,time.gmtime())
ff.date_metadata_modified = time.strftime(time_fmt,time.gmtime())
ff.product_version = "ICOADS %s netCDF4" %version
ff.keywords_vocabulary = "Global Change Master Directory (GCMD) 2015. GCMD Keywords, Version 8.1."
ff.cdm_data_type = 'Point'
#ff.metadata_link = 'http://rda.ucar.edu/datasets/ds548.0/#!docs'
ff.metadata_link = ''
if len(set(data.data['IM'])) == 1:
ff.IMMA_Version = str(data.data['IM'][0])
else:
print('%s: check IMMA version' %out_file)
if len(set(data.data['RN1'])) == 1:
ff.Release_Number_Primary = str(data.data['RN1'][0])
else:
print('%s: check Release_Number_Primary' %out_file)
if len(set(data.data['RN2'])) == 1:
ff.Release_Number_Secondary = str(data.data['RN2'][0])
else:
print('%s: check Release_Number_Secondary' %out_file)
if len(set(data.data['RN3'])) == 1:
ff.Release_Number_Tertiary = str(data.data['RN3'][0])
else:
print('%s: check Release_Number_Tertiary' %out_file)
if len(set(data.data['RSA'])) == 1:
ff.Release_status_indicator = str(data.data['RSA'][0])
else:
print('%s: check RSA' %out_file)
#ff.comment = ""
ff.references = 'http://rda.ucar.edu/datasets/ds548.0/docs/R3.0-citation.pdf'
ff.history = time.strftime(time_fmt,time.gmtime()) + ": Converted from IMMA1 format to netCDF4 format by Z.W. "
fpath = kwargs.get('fpath')
if fpath is None:
fpath = fpath_default
#ftxt = open("%s%s.txt" %(fpath,out_file[0:-3]), 'w')
#ftxt.write('Saving to %s ...\n' %out_file);
ff = netCDF4.Dataset(fpath + out_file.replace('IMMA1','ICOADS'), 'w', format='NETCDF4')
Add_gattrs(ff)
ff.createDimension('obs',len(data.data['YR']))
'''
# save time in Julian Days
timein = ff.createVariable('time','f8',('obs',),zlib=True,complevel=4)
timein.long_name = "time"
timein.standard_name = "time"
timein.units = "days since -4713-1-1 12:0:0 "
timein.calendar = "julian"
timein.axis = "T"
timein.comment = "Julian days since noon on January 1, 4713 BC. Missing values of date (DD in date) are replaced by 0 and missing values in HR are filled with 0.0 in this calculation. See actural values in date, HR for reference."
timein[:] = data.data['Julian'][:]
'''
# save time in Julian Days since the beginning of ICOADS data: 1662-10-15 12:00:00
timein = ff.createVariable('time','f8',('obs',),zlib=True,complevel=4)
timein.long_name = "time"
timein.standard_name = "time"
timein.units = "days since 1662-10-15 12:00:00"
timein.calendar = "julian"
timein.axis = "T"
timein.comment = "Julian days since the beginning of the ICOADS record, which is 1662-10-15 12:00:00. Missing values of date (DD in date) are replaced by 0 and missing values in HR are filled with 0.0 in this calculation. See actual values in date, HR for reference."
timein[:] = data.data['Julian1'][:]
# save date in YYYYMMDD
ff.createDimension('DATE_len',len(data.data['DATE'][0]))
date = ff.createVariable('date','S1',('obs','DATE_len',),zlib=True,complevel=4)
date.long_name = "date in YYYYMMDD"
#date.valid_min = '16000101'
#date.valid_max = '20241231'
date.format = 'YYYYMMDD'
#date.axis = "T"
date.comment = "YYYY: four digital year, MM: two digital month and DD: two digital date. Missing values of DD have been filled with 99."
date[:] = [netCDF4.stringtochar(np.array(x)) for x in data.data['DATE']]
#print data.data['YR']
crsout = ff.createVariable('crs','i')
crsout.grid_mapping_name = "latitude_longitude"
crsout.epsg_code = "EPSG:4326"
crsout.semi_major_axis = 6378137.0
crsout.inverse_flattening = 298.257223563
#crsout.comment = ''
dim_list = []
dim_dir = []
exclusives = ['YR','MO','DY','SUPD','IM','ATTC','ATTE','RN1','RN2','RN3','RSA']
'''
exclusives_2 = ['CDE','CDI','YR','MO','DY','SUPD','IM','ATTC','ATTE','RN1','RN2','RN3','RSA','ICNR','FNR','DPRO','DPRP','UFR','MFGR','MFGSR','MAR','MASR','BCR','ARCR','CDR','ASIR']
for atta in atta_list:
var_list = getParameters(atta)
for var in var_list:
if var in exclusives_2:
pass
else:
print var
att = get_var_att(var)
if 'flagvalues' in att:
if len(att['flagvalues']) > 0:
print var, att['flagvalues'], att['flagmeanings']
foo = att['flagvalues'].split(' ')
foo_m = att['flagmeanings'].split(' ')
for x,y in zip(foo,foo_m): print('%s: %s' %(x,y))
'''
for atta in atta_list:
var_list = getParameters(atta)
for var in var_list:
if var in data.data.keys():
if var in exclusives:
pass
else:
start = time.time()
#ftxt.write('%s start at %s. ' %(var,time.strftime(time_fmt,time.gmtime())));
index = [i for i, x in enumerate(data.data[var]) if x is not None]
# print var,data[var],index[0],data.data[var][index[0]]
if type(data.data[var][index[0]]) is int:
dataout = ff.createVariable(var,'i2',('obs',),fill_value = -99,zlib=True,complevel=4)
#dataout = ff.createVariable(var,'f4',('obs',),zlib=True,complevel=4)
dataout[index] = [data.data[var][idx] for idx in index]
elif type(data.data[var][index[0]]) is float:
if var == 'LAT':
dataout = ff.createVariable('lat','f4',('obs',),zlib=True,complevel=4)
elif var == 'LON':
dataout = ff.createVariable('lon','f4',('obs',),zlib=True,complevel=4)
else:
dataout = ff.createVariable(var,'f4',('obs',),fill_value = float(-9999),zlib=True,complevel=4)
dataout[index] = [data.data[var][idx] for idx in index]
elif type(data.data[var][index[0]]) is str:
#print var
if var == 'SUPD':
#ll = max([len(x) if x is not None else 0 for x in data.data[var] ])
#data.data[var] = [x.ljust(ll) if x is not None else None for x in data.data[var]]
pass
else:
ll = len(data.data[var][index[0]])
if ll not in dim_list:
ff.createDimension('%s_len' %var,ll)
dataout = ff.createVariable(var,'S1',('obs','%s_len' %var,),zlib=True,complevel=4)
dim_list.append(ll)
dim_dir.append(var)
else:
idx = dim_list.index(ll)
dataout = ff.createVariable(var,'S1',('obs','%s_len' %dim_dir[idx],),zlib=True,complevel=4)
dataout[index] = [netCDF4.stringtochar(np.array(data.data[var][idx])) for idx in index]
else:
print var, type(data.data[var][index[0]])
att = get_var_att(var)
if 'standardname' in att:
if len(att['standardname']) >0: dataout.standard_name = att['standardname']
dataout.long_name = att['longname'] if len(att['longname']) > 0 else ""
if len(att['unit']) > 0: dataout.units = att['unit']
if len(att['min_v']) > 0:
if 'int' in att['scaledtype']:
dataout.valid_min = np.int16(att['min_v'])
elif 'double' in att['scaledtype']:
dataout.valid_min = float(att['min_v'])
else:
dataout.valid_min = float(att['min_v'])
if len(att['max_v']) > 0:
if 'int' in att['scaledtype']:
dataout.valid_max = np.int16(att['max_v'])
elif 'double' in att['scaledtype']:
dataout.valid_max = float(att['max_v'])
else:
dataout.valid_max = float(att['max_v'])
if var == 'LAT': dataout.axis = 'Y'
if var == 'LON': dataout.axis = 'X'
#if len(att['min_v']) > 0:
# dataout.scale_factor = 1.
# dataout.add_offset = 0.
if 'flagvalues' in att:
if len(att['flagvalues']) >0:
foo = att['flagvalues'].split(' ')
dataout.flag_values = [np.int16(x) for x in foo]
if len(att['flagmeanings']) >0: dataout.flag_meanings = att['flagmeanings']
if var != 'LAT' and var != 'LON':
dataout.coordinates = "time lat lon"
dataout.grid_mapping = "crs"
dataout.cell_methods = "time: point"
if len(att['comment']) > 0: dataout.comment = att['comment']
if len(get_ancillary(att['ancillary'],data.data.keys())) > 0: dataout.ancillary_variables = get_ancillary(att['ancillary'],data.data.keys())
end = time.time()
#print var, end-start
#ftxt.write('Time used = %s sec\n' %(end-start));
#dataout.standard_name = "sea_surface_temperature"
#dataout.long_name = "Sea surface temperature"
#dataout.units = "degree_Celsius"
#ftxt.write('Done with %s' %out_file)
ff.close()
#ftxt.close() | identifier_body | |
IMMA2nc1.py | # -*- coding: utf-8 -*-
# Purpose: Python module for processing and saving IMMA1 to netCDF 4
# same shortnames are used as the IMMA1 data, please refere to IMMA1 documentation for more details
# IMMA1 documentation is at https://rda.ucar.edu/datasets/ds548.0/#!docs
# History: developed by Zhankun Wang between Oct 2016 and May 2017 for the BEDI ICOADS project
# (c) NOAA National Centers for Environmental Information
# contact: zhankun.wang@noaa.gov
import uuid
import time
import netCDF4
import numpy as np
import os
import jdutil
# change the path to where the program and documents are saved. one level above
fpath_default = '/nodc/projects/tsg/zwang/ICOADS/codes'
# change to where the python codes saved
os.chdir(fpath_default)
time_fmt = "%Y-%m-%dT%H:%M:%SZ"
att_doc = 2
if att_doc == 1:
f = open('%sTables_ICOADS.csv' %fpath_default, 'r')
lines = f.readlines()
lines = [x.rstrip("\r\n") for x in lines]
f.close()
No = [x.split(',')[0] for x in lines]
length = [x.split(',')[1] for x in lines]
abbr = [x.split(',')[2].upper() for x in lines]
longname = [x.split(',')[3] for x in lines]
min_values = [x.split(',')[4] for x in lines]
max_values = [x.split(',')[5] for x in lines]
units = [x.split(',')[6] for x in lines]
comments = [x.split(',')[7:] for x in lines]
elif att_doc == 2:
f = open('%sicoads_dsv.csv' %fpath_default, 'r')
lines = f.readlines()
lines = [x.rstrip("\r\n") for x in lines]
lines = [x.rstrip("\xa0") for x in lines]
f.close()
ancillary = [x.split(',')[1] for x in lines]
names = [x.split(',')[2] for x in lines]
units = [x.split(',')[5] for x in lines]
min_values = [x.split(',')[6] for x in lines]
max_values = [x.split(',')[7] for x in lines]
longname = [x.split(',')[9] for x in lines]
flagvalues = [x.split(',')[10] for x in lines]
# flagvalues = [x.replace(' ',',') for x in flagvalues]
flagmeanings = [x.split(',')[17] for x in lines]
standardname = [x.split(',')[18] for x in lines]
scaledtype = [x.split(',')[16] for x in lines]
comments = [x.split(',')[19] for x in lines]
keywords_list = [x.split(',')[22] for x in lines]
abbr = [x.split('-')[0] for x in names]
abbr_e = [x.split('-')[1] if '-' in x else x for x in names]
flagvalues = [x if 'blank' not in x else '' for x in flagvalues]
else:
print('Error: No proper variable attributes document is found!')
parameters = {}
attachment = {}
atta_list = [0,1,5,6,7,8,9,95,96,97,98,99]
attachment['00'] = 'CORE'
parameters['00'] = ('YR','MO','DY','HR','LAT','LON','IM','ATTC','TI','LI','DS','VS','NID','II','ID','C1','DI','D','WI','W','VI','VV','WW','W1','SLP','A','PPP','IT','AT','WBTI','WBT','DPTI','DPT','SI','SST','N','NH','CL','HI','H','CM','CH','WD','WP','WH','SD','SP','SH')
attachment['01'] = 'ICOADS ATTACHMENT'
parameters['01'] = ('BSI','B10','B1','DCK','SID','PT','DUPS','DUPC','TC','PB','WX','SX','C2','SQZ','SQA','AQZ','AQA','UQZ','UQA','VQZ','VQA','PQZ','PQA','DQZ','DQA','ND','SF','AF','UF','VF','PF','RF','ZNC','WNC','BNC','XNC','YNC','PNC','ANC','GNC','DNC','SNC','CNC','ENC','FNC','TNC','QCE','LZ','QCZ')
attachment['05'] = 'IMMT-5/FM13 ATTACHMENT'
parameters['05'] = ('OS','OP','FM','IMMV','IX','W2','WMI','SD2','SP2','SH2','IS','ES','RS','IC1','IC2','IC3','IC4','IC5','IR','RRR','TR','NU','QCI','QI1','QI2','QI3','QI4','QI5','QI6','QI7','QI8','QI9','QI10','QI11','QI12','QI13','QI14','QI15','QI16','QI17','QI18','QI19','QI20','QI21','HDG','COG','SOG','SLL','SLHH','RWD','RWS','QI22','QI23','QI24','QI25','QI26','QI27','QI28','QI29','RH','RHI','AWSI','IMONO')
attachment['06'] = 'MODEL QUALITY CONTROL ATTACHMENT'
parameters['06'] = ('CCCC','BUID','FBSRC','BMP','BSWU','SWU','BSWV','SWV','BSAT','BSRH','SRH','BSST','MST','MSH','BY','BM','BD','BH','BFL')
attachment['07'] = 'SHIP METADATA ATTACHMENT'
parameters['07'] = ('MDS','C1M','OPM','KOV','COR','TOB','TOT','EOT','LOT','TOH','EOH','SIM','LOV','DOS','HOP','HOT','HOB','HOA','SMF','SME','SMV')
attachment['08'] = 'NEAR-SURFACE OCEANOGRAPHIC DATA ATTACHMENT'
parameters['08'] = ('OTV','OTZ','OSV','OSZ','OOV','OOZ','OPV','OPZ','OSIV','OSIZ','ONV','ONZ','OPHV','OPHZ','OCV','OCZ','OAV','OAZ','OPCV','OPCZ','ODV','ODZ','PUID')
attachment['09'] = 'EDITED CLOUD REPORT ATTACHMENT'
parameters['09'] = ('CCE','WWE','NE','NHE','HE','CLE','CME','CHE','AM','AH','UM','UH','SBI','SA','RI')
attachment['95'] = 'REANALYSES QC/FEEDBACK ATTACHMENT'
parameters['95'] = ('ICNR','FNR','DPRO','DPRP','UFR','MFGR','MFGSR','MAR','MASR','BCR','ARCR','CDR','ASIR')
attachment['96'] = 'ICOADS VALUE-ADDED DATABASE ATTACHMENT'
parameters['96'] = ('ICNI','FNI','JVAD','VAD','IVAU1','JVAU1','VAU1','IVAU2','JVAU2','VAU2','IVAU3','JVAU3','VAU3','VQC','ARCI','CDI','ASII')
attachment['97'] = 'ERROR ATTACHMENT'
parameters['97'] = ('ICNE','FNE','CEF','ERRD','ARCE','CDE','ASIE')
attachment['98'] = 'UNIQUE ID ATTACHMENT'
parameters['98'] = ('UID','RN1','RN2','RN3','RSA','IRF')
attachment['99'] = 'SUPPLEMENTAL DATA ATTACHMENT'
parameters['99'] = ('ATTE','SUPD')
def get_var_att(var):
idx = abbr.index(var)
if att_doc == 1:
att = {'abbr':var,'longname':longname[idx],'min_v':min_values[idx],'max_v': max_values[idx],'unit':units[idx], 'comment': comments[idx]}
elif att_doc == 2:
att = {'abbr':var,'ancillary':ancillary[idx],'standardname':standardname[idx],'scaledtype':scaledtype[idx],'longname':longname[idx],'min_v':min_values[idx],'max_v': max_values[idx],'unit':units[idx], 'comment': comments[idx], 'flagvalues': flagvalues[idx], 'flagmeanings':flagmeanings[idx]}
else:
print('Error: No attribute document found.')
return att
def get_ancillary(anc_QC, check_list):
var = anc_QC.split(';')
var = [x.split('-')[0].strip() for x in var]
var = [x for x in var if x in check_list ]
return ' '.join(var)
def getParameters(i): | def save(out_file,data, **kwargs):
def duration(seconds):
t= []
for dm in (60, 60, 24, 7):
seconds, m = divmod(seconds, dm)
t.append(m)
t.append(seconds)
return ''.join('%d%s' % (num, unit)
for num, unit in zip(t[::-1], 'W DT H M S'.split())
if num)
def get_keywords(data):
keywords = []
for var in data.data.keys():
if var in abbr:
idx = abbr.index(var)
if len(keywords_list[idx])>0:
keywords.append(keywords_list[idx])
# print var, keywords_list[idx]
keywords = list(set(keywords))
keywords = ['Earth Science > %s' %x for x in keywords]
keywords = ', '.join(keywords)
return keywords
def Add_gattrs(ff):
lon_min = min(data['LON'])
lon_max = max(data['LON'])
lat_min = min(data['LAT'])
lat_max = max(data['LAT'])
start_time = min(data.data['Julian'])
end_time = max(data.data['Julian'])
dur_time = (end_time-start_time)*24.0*3600.0
start_time = jdutil.jd_to_datetime(start_time)
start_time_s = "%s-%02d-%02dT%02d:%02d:%02dZ" %(start_time.year,start_time.month,start_time.day,start_time.hour,start_time.minute,start_time.second)
end_time = jdutil.jd_to_datetime(end_time)
end_time_s = "%s-%02d-%02dT%02d:%02d:%02dZ" %(end_time.year,end_time.month,end_time.day,end_time.hour,end_time.minute,end_time.second)
version = out_file.split('_')[1]
#start_time_s = time.strftime(time_fmt,time.gmtime(float(start_time)))
#end_time_s = time.strftime(time_fmt,time.gmtime(float(end_time)))
ff.ncei_template_version = "NCEI_NetCDF_Point_Template_v2.0"
ff.featureType = "point"
ff.title = "International Comprehensive Ocean-Atmosphere Data Set (ICOADS) %s data collected from %s to %s." %(version, start_time_s, end_time_s)
ff.summary = "This file contains ICOADS %s data in netCDF4 format collected from %s to %s. The International Comprehensive Ocean-Atmosphere Data Set (ICOADS) offers surface marine data spanning the past three centuries, and simple gridded monthly summary products for 2-degree latitude x 2-degree longitude boxes back to 1800 (and 1degreex1degree boxes since 1960)--these data and products are freely distributed worldwide. As it contains observations from many different observing systems encompassing the evolution of measurement technology over hundreds of years, ICOADS is probably the most complete and heterogeneous collection of surface marine data in existence." %(version, start_time_s, end_time_s)
ff.keywords = get_keywords(data);
ff.Conventions = "CF-1.6, ACDD-1.3"
ff.id = out_file.split('.nc')[0].replace('IMMA1','ICOADS')
ff.naming_authority = "gov.noaa.ncei"
#ff.source = "http://rda.ucar.edu/data/ds548.0/imma1_r3.0.0/%s.tar" %out_file.split('-')[0]
ff.source = "%s.gz" %out_file.split('.nc')[0]
ff.processing_level = "Restructured from IMMA1 format to NetCDF4 format."
ff.acknowledgement = "Conversion of ICOADS data from IMMA1 to netCDF format by NCEI is supported by the NOAA Big Earth Data Initiative (BEDI)."
ff.license = "These data may be redistributed and used without restriction."
ff.standard_name_vocabulary = "CF Standard Name Table v31"
ff.date_created = time.strftime(time_fmt,time.gmtime())
ff.creator_name = "NCEI"
ff.creator_email = "ncei.info@noaa.gov"
ff.creator_url = "https://www.ncei.noaa.gov/"
ff.institution = "National Centers for Environmental Information (NCEI), NOAA"
ff.project = "International Comprehensive Ocean-Atmosphere Data Set (ICOADS) Project"
ff.publisher_name = "NCEI"
ff.publisher_email = "ncei.info@noaa.gov"
ff.publisher_url = "https://www.ncei.noaa.gov/"
ff.geospatial_bounds = "POLYGON ((%.4f %.4f,%.4f %.4f,%.4f %.4f,%.4f %.4f,%.4f %.4f))" %(lon_min,lat_min,lon_min,lat_max,lon_max,lat_max,lon_max,lat_min,lon_min,lat_min)
ff.geospatial_bounds_crs = "EPSG:4326"
ff.geospatial_lat_min = float("%.4f" %(lat_min))
ff.geospatial_lat_max = float("%.4f" %(lat_max))
ff.geospatial_lon_min = float("%.4f" %(lon_min))
ff.geospatial_lon_max = float("%.4f" %(lon_max))
ff.geospatial_lat_units = "degrees_north"
ff.geospatial_lon_units = "degrees_east"
ff.time_coverage_start = start_time_s
ff.time_coverage_end = end_time_s
ff.time_coverage_duration = 'P' + duration(dur_time)
ff.time_coverage_resolution = "vary"
ff.uuid = str(uuid.uuid4())
ff.sea_name = "World-Wide Distribution"
ff.creator_type = "group"
ff.creator_institution = "NOAA National Centers for Environmental Information (NCEI)"
ff.publisher_type = "institution"
ff.publisher_institution = "NOAA National Centers for Environmental Information (NCEI)"
ff.program = ""
ff.contributor_name = "Zhankun Wang; ICOADS team"
ff.contributor_role = "ICOADS Data Conversion to NetCDF; ICOADS IMMA1 Data Provider"
ff.date_modified = time.strftime(time_fmt,time.gmtime())
ff.date_issued = time.strftime(time_fmt,time.gmtime())
ff.date_metadata_modified = time.strftime(time_fmt,time.gmtime())
ff.product_version = "ICOADS %s netCDF4" %version
ff.keywords_vocabulary = "Global Change Master Directory (GCMD) 2015. GCMD Keywords, Version 8.1."
ff.cdm_data_type = 'Point'
#ff.metadata_link = 'http://rda.ucar.edu/datasets/ds548.0/#!docs'
ff.metadata_link = ''
if len(set(data.data['IM'])) == 1:
ff.IMMA_Version = str(data.data['IM'][0])
else:
print('%s: check IMMA version' %out_file)
if len(set(data.data['RN1'])) == 1:
ff.Release_Number_Primary = str(data.data['RN1'][0])
else:
print('%s: check Release_Number_Primary' %out_file)
if len(set(data.data['RN2'])) == 1:
ff.Release_Number_Secondary = str(data.data['RN2'][0])
else:
print('%s: check Release_Number_Secondary' %out_file)
if len(set(data.data['RN3'])) == 1:
ff.Release_Number_Tertiary = str(data.data['RN3'][0])
else:
print('%s: check Release_Number_Tertiary' %out_file)
if len(set(data.data['RSA'])) == 1:
ff.Release_status_indicator = str(data.data['RSA'][0])
else:
print('%s: check RSA' %out_file)
#ff.comment = ""
ff.references = 'http://rda.ucar.edu/datasets/ds548.0/docs/R3.0-citation.pdf'
ff.history = time.strftime(time_fmt,time.gmtime()) + ": Converted from IMMA1 format to netCDF4 format by Z.W. "
fpath = kwargs.get('fpath')
if fpath is None:
fpath = fpath_default
#ftxt = open("%s%s.txt" %(fpath,out_file[0:-3]), 'w')
#ftxt.write('Saving to %s ...\n' %out_file);
ff = netCDF4.Dataset(fpath + out_file.replace('IMMA1','ICOADS'), 'w', format='NETCDF4')
Add_gattrs(ff)
ff.createDimension('obs',len(data.data['YR']))
'''
# save time in Julian Days
timein = ff.createVariable('time','f8',('obs',),zlib=True,complevel=4)
timein.long_name = "time"
timein.standard_name = "time"
timein.units = "days since -4713-1-1 12:0:0 "
timein.calendar = "julian"
timein.axis = "T"
timein.comment = "Julian days since noon on January 1, 4713 BC. Missing values of date (DD in date) are replaced by 0 and missing values in HR are filled with 0.0 in this calculation. See actural values in date, HR for reference."
timein[:] = data.data['Julian'][:]
'''
# save time in Julian Days since the beginning of ICOADS data: 1662-10-15 12:00:00
timein = ff.createVariable('time','f8',('obs',),zlib=True,complevel=4)
timein.long_name = "time"
timein.standard_name = "time"
timein.units = "days since 1662-10-15 12:00:00"
timein.calendar = "julian"
timein.axis = "T"
timein.comment = "Julian days since the beginning of the ICOADS record, which is 1662-10-15 12:00:00. Missing values of date (DD in date) are replaced by 0 and missing values in HR are filled with 0.0 in this calculation. See actual values in date, HR for reference."
timein[:] = data.data['Julian1'][:]
# save date in YYYYMMDD
ff.createDimension('DATE_len',len(data.data['DATE'][0]))
date = ff.createVariable('date','S1',('obs','DATE_len',),zlib=True,complevel=4)
date.long_name = "date in YYYYMMDD"
#date.valid_min = '16000101'
#date.valid_max = '20241231'
date.format = 'YYYYMMDD'
#date.axis = "T"
date.comment = "YYYY: four digital year, MM: two digital month and DD: two digital date. Missing values of DD have been filled with 99."
date[:] = [netCDF4.stringtochar(np.array(x)) for x in data.data['DATE']]
#print data.data['YR']
crsout = ff.createVariable('crs','i')
crsout.grid_mapping_name = "latitude_longitude"
crsout.epsg_code = "EPSG:4326"
crsout.semi_major_axis = 6378137.0
crsout.inverse_flattening = 298.257223563
#crsout.comment = ''
dim_list = []
dim_dir = []
exclusives = ['YR','MO','DY','SUPD','IM','ATTC','ATTE','RN1','RN2','RN3','RSA']
'''
exclusives_2 = ['CDE','CDI','YR','MO','DY','SUPD','IM','ATTC','ATTE','RN1','RN2','RN3','RSA','ICNR','FNR','DPRO','DPRP','UFR','MFGR','MFGSR','MAR','MASR','BCR','ARCR','CDR','ASIR']
for atta in atta_list:
var_list = getParameters(atta)
for var in var_list:
if var in exclusives_2:
pass
else:
print var
att = get_var_att(var)
if 'flagvalues' in att:
if len(att['flagvalues']) > 0:
print var, att['flagvalues'], att['flagmeanings']
foo = att['flagvalues'].split(' ')
foo_m = att['flagmeanings'].split(' ')
for x,y in zip(foo,foo_m): print('%s: %s' %(x,y))
'''
for atta in atta_list:
var_list = getParameters(atta)
for var in var_list:
if var in data.data.keys():
if var in exclusives:
pass
else:
start = time.time()
#ftxt.write('%s start at %s. ' %(var,time.strftime(time_fmt,time.gmtime())));
index = [i for i, x in enumerate(data.data[var]) if x is not None]
# print var,data[var],index[0],data.data[var][index[0]]
if type(data.data[var][index[0]]) is int:
dataout = ff.createVariable(var,'i2',('obs',),fill_value = -99,zlib=True,complevel=4)
#dataout = ff.createVariable(var,'f4',('obs',),zlib=True,complevel=4)
dataout[index] = [data.data[var][idx] for idx in index]
elif type(data.data[var][index[0]]) is float:
if var == 'LAT':
dataout = ff.createVariable('lat','f4',('obs',),zlib=True,complevel=4)
elif var == 'LON':
dataout = ff.createVariable('lon','f4',('obs',),zlib=True,complevel=4)
else:
dataout = ff.createVariable(var,'f4',('obs',),fill_value = float(-9999),zlib=True,complevel=4)
dataout[index] = [data.data[var][idx] for idx in index]
elif type(data.data[var][index[0]]) is str:
#print var
if var == 'SUPD':
#ll = max([len(x) if x is not None else 0 for x in data.data[var] ])
#data.data[var] = [x.ljust(ll) if x is not None else None for x in data.data[var]]
pass
else:
ll = len(data.data[var][index[0]])
if ll not in dim_list:
ff.createDimension('%s_len' %var,ll)
dataout = ff.createVariable(var,'S1',('obs','%s_len' %var,),zlib=True,complevel=4)
dim_list.append(ll)
dim_dir.append(var)
else:
idx = dim_list.index(ll)
dataout = ff.createVariable(var,'S1',('obs','%s_len' %dim_dir[idx],),zlib=True,complevel=4)
dataout[index] = [netCDF4.stringtochar(np.array(data.data[var][idx])) for idx in index]
else:
print var, type(data.data[var][index[0]])
att = get_var_att(var)
if 'standardname' in att:
if len(att['standardname']) >0: dataout.standard_name = att['standardname']
dataout.long_name = att['longname'] if len(att['longname']) > 0 else ""
if len(att['unit']) > 0: dataout.units = att['unit']
if len(att['min_v']) > 0:
if 'int' in att['scaledtype']:
dataout.valid_min = np.int16(att['min_v'])
elif 'double' in att['scaledtype']:
dataout.valid_min = float(att['min_v'])
else:
dataout.valid_min = float(att['min_v'])
if len(att['max_v']) > 0:
if 'int' in att['scaledtype']:
dataout.valid_max = np.int16(att['max_v'])
elif 'double' in att['scaledtype']:
dataout.valid_max = float(att['max_v'])
else:
dataout.valid_max = float(att['max_v'])
if var == 'LAT': dataout.axis = 'Y'
if var == 'LON': dataout.axis = 'X'
#if len(att['min_v']) > 0:
# dataout.scale_factor = 1.
# dataout.add_offset = 0.
if 'flagvalues' in att:
if len(att['flagvalues']) >0:
foo = att['flagvalues'].split(' ')
dataout.flag_values = [np.int16(x) for x in foo]
if len(att['flagmeanings']) >0: dataout.flag_meanings = att['flagmeanings']
if var != 'LAT' and var != 'LON':
dataout.coordinates = "time lat lon"
dataout.grid_mapping = "crs"
dataout.cell_methods = "time: point"
if len(att['comment']) > 0: dataout.comment = att['comment']
if len(get_ancillary(att['ancillary'],data.data.keys())) > 0: dataout.ancillary_variables = get_ancillary(att['ancillary'],data.data.keys())
end = time.time()
#print var, end-start
#ftxt.write('Time used = %s sec\n' %(end-start));
#dataout.standard_name = "sea_surface_temperature"
#dataout.long_name = "Sea surface temperature"
#dataout.units = "degree_Celsius"
#ftxt.write('Done with %s' %out_file)
ff.close()
#ftxt.close() | return parameters["%02d" % i]
| random_line_split |
JsPopup.js | //数据列表检索排序字符串保存的键值(值以$.data的方式保存在_current_tab_page_id对应的对象上)
var _pad_adv_filter_id = "_pad_adv_filter_id";
//数据列表检索条件数据
var _pad_search_params_id = "_pad_search_params_id";
//页面初次加载时保存参数
var _pad_page_base_params_id = "_pad_page_base_params_id";
var _pad_grid_page_size = "gridPageSize";
_mp_last_focus_shift_time_millsec = 0; //上次弹层时间
var _ma_pop_idx = 1;
var _ma_pop_callback = new Object();
var _ma_pop_callback_beforeclose = new Object();
//给指定元素加载内容
function _p_a_load(url,pageContainerId,keepParams,data,callBack,isGridInit){
_pad_all_loadPage(url,pageContainerId,keepParams,data,callBack,isGridInit);
}
//keepParams 是否保留container上缓存的参数,首次加载时一般为false
function _pad_all_loadPage(url,pageContainerId,keepParams,data,callBack,isGridInit){
if(typeof(pageContainerId)=='string'){
if(pageContainerId.substring(0,1)=='#')
pageContainerId = pageContainerId.substring(1);
}
var containerObj = find_jquery_object(pageContainerId);
if(!data){
data = {};
}
var initPageSize = containerObj.attr(_pad_grid_page_size);
if(initPageSize && initPageSize>0){
//有初始化containerObj 中grid的pageSize
data = _pad_add_param_to_post_data(data,'gridPageSize',initPageSize);
}
//将容器id传入到action的loadPageId,在页面初始化脚本中可以使用
if(url.indexOf('loadPageId')==-1 && (!data || !data.loadPageId) && (typeof(data)!='string'||data.indexOf('loadPageId')==-1)){
data = _pad_add_param_to_post_data(data,'loadPageId',pageContainerId);
}
if(isGridInit && data){
containerObj.data(_pad_search_params_id, data);
}
if(!keepParams)
_pad_clear_container_old_data(pageContainerId);
var pageBaseParams = containerObj.data(_pad_page_base_params_id);
var param_idx = url.indexOf('?');
if(param_idx!=-1){
var param_idx_2 = url.indexOf('#');
var params_str = '';
if(param_idx_2!=-1){
params_str = url.substring(param_idx+1,param_idx_2);
}else{
params_str = url.substring(param_idx+1);
}
url = url.substring(0,param_idx);
if(params_str.length>0){
if(!data){
data = {};
}else if(Object.prototype.toString.call(data) === "[object String]"){
params_str = params_str + '&' + data;
data = {};
}
var param_arr = params_str.split('&');
for(var pi=0;pi<param_arr.length;pi++){
var p_key_val = param_arr[pi].split('=');
if(p_key_val.length>1){
data[p_key_val[0]] = p_key_val[1];
}
}
}
}
if(!pageBaseParams && data){
pageBaseParams = data;
}else{
pageBaseParams = _pad_mergeJsonObject(pageBaseParams, data);
}
containerObj.data(_pad_page_base_params_id, pageBaseParams);
$.ajax({
url:url,
type: "post",
data: pageBaseParams,
cache:false,
beforeSend:function(XMLHttpRequest){},
success:function(html){
if(html && isJson(html)){
//返回错误异常
if(html.err_text){
alert(html.err_text);
_hide_top_loading();
}
return;
}
_pad_add_pageInfo_to_loadPageHtml(html, pageContainerId, url);
//处理如果html中有grid,为grid加上containerId
var tempIdx1 = html.indexOf('<table');
if(tempIdx1!=-1){
tempIdx1 = tempIdx1 + 6;
var tempIdx2 = html.indexOf('>',tempIdx1);
var tempIdx3 = html.indexOf('table',tempIdx1);
if(tempIdx3!=-1 && tempIdx3< tempIdx2){
//尝试准确的定位"table.table:first"的table
html = html.substring(0,tempIdx1) + ' containerId="#'+pageContainerId+'"' + html.substring(tempIdx1);
}
}
containerObj.html(html);
containerObj.trigger('new_content_load');
//添加输入框相关效果,如 必填 等等
_pad_add_input_element(containerObj);
_update_pager_click_event(containerObj);
var anyGrid = _pad_findGridByContainerId(pageContainerId);
if(anyGrid.length>0){
add_event_for_jm_table(anyGrid);
}
//添加clearable输入框清楚按键
_pad_add_clearable_input_btn(pageContainerId);
if(callBack){
callBack(pageContainerId);
}
}
}).always(function(){});
}
function _pad_all_reloadPage(pageContainerId,more_parems,callback){
var container = find_jquery_object(pageContainerId);
if(container){
var url = container.attr('content_url');
_pad_all_loadPage(url, pageContainerId, true, more_parems, callback);
}
}
function _pad_add_clearable_input_btn(containerId){
var container = find_jquery_object(containerId);
container.find('input.clearable').each(function(){
$(this).wrap('<div class="clearable_container"></div>');
var clear_btn = $('<i class="icon-remove clear_btn"></i>');
clear_btn.click(function(){
$(this).prev('input').val('');
});
$(this).after(clear_btn);
});
}
function add_event_for_jm_table(gridTable){
var gridContainerId = gridTable.attr('containerId');
add_event_for_jm_table_sort(gridContainerId);
}
function add_event_for_jm_table_sort(containerId){
if(containerId.substring(0,1)!='#')
containerId = '#' + containerId;
var container = $(containerId);
var page_params = container.data(_pad_page_base_params_id);
if(page_params && page_params.sort_column){
var on_sorting = container.find('[sort_column="'+page_params.sort_column+'"]');
if(on_sorting.length==1){
on_sorting.attr('sort_type', page_params.sort_type);
}
}
container.find('.tab_sorter').each(function(){
var column = $(this);
var sort_column = column.attr('sort_column');
if(sort_column!=''){
var column_table = column.parents('[content_url]:first');
var sort_type = column.attr('sort_type');
column_table.removeClass('icon-sort-up icon-sort-down');
if(sort_type=='asc'){
column.addClass('icon-sort-up');
}else if(sort_type=='desc'){
column.addClass('icon-sort-down');
}else{
column.addClass('icon-sort');
}
column.unbind('click').bind('click',function(){
_show_top_loading();
var thiscolumn = $(this);
var thissort = thiscolumn.attr('sort_column');
var thistype = thiscolumn.attr('sort_type');
if(thiscolumn.is('.icon-sort-down')){
thistype = 'asc';
}else if(thiscolumn.is('.icon-sort-up')){
thistype = '';
}else{
thistype = 'desc';
}
thiscolumn.attr('sort_type',thistype);
var table_id = column_table.attr('id');
var table_url = column_table.attr('content_url');
var params = column_table.data(_pad_page_base_params_id);
if(!params){
params = {};
}
params = _pad_add_param_to_post_data(params,'sort_column',thissort);
params = _pad_add_param_to_post_data(params,'sort_type',thistype);
_p_a_load(table_url, table_id, null, params, function(){
_hide_top_loading();
});
});
}
});
}
function _hide_top_loading() {}
function _show_top_loading() {}
function _update_pager_click_event(container){
var pagerObjs = container.find('.pagination.in_tab');
pagerObjs.each(function(){
$(this).find('a').each(function() {
$(this).click(function (event) {
var url = $(this).attr('href');
_pad_all_loadPage(url,container.attr('id'),true);
return false;//阻止链接跳转
});
});
});
}
var _pad_temp_input_id_idx = 1;
function _pad_add_input_element(container){
var mustObjs = container.find('.must_input');
mustObjs.each(function(){
var inputId = _pad_check_temp_id_to_jobj($(this));
var miGroup = _pad_check_input_group_parent($(this));
var miSign = $('<i class="icon-warning-sign mi_sign" title="必填"> 必填</i>');
miSign.attr('input_id',inputId);
$(this).after(miSign);
miSign.click(function(){
$(this).removeClass('shake');
});
});
var clearAbleObjs = container.find('.clear_able');
clearAbleObjs.each(function(){
var inputId = _pad_check_temp_id_to_jobj($(this));
var miGroup = _pad_check_input_group_parent($(this));
var inner_btn_clear = $('<span class="input_inner_btn icon-remove red"></span>');
inner_btn_clear.attr('input_id',inputId);
$(this).after(inner_btn_clear);
miGroup.hover(
function(){
inner_btn_clear.show();
}
,function(){
inner_btn_clear.hide();
}
);
inner_btn_clear.click(function(e){
e.stopPropagation();
e.preventDefault();
var targetId = $(this).attr('input_id');
var targetObj = $('#'+targetId);
targetObj.prop("value",'');
//targetObj.val('');
targetObj.removeData();
});
});
var _cp_colorPicker = $('#_cp_color_select_div');
if(_cp_colorPicker.length>0){
var colorableObjs = container.find('.color_picker');
colorableObjs.each(function(){
var inputId = _pad_check_temp_id_to_jobj($(this));
$(this).click(function(e){
e.stopPropagation();
e.preventDefault();
});
});
}
}
function _pad_check_temp_id_to_jobj(jobj){
var inputId = jobj.attr('id');
if(!inputId || inputId==''){
inputId = 'input_temp_id_'+_pad_temp_input_id_idx;
_pad_temp_input_id_idx ++;
jobj.attr('id',inputId);
}
return inputId;
}
function _pad_check_input_group_parent(jobj){
var parent = jobj.parent();
var retobj = null;
if(parent.is('.mi_group')){
retobj = parent;
}else{
retobj = $('<div class="mi_group"></div>');
jobj.wrap(retobj);
}
return jobj.parent();
}
function _pad_clear_container_old_data(containerId){
if(containerId.substring(0,1)!='#')
containerId = '#' + containerId;
var container = $(containerId);
container.attr('content_url','');
//不去掉就没法设置pageSize
//container.removeAttr(_pad_grid_page_size);
container.removeAttr('pageNo');
container.removeData(_pad_adv_filter_id);
container.removeData(_pad_search_params_id);
container.removeData(_pad_page_base_params_id);
try{
container.removeData(_grid_row_selected_row_ids);
}catch(e){}
try{
//_all_gridSearchClear(containerId); //页面暂时没有这个逻辑,vix中有
}catch(e){
alert(e);
}
}
function _pad_findGridByContainerId(containerId){
if(containerId.substring(0,1)!='#')
containerId = '#' + containerId;
var containerObj = $(containerId);
var anyGrid = containerObj.find('table.table:first');
if(anyGrid.length>0){
var ori_containerId = anyGrid.attr('containerId');
if(!ori_containerId || ori_containerId==''){
anyGrid.attr('containerId',containerId);
}
}
return anyGrid;
}
function _pad_add_pageInfo_to_loadPageHtml(jqHtml, pageContainerId, url){
var container = find_jquery_object(pageContainerId);
container.attr('content_url',url);
}
function _pad_mergeJsonObject(baseData, newData){
if(!baseData)
return newData;
if(!newData)
return baseData;
var resultJsonObject={};
for(var attr in baseData){
resultJsonObject[attr]=baseData[attr];
}
for(var attr in newData){
resultJsonObject[attr]=newData[attr];
}
return resultJsonObject;
}
function find_jquery_object(obj){
var jObj = null;
//check if obj is just id
if(obj instanceof jQuery){
jObj = obj;
}else{
if(typeof(obj)=='string'){
if(obj.substring(0,1)!='#')
obj = '#' + obj;
jObj = $(obj);
}else{
jObj = $(obj);
}
}
return jObj;
}
function _pad_add_param_to_post_data(data, paramName, paramValue){
if(!data || data.length==0){
data = paramName+'='+paramValue;
}else{
if(typeof(data)=='string'){
if(data!=''){
if(data.substring(0,1)=='&'){
data = data.substring(1);
}
if(data.substring(data.length-1)=='&'){
data = data.substring(0,data.length-1);
}
if(data!=''){
var param_arr = data.split('&');
data = {};
for(var pi=0;pi<param_arr.length;pi++){
var p_key_val = param_arr[pi].split('=');
if(p_key_val.length>1){
data[p_key_val[0]] = p_key_val[1];
}
}
}
}
}
data[paramName] = paramValue;
}
return data;
}
function isJson(obj){
return typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
}
/**
* 弹框显示内容
* @param ma_mark 弹框标识(非id),相同标识只弹出一个窗口
* @param title 窗口标题
* @param url 加载内容url,优先使用url再使用content
* @param content 窗口显示内容,当url有效时,可作为提交参数(数组格式)
* @param position 位置信息数组,可设置width,height,left/right,top/bottom
* @param callback 回调函数,可设置 afterinit,beforeclose(点击右上角关闭时),finishwork(在显示内容内根据自定义情况执行)
* @private
*/
function _add_moveable_popup(ma_mark,title,url,content,position,callback){
//此判断无法处理并发情况,暂时不深入处理
if(ma_mark && $('.moveable_popup_win[identity="'+ma_mark+'"]').length>0){
_close_moveable_popup(ma_mark);//改为关闭之前的
}
var mapop = $('<div class="moveable_popup_win any_focus_pop my_focus_pop"><div class="title_bar"></div><div class="close_btn icon-remove" ma_mark="'+ma_mark+'"></div><div class="content_here"></div><div class="button_here"></div></div>');
var ma_id = 'ma_pop_'+_ma_pop_idx;
mapop.attr('id',ma_id);
mapop.attr('idx',_ma_pop_idx);
if(!ma_mark || ma_mark==''){
ma_mark = ma_id;
}
if(ma_mark){
mapop.attr('identity',ma_mark);
}
$('.my_focus_pop').removeClass('my_focus_pop');
$('#main-content').append(mapop);
var content_obj = mapop.find('.content_here:first');
var ma_content_id = 'ma_pop_content_'+_ma_pop_idx;
content_obj.attr('id',ma_content_id);
_ma_pop_idx ++;
var titlebar = mapop.find('.title_bar:first');
titlebar.html(title);
if(!callback){
callback = {};
_ma_pop_callback[ma_mark] = null;
_ma_pop_callback_beforeclose[ma_mark] = null;
}else{
if(callback.finishwork){
_ma_pop_callback[ma_mark] = callback.finishwork;
}
if(callback.beforeclose) {
_ma_pop_callback_beforeclose[ma_mark] = callback.beforeclose;
}
}
mapop.resizable();
mapop.delegate('.close_btn','click',function(){
_close_moveable_popup($(this).attr('ma_mark'));
});
var mp_data = {};
mp_data.moveable_pop_mark = ma_mark;
if(url){
mp_data = _pad_mergeJsonObject(mp_data,content);
_pad_all_loadPage(url,ma_content_id,true,mp_data,function(){
_ma_check_button(mapop);
mapop.show();
_reposition_moveable_pop(mapop,position);
if(callback.afterinit){
callback.afterinit(ma_id,ma_content_id);
}
});
}else{
content_obj.html(content);
_reposition_moveable_pop(mapop,position);
_ma_check_button(mapop);
mapop.show();
if(callback.afterinit){
callback.afterinit(ma_id,ma_content_id);
}
}
_mp_last_focus_shift_time_millsec = new Date().getTime();
mapop.draggabilly({
handle: '.title_bar'
});
}
function _ma_check_button(mapop){
var button_old = mapop.find('.pop_win_buttons:first');
var button_new = mapop.find('.button_here:first');
var fixed_buttons = button_new.find('.ma_fixed_button');
var fixed_btn_group = $('<span class="ma_fixed_button_group"></span>');
fixed_buttons.each(function(){
fixed_btn_group.append($(this));
});
var close_btn = $('<a class="btn close_btn">关闭</a>');
close_btn.attr('ma_mark', mapop.attr('identity'));
if(button_old.length>0){
button_new.html('');
button_new.append(fixed_btn_group);
button_new.append(button_old.html());
button_new.appe | button_old.remove();
}else{
button_new.html(close_btn);//默认添加关闭按键
button_new.prepend(fixed_btn_group);
}
}
function _reload_moveable_pop(ma_mark, more_parems){
if(ma_mark && $('.moveable_popup_win[identity="'+ma_mark+'"]').length>0){
_pad_all_reloadPage($('.moveable_popup_win[identity="'+ma_mark+'"]').find('.content_here:first').attr('id'),more_parems, function(){
_ma_check_button($('.moveable_popup_win[identity="'+ma_mark+'"]'));
});
}
}
function _find_moveable_pop_by_ma_mark(ma_mark){
return $('.moveable_popup_win[identity="'+ma_mark+'"]');
}
function _reposition_moveable_pop(mapop,position){
if(position){
if(position.width>0){
position.width = position.width + 30;
mapop.css('width',position.width);
}
var p_height = position.height;
if(isNaN(p_height)){
p_height = 0;
}
if(position.auto_height){
var content_container = mapop.find('.content_here:first');
var content_height = content_container[0].scrollHeight;
if(!isNaN(content_height)){
if(p_height>content_height){
p_height = content_height + 80;
}
if(p_height<230){
p_height = 230;
}
}
mapop.css('height', p_height);
}else{
mapop.css('height', p_height+50);
}
if(!isNaN(position.left)){
mapop.css('left',position.left);
}else if(!isNaN(position.right)){
var width = mapop.outerWidth();
var win_width = $(document).innerWidth();
var left = win_width - width - position.right;
mapop.css('left',left);
}
if(!isNaN(position.top)){
mapop.css('top',position.top);
}else if(!isNaN(position.bottom)){
var height = mapop.outerHeight();
var win_height = $(window).innerHeight();
var top = win_height - height - position.bottom;
if(top<0){
top = 0;
}
mapop.css('top',top);
}
}
}
function _run_moveable_callback_finishwork(ma_mark, params){
if(ma_mark && $('.moveable_popup_win[identity="'+ma_mark+'"]').length>0){
if(_ma_pop_callback[ma_mark]){
_ma_pop_callback[ma_mark](params);
}
}
}
function _close_moveable_popup(ma_mark){
if(_ma_pop_callback_beforeclose[ma_mark]){
_ma_pop_callback_beforeclose[ma_mark](ma_mark);
}
if(ma_mark && $('.moveable_popup_win[identity="'+ma_mark+'"]').length>0){
$('.moveable_popup_win[identity="'+ma_mark+'"]').remove();
_ma_pop_callback[ma_mark] = null;
_ma_pop_callback_beforeclose[ma_mark] = null;
}else{
$('.moveable_popup_win.my_focus_pop').remove();
}
} | nd(close_btn);
| identifier_name |
JsPopup.js | //数据列表检索排序字符串保存的键值(值以$.data的方式保存在_current_tab_page_id对应的对象上)
var _pad_adv_filter_id = "_pad_adv_filter_id";
//数据列表检索条件数据
var _pad_search_params_id = "_pad_search_params_id";
//页面初次加载时保存参数
var _pad_page_base_params_id = "_pad_page_base_params_id";
var _pad_grid_page_size = "gridPageSize";
_mp_last_focus_shift_time_millsec = 0; //上次弹层时间
var _ma_pop_idx = 1;
var _ma_pop_callback = new Object();
var _ma_pop_callback_beforeclose = new Object();
//给指定元素加载内容
function _p_a_load(url,pageContainerId,keepParams,data,callBack,isGridInit){
_pad_all_loadPage(url,pageContainerId,keepParams,data,callBack,isGridInit);
}
//keepParams 是否保留container上缓存的参数,首次加载时一般为false
function _pad_all_loadPage(url,pageContainerId,keepParams,data,callBack,isGridInit){
if(typeof(pageContainerId)=='string'){
if(pageContainerId.substring(0,1)=='#')
pageContainerId = pageContainerId.substring(1);
}
var containerObj = find_jquery_object(pageContainerId);
if(!data){
data = {};
}
var initPageSize = containerObj.attr(_pad_grid_page_size);
if(initPageSize && initPageSize>0){
//有初始化containerObj 中grid的pageSize
data = _pad_add_param_to_post_data(data,'gridPageSize',initPageSize);
}
//将容器id传入到action的loadPageId,在页面初始化脚本中可以使用
if(url.indexOf('loadPageId')==-1 && (!data || !data.loadPageId) && (typeof(data)!='string'||data.indexOf('loadPageId')==-1)){
data = _pad_add_param_to_post_data(data,'loadPageId',pageContainerId);
}
if(isGridInit && data){
containerObj.data(_pad_search_params_id, data);
}
if(!keepParams)
_pad_clear_container_old_data(pageContainerId);
var pageBaseParams = containerObj.data(_pad_page_base_params_id);
var param_idx = url.indexOf('?');
if(param_idx!=-1){
var param_idx_2 = url.indexOf('#');
var params_str = '';
if(param_idx_2!=-1){
params_str = url.substring(param_idx+1,param_idx_2);
}else{
params_str = url.substring(param_idx+1);
}
url = url.substring(0,param_idx);
if(params_str.length>0){
if(!data){
data = {};
}else if(Object.prototype.toString.call(data) === "[object String]"){
params_str = params_str + '&' + data;
data = {};
}
var param_arr = params_str.split('&');
for(var pi=0;pi<param_arr.length;pi++){
var p_key_val = param_arr[pi].split('=');
if(p_key_val.length>1){
data[p_key_val[0]] = p_key_val[1];
}
}
}
}
if(!pageBaseParams && data){
pageBaseParams = data;
}else{
pageBaseParams = _pad_mergeJsonObject(pageBaseParams, data);
}
containerObj.data(_pad_page_base_params_id, pageBaseParams);
$.ajax({
url:url,
type: "post",
data: pageBaseParams,
cache:false,
beforeSend:function(XMLHttpRequest){},
success:function(html){
if(html && isJson(html)){
//返回错误异常
if(html.err_text){
alert(html.err_text);
_hide_top_loading();
}
return;
}
_pad_add_pageInfo_to_loadPageHtml(html, pageContainerId, url);
//处理如果html中有grid,为grid加上containerId
var tempIdx1 = html.indexOf('<table');
if(tempIdx1!=-1){
tempIdx1 = tempIdx1 + 6;
var tempIdx2 = html.indexOf('>',tempIdx1);
var tempIdx3 = html.indexOf('table',tempIdx1);
if(tempIdx3!=-1 && tempIdx3< tempIdx2){
//尝试准确的定位"table.table:first"的table
html = html.substring(0,tempIdx1) + ' containerId="#'+pageContainerId+'"' + html.substring(tempIdx1);
}
}
containerObj.html(html);
containerObj.trigger('new_content_load');
//添加输入框相关效果,如 必填 等等
_pad_add_input_element(containerObj);
_update_pager_click_event(containerObj);
var anyGrid = _pad_findGridByContainerId(pageContainerId);
if(anyGrid.length>0){
add_event_for_jm_table(anyGrid);
}
//添加clearable输入框清楚按键
_pad_add_clearable_input_btn(pageContainerId);
if(callBack){
callBack(pageContainerId);
}
}
}).always(function(){});
}
function _pad_all_reloadPage(pageContainerId,more_parems,callback){
var container = find_jquery_object(pageContainerId);
if(container){
var url = container.attr('content_url');
_pad_all_loadPage(url, pageContainerId, true, more_parems, callback);
}
}
function _pad_add_clearable_input_btn(containerId){
var container = find_jquery_object(containerId);
container.find('input.clearable').each(function(){
$(this).wrap('<div class="clearable_container"></div>');
var clear_btn = $('<i class="icon-remove clear_btn"></i>');
clear_btn.click(function(){
$(this).prev('input').val('');
});
$(this).after(clear_btn);
});
}
function add_event_for_jm_table(gridTable){
var gridContainerId = gridTable.attr('containerId');
add_event_for_jm_table_sort(gridContainerId);
}
function add_event_for_jm_table_sort(containerId){
if(containerId.substring(0,1)!='#')
containerId = '#' + containerId;
var container = $(containerId);
var page_params = container.data(_pad_page_base_params_id);
if(page_params && page_params.sort_column){
var on_sorting = container.find('[sort_column="'+page_params.sort_column+'"]');
if(on_sorting.length==1){
on_sorting.attr('sort_type', page_params.sort_type);
}
}
container.find('.tab_sorter').each(function(){
var column = $(this);
var sort_column = column.attr('sort_column');
if(sort_column!=''){
var column_table = column.parents('[content_url]:first');
var sort_type = column.attr('sort_type');
column_table.removeClass('icon-sort-up icon-sort-down');
if(sort_type=='asc'){
column.addClass('icon-sort-up');
}else if(sort_type=='desc'){
column.addClass('icon-sort-down');
}else{
column.addClass('icon-sort');
}
column.unbind('click').bind('click',function(){
_show_top_loading();
var thiscolumn = $(this);
var thissort = thiscolumn.attr('sort_column');
var thistype = thiscolumn.attr('sort_type');
if(thiscolumn.is('.icon-sort-down')){
thistype = 'asc';
}else if(thiscolumn.is('.icon-sort-up')){
thistype = '';
}else{
thistype = 'desc';
}
thiscolumn.attr('sort_type',thistype);
var table_id = column_table.attr('id');
var table_url = column_table.attr('content_url');
var params = column_table.data(_pad_page_base_params_id);
if(!params){
params = {};
}
params = _pad_add_param_to_post_data(params,'sort_column',thissort);
params = _pad_add_param_to_post_data(params,'sort_type',thistype);
_p_a_load(table_url, table_id, null, params, function(){
_hide_top_loading();
});
});
}
});
}
function _hide_top_loading() {}
function _show_top_loading() {}
function _update_pager_click_event(container){
var pagerObjs = container.find('.pagination.in_tab');
pagerObjs.each(function(){
$(this).find('a').each(function() {
$(this).click(function (event) {
var url = $(this).attr('href');
_pad_all_loadPage(url,container.attr('id'),true);
return false;//阻止链接跳转
});
});
});
}
var _pad_temp_input_id_idx = 1;
function _pad_add_input_element(container){
var mustObjs = container.find('.must_input');
mustObjs.each(function(){
var inputId = _pad_check_temp_id_to_jobj($(this));
var miGroup = _pad_check_input_group_parent($(this));
var miSign = $('<i class="icon-warning-sign mi_sign" title="必填"> 必填</i>');
miSign.attr('input_id',inputId);
$(this).after(miSign);
miSign.click(function(){
$(this).removeClass('shake');
});
});
var clearAbleObjs = container.find('.clear_able');
clearAbleObjs.each(function(){
var inputId = _pad_check_temp_id_to_jobj($(this));
var miGroup = _pad_check_input_group_parent($(this));
var inner_btn_clear = $('<span class="input_inner_btn icon-remove red"></span>');
inner_btn_clear.attr('input_id',inputId);
$(this).after(inner_btn_clear);
miGroup.hover(
function(){
inner_btn_clear.show();
}
,function(){
inner_btn_clear.hide();
}
);
inner_btn_clear.click(function(e){
e.stopPropagation();
e.preventDefault();
var targetId = $(this).attr('input_id');
var targetObj = $('#'+targetId);
targetObj.prop("value",'');
//targetObj.val('');
targetObj.removeData();
});
});
var _cp_colorPicker = $('#_cp_color_select_div');
if(_cp_colorPicker.length>0){
var colorableObjs = container.find('.color_picker');
colorableObjs.each(function(){
var inputId = _pad_check_temp_id_to_jobj($(this));
$(this).click(function(e){
e.stopPropagation();
e.preventDefault();
});
});
}
}
function _pad_check_temp_id_to_jobj(jobj){
var inputId = jobj.attr('id');
if(!inputId || inputId==''){
inputId = 'input_temp_id_'+_pad_temp_input_id_idx;
_pad_temp_input_id_idx ++;
jobj.attr('id',inputId);
}
return inputId;
}
function _pad_check_input_group_parent(jobj){
var parent = jobj.parent();
var retobj = null;
if(parent.is('.mi_group')){
retobj = parent;
}else{
retobj = $('<div class="mi_group"></div>');
jobj.wrap(retobj);
}
return jobj.parent();
}
function _pad_clear_container_old_data(containerId){
if(containerId.substring(0,1)!='#')
containerId = '#' + containerId;
var container = $(containerId);
container.attr('content_url','');
//不去掉就没法设置pageSize
//container.removeAttr(_pad_grid_page_size);
container.removeAttr('pageNo');
container.removeData(_pad_adv_filter_id);
container.removeData(_pad_search_params_id);
container.removeData(_pad_page_base_params_id);
try{
container.removeData(_grid_row_selected_row_ids);
}catch(e){}
try{
//_all_gridSearchClear(containerId); //页面暂时没有这个逻辑,vix中有
}catch(e){
alert(e);
}
}
function _pad_findGridByContainerId(containerId){
if(containerId.substring(0,1)!='#')
containerId = '#' + containerId;
var containerObj = $(containerId);
var anyGrid = containerObj.find('table.table:first');
if(anyGrid.length>0){
var ori_containerId = anyGrid.attr('containerId');
if(!ori_containerId || ori_containerId==''){
anyGrid.attr('containerId',containerId);
}
}
return anyGrid;
}
function _pad_add_pageInfo_to_loadPageHtml(jqHtml, pageContainerId, url){
var container = find_jquery_object(pageContainerId);
container.attr('content_url',url);
}
function _pad_mergeJsonObject(baseData, newData){
if(!baseData)
return newData;
if(!newData)
return baseData;
var resultJsonObject={};
for(var attr in baseData){
resultJsonObject[attr]=baseData[attr];
}
for(var attr in newData){
resultJsonObject[attr]=newData[attr];
}
return resultJsonObject;
}
function find_jquery_object(obj){
var jObj = null;
//check if obj is just id
if(obj instanceof jQuery){
jObj = obj;
}else{
if(typeof(obj)=='string'){
if(obj.substring(0,1)!='#')
obj = '#' + obj;
jObj = $(obj);
}else{
jObj = $(obj);
}
}
return jObj;
}
function _pad_add_param_to_post_data(data, paramName, paramValue){
if(!data || data.length==0){
data = paramName+'='+paramValue;
}else{
if(typeof(data)=='string'){
if(data!=''){
if(data.substring(0,1)=='&'){
data = data.substring(1);
}
if(data.substring(data.length-1)=='&'){
data = data.substring(0,data.length-1);
}
if(data!=''){
var param_arr = data.split('&');
data = {};
for(var pi=0;pi<param_arr.length;pi++){
var p_key_val = param_arr[pi].split('=');
if(p_key_val.length>1){
data[p_key_val[0]] = p_key_val[1];
}
}
}
}
}
data[paramName] = paramValue;
}
return data;
}
function isJson(obj){
return typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
}
/**
* 弹框显示内容
* @param ma_mark 弹框标识(非id),相同标识只弹出一个窗口
* @param title 窗口标题
* @param url 加载内容url,优先使用url再使用content
* @param content 窗口显示内容,当url有效时,可作为提交参数(数组格式)
* @param position 位置信息数组,可设置width,height,left/right,top/bottom
* @param callback 回调函数,可设置 afterinit,beforeclose(点击右上角关闭时),finishwork(在显示内容内根据自定义情况执行)
* @private
*/
function _add_moveable_popup(ma_mark,title,url,content,position,callback){
//此判断无法处理并发情况,暂时不深入处理
if(ma_mark && $('.moveable_popup_win[identity="'+ma_mark+'"]').length>0){
_close_moveable_popup(ma_mark);//改为关闭之前的
}
var mapop = $('<div class="moveable_popup_win any_focus_pop my_focus_pop"><div class="title_bar"></div><div class="close_btn icon-remove" ma_mark="'+ma_mark+'"></div><div class="content_here"></div><div class="button_here"></div></div>');
var ma_id = 'ma_pop_'+_ma_pop_idx;
mapop.attr('id',ma_id);
mapop.attr('idx',_ma_pop_idx);
if(!ma_mark || ma_mark==''){
ma_mark = ma_id;
}
if(ma_mark){
mapop.attr('identity',ma_mark);
}
$('.my_focus_pop').removeClass('my_focus_pop');
$('#main-content').append(mapop);
var content_obj = mapop.find('.content_here:first');
var ma_content_id = 'ma_pop_content_'+_ma_pop_idx;
content_obj.attr('id',ma_content_id);
_ma_pop_idx ++;
var titlebar = mapop.find('.title_bar:first');
titlebar.html(title);
if(!callback){
callback = {};
_ma_pop_callback[ma_mark] = null;
_ma_pop_callback_beforeclose[ma_mark] = null;
}else{
if(callback.finishwork){
_ma_pop_callback[ma_mark] = callback.finishwork;
}
if(callback.beforeclose) {
_ma_pop_callback_beforeclose[ma_mark] = callback.beforeclose;
}
}
mapop.resizable();
mapop.delegate('.close_btn','click',function(){
_close_moveable_popup($(this).attr('ma_mark'));
});
var mp_data = {};
mp_data.moveable_pop_mark = ma_mark;
if(url){
mp_data = _pad_mergeJsonObject(mp_data,content);
_pad_all_loadPage(url,ma_content_id,true,mp_data,function(){
_ma_check_button(mapop);
mapop.show();
_reposition_moveable_pop(mapop,position);
if(callback.afterinit){
callback.afterinit(ma_id,ma_content_id);
}
});
}else{
content_obj.html(content);
_reposition_moveable_pop(mapop,position);
_ma_check_button(mapop);
mapop.show();
if(callback.afterinit){
callback.afterinit(ma_id,ma_content_id);
}
}
_mp_last_focus_shift_time_millsec = new Date().getTime();
mapop.draggabilly({
handle: '.title_bar'
});
}
function _ma_check_button(mapop){
var button_old = mapop.find('.pop_win_buttons:first');
var button_new = mapop.find('.button_here:first');
var fixed_buttons = button_new.find('.ma_fixed_button');
var fixed_btn_group = $('<span class="ma_fixed_button_group"></span>');
fixed_buttons.each(function(){
fixed_btn_group.append($(this));
});
var close_btn = $('<a class="btn close_btn">关闭</a>');
close_btn.attr('ma_mark', mapop.attr('identity'));
if(button_old.length>0){
button_new.html('');
button_new.append(fixed_btn_group);
button_new.append(button_old.html());
button_new.append(close_btn);
button_old.remove();
}else{
button_new.html(close_btn);//默认添加关闭按键
button_new.prepend(fixed_btn_group);
}
}
function _reload_moveable_pop(ma_mark, more_parems){
if(ma_mark && $('.moveable_popup_win[identity="'+ma_mark+'"]').length>0){
_pad_all_reloadPage($('.moveable_popup_win[identity="'+ma_mark+'"]').find('.content_here:first').attr('id'),more_parems, function(){
_ma_check_button($('.moveable_popup_win[identity="'+ma_mark+'"]'));
});
}
}
function _find_moveable_pop_by_ma_mark(ma_mark){
return $('.moveable_popup_win[identity="'+ma_mark+'"]');
}
function _reposition_moveable_pop(mapop,position){
if(position){
if(position.width>0){
position.width = position.width + 30;
mapop.css('width',position.width);
}
var p_height = position.height;
if(isNaN(p_height)){
p_height = 0;
}
if(position.auto_height){
var content_container = mapop.find('.content_here:first');
var content_height = content_container[0].scrollHeight;
if(!isNaN(content_height)){
if(p_height>content_height){
p_height = content_height + 80;
}
if(p_height<230){
p_height = 230;
| able_popup_win.my_focus_pop').remove();
}
} | }
}
mapop.css('height', p_height);
}else{
mapop.css('height', p_height+50);
}
if(!isNaN(position.left)){
mapop.css('left',position.left);
}else if(!isNaN(position.right)){
var width = mapop.outerWidth();
var win_width = $(document).innerWidth();
var left = win_width - width - position.right;
mapop.css('left',left);
}
if(!isNaN(position.top)){
mapop.css('top',position.top);
}else if(!isNaN(position.bottom)){
var height = mapop.outerHeight();
var win_height = $(window).innerHeight();
var top = win_height - height - position.bottom;
if(top<0){
top = 0;
}
mapop.css('top',top);
}
}
}
function _run_moveable_callback_finishwork(ma_mark, params){
if(ma_mark && $('.moveable_popup_win[identity="'+ma_mark+'"]').length>0){
if(_ma_pop_callback[ma_mark]){
_ma_pop_callback[ma_mark](params);
}
}
}
function _close_moveable_popup(ma_mark){
if(_ma_pop_callback_beforeclose[ma_mark]){
_ma_pop_callback_beforeclose[ma_mark](ma_mark);
}
if(ma_mark && $('.moveable_popup_win[identity="'+ma_mark+'"]').length>0){
$('.moveable_popup_win[identity="'+ma_mark+'"]').remove();
_ma_pop_callback[ma_mark] = null;
_ma_pop_callback_beforeclose[ma_mark] = null;
}else{
$('.move | identifier_body |
JsPopup.js | //数据列表检索排序字符串保存的键值(值以$.data的方式保存在_current_tab_page_id对应的对象上)
var _pad_adv_filter_id = "_pad_adv_filter_id";
//数据列表检索条件数据
var _pad_search_params_id = "_pad_search_params_id";
//页面初次加载时保存参数
var _pad_page_base_params_id = "_pad_page_base_params_id";
var _pad_grid_page_size = "gridPageSize";
_mp_last_focus_shift_time_millsec = 0; //上次弹层时间
var _ma_pop_idx = 1;
var _ma_pop_callback = new Object();
var _ma_pop_callback_beforeclose = new Object();
//给指定元素加载内容
function _p_a_load(url,pageContainerId,keepParams,data,callBack,isGridInit){
_pad_all_loadPage(url,pageContainerId,keepParams,data,callBack,isGridInit);
}
//keepParams 是否保留container上缓存的参数,首次加载时一般为false
function _pad_all_loadPage(url,pageContainerId,keepParams,data,callBack,isGridInit){
if(typeof(pageContainerId)=='string'){
if(pageContainerId.substring(0,1)=='#')
pageContainerId = pageContainerId.substring(1);
}
var containerObj = find_jquery_object(pageContainerId);
if(!data){
data = {};
}
var initPageSize = containerObj.attr(_pad_grid_page_size);
if(initPageSize && initPageSize>0){
//有初始化containerObj 中grid的pageSize
data = _pad_add_param_to_post_data(data,'gridPageSize',initPageSize);
}
//将容器id传入到action的loadPageId,在页面初始化脚本中可以使用
if(url.indexOf('loadPageId')==-1 && (!data || !data.loadPageId) && (typeof(data)!='string'||data.indexOf('loadPageId')==-1)){
data = _pad_add_param_to_post_data(data,'loadPageId',pageContainerId);
}
if(isGridInit && data){
containerObj.data(_pad_search_params_id, data);
}
if(!keepParams)
_pad_clear_container_old_data(pageContainerId);
var pageBaseParams = containerObj.data(_pad_page_base_params_id);
var param_idx = url.indexOf('?');
if(param_idx!=-1){
var param_idx_2 = url.indexOf('#');
var params_str = '';
if(param_idx_2!=-1){
params_str = url.substring(param_idx+1,param_idx_2);
}else{
params_str = url.substring(param_idx+1);
}
url = url.substring(0,param_idx);
if(params_str.length>0){
if(!data){
data = {};
}else if(Object.prototype.toString.call(data) === "[object String]"){
params_str = params_str + '&' + data;
data = {};
}
var param_arr = params_str.split('&');
for(var pi=0;pi<param_arr.length;pi++){
var p_key_val = param_arr[pi].split('=');
if(p_key_val.length>1){
data[p_key_val[0]] = p_key_val[1];
}
}
}
}
if(!pageBaseParams && data){
pageBaseParams = data;
}else{
pageBaseParams = _pad_mergeJsonObject(pageBaseParams, data);
}
containerObj.data(_pad_page_base_params_id, pageBaseParams);
$.ajax({
url:url,
type: "post",
data: pageBaseParams,
cache:false,
beforeSend:function(XMLHttpRequest){},
success:function(html){
if(html && isJson(html)){
//返回错误异常
if(html.err_text){
alert(html.err_text);
_hide_top_loading();
}
return;
}
_pad_add_pageInfo_to_loadPageHtml(html, pageContainerId, url);
//处理如果html中有grid,为grid加上containerId
var tempIdx1 = html.indexOf('<table');
if(tempIdx1!=-1){
tempIdx1 = tempIdx1 + 6;
var tempIdx2 = html.indexOf('>',tempIdx1);
var tempIdx3 = html.indexOf('table',tempIdx1);
if(tempIdx3!=-1 && tempIdx3< tempIdx2){
//尝试准确的定位"table.table:first"的table
html = html.substring(0,tempIdx1) + ' containerId="#'+pageContainerId+'"' + html.substring(tempIdx1);
}
}
containerObj.html(html);
containerObj.trigger('new_content_load');
//添加输入框相关效果,如 必填 等等
_pad_add_input_element(containerObj);
_update_pager_click_event(containerObj);
var anyGrid = _pad_findGridByContainerId(pageContainerId);
if(anyGrid.length>0){
add_event_for_jm_table(anyGrid);
}
//添加clearable输入框清楚按键
_pad_add_clearable_input_btn(pageContainerId);
if(callBack){
callBack(pageContainerId);
}
}
}).always(function(){});
}
function _pad_all_reloadPage(pageContainerId,more_parems,callback){
var container = find_jquery_object(pageContainerId);
if(container){
var url = container.attr('content_url');
_pad_all_loadPage(url, pageContainerId, true, more_parems, callback);
}
}
function _pad_add_clearable_input_btn(containerId){
var container = find_jquery_object(containerId);
container.find('input.clearable').each(function(){
$(this).wrap('<div class="clearable_container"></div>');
var clear_btn = $('<i class="icon-remove clear_btn"></i>');
clear_btn.click(function(){
$(this).prev('input').val('');
});
$(this).after(clear_btn);
});
}
function add_event_for_jm_table(gridTable){
var gridContainerId = gridTable.attr('containerId');
add_event_for_jm_table_sort(gridContainerId);
}
function add_event_for_jm_table_sort(containerId){
if(containerId.substring(0,1)!='#')
containerId = '#' + containerId;
var container = $(containerId);
var page_params = container.data(_pad_page_base_params_id);
if(page_params && page_params.sort_column){
var on_sorting = container.find('[sort_column="'+page_params.sort_column+'"]');
if(on_sorting.length==1){
on_sorting.attr('sort_type', page_params.sort_type);
}
}
container.find('.tab_sorter').each(function(){
var column = $(this);
var sort_column = column.attr('sort_column');
if(sort_column!=''){
var column_table = column.parents('[content_url]:first');
var sort_type = column.attr('sort_type');
column_table.removeClass('icon-sort-up icon-sort-down');
if(sort_type=='asc'){
column.addClass('icon-sort-up');
}else if(sort_type=='desc'){
column.addClass('icon-sort-down');
}else{
column.addClass('icon-sort');
}
column.unbind('click').bind('click',function(){
_show_top_loading();
var thiscolumn = $(this);
var thissort = thiscolumn.attr('sort_column');
var thistype = thiscolumn.attr('sort_type');
if(thiscolumn.is('.icon-sort-down')){
thistype = 'asc';
}else if(thiscolumn.is('.icon-sort-up')){
thistype = '';
}else{
thistype = 'desc';
}
thiscolumn.attr('sort_type',thistype);
var table_id = column_table.attr('id');
var table_url = column_table.attr('content_url');
var params = column_table.data(_pad_page_base_params_id);
if(!params){
params = {};
}
params = _pad_add_param_to_post_data(params,'sort_column',thissort);
params = _pad_add_param_to_post_data(params,'sort_type',thistype);
_p_a_load(table_url, table_id, null, params, function(){
_hide_top_loading();
});
});
}
});
}
function _hide_top_loading() {}
function _show_top_loading() {}
function _update_pager_click_event(container){
var pagerObjs = container.find('.pagination.in_tab');
pagerObjs.each(function(){
$(this).find('a').each(function() {
$(this).click(function (event) {
var url = $(this).attr('href');
_pad_all_loadPage(url,container.attr('id'),true);
return false;//阻止链接跳转
});
});
});
}
var _pad_temp_input_id_idx = 1;
function _pad_add_input_element(container){
var mustObjs = container.find('.must_input');
mustObjs.each(function(){
var inputId = _pad_check_temp_id_to_jobj($(this));
var miGroup = _pad_check_input_group_parent($(this));
var miSign = $('<i class="icon-warning-sign mi_sign" title="必填"> 必填</i>');
miSign.attr('input_id',inputId);
$(this).after(miSign);
miSign.click(function(){
$(this).removeClass('shake');
});
});
var clearAbleObjs = container.find('.clear_able');
clearAbleObjs.each(function(){
var inputId = _pad_check_temp_id_to_jobj($(this));
var miGroup = _pad_check_input_group_parent($(this));
var inner_btn_clear = $('<span class="input_inner_btn icon-remove red"></span>');
inner_btn_clear.attr('input_id',inputId);
$(this).after(inner_btn_clear);
miGroup.hover(
function(){
inner_btn_clear.show();
}
,function(){
inner_btn_clear.hide();
}
);
inner_btn_clear.click(function(e){
e.stopPropagation();
e.preventDefault();
var targetId = $(this).attr('input_id');
var targetObj = $('#'+targetId);
targetObj.prop("value",'');
//targetObj.val('');
targetObj.removeData();
});
});
var _cp_colorPicker = $('#_cp_color_select_div');
if(_cp_colorPicker.length>0){
var colorableObjs = container.find('.color_picker');
colorableObjs.each(function(){
var inputId = _pad_check_temp_id_to_jobj($(this));
$(this).click(function(e){
e.stopPropagation();
e.preventDefault();
});
});
}
}
function _pad_check_temp_id_to_jobj(jobj){
var inputId = jobj.attr('id');
if(!inputId || inputId==''){
inputId = 'input_temp_id_'+_pad_temp_input_id_idx;
_pad_temp_input_id_idx ++;
jobj.attr('id',inputId);
}
return inputId;
}
function _pad_check_input_group_parent(jobj){
var parent = jobj.parent();
var retobj = null;
if(parent.is('.mi_group')){
retobj = parent;
}else{
retobj = $('<div class="mi_group"></div>');
jobj.wrap(retobj);
}
return jobj.parent();
}
function _pad_clear_container_old_data(containerId){
if(containerId.substring(0,1)!='#')
containerId = '#' + containerId;
var container = $(containerId);
container.attr('content_url','');
//不去掉就没法设置pageSize
//container.removeAttr(_pad_grid_page_size);
container.removeAttr('pageNo');
container.removeData(_pad_adv_filter_id);
container.removeData(_pad_search_params_id);
container.removeData(_pad_page_base_params_id);
try{
container.removeData(_grid_row_selected_row_ids);
}catch(e){}
try{
//_all_gridSearchClear(containerId); //页面暂时没有这个逻辑,vix中有
}catch(e){
alert(e);
}
}
function _pad_findGridByContainerId(containerId){
if(containerId.substring(0,1)!='#')
containerId = '#' + containerId;
var containerObj = $(containerId);
var anyGrid = containerObj.find('table.table:first');
if(anyGrid.length>0){
var ori_containerId = anyGrid.attr('containerId');
if(!ori_containerId || ori_containerId==''){
anyGrid.attr('containerId',containerId);
}
}
return anyGrid;
}
function _pad_add_pageInfo_to_loadPageHtml(jqHtml, pageContainerId, url){
var container = find_jquery_object(pageContainerId);
container.attr('content_url',url);
}
function _pad_mergeJsonObject(baseData, newData){
if(!baseData)
return newData;
if(!newData)
return baseData;
var resultJsonObject={};
for(var attr in baseData){
resultJsonObject[attr]=baseData[attr];
}
for(var attr in newData){
resultJsonObject[attr]=newData[attr];
}
return resultJsonObject;
}
function find_jquery_object(obj){
var jObj = null;
//check if obj is just id
if(obj instanceof jQuery){
jObj = obj;
}else{
if(typeof(obj)=='string'){
if(obj.substring(0,1)!='#')
obj = '#' + obj;
jObj = $(obj);
}else{
jObj = $(obj);
}
}
return jObj;
}
function _pad_add_param_to_post_data(data, paramName, paramValue){
if(!data || data.length==0){
data = paramName+'='+paramValue;
}else{
if(typeof(data)=='string'){
if(data!=''){
if(data.substring(0,1)=='&'){
data = data.substring(1);
}
if(data.substring(data.length-1)=='&'){
data = data.substring(0,data.length-1);
}
if(data!=''){
var param_arr = data.split('&');
data = {};
for(var pi=0;pi<param_arr.length;pi++){
var p_key_val = param_arr[pi].split('=');
if(p_key_val.length>1){
data[p_key_val[0]] = p_key_val[1];
}
}
}
}
}
data[paramName] = paramValue;
}
return data;
}
function isJson(obj){
return typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
}
/**
* 弹框显示内容
* @param ma_mark 弹框标识(非id),相同标识只弹出一个窗口
* @param title 窗口标题
* @param url 加载内容url,优先使用url再使用content
* @param content 窗口显示内容,当url有效时,可作为提交参数(数组格式)
* @param position 位置信息数组,可设置width,height,left/right,top/bottom
* @param callback 回调函数,可设置 afterinit,beforeclose(点击右上角关闭时),finishwork(在显示内容内根据自定义情况执行)
* @private
*/
function _add_moveable_popup(ma_mark,title,url,content,position,callback){
//此判断无法处理并发情况,暂时不深入处理
if(ma_mark && $('.moveable_popup_win[identity="'+ma_mark+'"]').length>0){
_close_moveable_popup(ma_mark);//改为关闭之前的
}
var mapop = $('<div class="moveable_popup_win any_focus_pop my_focus_pop"><div class="title_bar"></div><div class="close_btn icon-remove" ma_mark="'+ma_mark+'"></div><div class="content_here"></div><div class="button_here"></div></div>');
var ma_id = 'ma_pop_'+_ma_pop_idx;
mapop.attr('id',ma_id);
mapop.attr('idx',_ma_pop_idx);
if(!ma_mark || ma_mark==''){
ma_mark = ma_id;
}
if(ma_mark){
mapop.attr('identity',ma_mark);
}
$('.my_focus_pop').removeClass('my_focus_pop');
$('#main-content').append(mapop);
var content_obj = mapop.find('.content_here:first');
var ma_content_id = 'ma_pop_content_'+_ma_pop_idx;
content_obj.attr('id',ma_content_id);
_ma_pop_idx ++;
var titlebar = mapop.find('.title_bar:first');
titlebar.html(title);
if(!callback){
callback = {};
_ma_pop_callback[ma_mark] = null;
_ma_pop_callback_beforeclose[ma_mark] = null;
}else{
if(callback.finishwork){
_ma_pop_callback[ma_mark] = callback.finishwork;
}
if(callback.beforeclose) {
_ma_pop_callback_beforeclose[ma_mark] = callback.beforeclose;
}
}
mapop.resizable();
mapop.delegate('.close_btn','click',function(){
_close_moveable_popup($(this).attr('ma_mark'));
});
var mp_data = {};
mp_data.moveable_pop_mark = ma_mark;
if(url){
mp_data = _pad_mergeJsonObject(mp_data,content);
_pad_all_loadPage(url,ma_content_id,true,mp_data,function(){
_ma_check_button(mapop);
mapop.show();
_reposition_moveable_pop(mapop,position);
if(callback.afterinit){
callback.afterinit(ma_id,ma_content_id);
}
});
}else{
content_obj.html(content);
_reposition_moveable_pop(mapop,position);
_ma_check_button(mapop);
mapop.show();
if(callback.afterinit){
callback.afterinit(ma_id,ma_content_id);
}
}
_mp_last_focus_shift_time_millsec = new Date().getTime();
mapop.draggabilly({
handle: '.title_bar'
});
}
function _ma_check_button(mapop){
var button_old = mapop.find('.pop_win_buttons:first');
var button_new = mapop.find('.button_here:first');
var fixed_buttons = button_new.find('.ma_fixed_button');
var fixed_btn_group = $('<span class="ma_fixed_button_group"></span>');
fixed_buttons.each(function(){
fixed_btn_group.append($(this));
});
var close_btn = $('<a class="btn close_btn">关闭</a>');
close_btn.attr('ma_mark', mapop.attr('identity'));
if(button_old.length>0){
button_new.html('');
button_new.append(fixed_btn_group);
button_new.append(button_old.html());
button_new.append(close_btn);
button_old.remove();
}else{
button_new.html(close_btn);//默认添加关闭按键
button_new.prepend(fixed_btn_group);
}
}
function _reload_moveable_pop(ma_mark, more_parems){
if(ma_mark && $('.moveable_popup_win[identity="'+ma_mark+'"]').length>0){
_pad_all_reloadPage($('.moveable_popup_win[identity="'+ma_mark+'"]').find('.content_here:first').attr('id'),more_parems, function(){
_ma_check_button($('.moveable_popup_win[identity="'+ma_mark+'"]'));
});
}
}
function _find_moveable_pop_by_ma_mark(ma_mark){
return $('.moveable_popup_win[identity="'+ma_mark+'"]');
}
function _reposition_moveable_pop(mapop,position){
if(position){
if(position.width>0){
position.width = position.width + 30;
mapop.css('width',position.width);
}
var p_height = position.height;
if(isNaN(p_height)){
p_height = 0;
}
if(position.auto_height){
var content_container = mapop.find('.content_here:first');
var content_height = content_container[0].scrollHeight;
if(!isNaN(content_height)){
if(p_height>content_height){
p_height = content_height + 80;
}
if(p_height<230){
p_height = 230;
}
}
mapop.css('height', p_height);
}else{
mapop.css('height', p_height+50);
}
if(!isNaN(position.left)){
mapop.css('left',position.left);
}else if(!isNaN(position.right)){
var width = mapop.outerWidth();
var win_width = $(document).innerWidth();
var left = win_width - width - position.right;
mapop.css('left',left);
}
if(!isNaN(position.top)){
mapop.css('top',position.top);
}else if(!isNaN(position.bottom)){
var height = mapop.outerHeight();
var win_height = $(window).innerHeight();
var top = win_height - height - position.bottom;
| }
mapop.css('top',top);
}
}
}
function _run_moveable_callback_finishwork(ma_mark, params){
if(ma_mark && $('.moveable_popup_win[identity="'+ma_mark+'"]').length>0){
if(_ma_pop_callback[ma_mark]){
_ma_pop_callback[ma_mark](params);
}
}
}
function _close_moveable_popup(ma_mark){
if(_ma_pop_callback_beforeclose[ma_mark]){
_ma_pop_callback_beforeclose[ma_mark](ma_mark);
}
if(ma_mark && $('.moveable_popup_win[identity="'+ma_mark+'"]').length>0){
$('.moveable_popup_win[identity="'+ma_mark+'"]').remove();
_ma_pop_callback[ma_mark] = null;
_ma_pop_callback_beforeclose[ma_mark] = null;
}else{
$('.moveable_popup_win.my_focus_pop').remove();
}
} | if(top<0){
top = 0;
| conditional_block |
JsPopup.js | //数据列表检索排序字符串保存的键值(值以$.data的方式保存在_current_tab_page_id对应的对象上)
var _pad_adv_filter_id = "_pad_adv_filter_id";
//数据列表检索条件数据
var _pad_search_params_id = "_pad_search_params_id";
//页面初次加载时保存参数
var _pad_page_base_params_id = "_pad_page_base_params_id";
var _pad_grid_page_size = "gridPageSize";
_mp_last_focus_shift_time_millsec = 0; //上次弹层时间
var _ma_pop_idx = 1;
var _ma_pop_callback = new Object();
var _ma_pop_callback_beforeclose = new Object();
//给指定元素加载内容
function _p_a_load(url,pageContainerId,keepParams,data,callBack,isGridInit){
_pad_all_loadPage(url,pageContainerId,keepParams,data,callBack,isGridInit);
}
//keepParams 是否保留container上缓存的参数,首次加载时一般为false
function _pad_all_loadPage(url,pageContainerId,keepParams,data,callBack,isGridInit){
if(typeof(pageContainerId)=='string'){
if(pageContainerId.substring(0,1)=='#')
pageContainerId = pageContainerId.substring(1);
}
var containerObj = find_jquery_object(pageContainerId);
if(!data){
data = {};
}
var initPageSize = containerObj.attr(_pad_grid_page_size);
if(initPageSize && initPageSize>0){
//有初始化containerObj 中grid的pageSize
data = _pad_add_param_to_post_data(data,'gridPageSize',initPageSize);
}
//将容器id传入到action的loadPageId,在页面初始化脚本中可以使用
if(url.indexOf('loadPageId')==-1 && (!data || !data.loadPageId) && (typeof(data)!='string'||data.indexOf('loadPageId')==-1)){
data = _pad_add_param_to_post_data(data,'loadPageId',pageContainerId);
}
if(isGridInit && data){
containerObj.data(_pad_search_params_id, data);
}
if(!keepParams)
_pad_clear_container_old_data(pageContainerId);
var pageBaseParams = containerObj.data(_pad_page_base_params_id);
var param_idx = url.indexOf('?');
if(param_idx!=-1){
var param_idx_2 = url.indexOf('#');
var params_str = '';
if(param_idx_2!=-1){
params_str = url.substring(param_idx+1,param_idx_2);
}else{
params_str = url.substring(param_idx+1);
}
url = url.substring(0,param_idx);
if(params_str.length>0){
if(!data){
data = {};
}else if(Object.prototype.toString.call(data) === "[object String]"){
params_str = params_str + '&' + data;
data = {};
}
var param_arr = params_str.split('&');
for(var pi=0;pi<param_arr.length;pi++){
var p_key_val = param_arr[pi].split('=');
if(p_key_val.length>1){
data[p_key_val[0]] = p_key_val[1];
}
}
}
}
if(!pageBaseParams && data){
pageBaseParams = data;
}else{
pageBaseParams = _pad_mergeJsonObject(pageBaseParams, data);
}
containerObj.data(_pad_page_base_params_id, pageBaseParams);
$.ajax({
url:url,
type: "post",
data: pageBaseParams,
cache:false,
beforeSend:function(XMLHttpRequest){},
success:function(html){
if(html && isJson(html)){
//返回错误异常
if(html.err_text){
alert(html.err_text);
_hide_top_loading();
}
return;
}
_pad_add_pageInfo_to_loadPageHtml(html, pageContainerId, url); | if(tempIdx1!=-1){
tempIdx1 = tempIdx1 + 6;
var tempIdx2 = html.indexOf('>',tempIdx1);
var tempIdx3 = html.indexOf('table',tempIdx1);
if(tempIdx3!=-1 && tempIdx3< tempIdx2){
//尝试准确的定位"table.table:first"的table
html = html.substring(0,tempIdx1) + ' containerId="#'+pageContainerId+'"' + html.substring(tempIdx1);
}
}
containerObj.html(html);
containerObj.trigger('new_content_load');
//添加输入框相关效果,如 必填 等等
_pad_add_input_element(containerObj);
_update_pager_click_event(containerObj);
var anyGrid = _pad_findGridByContainerId(pageContainerId);
if(anyGrid.length>0){
add_event_for_jm_table(anyGrid);
}
//添加clearable输入框清楚按键
_pad_add_clearable_input_btn(pageContainerId);
if(callBack){
callBack(pageContainerId);
}
}
}).always(function(){});
}
function _pad_all_reloadPage(pageContainerId,more_parems,callback){
var container = find_jquery_object(pageContainerId);
if(container){
var url = container.attr('content_url');
_pad_all_loadPage(url, pageContainerId, true, more_parems, callback);
}
}
function _pad_add_clearable_input_btn(containerId){
var container = find_jquery_object(containerId);
container.find('input.clearable').each(function(){
$(this).wrap('<div class="clearable_container"></div>');
var clear_btn = $('<i class="icon-remove clear_btn"></i>');
clear_btn.click(function(){
$(this).prev('input').val('');
});
$(this).after(clear_btn);
});
}
function add_event_for_jm_table(gridTable){
var gridContainerId = gridTable.attr('containerId');
add_event_for_jm_table_sort(gridContainerId);
}
function add_event_for_jm_table_sort(containerId){
if(containerId.substring(0,1)!='#')
containerId = '#' + containerId;
var container = $(containerId);
var page_params = container.data(_pad_page_base_params_id);
if(page_params && page_params.sort_column){
var on_sorting = container.find('[sort_column="'+page_params.sort_column+'"]');
if(on_sorting.length==1){
on_sorting.attr('sort_type', page_params.sort_type);
}
}
container.find('.tab_sorter').each(function(){
var column = $(this);
var sort_column = column.attr('sort_column');
if(sort_column!=''){
var column_table = column.parents('[content_url]:first');
var sort_type = column.attr('sort_type');
column_table.removeClass('icon-sort-up icon-sort-down');
if(sort_type=='asc'){
column.addClass('icon-sort-up');
}else if(sort_type=='desc'){
column.addClass('icon-sort-down');
}else{
column.addClass('icon-sort');
}
column.unbind('click').bind('click',function(){
_show_top_loading();
var thiscolumn = $(this);
var thissort = thiscolumn.attr('sort_column');
var thistype = thiscolumn.attr('sort_type');
if(thiscolumn.is('.icon-sort-down')){
thistype = 'asc';
}else if(thiscolumn.is('.icon-sort-up')){
thistype = '';
}else{
thistype = 'desc';
}
thiscolumn.attr('sort_type',thistype);
var table_id = column_table.attr('id');
var table_url = column_table.attr('content_url');
var params = column_table.data(_pad_page_base_params_id);
if(!params){
params = {};
}
params = _pad_add_param_to_post_data(params,'sort_column',thissort);
params = _pad_add_param_to_post_data(params,'sort_type',thistype);
_p_a_load(table_url, table_id, null, params, function(){
_hide_top_loading();
});
});
}
});
}
function _hide_top_loading() {}
function _show_top_loading() {}
function _update_pager_click_event(container){
var pagerObjs = container.find('.pagination.in_tab');
pagerObjs.each(function(){
$(this).find('a').each(function() {
$(this).click(function (event) {
var url = $(this).attr('href');
_pad_all_loadPage(url,container.attr('id'),true);
return false;//阻止链接跳转
});
});
});
}
var _pad_temp_input_id_idx = 1;
function _pad_add_input_element(container){
var mustObjs = container.find('.must_input');
mustObjs.each(function(){
var inputId = _pad_check_temp_id_to_jobj($(this));
var miGroup = _pad_check_input_group_parent($(this));
var miSign = $('<i class="icon-warning-sign mi_sign" title="必填"> 必填</i>');
miSign.attr('input_id',inputId);
$(this).after(miSign);
miSign.click(function(){
$(this).removeClass('shake');
});
});
var clearAbleObjs = container.find('.clear_able');
clearAbleObjs.each(function(){
var inputId = _pad_check_temp_id_to_jobj($(this));
var miGroup = _pad_check_input_group_parent($(this));
var inner_btn_clear = $('<span class="input_inner_btn icon-remove red"></span>');
inner_btn_clear.attr('input_id',inputId);
$(this).after(inner_btn_clear);
miGroup.hover(
function(){
inner_btn_clear.show();
}
,function(){
inner_btn_clear.hide();
}
);
inner_btn_clear.click(function(e){
e.stopPropagation();
e.preventDefault();
var targetId = $(this).attr('input_id');
var targetObj = $('#'+targetId);
targetObj.prop("value",'');
//targetObj.val('');
targetObj.removeData();
});
});
var _cp_colorPicker = $('#_cp_color_select_div');
if(_cp_colorPicker.length>0){
var colorableObjs = container.find('.color_picker');
colorableObjs.each(function(){
var inputId = _pad_check_temp_id_to_jobj($(this));
$(this).click(function(e){
e.stopPropagation();
e.preventDefault();
});
});
}
}
function _pad_check_temp_id_to_jobj(jobj){
var inputId = jobj.attr('id');
if(!inputId || inputId==''){
inputId = 'input_temp_id_'+_pad_temp_input_id_idx;
_pad_temp_input_id_idx ++;
jobj.attr('id',inputId);
}
return inputId;
}
function _pad_check_input_group_parent(jobj){
var parent = jobj.parent();
var retobj = null;
if(parent.is('.mi_group')){
retobj = parent;
}else{
retobj = $('<div class="mi_group"></div>');
jobj.wrap(retobj);
}
return jobj.parent();
}
function _pad_clear_container_old_data(containerId){
if(containerId.substring(0,1)!='#')
containerId = '#' + containerId;
var container = $(containerId);
container.attr('content_url','');
//不去掉就没法设置pageSize
//container.removeAttr(_pad_grid_page_size);
container.removeAttr('pageNo');
container.removeData(_pad_adv_filter_id);
container.removeData(_pad_search_params_id);
container.removeData(_pad_page_base_params_id);
try{
container.removeData(_grid_row_selected_row_ids);
}catch(e){}
try{
//_all_gridSearchClear(containerId); //页面暂时没有这个逻辑,vix中有
}catch(e){
alert(e);
}
}
function _pad_findGridByContainerId(containerId){
if(containerId.substring(0,1)!='#')
containerId = '#' + containerId;
var containerObj = $(containerId);
var anyGrid = containerObj.find('table.table:first');
if(anyGrid.length>0){
var ori_containerId = anyGrid.attr('containerId');
if(!ori_containerId || ori_containerId==''){
anyGrid.attr('containerId',containerId);
}
}
return anyGrid;
}
function _pad_add_pageInfo_to_loadPageHtml(jqHtml, pageContainerId, url){
var container = find_jquery_object(pageContainerId);
container.attr('content_url',url);
}
function _pad_mergeJsonObject(baseData, newData){
if(!baseData)
return newData;
if(!newData)
return baseData;
var resultJsonObject={};
for(var attr in baseData){
resultJsonObject[attr]=baseData[attr];
}
for(var attr in newData){
resultJsonObject[attr]=newData[attr];
}
return resultJsonObject;
}
function find_jquery_object(obj){
var jObj = null;
//check if obj is just id
if(obj instanceof jQuery){
jObj = obj;
}else{
if(typeof(obj)=='string'){
if(obj.substring(0,1)!='#')
obj = '#' + obj;
jObj = $(obj);
}else{
jObj = $(obj);
}
}
return jObj;
}
function _pad_add_param_to_post_data(data, paramName, paramValue){
if(!data || data.length==0){
data = paramName+'='+paramValue;
}else{
if(typeof(data)=='string'){
if(data!=''){
if(data.substring(0,1)=='&'){
data = data.substring(1);
}
if(data.substring(data.length-1)=='&'){
data = data.substring(0,data.length-1);
}
if(data!=''){
var param_arr = data.split('&');
data = {};
for(var pi=0;pi<param_arr.length;pi++){
var p_key_val = param_arr[pi].split('=');
if(p_key_val.length>1){
data[p_key_val[0]] = p_key_val[1];
}
}
}
}
}
data[paramName] = paramValue;
}
return data;
}
function isJson(obj){
return typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
}
/**
* 弹框显示内容
* @param ma_mark 弹框标识(非id),相同标识只弹出一个窗口
* @param title 窗口标题
* @param url 加载内容url,优先使用url再使用content
* @param content 窗口显示内容,当url有效时,可作为提交参数(数组格式)
* @param position 位置信息数组,可设置width,height,left/right,top/bottom
* @param callback 回调函数,可设置 afterinit,beforeclose(点击右上角关闭时),finishwork(在显示内容内根据自定义情况执行)
* @private
*/
function _add_moveable_popup(ma_mark,title,url,content,position,callback){
//此判断无法处理并发情况,暂时不深入处理
if(ma_mark && $('.moveable_popup_win[identity="'+ma_mark+'"]').length>0){
_close_moveable_popup(ma_mark);//改为关闭之前的
}
var mapop = $('<div class="moveable_popup_win any_focus_pop my_focus_pop"><div class="title_bar"></div><div class="close_btn icon-remove" ma_mark="'+ma_mark+'"></div><div class="content_here"></div><div class="button_here"></div></div>');
var ma_id = 'ma_pop_'+_ma_pop_idx;
mapop.attr('id',ma_id);
mapop.attr('idx',_ma_pop_idx);
if(!ma_mark || ma_mark==''){
ma_mark = ma_id;
}
if(ma_mark){
mapop.attr('identity',ma_mark);
}
$('.my_focus_pop').removeClass('my_focus_pop');
$('#main-content').append(mapop);
var content_obj = mapop.find('.content_here:first');
var ma_content_id = 'ma_pop_content_'+_ma_pop_idx;
content_obj.attr('id',ma_content_id);
_ma_pop_idx ++;
var titlebar = mapop.find('.title_bar:first');
titlebar.html(title);
if(!callback){
callback = {};
_ma_pop_callback[ma_mark] = null;
_ma_pop_callback_beforeclose[ma_mark] = null;
}else{
if(callback.finishwork){
_ma_pop_callback[ma_mark] = callback.finishwork;
}
if(callback.beforeclose) {
_ma_pop_callback_beforeclose[ma_mark] = callback.beforeclose;
}
}
mapop.resizable();
mapop.delegate('.close_btn','click',function(){
_close_moveable_popup($(this).attr('ma_mark'));
});
var mp_data = {};
mp_data.moveable_pop_mark = ma_mark;
if(url){
mp_data = _pad_mergeJsonObject(mp_data,content);
_pad_all_loadPage(url,ma_content_id,true,mp_data,function(){
_ma_check_button(mapop);
mapop.show();
_reposition_moveable_pop(mapop,position);
if(callback.afterinit){
callback.afterinit(ma_id,ma_content_id);
}
});
}else{
content_obj.html(content);
_reposition_moveable_pop(mapop,position);
_ma_check_button(mapop);
mapop.show();
if(callback.afterinit){
callback.afterinit(ma_id,ma_content_id);
}
}
_mp_last_focus_shift_time_millsec = new Date().getTime();
mapop.draggabilly({
handle: '.title_bar'
});
}
function _ma_check_button(mapop){
var button_old = mapop.find('.pop_win_buttons:first');
var button_new = mapop.find('.button_here:first');
var fixed_buttons = button_new.find('.ma_fixed_button');
var fixed_btn_group = $('<span class="ma_fixed_button_group"></span>');
fixed_buttons.each(function(){
fixed_btn_group.append($(this));
});
var close_btn = $('<a class="btn close_btn">关闭</a>');
close_btn.attr('ma_mark', mapop.attr('identity'));
if(button_old.length>0){
button_new.html('');
button_new.append(fixed_btn_group);
button_new.append(button_old.html());
button_new.append(close_btn);
button_old.remove();
}else{
button_new.html(close_btn);//默认添加关闭按键
button_new.prepend(fixed_btn_group);
}
}
function _reload_moveable_pop(ma_mark, more_parems){
if(ma_mark && $('.moveable_popup_win[identity="'+ma_mark+'"]').length>0){
_pad_all_reloadPage($('.moveable_popup_win[identity="'+ma_mark+'"]').find('.content_here:first').attr('id'),more_parems, function(){
_ma_check_button($('.moveable_popup_win[identity="'+ma_mark+'"]'));
});
}
}
function _find_moveable_pop_by_ma_mark(ma_mark){
return $('.moveable_popup_win[identity="'+ma_mark+'"]');
}
function _reposition_moveable_pop(mapop,position){
if(position){
if(position.width>0){
position.width = position.width + 30;
mapop.css('width',position.width);
}
var p_height = position.height;
if(isNaN(p_height)){
p_height = 0;
}
if(position.auto_height){
var content_container = mapop.find('.content_here:first');
var content_height = content_container[0].scrollHeight;
if(!isNaN(content_height)){
if(p_height>content_height){
p_height = content_height + 80;
}
if(p_height<230){
p_height = 230;
}
}
mapop.css('height', p_height);
}else{
mapop.css('height', p_height+50);
}
if(!isNaN(position.left)){
mapop.css('left',position.left);
}else if(!isNaN(position.right)){
var width = mapop.outerWidth();
var win_width = $(document).innerWidth();
var left = win_width - width - position.right;
mapop.css('left',left);
}
if(!isNaN(position.top)){
mapop.css('top',position.top);
}else if(!isNaN(position.bottom)){
var height = mapop.outerHeight();
var win_height = $(window).innerHeight();
var top = win_height - height - position.bottom;
if(top<0){
top = 0;
}
mapop.css('top',top);
}
}
}
function _run_moveable_callback_finishwork(ma_mark, params){
if(ma_mark && $('.moveable_popup_win[identity="'+ma_mark+'"]').length>0){
if(_ma_pop_callback[ma_mark]){
_ma_pop_callback[ma_mark](params);
}
}
}
function _close_moveable_popup(ma_mark){
if(_ma_pop_callback_beforeclose[ma_mark]){
_ma_pop_callback_beforeclose[ma_mark](ma_mark);
}
if(ma_mark && $('.moveable_popup_win[identity="'+ma_mark+'"]').length>0){
$('.moveable_popup_win[identity="'+ma_mark+'"]').remove();
_ma_pop_callback[ma_mark] = null;
_ma_pop_callback_beforeclose[ma_mark] = null;
}else{
$('.moveable_popup_win.my_focus_pop').remove();
}
} | //处理如果html中有grid,为grid加上containerId
var tempIdx1 = html.indexOf('<table'); | random_line_split |
plot_utils.py | import plotly.graph_objects as go
import numpy as np
import pandas as pd
import plotly.express as px
import cv2
from matplotlib import pyplot as plt
from matplotlib import cm
from matplotlib.collections import PolyCollection
from mpl_toolkits.mplot3d import Axes3D
import math
def | (disp, scanline_index, color, title):
coords = get_disparity_plot_coords(disp, scanline_index = scanline_index)
plt.plot(coords)
def get_disparity_plot_coords(disp, scanline_index=0):
current = next = disp[0,0]
current_plot_coords = [0,0]
for j in range ((disp.shape[1])):
next = disp[scanline_index, j]
coordinate_diff = get_disparity_scanline_move(current, next)
current_plot_coords.append(
(current_plot_coords[-1][0] + coordinate_diff[0],
current_plot_coords[-1][1] + coordinate_diff[1])
)
current = next
return current_plot_coords
def get_disparity_scanline_move(current, next):
if next==0:
return (1,0)
if(current==next):
return (1,1)
#if it is brighter?
if(next>current):
return (np.abs(next-current)+1, 1)
#if it is darker?
return (1,np.abs(next - current)+1)
def scatter_3d_results(x_label, y_label, metrix, FILE_PATH_OR_DATAFRAME, cmm="viridis"):
if(FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'):
data = pd.read_csv(FILE_PATH_OR_DATAFRAME)
data.columns = np.array([str.strip(col) for col in data.columns])
else:
data = FILE_PATH_OR_DATAFRAME
x,y,z = data[x_label], data[y_label], data[metrix]
fig = plt.figure()
ax = fig.gca(projection="3d")
ax.set_xlabel(x_label)
ax.set_ylabel(y_label)
ax.set_zlabel(metrix)
ax.scatter(x,y, z, c=z, cmap = "viridis")
plt.show()
def polyine_3d(x_label, y_label, metrix, data, occl_counted=False):
scenes = data["scene"].unique()
X = np.array(data[x_label].unique())
Y= np.array(data[y_label].unique())
data = data[data["are_occlusions_errors"] == occl_counted]
data = data.sort_values(by=[x_label, y_label])
z = pd.pivot_table(data, values=[metrix], columns=[x_label], index=[y_label]).values
Z = np.nan_to_num(z, nan=2000)
verts = []
mins = []
for i in range(X.shape[0]):
current_column = Z[:, i]
min_loc, min_val = X[np.argmin(current_column)], current_column.min()
temp = list(zip(Y, current_column))
verts.append(temp)
mins.append((min_loc, min_val, X[i]))
stop_here = 1
poly = PolyCollection(verts, facecolors=[get_random_color() for x in X])
poly.set_alpha(1)
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
surf_x, surf_y = np.meshgrid(Y, X)
surf_z = np.empty((len(X), len(Y)))
surf_z[:, :] = data[metrix].min()
ax.plot_surface(surf_x, surf_y, surf_z, color=(0.3,0.3,0.9, 0.6))
ax.add_collection3d(poly, zs = X, zdir='y')
#annotating minimums for enhanced readibility
for x,z,y in mins:
label = 'min: %.2f (%d, %d)' % (z, x, y)
ax.text(x, y, z, label)
ax.set_xlabel(y_label)
ax.set_xlim3d(0, Y[-1])
ax.set_ylabel(x_label)
ax.set_ylim3d(0, X[-1])
ax.set_zlabel(metrix)
ax.set_zlim3d(0, 2000)
plt.grid()
plt.show()
return fig, ax
def bar_3d_by_scenes(x_label, y_label, metrix, FILE_PATH_OR_DATAFRAME, occl_counted=False):
if (FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'):
data = pd.read_csv(FILE_PATH_OR_DATAFRAME)
data.columns = np.array([str.strip(col) for col in data.columns])
else:
data = FILE_PATH_OR_DATAFRAME
scenes = data["scene"].unique()
data = data[data["are_occlusions_errors"]==occl_counted]
data = data.sort_values(by=[x_label, y_label])
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
colors = [get_random_color() for scene in scenes]
for x_param in data[x_label].unique():
temp_outer = data[data[x_label]==x_param]
for i, scene in enumerate(scenes):
temp_inner = temp_outer[(temp_outer["scene"]==scene)]
ax.bar(temp_inner[x_label], temp_inner[metrix], zs=temp_inner[y_label], zdir="y", color=colors[i], alpha=0.8)
ax.set_xlabel(x_label)
ax.set_ylabel(y_label)
ax.set_zlabel(metrix)
plt.show()
def get_random_color(alpha=0.8):
r = np.random.rand()
g = np.random.rand()
b = np.random.rand()
return (r,g,b, alpha)
def plot_3d_results(x_label,y_label,metrix, FILE_PATH_OR_DATAFRAME, steps=None):
if(FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'):
data = pd.read_csv(FILE_PATH_OR_DATAFRAME)
data.columns = np.array([str.strip(col) for col in data.columns])
else:
data = FILE_PATH_OR_DATAFRAME
x = np.array(data[x_label].unique())[:, np.newaxis]
y = np.array(data[y_label].unique())[:, np.newaxis]
z = pd.pivot_table(data, values=[metrix], columns=[x_label], index=[y_label]).values
z = np.nan_to_num(z, nan=1000000)
print("Z's shape is: {0}".format(z.shape))
x_diff_step = (x.max() - x.min()) / z.shape[1] if steps is None else steps[1]
y_diff_step = (y.max()-y.min())/z.shape[0] if steps is None else steps[0]
X = np.arange(x.min(), x.max()+1, x_diff_step)[:, np.newaxis]
Y = np.arange(y.min(), y.max() +1, y_diff_step)[:, np.newaxis]
X, Y = np.meshgrid(X, Y)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_zlim(data[metrix].min()-100, data[metrix].max()+100)
ax.plot_surface(X, Y, z, cmap=cm.tab20b)
ax.set_xlabel(x_label)
ax.set_ylabel(y_label)
ax.set_zlabel(metrix)
plt.show()
row_with_min = data[metrix].idxmin()
min_row = data.loc[row_with_min]
return min_row
#it is 4d in reality
def plotly_4d_results(x_label,y_label, z_label, metrix, FILE_PATH_OR_DATAFRAME, ):
if(FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'):
data = pd.read_csv(FILE_PATH_OR_DATAFRAME)
data.columns = np.array([str.strip(col) for col in data.columns])
else:
data = FILE_PATH_OR_DATAFRAME
data = data[[x_label, y_label, z_label, metrix]]
data = data.sort_values(by=[x_label, y_label, z_label], ascending = True)
values = np.nan_to_num(data[[metrix]].values)
x = np.array(data[x_label].unique())[:, np.newaxis]
y = np.array(data[y_label].unique())[:, np.newaxis]
z = np.array(data[z_label].unique())[:, np.newaxis]
x_step = (x.max() - x.min()) / (x.shape[0]-1)
y_step = (y.max() - y.min()) / (y.shape[0]-1)
z_step =(z.max() - z.min()) / (z.shape[0]-1)
# good cmap = px.colors.diverging.Spectral
# px.colors.sequential.Rainbow
# px.colors.sequential.Angset
X, Y, Z = np.mgrid[x.min():x.max()+x_step:x_step, y.min():y.max()+y_step:y_step, z.min():z.max()+z_step:z_step]
fig = go.Figure(data=go.Volume(
x=X.flatten(),
y=Y.flatten(),
z=Z.flatten(),
value=values.flatten(),
cmin=values.min(),
cmax=values.max(),
opacity=0.3, # needs to be small to see through all surfaces
surface_count=20,
colorscale=px.colors.diverging.Spectral
))
fig.show()
def plot_disparity_3d(disparity, cmm = cm.viridis):
x = np.arange(0, disparity.shape[0])[:, np.newaxis]
y = np.arange(0, disparity.shape[1])[:, np.newaxis]
fig = plt.figure()
ax = fig.gca(projection="3d")
ax.plot_surface(x,y.T, disparity, cmap = cmm)
def plot_images(imgs, titles, cmode = "gray", ncols= 4, hspace=0.5, wspace=0.5):
assert len(imgs) == len(titles)
n = len(imgs)
row_number = math.ceil(n / ncols)
fig = plt.subplots(figsize=[20, int(4*row_number)])
plt.subplots_adjust(hspace=hspace, wspace=wspace)
for i, img in enumerate(imgs):
ax = plt.subplot(row_number, ncols, i + 1)
ax.set_title("%s\n (%dx%d)" % (titles[i], img.shape[1], img.shape[0]))
plt.imshow(img, cmode)
return fig
if __name__ == "__main__":
import sys
import os
from components.utils import middlebury_utils as mbu
import project_helpers
sys.path.append(os.path.join("..", ".."))
ROOT_PATH = project_helpers.get_project_dir()
EXPERIMENT_TITLE = "EXP_000-Baseline"
DATASET_FOLDER = os.path.join(ROOT_PATH, "datasets", "middlebury")
LOG_FOLDER = os.path.join(ROOT_PATH, "experiments", "logs")
CSV_FOLDER = os.path.join(LOG_FOLDER, EXPERIMENT_TITLE + ".csv")
SCENES = ["teddy", "cones"]
YEAR = 2003
loaded_imgs_and_paths = list(mbu.get_images(DATASET_FOLDER, YEAR, scene) for scene in SCENES)
"""for im, path in loaded_imgs_and_paths:
plot_images(im, path)
import os
ROOT = os.path.join("..", "..")
SELECTED_DATASET = "middlebury_2003"
SELECTED_SCENE = "teddy"
SELECTED_IMAGE = "2-6"
IMG_LOAD_PATH = os.path.join(ROOT, "datasets", "middlebury", SELECTED_DATASET, SELECTED_SCENE)
left = cv2.imread(os.path.join(IMG_LOAD_PATH, "im2.png"), cv2.IMREAD_GRAYSCALE)
right = cv2.imread(os.path.join(IMG_LOAD_PATH, "im6.png"), cv2.IMREAD_GRAYSCALE)
gt = cv2.imread(os.path.join(IMG_LOAD_PATH, "disp2.png"), cv2.IMREAD_GRAYSCALE)
occl = cv2.imread(os.path.join(IMG_LOAD_PATH, "teddy_occl.png"), cv2.IMREAD_GRAYSCALE)
coloured_left = cv2.imread(os.path.join(IMG_LOAD_PATH, "im2.png"))
plod3d_with_img_surface(gt, surface = coloured_left, finess=5, rotation=True)"""
"""
========================================
Create 2D bar graphs in different planes
========================================
Demonstrates making a 3D plot which has 2D bar graphs projected onto
planes y=0, y=1, etc.
"""
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
xs = np.arange(20)
ys = np.random.rand(20)
# You can provide either a single color or an array. To demonstrate this,
# the first bar of each set will be colored cyan.
cs = [c] * len(xs)
cs[0] = 'c'
ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
p = "../../experiments/logs/ALG_005_EXP_001-PatchMatch-MacLean_et_al-Numba.csv"
data = pd.read_csv(p)
new_cols = np.array(data["kernel_size"].str.split("x").to_list()).astype(np.int8)
data["k_h"], data["k_w"] = new_cols[:, 0], new_cols[:, 1]
#selected_scene = data[(data["scene"]=="cones") & (data["are_occlusions_errors"]==False)]
selected_scene = data
# todo: print a scene by occlusion subplot figure
#bar_3d_by_scenes("k_h", "k_w", "mse", selected_scene)
polyine_3d("k_h", "k_w", "mse", selected_scene)
min = data[data["mse"] == data["mse"].min()]
print(min[["kernel_size", "mse"]])
| plot_disp_line | identifier_name |
plot_utils.py | import plotly.graph_objects as go
import numpy as np
import pandas as pd
import plotly.express as px
import cv2
from matplotlib import pyplot as plt
from matplotlib import cm
from matplotlib.collections import PolyCollection
from mpl_toolkits.mplot3d import Axes3D
import math
def plot_disp_line(disp, scanline_index, color, title):
coords = get_disparity_plot_coords(disp, scanline_index = scanline_index)
plt.plot(coords)
def get_disparity_plot_coords(disp, scanline_index=0):
current = next = disp[0,0]
current_plot_coords = [0,0]
for j in range ((disp.shape[1])):
next = disp[scanline_index, j]
coordinate_diff = get_disparity_scanline_move(current, next)
current_plot_coords.append(
(current_plot_coords[-1][0] + coordinate_diff[0],
current_plot_coords[-1][1] + coordinate_diff[1])
)
current = next
return current_plot_coords
def get_disparity_scanline_move(current, next):
if next==0:
return (1,0)
if(current==next):
|
#if it is brighter?
if(next>current):
return (np.abs(next-current)+1, 1)
#if it is darker?
return (1,np.abs(next - current)+1)
def scatter_3d_results(x_label, y_label, metrix, FILE_PATH_OR_DATAFRAME, cmm="viridis"):
if(FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'):
data = pd.read_csv(FILE_PATH_OR_DATAFRAME)
data.columns = np.array([str.strip(col) for col in data.columns])
else:
data = FILE_PATH_OR_DATAFRAME
x,y,z = data[x_label], data[y_label], data[metrix]
fig = plt.figure()
ax = fig.gca(projection="3d")
ax.set_xlabel(x_label)
ax.set_ylabel(y_label)
ax.set_zlabel(metrix)
ax.scatter(x,y, z, c=z, cmap = "viridis")
plt.show()
def polyine_3d(x_label, y_label, metrix, data, occl_counted=False):
scenes = data["scene"].unique()
X = np.array(data[x_label].unique())
Y= np.array(data[y_label].unique())
data = data[data["are_occlusions_errors"] == occl_counted]
data = data.sort_values(by=[x_label, y_label])
z = pd.pivot_table(data, values=[metrix], columns=[x_label], index=[y_label]).values
Z = np.nan_to_num(z, nan=2000)
verts = []
mins = []
for i in range(X.shape[0]):
current_column = Z[:, i]
min_loc, min_val = X[np.argmin(current_column)], current_column.min()
temp = list(zip(Y, current_column))
verts.append(temp)
mins.append((min_loc, min_val, X[i]))
stop_here = 1
poly = PolyCollection(verts, facecolors=[get_random_color() for x in X])
poly.set_alpha(1)
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
surf_x, surf_y = np.meshgrid(Y, X)
surf_z = np.empty((len(X), len(Y)))
surf_z[:, :] = data[metrix].min()
ax.plot_surface(surf_x, surf_y, surf_z, color=(0.3,0.3,0.9, 0.6))
ax.add_collection3d(poly, zs = X, zdir='y')
#annotating minimums for enhanced readibility
for x,z,y in mins:
label = 'min: %.2f (%d, %d)' % (z, x, y)
ax.text(x, y, z, label)
ax.set_xlabel(y_label)
ax.set_xlim3d(0, Y[-1])
ax.set_ylabel(x_label)
ax.set_ylim3d(0, X[-1])
ax.set_zlabel(metrix)
ax.set_zlim3d(0, 2000)
plt.grid()
plt.show()
return fig, ax
def bar_3d_by_scenes(x_label, y_label, metrix, FILE_PATH_OR_DATAFRAME, occl_counted=False):
if (FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'):
data = pd.read_csv(FILE_PATH_OR_DATAFRAME)
data.columns = np.array([str.strip(col) for col in data.columns])
else:
data = FILE_PATH_OR_DATAFRAME
scenes = data["scene"].unique()
data = data[data["are_occlusions_errors"]==occl_counted]
data = data.sort_values(by=[x_label, y_label])
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
colors = [get_random_color() for scene in scenes]
for x_param in data[x_label].unique():
temp_outer = data[data[x_label]==x_param]
for i, scene in enumerate(scenes):
temp_inner = temp_outer[(temp_outer["scene"]==scene)]
ax.bar(temp_inner[x_label], temp_inner[metrix], zs=temp_inner[y_label], zdir="y", color=colors[i], alpha=0.8)
ax.set_xlabel(x_label)
ax.set_ylabel(y_label)
ax.set_zlabel(metrix)
plt.show()
def get_random_color(alpha=0.8):
r = np.random.rand()
g = np.random.rand()
b = np.random.rand()
return (r,g,b, alpha)
def plot_3d_results(x_label,y_label,metrix, FILE_PATH_OR_DATAFRAME, steps=None):
if(FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'):
data = pd.read_csv(FILE_PATH_OR_DATAFRAME)
data.columns = np.array([str.strip(col) for col in data.columns])
else:
data = FILE_PATH_OR_DATAFRAME
x = np.array(data[x_label].unique())[:, np.newaxis]
y = np.array(data[y_label].unique())[:, np.newaxis]
z = pd.pivot_table(data, values=[metrix], columns=[x_label], index=[y_label]).values
z = np.nan_to_num(z, nan=1000000)
print("Z's shape is: {0}".format(z.shape))
x_diff_step = (x.max() - x.min()) / z.shape[1] if steps is None else steps[1]
y_diff_step = (y.max()-y.min())/z.shape[0] if steps is None else steps[0]
X = np.arange(x.min(), x.max()+1, x_diff_step)[:, np.newaxis]
Y = np.arange(y.min(), y.max() +1, y_diff_step)[:, np.newaxis]
X, Y = np.meshgrid(X, Y)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_zlim(data[metrix].min()-100, data[metrix].max()+100)
ax.plot_surface(X, Y, z, cmap=cm.tab20b)
ax.set_xlabel(x_label)
ax.set_ylabel(y_label)
ax.set_zlabel(metrix)
plt.show()
row_with_min = data[metrix].idxmin()
min_row = data.loc[row_with_min]
return min_row
#it is 4d in reality
def plotly_4d_results(x_label,y_label, z_label, metrix, FILE_PATH_OR_DATAFRAME, ):
if(FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'):
data = pd.read_csv(FILE_PATH_OR_DATAFRAME)
data.columns = np.array([str.strip(col) for col in data.columns])
else:
data = FILE_PATH_OR_DATAFRAME
data = data[[x_label, y_label, z_label, metrix]]
data = data.sort_values(by=[x_label, y_label, z_label], ascending = True)
values = np.nan_to_num(data[[metrix]].values)
x = np.array(data[x_label].unique())[:, np.newaxis]
y = np.array(data[y_label].unique())[:, np.newaxis]
z = np.array(data[z_label].unique())[:, np.newaxis]
x_step = (x.max() - x.min()) / (x.shape[0]-1)
y_step = (y.max() - y.min()) / (y.shape[0]-1)
z_step =(z.max() - z.min()) / (z.shape[0]-1)
# good cmap = px.colors.diverging.Spectral
# px.colors.sequential.Rainbow
# px.colors.sequential.Angset
X, Y, Z = np.mgrid[x.min():x.max()+x_step:x_step, y.min():y.max()+y_step:y_step, z.min():z.max()+z_step:z_step]
fig = go.Figure(data=go.Volume(
x=X.flatten(),
y=Y.flatten(),
z=Z.flatten(),
value=values.flatten(),
cmin=values.min(),
cmax=values.max(),
opacity=0.3, # needs to be small to see through all surfaces
surface_count=20,
colorscale=px.colors.diverging.Spectral
))
fig.show()
def plot_disparity_3d(disparity, cmm = cm.viridis):
x = np.arange(0, disparity.shape[0])[:, np.newaxis]
y = np.arange(0, disparity.shape[1])[:, np.newaxis]
fig = plt.figure()
ax = fig.gca(projection="3d")
ax.plot_surface(x,y.T, disparity, cmap = cmm)
def plot_images(imgs, titles, cmode = "gray", ncols= 4, hspace=0.5, wspace=0.5):
assert len(imgs) == len(titles)
n = len(imgs)
row_number = math.ceil(n / ncols)
fig = plt.subplots(figsize=[20, int(4*row_number)])
plt.subplots_adjust(hspace=hspace, wspace=wspace)
for i, img in enumerate(imgs):
ax = plt.subplot(row_number, ncols, i + 1)
ax.set_title("%s\n (%dx%d)" % (titles[i], img.shape[1], img.shape[0]))
plt.imshow(img, cmode)
return fig
if __name__ == "__main__":
import sys
import os
from components.utils import middlebury_utils as mbu
import project_helpers
sys.path.append(os.path.join("..", ".."))
ROOT_PATH = project_helpers.get_project_dir()
EXPERIMENT_TITLE = "EXP_000-Baseline"
DATASET_FOLDER = os.path.join(ROOT_PATH, "datasets", "middlebury")
LOG_FOLDER = os.path.join(ROOT_PATH, "experiments", "logs")
CSV_FOLDER = os.path.join(LOG_FOLDER, EXPERIMENT_TITLE + ".csv")
SCENES = ["teddy", "cones"]
YEAR = 2003
loaded_imgs_and_paths = list(mbu.get_images(DATASET_FOLDER, YEAR, scene) for scene in SCENES)
"""for im, path in loaded_imgs_and_paths:
plot_images(im, path)
import os
ROOT = os.path.join("..", "..")
SELECTED_DATASET = "middlebury_2003"
SELECTED_SCENE = "teddy"
SELECTED_IMAGE = "2-6"
IMG_LOAD_PATH = os.path.join(ROOT, "datasets", "middlebury", SELECTED_DATASET, SELECTED_SCENE)
left = cv2.imread(os.path.join(IMG_LOAD_PATH, "im2.png"), cv2.IMREAD_GRAYSCALE)
right = cv2.imread(os.path.join(IMG_LOAD_PATH, "im6.png"), cv2.IMREAD_GRAYSCALE)
gt = cv2.imread(os.path.join(IMG_LOAD_PATH, "disp2.png"), cv2.IMREAD_GRAYSCALE)
occl = cv2.imread(os.path.join(IMG_LOAD_PATH, "teddy_occl.png"), cv2.IMREAD_GRAYSCALE)
coloured_left = cv2.imread(os.path.join(IMG_LOAD_PATH, "im2.png"))
plod3d_with_img_surface(gt, surface = coloured_left, finess=5, rotation=True)"""
"""
========================================
Create 2D bar graphs in different planes
========================================
Demonstrates making a 3D plot which has 2D bar graphs projected onto
planes y=0, y=1, etc.
"""
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
xs = np.arange(20)
ys = np.random.rand(20)
# You can provide either a single color or an array. To demonstrate this,
# the first bar of each set will be colored cyan.
cs = [c] * len(xs)
cs[0] = 'c'
ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
p = "../../experiments/logs/ALG_005_EXP_001-PatchMatch-MacLean_et_al-Numba.csv"
data = pd.read_csv(p)
new_cols = np.array(data["kernel_size"].str.split("x").to_list()).astype(np.int8)
data["k_h"], data["k_w"] = new_cols[:, 0], new_cols[:, 1]
#selected_scene = data[(data["scene"]=="cones") & (data["are_occlusions_errors"]==False)]
selected_scene = data
# todo: print a scene by occlusion subplot figure
#bar_3d_by_scenes("k_h", "k_w", "mse", selected_scene)
polyine_3d("k_h", "k_w", "mse", selected_scene)
min = data[data["mse"] == data["mse"].min()]
print(min[["kernel_size", "mse"]])
| return (1,1) | conditional_block |
plot_utils.py | import plotly.graph_objects as go
import numpy as np
import pandas as pd
import plotly.express as px
import cv2
from matplotlib import pyplot as plt
from matplotlib import cm
from matplotlib.collections import PolyCollection
from mpl_toolkits.mplot3d import Axes3D
import math
def plot_disp_line(disp, scanline_index, color, title):
coords = get_disparity_plot_coords(disp, scanline_index = scanline_index)
plt.plot(coords)
def get_disparity_plot_coords(disp, scanline_index=0):
current = next = disp[0,0]
current_plot_coords = [0,0]
for j in range ((disp.shape[1])):
next = disp[scanline_index, j]
coordinate_diff = get_disparity_scanline_move(current, next)
current_plot_coords.append(
(current_plot_coords[-1][0] + coordinate_diff[0],
current_plot_coords[-1][1] + coordinate_diff[1])
)
current = next
return current_plot_coords
def get_disparity_scanline_move(current, next):
if next==0:
return (1,0)
if(current==next):
return (1,1)
#if it is brighter?
if(next>current):
return (np.abs(next-current)+1, 1)
#if it is darker?
return (1,np.abs(next - current)+1)
def scatter_3d_results(x_label, y_label, metrix, FILE_PATH_OR_DATAFRAME, cmm="viridis"):
if(FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'):
data = pd.read_csv(FILE_PATH_OR_DATAFRAME)
data.columns = np.array([str.strip(col) for col in data.columns])
else:
data = FILE_PATH_OR_DATAFRAME
x,y,z = data[x_label], data[y_label], data[metrix]
fig = plt.figure()
ax = fig.gca(projection="3d")
ax.set_xlabel(x_label)
ax.set_ylabel(y_label)
ax.set_zlabel(metrix)
ax.scatter(x,y, z, c=z, cmap = "viridis")
plt.show()
def polyine_3d(x_label, y_label, metrix, data, occl_counted=False):
scenes = data["scene"].unique()
X = np.array(data[x_label].unique())
Y= np.array(data[y_label].unique())
data = data[data["are_occlusions_errors"] == occl_counted]
data = data.sort_values(by=[x_label, y_label])
z = pd.pivot_table(data, values=[metrix], columns=[x_label], index=[y_label]).values
Z = np.nan_to_num(z, nan=2000)
verts = []
mins = []
for i in range(X.shape[0]):
current_column = Z[:, i]
min_loc, min_val = X[np.argmin(current_column)], current_column.min()
temp = list(zip(Y, current_column))
verts.append(temp)
mins.append((min_loc, min_val, X[i]))
stop_here = 1
poly = PolyCollection(verts, facecolors=[get_random_color() for x in X])
poly.set_alpha(1)
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
surf_x, surf_y = np.meshgrid(Y, X)
surf_z = np.empty((len(X), len(Y)))
surf_z[:, :] = data[metrix].min()
ax.plot_surface(surf_x, surf_y, surf_z, color=(0.3,0.3,0.9, 0.6))
ax.add_collection3d(poly, zs = X, zdir='y')
#annotating minimums for enhanced readibility
for x,z,y in mins:
label = 'min: %.2f (%d, %d)' % (z, x, y)
ax.text(x, y, z, label)
ax.set_xlabel(y_label)
ax.set_xlim3d(0, Y[-1])
ax.set_ylabel(x_label)
ax.set_ylim3d(0, X[-1])
ax.set_zlabel(metrix)
ax.set_zlim3d(0, 2000)
plt.grid()
plt.show()
return fig, ax
| def bar_3d_by_scenes(x_label, y_label, metrix, FILE_PATH_OR_DATAFRAME, occl_counted=False):
if (FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'):
data = pd.read_csv(FILE_PATH_OR_DATAFRAME)
data.columns = np.array([str.strip(col) for col in data.columns])
else:
data = FILE_PATH_OR_DATAFRAME
scenes = data["scene"].unique()
data = data[data["are_occlusions_errors"]==occl_counted]
data = data.sort_values(by=[x_label, y_label])
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
colors = [get_random_color() for scene in scenes]
for x_param in data[x_label].unique():
temp_outer = data[data[x_label]==x_param]
for i, scene in enumerate(scenes):
temp_inner = temp_outer[(temp_outer["scene"]==scene)]
ax.bar(temp_inner[x_label], temp_inner[metrix], zs=temp_inner[y_label], zdir="y", color=colors[i], alpha=0.8)
ax.set_xlabel(x_label)
ax.set_ylabel(y_label)
ax.set_zlabel(metrix)
plt.show()
def get_random_color(alpha=0.8):
r = np.random.rand()
g = np.random.rand()
b = np.random.rand()
return (r,g,b, alpha)
def plot_3d_results(x_label,y_label,metrix, FILE_PATH_OR_DATAFRAME, steps=None):
if(FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'):
data = pd.read_csv(FILE_PATH_OR_DATAFRAME)
data.columns = np.array([str.strip(col) for col in data.columns])
else:
data = FILE_PATH_OR_DATAFRAME
x = np.array(data[x_label].unique())[:, np.newaxis]
y = np.array(data[y_label].unique())[:, np.newaxis]
z = pd.pivot_table(data, values=[metrix], columns=[x_label], index=[y_label]).values
z = np.nan_to_num(z, nan=1000000)
print("Z's shape is: {0}".format(z.shape))
x_diff_step = (x.max() - x.min()) / z.shape[1] if steps is None else steps[1]
y_diff_step = (y.max()-y.min())/z.shape[0] if steps is None else steps[0]
X = np.arange(x.min(), x.max()+1, x_diff_step)[:, np.newaxis]
Y = np.arange(y.min(), y.max() +1, y_diff_step)[:, np.newaxis]
X, Y = np.meshgrid(X, Y)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_zlim(data[metrix].min()-100, data[metrix].max()+100)
ax.plot_surface(X, Y, z, cmap=cm.tab20b)
ax.set_xlabel(x_label)
ax.set_ylabel(y_label)
ax.set_zlabel(metrix)
plt.show()
row_with_min = data[metrix].idxmin()
min_row = data.loc[row_with_min]
return min_row
#it is 4d in reality
def plotly_4d_results(x_label,y_label, z_label, metrix, FILE_PATH_OR_DATAFRAME, ):
if(FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'):
data = pd.read_csv(FILE_PATH_OR_DATAFRAME)
data.columns = np.array([str.strip(col) for col in data.columns])
else:
data = FILE_PATH_OR_DATAFRAME
data = data[[x_label, y_label, z_label, metrix]]
data = data.sort_values(by=[x_label, y_label, z_label], ascending = True)
values = np.nan_to_num(data[[metrix]].values)
x = np.array(data[x_label].unique())[:, np.newaxis]
y = np.array(data[y_label].unique())[:, np.newaxis]
z = np.array(data[z_label].unique())[:, np.newaxis]
x_step = (x.max() - x.min()) / (x.shape[0]-1)
y_step = (y.max() - y.min()) / (y.shape[0]-1)
z_step =(z.max() - z.min()) / (z.shape[0]-1)
# good cmap = px.colors.diverging.Spectral
# px.colors.sequential.Rainbow
# px.colors.sequential.Angset
X, Y, Z = np.mgrid[x.min():x.max()+x_step:x_step, y.min():y.max()+y_step:y_step, z.min():z.max()+z_step:z_step]
fig = go.Figure(data=go.Volume(
x=X.flatten(),
y=Y.flatten(),
z=Z.flatten(),
value=values.flatten(),
cmin=values.min(),
cmax=values.max(),
opacity=0.3, # needs to be small to see through all surfaces
surface_count=20,
colorscale=px.colors.diverging.Spectral
))
fig.show()
def plot_disparity_3d(disparity, cmm = cm.viridis):
x = np.arange(0, disparity.shape[0])[:, np.newaxis]
y = np.arange(0, disparity.shape[1])[:, np.newaxis]
fig = plt.figure()
ax = fig.gca(projection="3d")
ax.plot_surface(x,y.T, disparity, cmap = cmm)
def plot_images(imgs, titles, cmode = "gray", ncols= 4, hspace=0.5, wspace=0.5):
assert len(imgs) == len(titles)
n = len(imgs)
row_number = math.ceil(n / ncols)
fig = plt.subplots(figsize=[20, int(4*row_number)])
plt.subplots_adjust(hspace=hspace, wspace=wspace)
for i, img in enumerate(imgs):
ax = plt.subplot(row_number, ncols, i + 1)
ax.set_title("%s\n (%dx%d)" % (titles[i], img.shape[1], img.shape[0]))
plt.imshow(img, cmode)
return fig
if __name__ == "__main__":
import sys
import os
from components.utils import middlebury_utils as mbu
import project_helpers
sys.path.append(os.path.join("..", ".."))
ROOT_PATH = project_helpers.get_project_dir()
EXPERIMENT_TITLE = "EXP_000-Baseline"
DATASET_FOLDER = os.path.join(ROOT_PATH, "datasets", "middlebury")
LOG_FOLDER = os.path.join(ROOT_PATH, "experiments", "logs")
CSV_FOLDER = os.path.join(LOG_FOLDER, EXPERIMENT_TITLE + ".csv")
SCENES = ["teddy", "cones"]
YEAR = 2003
loaded_imgs_and_paths = list(mbu.get_images(DATASET_FOLDER, YEAR, scene) for scene in SCENES)
"""for im, path in loaded_imgs_and_paths:
plot_images(im, path)
import os
ROOT = os.path.join("..", "..")
SELECTED_DATASET = "middlebury_2003"
SELECTED_SCENE = "teddy"
SELECTED_IMAGE = "2-6"
IMG_LOAD_PATH = os.path.join(ROOT, "datasets", "middlebury", SELECTED_DATASET, SELECTED_SCENE)
left = cv2.imread(os.path.join(IMG_LOAD_PATH, "im2.png"), cv2.IMREAD_GRAYSCALE)
right = cv2.imread(os.path.join(IMG_LOAD_PATH, "im6.png"), cv2.IMREAD_GRAYSCALE)
gt = cv2.imread(os.path.join(IMG_LOAD_PATH, "disp2.png"), cv2.IMREAD_GRAYSCALE)
occl = cv2.imread(os.path.join(IMG_LOAD_PATH, "teddy_occl.png"), cv2.IMREAD_GRAYSCALE)
coloured_left = cv2.imread(os.path.join(IMG_LOAD_PATH, "im2.png"))
plod3d_with_img_surface(gt, surface = coloured_left, finess=5, rotation=True)"""
"""
========================================
Create 2D bar graphs in different planes
========================================
Demonstrates making a 3D plot which has 2D bar graphs projected onto
planes y=0, y=1, etc.
"""
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
xs = np.arange(20)
ys = np.random.rand(20)
# You can provide either a single color or an array. To demonstrate this,
# the first bar of each set will be colored cyan.
cs = [c] * len(xs)
cs[0] = 'c'
ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
p = "../../experiments/logs/ALG_005_EXP_001-PatchMatch-MacLean_et_al-Numba.csv"
data = pd.read_csv(p)
new_cols = np.array(data["kernel_size"].str.split("x").to_list()).astype(np.int8)
data["k_h"], data["k_w"] = new_cols[:, 0], new_cols[:, 1]
#selected_scene = data[(data["scene"]=="cones") & (data["are_occlusions_errors"]==False)]
selected_scene = data
# todo: print a scene by occlusion subplot figure
#bar_3d_by_scenes("k_h", "k_w", "mse", selected_scene)
polyine_3d("k_h", "k_w", "mse", selected_scene)
min = data[data["mse"] == data["mse"].min()]
print(min[["kernel_size", "mse"]]) | random_line_split | |
plot_utils.py | import plotly.graph_objects as go
import numpy as np
import pandas as pd
import plotly.express as px
import cv2
from matplotlib import pyplot as plt
from matplotlib import cm
from matplotlib.collections import PolyCollection
from mpl_toolkits.mplot3d import Axes3D
import math
def plot_disp_line(disp, scanline_index, color, title):
coords = get_disparity_plot_coords(disp, scanline_index = scanline_index)
plt.plot(coords)
def get_disparity_plot_coords(disp, scanline_index=0):
current = next = disp[0,0]
current_plot_coords = [0,0]
for j in range ((disp.shape[1])):
next = disp[scanline_index, j]
coordinate_diff = get_disparity_scanline_move(current, next)
current_plot_coords.append(
(current_plot_coords[-1][0] + coordinate_diff[0],
current_plot_coords[-1][1] + coordinate_diff[1])
)
current = next
return current_plot_coords
def get_disparity_scanline_move(current, next):
|
def scatter_3d_results(x_label, y_label, metrix, FILE_PATH_OR_DATAFRAME, cmm="viridis"):
if(FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'):
data = pd.read_csv(FILE_PATH_OR_DATAFRAME)
data.columns = np.array([str.strip(col) for col in data.columns])
else:
data = FILE_PATH_OR_DATAFRAME
x,y,z = data[x_label], data[y_label], data[metrix]
fig = plt.figure()
ax = fig.gca(projection="3d")
ax.set_xlabel(x_label)
ax.set_ylabel(y_label)
ax.set_zlabel(metrix)
ax.scatter(x,y, z, c=z, cmap = "viridis")
plt.show()
def polyine_3d(x_label, y_label, metrix, data, occl_counted=False):
scenes = data["scene"].unique()
X = np.array(data[x_label].unique())
Y= np.array(data[y_label].unique())
data = data[data["are_occlusions_errors"] == occl_counted]
data = data.sort_values(by=[x_label, y_label])
z = pd.pivot_table(data, values=[metrix], columns=[x_label], index=[y_label]).values
Z = np.nan_to_num(z, nan=2000)
verts = []
mins = []
for i in range(X.shape[0]):
current_column = Z[:, i]
min_loc, min_val = X[np.argmin(current_column)], current_column.min()
temp = list(zip(Y, current_column))
verts.append(temp)
mins.append((min_loc, min_val, X[i]))
stop_here = 1
poly = PolyCollection(verts, facecolors=[get_random_color() for x in X])
poly.set_alpha(1)
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
surf_x, surf_y = np.meshgrid(Y, X)
surf_z = np.empty((len(X), len(Y)))
surf_z[:, :] = data[metrix].min()
ax.plot_surface(surf_x, surf_y, surf_z, color=(0.3,0.3,0.9, 0.6))
ax.add_collection3d(poly, zs = X, zdir='y')
#annotating minimums for enhanced readibility
for x,z,y in mins:
label = 'min: %.2f (%d, %d)' % (z, x, y)
ax.text(x, y, z, label)
ax.set_xlabel(y_label)
ax.set_xlim3d(0, Y[-1])
ax.set_ylabel(x_label)
ax.set_ylim3d(0, X[-1])
ax.set_zlabel(metrix)
ax.set_zlim3d(0, 2000)
plt.grid()
plt.show()
return fig, ax
def bar_3d_by_scenes(x_label, y_label, metrix, FILE_PATH_OR_DATAFRAME, occl_counted=False):
if (FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'):
data = pd.read_csv(FILE_PATH_OR_DATAFRAME)
data.columns = np.array([str.strip(col) for col in data.columns])
else:
data = FILE_PATH_OR_DATAFRAME
scenes = data["scene"].unique()
data = data[data["are_occlusions_errors"]==occl_counted]
data = data.sort_values(by=[x_label, y_label])
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
colors = [get_random_color() for scene in scenes]
for x_param in data[x_label].unique():
temp_outer = data[data[x_label]==x_param]
for i, scene in enumerate(scenes):
temp_inner = temp_outer[(temp_outer["scene"]==scene)]
ax.bar(temp_inner[x_label], temp_inner[metrix], zs=temp_inner[y_label], zdir="y", color=colors[i], alpha=0.8)
ax.set_xlabel(x_label)
ax.set_ylabel(y_label)
ax.set_zlabel(metrix)
plt.show()
def get_random_color(alpha=0.8):
r = np.random.rand()
g = np.random.rand()
b = np.random.rand()
return (r,g,b, alpha)
def plot_3d_results(x_label,y_label,metrix, FILE_PATH_OR_DATAFRAME, steps=None):
if(FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'):
data = pd.read_csv(FILE_PATH_OR_DATAFRAME)
data.columns = np.array([str.strip(col) for col in data.columns])
else:
data = FILE_PATH_OR_DATAFRAME
x = np.array(data[x_label].unique())[:, np.newaxis]
y = np.array(data[y_label].unique())[:, np.newaxis]
z = pd.pivot_table(data, values=[metrix], columns=[x_label], index=[y_label]).values
z = np.nan_to_num(z, nan=1000000)
print("Z's shape is: {0}".format(z.shape))
x_diff_step = (x.max() - x.min()) / z.shape[1] if steps is None else steps[1]
y_diff_step = (y.max()-y.min())/z.shape[0] if steps is None else steps[0]
X = np.arange(x.min(), x.max()+1, x_diff_step)[:, np.newaxis]
Y = np.arange(y.min(), y.max() +1, y_diff_step)[:, np.newaxis]
X, Y = np.meshgrid(X, Y)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_zlim(data[metrix].min()-100, data[metrix].max()+100)
ax.plot_surface(X, Y, z, cmap=cm.tab20b)
ax.set_xlabel(x_label)
ax.set_ylabel(y_label)
ax.set_zlabel(metrix)
plt.show()
row_with_min = data[metrix].idxmin()
min_row = data.loc[row_with_min]
return min_row
#it is 4d in reality
def plotly_4d_results(x_label,y_label, z_label, metrix, FILE_PATH_OR_DATAFRAME, ):
if(FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'):
data = pd.read_csv(FILE_PATH_OR_DATAFRAME)
data.columns = np.array([str.strip(col) for col in data.columns])
else:
data = FILE_PATH_OR_DATAFRAME
data = data[[x_label, y_label, z_label, metrix]]
data = data.sort_values(by=[x_label, y_label, z_label], ascending = True)
values = np.nan_to_num(data[[metrix]].values)
x = np.array(data[x_label].unique())[:, np.newaxis]
y = np.array(data[y_label].unique())[:, np.newaxis]
z = np.array(data[z_label].unique())[:, np.newaxis]
x_step = (x.max() - x.min()) / (x.shape[0]-1)
y_step = (y.max() - y.min()) / (y.shape[0]-1)
z_step =(z.max() - z.min()) / (z.shape[0]-1)
# good cmap = px.colors.diverging.Spectral
# px.colors.sequential.Rainbow
# px.colors.sequential.Angset
X, Y, Z = np.mgrid[x.min():x.max()+x_step:x_step, y.min():y.max()+y_step:y_step, z.min():z.max()+z_step:z_step]
fig = go.Figure(data=go.Volume(
x=X.flatten(),
y=Y.flatten(),
z=Z.flatten(),
value=values.flatten(),
cmin=values.min(),
cmax=values.max(),
opacity=0.3, # needs to be small to see through all surfaces
surface_count=20,
colorscale=px.colors.diverging.Spectral
))
fig.show()
def plot_disparity_3d(disparity, cmm = cm.viridis):
x = np.arange(0, disparity.shape[0])[:, np.newaxis]
y = np.arange(0, disparity.shape[1])[:, np.newaxis]
fig = plt.figure()
ax = fig.gca(projection="3d")
ax.plot_surface(x,y.T, disparity, cmap = cmm)
def plot_images(imgs, titles, cmode = "gray", ncols= 4, hspace=0.5, wspace=0.5):
assert len(imgs) == len(titles)
n = len(imgs)
row_number = math.ceil(n / ncols)
fig = plt.subplots(figsize=[20, int(4*row_number)])
plt.subplots_adjust(hspace=hspace, wspace=wspace)
for i, img in enumerate(imgs):
ax = plt.subplot(row_number, ncols, i + 1)
ax.set_title("%s\n (%dx%d)" % (titles[i], img.shape[1], img.shape[0]))
plt.imshow(img, cmode)
return fig
if __name__ == "__main__":
import sys
import os
from components.utils import middlebury_utils as mbu
import project_helpers
sys.path.append(os.path.join("..", ".."))
ROOT_PATH = project_helpers.get_project_dir()
EXPERIMENT_TITLE = "EXP_000-Baseline"
DATASET_FOLDER = os.path.join(ROOT_PATH, "datasets", "middlebury")
LOG_FOLDER = os.path.join(ROOT_PATH, "experiments", "logs")
CSV_FOLDER = os.path.join(LOG_FOLDER, EXPERIMENT_TITLE + ".csv")
SCENES = ["teddy", "cones"]
YEAR = 2003
loaded_imgs_and_paths = list(mbu.get_images(DATASET_FOLDER, YEAR, scene) for scene in SCENES)
"""for im, path in loaded_imgs_and_paths:
plot_images(im, path)
import os
ROOT = os.path.join("..", "..")
SELECTED_DATASET = "middlebury_2003"
SELECTED_SCENE = "teddy"
SELECTED_IMAGE = "2-6"
IMG_LOAD_PATH = os.path.join(ROOT, "datasets", "middlebury", SELECTED_DATASET, SELECTED_SCENE)
left = cv2.imread(os.path.join(IMG_LOAD_PATH, "im2.png"), cv2.IMREAD_GRAYSCALE)
right = cv2.imread(os.path.join(IMG_LOAD_PATH, "im6.png"), cv2.IMREAD_GRAYSCALE)
gt = cv2.imread(os.path.join(IMG_LOAD_PATH, "disp2.png"), cv2.IMREAD_GRAYSCALE)
occl = cv2.imread(os.path.join(IMG_LOAD_PATH, "teddy_occl.png"), cv2.IMREAD_GRAYSCALE)
coloured_left = cv2.imread(os.path.join(IMG_LOAD_PATH, "im2.png"))
plod3d_with_img_surface(gt, surface = coloured_left, finess=5, rotation=True)"""
"""
========================================
Create 2D bar graphs in different planes
========================================
Demonstrates making a 3D plot which has 2D bar graphs projected onto
planes y=0, y=1, etc.
"""
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
xs = np.arange(20)
ys = np.random.rand(20)
# You can provide either a single color or an array. To demonstrate this,
# the first bar of each set will be colored cyan.
cs = [c] * len(xs)
cs[0] = 'c'
ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
p = "../../experiments/logs/ALG_005_EXP_001-PatchMatch-MacLean_et_al-Numba.csv"
data = pd.read_csv(p)
new_cols = np.array(data["kernel_size"].str.split("x").to_list()).astype(np.int8)
data["k_h"], data["k_w"] = new_cols[:, 0], new_cols[:, 1]
#selected_scene = data[(data["scene"]=="cones") & (data["are_occlusions_errors"]==False)]
selected_scene = data
# todo: print a scene by occlusion subplot figure
#bar_3d_by_scenes("k_h", "k_w", "mse", selected_scene)
polyine_3d("k_h", "k_w", "mse", selected_scene)
min = data[data["mse"] == data["mse"].min()]
print(min[["kernel_size", "mse"]])
| if next==0:
return (1,0)
if(current==next):
return (1,1)
#if it is brighter?
if(next>current):
return (np.abs(next-current)+1, 1)
#if it is darker?
return (1,np.abs(next - current)+1) | identifier_body |
gui.py | import tkinter
from tkinter import ttk
from tkinter import simpledialog
from tkinter import messagebox
from course import Course
from section import Section
class About_Dialog(simpledialog.Dialog):
def __init__(self, parent, title="Class Grader"):
super().__init__(parent, title=title)
def body (self, master):
description ="""
Class Grader is a college Python project
demonstrating I/O, classes, data structures, matplotlib, and tkinter.
Author: Thomas Bender
Contact: tbender4@gmail.com
This software is open source and is hosted on github.com/tbender4/Class-Grader"""
tkinter.Label(master, text=description).grid(column=0, row=0)
return master
def buttonbox(self):
# Similar to stock but only a close button
box = tkinter.Frame(self)
w = tkinter.Button(box, text="Close", width=10, command=self.cancel)
w.pack(side=tkinter.LEFT, padx=5, pady=5)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.cancel)
box.pack()
class New_Course(simpledialog.Dialog): #inherit tkinter.simpledialog
def __init__(self, parent):
self.new_course_ID = ""
self.new_course_name = ""
super().__init__(parent, title="Enter Course Information:") #inherited constructor needs original window
def body(self, master):
tkinter.Label(master, text="Course ID (ex: MAC108):").grid(column = 0, row=0, sticky='w')
tkinter.Label(master, text="Course Full Name (ex: Intro to Python):").grid(column = 0, row=1)
self.new_course_ID = tkinter.Entry(master)
self.new_course_name = tkinter.Entry(master)
self.new_course_ID.grid(column=1,row=0)
self.new_course_name.grid(column=1,row=1)
return None
def validate(self):
if self.new_course_ID.get().strip() == '' or self.new_course_name.get().strip() == '':
return 0
return 1
def apply(self):
print("apply hit")
print(str(self.new_course_ID.get()))
# self.parent.withdraw()
# TODO: Save this to the actual course data. Then draw window.
course_window(self.new_course_ID.get().strip(), self.new_course_name.get().strip())
class New_Student(simpledialog.Dialog): # inherit tkinter.simpledialog
def __init__(self, parent):
# inherited constructor needs original window
super().__init__(parent, title="Enter Student Information:")
def body(self, master):
tkinter.Label(master, text="Last Name").grid(
column=0, row=0, sticky='w')
tkinter.Label(master, text="First Name:").grid(
column=0, row=1)
self.last_name_entry = tkinter.Entry(master)
self.first_name_entry = tkinter.Entry(master)
self.last_name_entry.grid(column=1, row=0)
self.first_name_entry.grid(column=1, row=1)
return None
def validate(self):
if self.last_name_entry.get().strip() == '' or self.first_name_entry.get().strip() == '':
return 0
return 1
def apply(self):
print("apply hit")
self.last_name = self.last_name_entry.get().strip()
self.first_name = self.first_name_entry.get().strip()
class Section_Tree(ttk.Treeview): #table view. possibly rewrite with inheritance
def __init__(self, master, section=Course('MAC000', 'test_000').sectionList[0]):
# self.section_tree = section_tree
self.section = section
self.master = master
self.student_grade_list = self.section.student_grade_list
super().__init__(master)
#Tree view
#formatting columns
header_name_dict = {
# 'student_id':'ID',
'student_name': 'Name',
'attendance': 'Attendance',
'homework': 'Homework',
'quiz': 'Quiz',
'exam': 'Exam'
}
self['columns'] = list(header_name_dict.keys())
for key, value in header_name_dict.items():
self.column(key, width=50)
self.heading(key, text=value)
self.heading('#0', text='ID') #ID pertains to student ID
self.column('#0', width=40)
self.column('attendance', width=70)
self.column('homework', width=70)
self.column('student_name', width=180)
#inserting existing values from section
for student_grade in self.student_grade_list:
a, b, text, values = self.gen_child(student_grade)
#b, c, and d, e should be attendances, homeworks, quizzes, exams
self.insert(a, b, text=text, values=values)
def gen_child(self, student_grade, last_name = None, first_name = None):
#if options are provided, overwrite info with given info (should reflect in data as well)
if last_name != None and first_name != None:
student_grade['student'].last_name = last_name
student_grade['student'].first_name = first_name
student_grade['student'].updateLF()
student_ID = student_grade['student'].student_id
student_last = student_grade['student'].last_name
student_first = student_grade['student'].first_name
student_last_first = student_grade['student'].last_first
return ('', 'end', student_ID, (student_last_first , 'a', 'b', 'c', 'd'))
def add_student(self, last_name = 'test', first_name = 'name_man'):
# first gets the info. Then adds it to the section. then inserts the data into the tree.
# it's possible that the data may be reconstructed. so it's properly synced (need to decide best route)
# new_student = New_Student(self.master)
new_student = New_Student(self)
last_name = new_student.last_name
first_name = new_student.first_name
print('adding student:', last_name, first_name)
new_student_grade = self.section.addStudentGrade(last_name, first_name) #this adds a student_grade, not Student
print(new_student_grade)
a, b, text, values = self.gen_child(new_student_grade, last_name, first_name)
self.insert(a, b, text=text, values=values)
def edit_student(self):
# TODO: Have the whole student_grade be stored as a hidden value
focus = self.focus()
# print(focus[]
#this is dirty. doesn't save information properly
#Having the student as an argument would be best student would be best
l_f = self.item(focus)['values'][0].split(",")
last = l_f[0]
first = l_f[1]
print('test', l_f)
new_student = Edit_Student(self.master, last, first)
last_first = new_student.last_name + ', ' + new_student.first_name
self.item(focus, values=(last_first, new_student.att_avg, new_student.hw_avg, new_student.exam_avg, new_student.quiz_avg))
print(self.item(self.focus()))
class Edit_Student(simpledialog.Dialog): # inherit tkinter.simpledialog
def __init__(self, parent, last_name='l', first_name='f'):
# inherited constructor needs original window
self.last_name = last_name
self.first_name = first_name
super().__init__(parent, title="Edit Student Information:")
def body(self, master):
tkinter.Label(master, text="Last Name").grid(
column=0, row=0, sticky='e')
tkinter.Label(master, text="First Name:").grid(
column=0, row=1, sticky='e')
print(self.last_name, self.first_name)
self.last_name_entry = tkinter.Entry(master)
self.last_name_entry.insert(0, self.last_name)
self.first_name_entry = tkinter.Entry(master)
self.first_name_entry.insert(0, self.first_name)
self.last_name_entry.grid(column=1, row=0)
self.first_name_entry.grid(column=1, row=1)
tkinter.Label(master, text="Attendance\n(0 for absent, 1 for present):").grid(row=2)
tkinter.Label(master, text="Homework:\n(from 0 - 100)").grid(row=2, column=1)
tkinter.Label(master, text="Quiz:\n(from 0 - 100)").grid(row=2, column=2)
tkinter.Label(master, text="Exam:\n(from 0 - 100)").grid(row=2, column=3)
self.att_entry = []
for i in range(3,15):
entry = tkinter.Entry(master)
entry.insert(0, '0')
entry.grid(row=i, column = 0)
self.att_entry.append(entry)
self.hw_entry = []
for i in range(3, 15):
entry = tkinter.Entry(master)
entry.insert(0, '0')
entry.grid(row=i, column=1)
self.hw_entry.append(entry)
self.quiz_entry = []
for i in range(3, 15):
entry = tkinter.Entry(master)
entry.insert(0, '0')
entry.grid(row=i, column=2)
self.quiz_entry.append(entry)
self.exam_entry = []
for i in range(3, 7):
entry = tkinter.Entry(master)
entry.insert(0, '0')
entry.grid(row=i, column=3)
self.exam_entry.append(entry)
return None
def validate(self):
try:
for entry in self.att_entry:
value = int(entry.get().strip())
if value > 1 or value < 0:
return 0
for entry in self.hw_entry:
value = int(entry.get().strip())
if value > 100 or value < 0:
return 0
for entry in self.quiz_entry:
value = int(entry.get().strip())
if value > 100 or value < 0:
return 0
for entry in self.exam_entry:
|
except ValueError:
return 0
if self.last_name_entry.get().strip() == '' or self.first_name_entry.get().strip() == '':
return 0
return 1
def apply(self):
print("apply hit")
self.last_name = self.last_name_entry.get().strip()
self.first_name = self.first_name_entry.get().strip()
self.att_avg = 100 # reports back as percentage
att_sum = 0
for i in self.att_entry:
att_sum += int(i.get().strip())
print(att_sum)
self.att_avg = str(round(att_sum / len(self.att_entry) * 100, 2))+"%"
hw_sum = 0
for i in self.hw_entry:
hw_sum += int(i.get().strip()) / 100
self.hw_avg = str(round(hw_sum / len(self.hw_entry) * 100, 2))+"%"
quiz_sum = 0
for i in self.quiz_entry:
quiz_sum += int(i.get().strip()) / 100
self.quiz_avg = str(round(quiz_sum / len(self.quiz_entry) * 100, 2))+"%"
exam_sum = 0
for i in self.exam_entry:
exam_sum += int(i.get().strip()) / 100
self.exam_avg = str(round(exam_sum / len(self.exam_entry) * 100, 2))+"%"
class Section_Frame(tkinter.Frame):
# ---------------------
# ----------------
# | |
# | Tree |
# | |
# ----------------
# |add| |edit|
#
# ---------------------
def __init__(self, master, section = Section()):
super().__init__(master)
section_tree = Section_Tree(self, section)
add_button = tkinter.Button(self, text='Add Student', command = section_tree.add_student)
edit_button = tkinter.Button(self, text='Edit Student', command = section_tree.edit_student)
section_tree.grid(row=0,columnspan=2)
add_button.grid(row=1, column = 0)
edit_button.grid(row=1, column=1)
# tkinter.Label(self, text='Custom frame').grid(row=0)
def new_course():
New_Course(main_window)
def test_course():
course_window('MAC000', 'Intro to Testing')
def course_window(course_ID, course_name):
def report_size(window): #debug to report window size for testing
print(window.winfo_width(), window.winfo_height())
def add_new_section(notebook, course):
s_frame = Section_Frame(notebook, course.addNewSection())
text = course.courseID + '-' + "{:02d}".format(course.sectionList[-1].sectionID)
# notebook.add(child=frame, text=text)
notebook.add(child=s_frame, text=text)
#generation of the course in question
#TODO show more than one course in the GUI at the same time
course = Course(course_ID, course_name)
course.printCourse()
course_window=tkinter.Toplevel()
#course_window.geometry('540x400')
#Menu Bar
menu_bar = tkinter.Menu(course_window)
file_menu = tkinter.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="Save", command=course.writeToFile)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=main_window.destroy)
menu_bar.add_cascade(label="File", menu=file_menu)
help_menu = tkinter.Menu(menu_bar, tearoff=0)
help_menu.add_command(label="About", command=lambda: About_Dialog(course_window)) #lamba fixes arguments
menu_bar.add_cascade(label="Help", menu=help_menu)
course_window.config(menu=menu_bar)
#window elements with course:
tkinter.Label(course_window, text = course.courseID + ' - ' + course_name, font=(None, 16)).grid(sticky='W', row=0, column= 0)
sections_notebook = ttk.Notebook(master=course_window)
sections_notebook.grid(row=2, columnspan=2, sticky='NS') # colspan is dirty button spacing fix
#Generate tables from current list
for section in course.sectionList:
section_frame = Section_Frame(sections_notebook, section)
sections_notebook.add(child=section_frame, text=course.courseID + '-' + "{:02d}".format(course.sectionList[-1].sectionID))
#placing course_window grid
tkinter.Button(course_window, text="Report size",
command=lambda: report_size(course_window)).grid(row=1, sticky='W')
add_button = tkinter.Button(course_window, text="Add Section",
command=lambda: add_new_section(sections_notebook, course))
add_button.grid(column=1, row=1, sticky='W')
tkinter.Button(course_window, text='Print Course',
command=course.printCourse).grid(row=3, sticky='w')
main_window = tkinter.Tk()
main_window.title("Class Grader")
#main_window.geometry('400x300')
new_course_button = tkinter.Button(main_window, text="New", state='normal', command=new_course)
test_course_button = tkinter.Button(main_window, text="Test", state='normal', command=test_course)
new_course_button.grid(column=0, row=0)
test_course_button.grid(column=0, row=1)
label = tkinter.Label(main_window, text='Create a new course')
label.grid(column=1, row=0)
# test_button = tkinter.Button(main_window, text="test", state='normal', command=new_course)
# test_button.grid(column=0, row=1)
| value = int(entry.get().strip())
if value > 100 or value < 0:
return 0 | conditional_block |
gui.py | import tkinter
from tkinter import ttk
from tkinter import simpledialog
from tkinter import messagebox
from course import Course
from section import Section
class About_Dialog(simpledialog.Dialog):
def __init__(self, parent, title="Class Grader"):
super().__init__(parent, title=title)
def body (self, master):
description ="""
Class Grader is a college Python project
demonstrating I/O, classes, data structures, matplotlib, and tkinter.
Author: Thomas Bender
Contact: tbender4@gmail.com
This software is open source and is hosted on github.com/tbender4/Class-Grader"""
tkinter.Label(master, text=description).grid(column=0, row=0)
return master
def buttonbox(self):
# Similar to stock but only a close button
box = tkinter.Frame(self)
w = tkinter.Button(box, text="Close", width=10, command=self.cancel)
w.pack(side=tkinter.LEFT, padx=5, pady=5)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.cancel)
box.pack()
class New_Course(simpledialog.Dialog): #inherit tkinter.simpledialog
def __init__(self, parent):
self.new_course_ID = ""
self.new_course_name = ""
super().__init__(parent, title="Enter Course Information:") #inherited constructor needs original window
def body(self, master):
tkinter.Label(master, text="Course ID (ex: MAC108):").grid(column = 0, row=0, sticky='w')
tkinter.Label(master, text="Course Full Name (ex: Intro to Python):").grid(column = 0, row=1)
self.new_course_ID = tkinter.Entry(master)
self.new_course_name = tkinter.Entry(master)
self.new_course_ID.grid(column=1,row=0)
self.new_course_name.grid(column=1,row=1)
return None
def validate(self):
if self.new_course_ID.get().strip() == '' or self.new_course_name.get().strip() == '':
return 0
return 1
def apply(self):
print("apply hit")
print(str(self.new_course_ID.get()))
# self.parent.withdraw()
# TODO: Save this to the actual course data. Then draw window.
course_window(self.new_course_ID.get().strip(), self.new_course_name.get().strip())
class New_Student(simpledialog.Dialog): # inherit tkinter.simpledialog
def __init__(self, parent):
# inherited constructor needs original window
super().__init__(parent, title="Enter Student Information:")
def body(self, master):
tkinter.Label(master, text="Last Name").grid(
column=0, row=0, sticky='w')
tkinter.Label(master, text="First Name:").grid(
column=0, row=1)
self.last_name_entry = tkinter.Entry(master)
self.first_name_entry = tkinter.Entry(master)
self.last_name_entry.grid(column=1, row=0)
self.first_name_entry.grid(column=1, row=1)
return None
def validate(self):
if self.last_name_entry.get().strip() == '' or self.first_name_entry.get().strip() == '':
return 0
return 1
def apply(self):
print("apply hit")
self.last_name = self.last_name_entry.get().strip()
self.first_name = self.first_name_entry.get().strip()
class Section_Tree(ttk.Treeview): #table view. possibly rewrite with inheritance
def __init__(self, master, section=Course('MAC000', 'test_000').sectionList[0]):
# self.section_tree = section_tree
self.section = section
self.master = master
self.student_grade_list = self.section.student_grade_list
super().__init__(master)
#Tree view
#formatting columns
header_name_dict = {
# 'student_id':'ID',
'student_name': 'Name',
'attendance': 'Attendance',
'homework': 'Homework',
'quiz': 'Quiz',
'exam': 'Exam'
}
self['columns'] = list(header_name_dict.keys())
for key, value in header_name_dict.items():
self.column(key, width=50)
self.heading(key, text=value)
self.heading('#0', text='ID') #ID pertains to student ID
self.column('#0', width=40)
self.column('attendance', width=70)
self.column('homework', width=70)
self.column('student_name', width=180)
#inserting existing values from section
for student_grade in self.student_grade_list:
a, b, text, values = self.gen_child(student_grade)
#b, c, and d, e should be attendances, homeworks, quizzes, exams
self.insert(a, b, text=text, values=values)
def gen_child(self, student_grade, last_name = None, first_name = None):
#if options are provided, overwrite info with given info (should reflect in data as well)
if last_name != None and first_name != None:
student_grade['student'].last_name = last_name
student_grade['student'].first_name = first_name
student_grade['student'].updateLF()
student_ID = student_grade['student'].student_id
student_last = student_grade['student'].last_name
student_first = student_grade['student'].first_name
student_last_first = student_grade['student'].last_first
return ('', 'end', student_ID, (student_last_first , 'a', 'b', 'c', 'd'))
def add_student(self, last_name = 'test', first_name = 'name_man'):
# first gets the info. Then adds it to the section. then inserts the data into the tree.
# it's possible that the data may be reconstructed. so it's properly synced (need to decide best route)
# new_student = New_Student(self.master)
new_student = New_Student(self)
last_name = new_student.last_name
first_name = new_student.first_name
print('adding student:', last_name, first_name)
new_student_grade = self.section.addStudentGrade(last_name, first_name) #this adds a student_grade, not Student
print(new_student_grade)
a, b, text, values = self.gen_child(new_student_grade, last_name, first_name)
self.insert(a, b, text=text, values=values)
def edit_student(self):
# TODO: Have the whole student_grade be stored as a hidden value
focus = self.focus()
# print(focus[]
#this is dirty. doesn't save information properly
#Having the student as an argument would be best student would be best
l_f = self.item(focus)['values'][0].split(",")
last = l_f[0]
first = l_f[1]
print('test', l_f)
new_student = Edit_Student(self.master, last, first)
last_first = new_student.last_name + ', ' + new_student.first_name
self.item(focus, values=(last_first, new_student.att_avg, new_student.hw_avg, new_student.exam_avg, new_student.quiz_avg))
print(self.item(self.focus()))
class Edit_Student(simpledialog.Dialog): # inherit tkinter.simpledialog
def __init__(self, parent, last_name='l', first_name='f'):
# inherited constructor needs original window
self.last_name = last_name
self.first_name = first_name
super().__init__(parent, title="Edit Student Information:")
def body(self, master):
tkinter.Label(master, text="Last Name").grid(
column=0, row=0, sticky='e')
tkinter.Label(master, text="First Name:").grid(
column=0, row=1, sticky='e')
print(self.last_name, self.first_name)
self.last_name_entry = tkinter.Entry(master)
self.last_name_entry.insert(0, self.last_name)
self.first_name_entry = tkinter.Entry(master)
self.first_name_entry.insert(0, self.first_name)
self.last_name_entry.grid(column=1, row=0)
self.first_name_entry.grid(column=1, row=1)
tkinter.Label(master, text="Attendance\n(0 for absent, 1 for present):").grid(row=2)
tkinter.Label(master, text="Homework:\n(from 0 - 100)").grid(row=2, column=1)
tkinter.Label(master, text="Quiz:\n(from 0 - 100)").grid(row=2, column=2)
tkinter.Label(master, text="Exam:\n(from 0 - 100)").grid(row=2, column=3)
self.att_entry = []
for i in range(3,15):
entry = tkinter.Entry(master)
entry.insert(0, '0')
entry.grid(row=i, column = 0)
self.att_entry.append(entry)
self.hw_entry = []
for i in range(3, 15):
entry = tkinter.Entry(master)
entry.insert(0, '0')
entry.grid(row=i, column=1)
self.hw_entry.append(entry)
self.quiz_entry = []
for i in range(3, 15):
entry = tkinter.Entry(master)
entry.insert(0, '0')
entry.grid(row=i, column=2)
self.quiz_entry.append(entry)
self.exam_entry = []
for i in range(3, 7):
entry = tkinter.Entry(master)
entry.insert(0, '0')
entry.grid(row=i, column=3)
self.exam_entry.append(entry)
return None
def validate(self):
try:
for entry in self.att_entry:
value = int(entry.get().strip())
if value > 1 or value < 0:
return 0
for entry in self.hw_entry:
value = int(entry.get().strip())
if value > 100 or value < 0:
return 0
for entry in self.quiz_entry:
value = int(entry.get().strip())
if value > 100 or value < 0:
return 0
for entry in self.exam_entry:
value = int(entry.get().strip())
if value > 100 or value < 0:
return 0
except ValueError:
return 0
if self.last_name_entry.get().strip() == '' or self.first_name_entry.get().strip() == '':
return 0
return 1
def | (self):
print("apply hit")
self.last_name = self.last_name_entry.get().strip()
self.first_name = self.first_name_entry.get().strip()
self.att_avg = 100 # reports back as percentage
att_sum = 0
for i in self.att_entry:
att_sum += int(i.get().strip())
print(att_sum)
self.att_avg = str(round(att_sum / len(self.att_entry) * 100, 2))+"%"
hw_sum = 0
for i in self.hw_entry:
hw_sum += int(i.get().strip()) / 100
self.hw_avg = str(round(hw_sum / len(self.hw_entry) * 100, 2))+"%"
quiz_sum = 0
for i in self.quiz_entry:
quiz_sum += int(i.get().strip()) / 100
self.quiz_avg = str(round(quiz_sum / len(self.quiz_entry) * 100, 2))+"%"
exam_sum = 0
for i in self.exam_entry:
exam_sum += int(i.get().strip()) / 100
self.exam_avg = str(round(exam_sum / len(self.exam_entry) * 100, 2))+"%"
class Section_Frame(tkinter.Frame):
# ---------------------
# ----------------
# | |
# | Tree |
# | |
# ----------------
# |add| |edit|
#
# ---------------------
def __init__(self, master, section = Section()):
super().__init__(master)
section_tree = Section_Tree(self, section)
add_button = tkinter.Button(self, text='Add Student', command = section_tree.add_student)
edit_button = tkinter.Button(self, text='Edit Student', command = section_tree.edit_student)
section_tree.grid(row=0,columnspan=2)
add_button.grid(row=1, column = 0)
edit_button.grid(row=1, column=1)
# tkinter.Label(self, text='Custom frame').grid(row=0)
def new_course():
New_Course(main_window)
def test_course():
course_window('MAC000', 'Intro to Testing')
def course_window(course_ID, course_name):
def report_size(window): #debug to report window size for testing
print(window.winfo_width(), window.winfo_height())
def add_new_section(notebook, course):
s_frame = Section_Frame(notebook, course.addNewSection())
text = course.courseID + '-' + "{:02d}".format(course.sectionList[-1].sectionID)
# notebook.add(child=frame, text=text)
notebook.add(child=s_frame, text=text)
#generation of the course in question
#TODO show more than one course in the GUI at the same time
course = Course(course_ID, course_name)
course.printCourse()
course_window=tkinter.Toplevel()
#course_window.geometry('540x400')
#Menu Bar
menu_bar = tkinter.Menu(course_window)
file_menu = tkinter.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="Save", command=course.writeToFile)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=main_window.destroy)
menu_bar.add_cascade(label="File", menu=file_menu)
help_menu = tkinter.Menu(menu_bar, tearoff=0)
help_menu.add_command(label="About", command=lambda: About_Dialog(course_window)) #lamba fixes arguments
menu_bar.add_cascade(label="Help", menu=help_menu)
course_window.config(menu=menu_bar)
#window elements with course:
tkinter.Label(course_window, text = course.courseID + ' - ' + course_name, font=(None, 16)).grid(sticky='W', row=0, column= 0)
sections_notebook = ttk.Notebook(master=course_window)
sections_notebook.grid(row=2, columnspan=2, sticky='NS') # colspan is dirty button spacing fix
#Generate tables from current list
for section in course.sectionList:
section_frame = Section_Frame(sections_notebook, section)
sections_notebook.add(child=section_frame, text=course.courseID + '-' + "{:02d}".format(course.sectionList[-1].sectionID))
#placing course_window grid
tkinter.Button(course_window, text="Report size",
command=lambda: report_size(course_window)).grid(row=1, sticky='W')
add_button = tkinter.Button(course_window, text="Add Section",
command=lambda: add_new_section(sections_notebook, course))
add_button.grid(column=1, row=1, sticky='W')
tkinter.Button(course_window, text='Print Course',
command=course.printCourse).grid(row=3, sticky='w')
main_window = tkinter.Tk()
main_window.title("Class Grader")
#main_window.geometry('400x300')
new_course_button = tkinter.Button(main_window, text="New", state='normal', command=new_course)
test_course_button = tkinter.Button(main_window, text="Test", state='normal', command=test_course)
new_course_button.grid(column=0, row=0)
test_course_button.grid(column=0, row=1)
label = tkinter.Label(main_window, text='Create a new course')
label.grid(column=1, row=0)
# test_button = tkinter.Button(main_window, text="test", state='normal', command=new_course)
# test_button.grid(column=0, row=1)
| apply | identifier_name |
gui.py | import tkinter
from tkinter import ttk
from tkinter import simpledialog
from tkinter import messagebox
from course import Course
from section import Section
class About_Dialog(simpledialog.Dialog):
def __init__(self, parent, title="Class Grader"):
super().__init__(parent, title=title)
def body (self, master):
description ="""
Class Grader is a college Python project
demonstrating I/O, classes, data structures, matplotlib, and tkinter.
Author: Thomas Bender
Contact: tbender4@gmail.com
This software is open source and is hosted on github.com/tbender4/Class-Grader"""
tkinter.Label(master, text=description).grid(column=0, row=0)
return master
def buttonbox(self):
# Similar to stock but only a close button
box = tkinter.Frame(self)
w = tkinter.Button(box, text="Close", width=10, command=self.cancel)
w.pack(side=tkinter.LEFT, padx=5, pady=5)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.cancel)
box.pack()
class New_Course(simpledialog.Dialog): #inherit tkinter.simpledialog
def __init__(self, parent):
self.new_course_ID = ""
self.new_course_name = ""
super().__init__(parent, title="Enter Course Information:") #inherited constructor needs original window
def body(self, master):
tkinter.Label(master, text="Course ID (ex: MAC108):").grid(column = 0, row=0, sticky='w')
tkinter.Label(master, text="Course Full Name (ex: Intro to Python):").grid(column = 0, row=1)
self.new_course_ID = tkinter.Entry(master)
self.new_course_name = tkinter.Entry(master)
self.new_course_ID.grid(column=1,row=0)
self.new_course_name.grid(column=1,row=1)
return None
def validate(self):
if self.new_course_ID.get().strip() == '' or self.new_course_name.get().strip() == '':
return 0
return 1
def apply(self):
print("apply hit")
print(str(self.new_course_ID.get()))
# self.parent.withdraw()
# TODO: Save this to the actual course data. Then draw window.
course_window(self.new_course_ID.get().strip(), self.new_course_name.get().strip())
class New_Student(simpledialog.Dialog): # inherit tkinter.simpledialog
def __init__(self, parent):
# inherited constructor needs original window |
tkinter.Label(master, text="Last Name").grid(
column=0, row=0, sticky='w')
tkinter.Label(master, text="First Name:").grid(
column=0, row=1)
self.last_name_entry = tkinter.Entry(master)
self.first_name_entry = tkinter.Entry(master)
self.last_name_entry.grid(column=1, row=0)
self.first_name_entry.grid(column=1, row=1)
return None
def validate(self):
if self.last_name_entry.get().strip() == '' or self.first_name_entry.get().strip() == '':
return 0
return 1
def apply(self):
print("apply hit")
self.last_name = self.last_name_entry.get().strip()
self.first_name = self.first_name_entry.get().strip()
class Section_Tree(ttk.Treeview): #table view. possibly rewrite with inheritance
def __init__(self, master, section=Course('MAC000', 'test_000').sectionList[0]):
# self.section_tree = section_tree
self.section = section
self.master = master
self.student_grade_list = self.section.student_grade_list
super().__init__(master)
#Tree view
#formatting columns
header_name_dict = {
# 'student_id':'ID',
'student_name': 'Name',
'attendance': 'Attendance',
'homework': 'Homework',
'quiz': 'Quiz',
'exam': 'Exam'
}
self['columns'] = list(header_name_dict.keys())
for key, value in header_name_dict.items():
self.column(key, width=50)
self.heading(key, text=value)
self.heading('#0', text='ID') #ID pertains to student ID
self.column('#0', width=40)
self.column('attendance', width=70)
self.column('homework', width=70)
self.column('student_name', width=180)
#inserting existing values from section
for student_grade in self.student_grade_list:
a, b, text, values = self.gen_child(student_grade)
#b, c, and d, e should be attendances, homeworks, quizzes, exams
self.insert(a, b, text=text, values=values)
def gen_child(self, student_grade, last_name = None, first_name = None):
#if options are provided, overwrite info with given info (should reflect in data as well)
if last_name != None and first_name != None:
student_grade['student'].last_name = last_name
student_grade['student'].first_name = first_name
student_grade['student'].updateLF()
student_ID = student_grade['student'].student_id
student_last = student_grade['student'].last_name
student_first = student_grade['student'].first_name
student_last_first = student_grade['student'].last_first
return ('', 'end', student_ID, (student_last_first , 'a', 'b', 'c', 'd'))
def add_student(self, last_name = 'test', first_name = 'name_man'):
# first gets the info. Then adds it to the section. then inserts the data into the tree.
# it's possible that the data may be reconstructed. so it's properly synced (need to decide best route)
# new_student = New_Student(self.master)
new_student = New_Student(self)
last_name = new_student.last_name
first_name = new_student.first_name
print('adding student:', last_name, first_name)
new_student_grade = self.section.addStudentGrade(last_name, first_name) #this adds a student_grade, not Student
print(new_student_grade)
a, b, text, values = self.gen_child(new_student_grade, last_name, first_name)
self.insert(a, b, text=text, values=values)
def edit_student(self):
# TODO: Have the whole student_grade be stored as a hidden value
focus = self.focus()
# print(focus[]
#this is dirty. doesn't save information properly
#Having the student as an argument would be best student would be best
l_f = self.item(focus)['values'][0].split(",")
last = l_f[0]
first = l_f[1]
print('test', l_f)
new_student = Edit_Student(self.master, last, first)
last_first = new_student.last_name + ', ' + new_student.first_name
self.item(focus, values=(last_first, new_student.att_avg, new_student.hw_avg, new_student.exam_avg, new_student.quiz_avg))
print(self.item(self.focus()))
class Edit_Student(simpledialog.Dialog): # inherit tkinter.simpledialog
def __init__(self, parent, last_name='l', first_name='f'):
# inherited constructor needs original window
self.last_name = last_name
self.first_name = first_name
super().__init__(parent, title="Edit Student Information:")
def body(self, master):
tkinter.Label(master, text="Last Name").grid(
column=0, row=0, sticky='e')
tkinter.Label(master, text="First Name:").grid(
column=0, row=1, sticky='e')
print(self.last_name, self.first_name)
self.last_name_entry = tkinter.Entry(master)
self.last_name_entry.insert(0, self.last_name)
self.first_name_entry = tkinter.Entry(master)
self.first_name_entry.insert(0, self.first_name)
self.last_name_entry.grid(column=1, row=0)
self.first_name_entry.grid(column=1, row=1)
tkinter.Label(master, text="Attendance\n(0 for absent, 1 for present):").grid(row=2)
tkinter.Label(master, text="Homework:\n(from 0 - 100)").grid(row=2, column=1)
tkinter.Label(master, text="Quiz:\n(from 0 - 100)").grid(row=2, column=2)
tkinter.Label(master, text="Exam:\n(from 0 - 100)").grid(row=2, column=3)
self.att_entry = []
for i in range(3,15):
entry = tkinter.Entry(master)
entry.insert(0, '0')
entry.grid(row=i, column = 0)
self.att_entry.append(entry)
self.hw_entry = []
for i in range(3, 15):
entry = tkinter.Entry(master)
entry.insert(0, '0')
entry.grid(row=i, column=1)
self.hw_entry.append(entry)
self.quiz_entry = []
for i in range(3, 15):
entry = tkinter.Entry(master)
entry.insert(0, '0')
entry.grid(row=i, column=2)
self.quiz_entry.append(entry)
self.exam_entry = []
for i in range(3, 7):
entry = tkinter.Entry(master)
entry.insert(0, '0')
entry.grid(row=i, column=3)
self.exam_entry.append(entry)
return None
def validate(self):
try:
for entry in self.att_entry:
value = int(entry.get().strip())
if value > 1 or value < 0:
return 0
for entry in self.hw_entry:
value = int(entry.get().strip())
if value > 100 or value < 0:
return 0
for entry in self.quiz_entry:
value = int(entry.get().strip())
if value > 100 or value < 0:
return 0
for entry in self.exam_entry:
value = int(entry.get().strip())
if value > 100 or value < 0:
return 0
except ValueError:
return 0
if self.last_name_entry.get().strip() == '' or self.first_name_entry.get().strip() == '':
return 0
return 1
def apply(self):
print("apply hit")
self.last_name = self.last_name_entry.get().strip()
self.first_name = self.first_name_entry.get().strip()
self.att_avg = 100 # reports back as percentage
att_sum = 0
for i in self.att_entry:
att_sum += int(i.get().strip())
print(att_sum)
self.att_avg = str(round(att_sum / len(self.att_entry) * 100, 2))+"%"
hw_sum = 0
for i in self.hw_entry:
hw_sum += int(i.get().strip()) / 100
self.hw_avg = str(round(hw_sum / len(self.hw_entry) * 100, 2))+"%"
quiz_sum = 0
for i in self.quiz_entry:
quiz_sum += int(i.get().strip()) / 100
self.quiz_avg = str(round(quiz_sum / len(self.quiz_entry) * 100, 2))+"%"
exam_sum = 0
for i in self.exam_entry:
exam_sum += int(i.get().strip()) / 100
self.exam_avg = str(round(exam_sum / len(self.exam_entry) * 100, 2))+"%"
class Section_Frame(tkinter.Frame):
# ---------------------
# ----------------
# | |
# | Tree |
# | |
# ----------------
# |add| |edit|
#
# ---------------------
def __init__(self, master, section = Section()):
super().__init__(master)
section_tree = Section_Tree(self, section)
add_button = tkinter.Button(self, text='Add Student', command = section_tree.add_student)
edit_button = tkinter.Button(self, text='Edit Student', command = section_tree.edit_student)
section_tree.grid(row=0,columnspan=2)
add_button.grid(row=1, column = 0)
edit_button.grid(row=1, column=1)
# tkinter.Label(self, text='Custom frame').grid(row=0)
def new_course():
New_Course(main_window)
def test_course():
course_window('MAC000', 'Intro to Testing')
def course_window(course_ID, course_name):
def report_size(window): #debug to report window size for testing
print(window.winfo_width(), window.winfo_height())
def add_new_section(notebook, course):
s_frame = Section_Frame(notebook, course.addNewSection())
text = course.courseID + '-' + "{:02d}".format(course.sectionList[-1].sectionID)
# notebook.add(child=frame, text=text)
notebook.add(child=s_frame, text=text)
#generation of the course in question
#TODO show more than one course in the GUI at the same time
course = Course(course_ID, course_name)
course.printCourse()
course_window=tkinter.Toplevel()
#course_window.geometry('540x400')
#Menu Bar
menu_bar = tkinter.Menu(course_window)
file_menu = tkinter.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="Save", command=course.writeToFile)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=main_window.destroy)
menu_bar.add_cascade(label="File", menu=file_menu)
help_menu = tkinter.Menu(menu_bar, tearoff=0)
help_menu.add_command(label="About", command=lambda: About_Dialog(course_window)) #lamba fixes arguments
menu_bar.add_cascade(label="Help", menu=help_menu)
course_window.config(menu=menu_bar)
#window elements with course:
tkinter.Label(course_window, text = course.courseID + ' - ' + course_name, font=(None, 16)).grid(sticky='W', row=0, column= 0)
sections_notebook = ttk.Notebook(master=course_window)
sections_notebook.grid(row=2, columnspan=2, sticky='NS') # colspan is dirty button spacing fix
#Generate tables from current list
for section in course.sectionList:
section_frame = Section_Frame(sections_notebook, section)
sections_notebook.add(child=section_frame, text=course.courseID + '-' + "{:02d}".format(course.sectionList[-1].sectionID))
#placing course_window grid
tkinter.Button(course_window, text="Report size",
command=lambda: report_size(course_window)).grid(row=1, sticky='W')
add_button = tkinter.Button(course_window, text="Add Section",
command=lambda: add_new_section(sections_notebook, course))
add_button.grid(column=1, row=1, sticky='W')
tkinter.Button(course_window, text='Print Course',
command=course.printCourse).grid(row=3, sticky='w')
main_window = tkinter.Tk()
main_window.title("Class Grader")
#main_window.geometry('400x300')
new_course_button = tkinter.Button(main_window, text="New", state='normal', command=new_course)
test_course_button = tkinter.Button(main_window, text="Test", state='normal', command=test_course)
new_course_button.grid(column=0, row=0)
test_course_button.grid(column=0, row=1)
label = tkinter.Label(main_window, text='Create a new course')
label.grid(column=1, row=0)
# test_button = tkinter.Button(main_window, text="test", state='normal', command=new_course)
# test_button.grid(column=0, row=1) | super().__init__(parent, title="Enter Student Information:")
def body(self, master): | random_line_split |
gui.py | import tkinter
from tkinter import ttk
from tkinter import simpledialog
from tkinter import messagebox
from course import Course
from section import Section
class About_Dialog(simpledialog.Dialog):
def __init__(self, parent, title="Class Grader"):
super().__init__(parent, title=title)
def body (self, master):
description ="""
Class Grader is a college Python project
demonstrating I/O, classes, data structures, matplotlib, and tkinter.
Author: Thomas Bender
Contact: tbender4@gmail.com
This software is open source and is hosted on github.com/tbender4/Class-Grader"""
tkinter.Label(master, text=description).grid(column=0, row=0)
return master
def buttonbox(self):
# Similar to stock but only a close button
box = tkinter.Frame(self)
w = tkinter.Button(box, text="Close", width=10, command=self.cancel)
w.pack(side=tkinter.LEFT, padx=5, pady=5)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.cancel)
box.pack()
class New_Course(simpledialog.Dialog): #inherit tkinter.simpledialog
def __init__(self, parent):
self.new_course_ID = ""
self.new_course_name = ""
super().__init__(parent, title="Enter Course Information:") #inherited constructor needs original window
def body(self, master):
tkinter.Label(master, text="Course ID (ex: MAC108):").grid(column = 0, row=0, sticky='w')
tkinter.Label(master, text="Course Full Name (ex: Intro to Python):").grid(column = 0, row=1)
self.new_course_ID = tkinter.Entry(master)
self.new_course_name = tkinter.Entry(master)
self.new_course_ID.grid(column=1,row=0)
self.new_course_name.grid(column=1,row=1)
return None
def validate(self):
if self.new_course_ID.get().strip() == '' or self.new_course_name.get().strip() == '':
return 0
return 1
def apply(self):
print("apply hit")
print(str(self.new_course_ID.get()))
# self.parent.withdraw()
# TODO: Save this to the actual course data. Then draw window.
course_window(self.new_course_ID.get().strip(), self.new_course_name.get().strip())
class New_Student(simpledialog.Dialog): # inherit tkinter.simpledialog
def __init__(self, parent):
# inherited constructor needs original window
super().__init__(parent, title="Enter Student Information:")
def body(self, master):
tkinter.Label(master, text="Last Name").grid(
column=0, row=0, sticky='w')
tkinter.Label(master, text="First Name:").grid(
column=0, row=1)
self.last_name_entry = tkinter.Entry(master)
self.first_name_entry = tkinter.Entry(master)
self.last_name_entry.grid(column=1, row=0)
self.first_name_entry.grid(column=1, row=1)
return None
def validate(self):
if self.last_name_entry.get().strip() == '' or self.first_name_entry.get().strip() == '':
return 0
return 1
def apply(self):
|
class Section_Tree(ttk.Treeview): #table view. possibly rewrite with inheritance
def __init__(self, master, section=Course('MAC000', 'test_000').sectionList[0]):
# self.section_tree = section_tree
self.section = section
self.master = master
self.student_grade_list = self.section.student_grade_list
super().__init__(master)
#Tree view
#formatting columns
header_name_dict = {
# 'student_id':'ID',
'student_name': 'Name',
'attendance': 'Attendance',
'homework': 'Homework',
'quiz': 'Quiz',
'exam': 'Exam'
}
self['columns'] = list(header_name_dict.keys())
for key, value in header_name_dict.items():
self.column(key, width=50)
self.heading(key, text=value)
self.heading('#0', text='ID') #ID pertains to student ID
self.column('#0', width=40)
self.column('attendance', width=70)
self.column('homework', width=70)
self.column('student_name', width=180)
#inserting existing values from section
for student_grade in self.student_grade_list:
a, b, text, values = self.gen_child(student_grade)
#b, c, and d, e should be attendances, homeworks, quizzes, exams
self.insert(a, b, text=text, values=values)
def gen_child(self, student_grade, last_name = None, first_name = None):
#if options are provided, overwrite info with given info (should reflect in data as well)
if last_name != None and first_name != None:
student_grade['student'].last_name = last_name
student_grade['student'].first_name = first_name
student_grade['student'].updateLF()
student_ID = student_grade['student'].student_id
student_last = student_grade['student'].last_name
student_first = student_grade['student'].first_name
student_last_first = student_grade['student'].last_first
return ('', 'end', student_ID, (student_last_first , 'a', 'b', 'c', 'd'))
def add_student(self, last_name = 'test', first_name = 'name_man'):
# first gets the info. Then adds it to the section. then inserts the data into the tree.
# it's possible that the data may be reconstructed. so it's properly synced (need to decide best route)
# new_student = New_Student(self.master)
new_student = New_Student(self)
last_name = new_student.last_name
first_name = new_student.first_name
print('adding student:', last_name, first_name)
new_student_grade = self.section.addStudentGrade(last_name, first_name) #this adds a student_grade, not Student
print(new_student_grade)
a, b, text, values = self.gen_child(new_student_grade, last_name, first_name)
self.insert(a, b, text=text, values=values)
def edit_student(self):
# TODO: Have the whole student_grade be stored as a hidden value
focus = self.focus()
# print(focus[]
#this is dirty. doesn't save information properly
#Having the student as an argument would be best student would be best
l_f = self.item(focus)['values'][0].split(",")
last = l_f[0]
first = l_f[1]
print('test', l_f)
new_student = Edit_Student(self.master, last, first)
last_first = new_student.last_name + ', ' + new_student.first_name
self.item(focus, values=(last_first, new_student.att_avg, new_student.hw_avg, new_student.exam_avg, new_student.quiz_avg))
print(self.item(self.focus()))
class Edit_Student(simpledialog.Dialog): # inherit tkinter.simpledialog
def __init__(self, parent, last_name='l', first_name='f'):
# inherited constructor needs original window
self.last_name = last_name
self.first_name = first_name
super().__init__(parent, title="Edit Student Information:")
def body(self, master):
tkinter.Label(master, text="Last Name").grid(
column=0, row=0, sticky='e')
tkinter.Label(master, text="First Name:").grid(
column=0, row=1, sticky='e')
print(self.last_name, self.first_name)
self.last_name_entry = tkinter.Entry(master)
self.last_name_entry.insert(0, self.last_name)
self.first_name_entry = tkinter.Entry(master)
self.first_name_entry.insert(0, self.first_name)
self.last_name_entry.grid(column=1, row=0)
self.first_name_entry.grid(column=1, row=1)
tkinter.Label(master, text="Attendance\n(0 for absent, 1 for present):").grid(row=2)
tkinter.Label(master, text="Homework:\n(from 0 - 100)").grid(row=2, column=1)
tkinter.Label(master, text="Quiz:\n(from 0 - 100)").grid(row=2, column=2)
tkinter.Label(master, text="Exam:\n(from 0 - 100)").grid(row=2, column=3)
self.att_entry = []
for i in range(3,15):
entry = tkinter.Entry(master)
entry.insert(0, '0')
entry.grid(row=i, column = 0)
self.att_entry.append(entry)
self.hw_entry = []
for i in range(3, 15):
entry = tkinter.Entry(master)
entry.insert(0, '0')
entry.grid(row=i, column=1)
self.hw_entry.append(entry)
self.quiz_entry = []
for i in range(3, 15):
entry = tkinter.Entry(master)
entry.insert(0, '0')
entry.grid(row=i, column=2)
self.quiz_entry.append(entry)
self.exam_entry = []
for i in range(3, 7):
entry = tkinter.Entry(master)
entry.insert(0, '0')
entry.grid(row=i, column=3)
self.exam_entry.append(entry)
return None
def validate(self):
try:
for entry in self.att_entry:
value = int(entry.get().strip())
if value > 1 or value < 0:
return 0
for entry in self.hw_entry:
value = int(entry.get().strip())
if value > 100 or value < 0:
return 0
for entry in self.quiz_entry:
value = int(entry.get().strip())
if value > 100 or value < 0:
return 0
for entry in self.exam_entry:
value = int(entry.get().strip())
if value > 100 or value < 0:
return 0
except ValueError:
return 0
if self.last_name_entry.get().strip() == '' or self.first_name_entry.get().strip() == '':
return 0
return 1
def apply(self):
print("apply hit")
self.last_name = self.last_name_entry.get().strip()
self.first_name = self.first_name_entry.get().strip()
self.att_avg = 100 # reports back as percentage
att_sum = 0
for i in self.att_entry:
att_sum += int(i.get().strip())
print(att_sum)
self.att_avg = str(round(att_sum / len(self.att_entry) * 100, 2))+"%"
hw_sum = 0
for i in self.hw_entry:
hw_sum += int(i.get().strip()) / 100
self.hw_avg = str(round(hw_sum / len(self.hw_entry) * 100, 2))+"%"
quiz_sum = 0
for i in self.quiz_entry:
quiz_sum += int(i.get().strip()) / 100
self.quiz_avg = str(round(quiz_sum / len(self.quiz_entry) * 100, 2))+"%"
exam_sum = 0
for i in self.exam_entry:
exam_sum += int(i.get().strip()) / 100
self.exam_avg = str(round(exam_sum / len(self.exam_entry) * 100, 2))+"%"
class Section_Frame(tkinter.Frame):
# ---------------------
# ----------------
# | |
# | Tree |
# | |
# ----------------
# |add| |edit|
#
# ---------------------
def __init__(self, master, section = Section()):
super().__init__(master)
section_tree = Section_Tree(self, section)
add_button = tkinter.Button(self, text='Add Student', command = section_tree.add_student)
edit_button = tkinter.Button(self, text='Edit Student', command = section_tree.edit_student)
section_tree.grid(row=0,columnspan=2)
add_button.grid(row=1, column = 0)
edit_button.grid(row=1, column=1)
# tkinter.Label(self, text='Custom frame').grid(row=0)
def new_course():
New_Course(main_window)
def test_course():
course_window('MAC000', 'Intro to Testing')
def course_window(course_ID, course_name):
def report_size(window): #debug to report window size for testing
print(window.winfo_width(), window.winfo_height())
def add_new_section(notebook, course):
s_frame = Section_Frame(notebook, course.addNewSection())
text = course.courseID + '-' + "{:02d}".format(course.sectionList[-1].sectionID)
# notebook.add(child=frame, text=text)
notebook.add(child=s_frame, text=text)
#generation of the course in question
#TODO show more than one course in the GUI at the same time
course = Course(course_ID, course_name)
course.printCourse()
course_window=tkinter.Toplevel()
#course_window.geometry('540x400')
#Menu Bar
menu_bar = tkinter.Menu(course_window)
file_menu = tkinter.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="Save", command=course.writeToFile)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=main_window.destroy)
menu_bar.add_cascade(label="File", menu=file_menu)
help_menu = tkinter.Menu(menu_bar, tearoff=0)
help_menu.add_command(label="About", command=lambda: About_Dialog(course_window)) #lamba fixes arguments
menu_bar.add_cascade(label="Help", menu=help_menu)
course_window.config(menu=menu_bar)
#window elements with course:
tkinter.Label(course_window, text = course.courseID + ' - ' + course_name, font=(None, 16)).grid(sticky='W', row=0, column= 0)
sections_notebook = ttk.Notebook(master=course_window)
sections_notebook.grid(row=2, columnspan=2, sticky='NS') # colspan is dirty button spacing fix
#Generate tables from current list
for section in course.sectionList:
section_frame = Section_Frame(sections_notebook, section)
sections_notebook.add(child=section_frame, text=course.courseID + '-' + "{:02d}".format(course.sectionList[-1].sectionID))
#placing course_window grid
tkinter.Button(course_window, text="Report size",
command=lambda: report_size(course_window)).grid(row=1, sticky='W')
add_button = tkinter.Button(course_window, text="Add Section",
command=lambda: add_new_section(sections_notebook, course))
add_button.grid(column=1, row=1, sticky='W')
tkinter.Button(course_window, text='Print Course',
command=course.printCourse).grid(row=3, sticky='w')
main_window = tkinter.Tk()
main_window.title("Class Grader")
#main_window.geometry('400x300')
new_course_button = tkinter.Button(main_window, text="New", state='normal', command=new_course)
test_course_button = tkinter.Button(main_window, text="Test", state='normal', command=test_course)
new_course_button.grid(column=0, row=0)
test_course_button.grid(column=0, row=1)
label = tkinter.Label(main_window, text='Create a new course')
label.grid(column=1, row=0)
# test_button = tkinter.Button(main_window, text="test", state='normal', command=new_course)
# test_button.grid(column=0, row=1)
| print("apply hit")
self.last_name = self.last_name_entry.get().strip()
self.first_name = self.first_name_entry.get().strip() | identifier_body |
txn.go | package internal
import (
"errors"
"net/http"
"strconv"
"sync"
"time"
"github.com/newrelic/go-agent/api"
"github.com/newrelic/go-agent/api/datastore"
"github.com/newrelic/go-agent/log"
)
type txnInput struct {
W http.ResponseWriter
Request *http.Request
Config api.Config
Reply *ConnectReply
Consumer dataConsumer
attrConfig *attributeConfig
}
type txn struct {
txnInput
// This mutex is required since the consumer may call the public API
// interface functions from different routines.
sync.Mutex
// finished indicates whether or not End() has been called. After
// finished has been set to true, no recording should occur.
finished bool
queuing time.Duration
start time.Time
name string // Work in progress name
isWeb bool
ignore bool
errors txnErrors // Lazily initialized.
errorsSeen uint64
attrs *attributes
// Fields relating to tracing and breakdown metrics/segments.
tracer tracer
// wroteHeader prevents capturing multiple response code errors if the
// user erroneously calls WriteHeader multiple times.
wroteHeader bool
// Fields assigned at completion
stop time.Time
duration time.Duration
finalName string // Full finalized metric name
zone apdexZone
apdexThreshold time.Duration
}
func newTxn(input txnInput, name string) *txn |
func (txn *txn) txnEventsEnabled() bool {
return txn.Config.TransactionEvents.Enabled &&
txn.Reply.CollectAnalyticsEvents
}
func (txn *txn) errorEventsEnabled() bool {
return txn.Config.ErrorCollector.CaptureEvents &&
txn.Reply.CollectErrorEvents
}
func (txn *txn) freezeName() {
if txn.ignore || ("" != txn.finalName) {
return
}
txn.finalName = CreateFullTxnName(txn.name, txn.Reply, txn.isWeb)
if "" == txn.finalName {
txn.ignore = true
}
}
func (txn *txn) getsApdex() bool {
return txn.isWeb
}
type createTxnMetricsArgs struct {
isWeb bool
duration time.Duration
exclusive time.Duration
name string
zone apdexZone
apdexThreshold time.Duration
errorsSeen uint64
}
func createTxnMetrics(args createTxnMetricsArgs, metrics *metricTable) {
// Duration Metrics
rollup := backgroundRollup
if args.isWeb {
rollup = webRollup
metrics.addDuration(dispatcherMetric, "", args.duration, 0, forced)
}
metrics.addDuration(args.name, "", args.duration, args.exclusive, forced)
metrics.addDuration(rollup, "", args.duration, args.exclusive, forced)
// Apdex Metrics
if args.zone != apdexNone {
metrics.addApdex(apdexRollup, "", args.apdexThreshold, args.zone, forced)
mname := apdexPrefix + removeFirstSegment(args.name)
metrics.addApdex(mname, "", args.apdexThreshold, args.zone, unforced)
}
// Error Metrics
if args.errorsSeen > 0 {
metrics.addSingleCount(errorsAll, forced)
if args.isWeb {
metrics.addSingleCount(errorsWeb, forced)
} else {
metrics.addSingleCount(errorsBackground, forced)
}
metrics.addSingleCount(errorsPrefix+args.name, forced)
}
}
func (txn *txn) mergeIntoHarvest(h *harvest) {
exclusive := time.Duration(0)
children := tracerRootChildren(&txn.tracer)
if txn.duration > children {
exclusive = txn.duration - children
}
createTxnMetrics(createTxnMetricsArgs{
isWeb: txn.isWeb,
duration: txn.duration,
exclusive: exclusive,
name: txn.finalName,
zone: txn.zone,
apdexThreshold: txn.apdexThreshold,
errorsSeen: txn.errorsSeen,
}, h.metrics)
if txn.queuing > 0 {
h.metrics.addDuration(queueMetric, "", txn.queuing, txn.queuing, forced)
}
mergeBreakdownMetrics(&txn.tracer, h.metrics, txn.finalName, txn.isWeb)
if txn.txnEventsEnabled() {
h.txnEvents.AddTxnEvent(&txnEvent{
Name: txn.finalName,
Timestamp: txn.start,
Duration: txn.duration,
queuing: txn.queuing,
zone: txn.zone,
attrs: txn.attrs,
datastoreExternalTotals: txn.tracer.datastoreExternalTotals,
})
}
requestURI := ""
if nil != txn.Request && nil != txn.Request.URL {
requestURI = safeURL(txn.Request.URL)
}
mergeTxnErrors(h.errorTraces, txn.errors, txn.finalName, requestURI, txn.attrs)
if txn.errorEventsEnabled() {
for _, e := range txn.errors {
h.errorEvents.Add(&errorEvent{
klass: e.klass,
msg: e.msg,
when: e.when,
txnName: txn.finalName,
duration: txn.duration,
queuing: txn.queuing,
attrs: txn.attrs,
datastoreExternalTotals: txn.tracer.datastoreExternalTotals,
})
}
}
}
func responseCodeIsError(cfg *api.Config, code int) bool {
if code < http.StatusBadRequest { // 400
return false
}
for _, ignoreCode := range cfg.ErrorCollector.IgnoreStatusCodes {
if code == ignoreCode {
return false
}
}
return true
}
var (
// statusCodeLookup avoids a strconv.Itoa call.
statusCodeLookup = map[int]string{
100: "100", 101: "101",
200: "200", 201: "201", 202: "202", 203: "203", 204: "204", 205: "205", 206: "206",
300: "300", 301: "301", 302: "302", 303: "303", 304: "304", 305: "305", 307: "307",
400: "400", 401: "401", 402: "402", 403: "403", 404: "404", 405: "405", 406: "406",
407: "407", 408: "408", 409: "409", 410: "410", 411: "411", 412: "412", 413: "413",
414: "414", 415: "415", 416: "416", 417: "417", 418: "418", 428: "428", 429: "429",
431: "431", 451: "451",
500: "500", 501: "501", 502: "502", 503: "503", 504: "504", 505: "505", 511: "511",
}
)
func headersJustWritten(txn *txn, code int) {
if txn.finished {
return
}
if txn.wroteHeader {
return
}
txn.wroteHeader = true
h := txn.W.Header()
txn.attrs.agent.ResponseHeadersContentType = h.Get("Content-Type")
if val := h.Get("Content-Length"); "" != val {
if x, err := strconv.Atoi(val); nil == err {
txn.attrs.agent.ResponseHeadersContentLength = x
}
}
txn.attrs.agent.ResponseCode = statusCodeLookup[code]
if txn.attrs.agent.ResponseCode == "" {
txn.attrs.agent.ResponseCode = strconv.Itoa(code)
}
if responseCodeIsError(&txn.Config, code) {
e := txnErrorFromResponseCode(code)
e.stack = getStackTrace(1)
txn.noticeErrorInternal(e)
}
}
func (txn *txn) Header() http.Header { return txn.W.Header() }
func (txn *txn) Write(b []byte) (int, error) {
n, err := txn.W.Write(b)
txn.Lock()
defer txn.Unlock()
headersJustWritten(txn, http.StatusOK)
return n, err
}
func (txn *txn) WriteHeader(code int) {
txn.W.WriteHeader(code)
txn.Lock()
defer txn.Unlock()
headersJustWritten(txn, code)
}
var (
// ErrAlreadyEnded is returned by public txn methods if End() has
// already been called.
ErrAlreadyEnded = errors.New("transaction has already ended")
)
func (txn *txn) End() error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
txn.finished = true
r := recover()
if nil != r {
e := txnErrorFromPanic(r)
e.stack = getStackTrace(0)
txn.noticeErrorInternal(e)
}
txn.stop = time.Now()
txn.duration = txn.stop.Sub(txn.start)
txn.freezeName()
if txn.getsApdex() {
txn.apdexThreshold = calculateApdexThreshold(txn.Reply, txn.finalName)
if txn.errorsSeen > 0 {
txn.zone = apdexFailing
} else {
txn.zone = calculateApdexZone(txn.apdexThreshold, txn.duration)
}
} else {
txn.zone = apdexNone
}
if log.DebugEnabled() {
log.Debug("transaction ended", log.Context{
"name": txn.finalName,
"duration_ms": txn.duration.Seconds() * 1000.0,
"ignored": txn.ignore,
"run": txn.Reply.RunID,
})
}
if !txn.ignore {
txn.Consumer.consume(txn.Reply.RunID, txn)
}
// Note that if a consumer uses `panic(nil)`, the panic will not
// propogate.
if nil != r {
panic(r)
}
return nil
}
func (txn *txn) AddAttribute(name string, value interface{}) error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
return addUserAttribute(txn.attrs, name, value, destAll)
}
var (
// ErrorsLocallyDisabled is returned if error capture is disabled by
// local configuration.
ErrorsLocallyDisabled = errors.New("errors locally disabled")
// ErrorsRemotelyDisabled is returned if error capture is disabled
// by remote configuration.
ErrorsRemotelyDisabled = errors.New("errors remotely disabled")
// ErrNilError is returned if the provided error is nil.
ErrNilError = errors.New("nil error")
)
const (
// HighSecurityErrorMsg is used in place of the error's message
// (err.String()) when high security moed is enabled.
HighSecurityErrorMsg = "message removed by high security setting"
)
func (txn *txn) noticeErrorInternal(err txnError) error {
// Increment errorsSeen even if errors are disabled: Error metrics do
// not depend on whether or not errors are enabled.
txn.errorsSeen++
if !txn.Config.ErrorCollector.Enabled {
return ErrorsLocallyDisabled
}
if !txn.Reply.CollectErrors {
return ErrorsRemotelyDisabled
}
if nil == txn.errors {
txn.errors = newTxnErrors(maxTxnErrors)
}
if txn.Config.HighSecurity {
err.msg = HighSecurityErrorMsg
}
err.when = time.Now()
txn.errors.Add(&err)
return nil
}
func (txn *txn) NoticeError(err error) error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
if nil == err {
return ErrNilError
}
e := txnErrorFromError(err)
e.stack = getStackTrace(2)
return txn.noticeErrorInternal(e)
}
func (txn *txn) SetName(name string) error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
txn.name = name
return nil
}
func (txn *txn) Ignore() error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
txn.ignore = true
return nil
}
func (txn *txn) StartSegment() api.Token {
token := invalidToken
txn.Lock()
if !txn.finished {
token = startSegment(&txn.tracer, time.Now())
}
txn.Unlock()
return token
}
func (txn *txn) EndSegment(token api.Token, name string) {
txn.Lock()
if !txn.finished {
endBasicSegment(&txn.tracer, token, time.Now(), name)
}
txn.Unlock()
}
func (txn *txn) EndDatastore(token api.Token, s datastore.Segment) {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return
}
endDatastoreSegment(&txn.tracer, token, time.Now(), s)
}
func (txn *txn) EndExternal(token api.Token, url string) {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return
}
endExternalSegment(&txn.tracer, token, time.Now(), hostFromExternalURL(url))
}
func (txn *txn) PrepareRequest(token api.Token, request *http.Request) {
txn.Lock()
defer txn.Unlock()
// TODO: handle request CAT headers
}
func hostFromRequestResponse(request *http.Request, response *http.Response) string {
if nil != response && nil != response.Request {
request = response.Request
}
if nil == request || nil == request.URL {
return ""
}
if "" != request.URL.Opaque {
return "opaque"
}
return request.URL.Host
}
func (txn *txn) EndRequest(token api.Token, request *http.Request, response *http.Response) {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return
}
// TODO: handle response CAT headers
host := hostFromRequestResponse(request, response)
endExternalSegment(&txn.tracer, token, time.Now(), host)
}
| {
txn := &txn{
txnInput: input,
start: time.Now(),
name: name,
isWeb: nil != input.Request,
attrs: newAttributes(input.attrConfig),
}
if nil != txn.Request {
h := input.Request.Header
txn.attrs.agent.RequestMethod = input.Request.Method
txn.attrs.agent.RequestAcceptHeader = h.Get("Accept")
txn.attrs.agent.RequestContentType = h.Get("Content-Type")
txn.attrs.agent.RequestHeadersHost = h.Get("Host")
txn.attrs.agent.RequestHeadersUserAgent = h.Get("User-Agent")
txn.attrs.agent.RequestHeadersReferer = safeURLFromString(h.Get("Referer"))
if cl := h.Get("Content-Length"); "" != cl {
if x, err := strconv.Atoi(cl); nil == err {
txn.attrs.agent.RequestContentLength = x
}
}
txn.queuing = queueDuration(h, txn.start)
}
txn.attrs.agent.HostDisplayName = txn.Config.HostDisplayName
return txn
} | identifier_body |
txn.go | package internal
import (
"errors"
"net/http"
"strconv"
"sync"
"time"
"github.com/newrelic/go-agent/api"
"github.com/newrelic/go-agent/api/datastore"
"github.com/newrelic/go-agent/log"
)
type txnInput struct {
W http.ResponseWriter
Request *http.Request
Config api.Config
Reply *ConnectReply
Consumer dataConsumer
attrConfig *attributeConfig
}
type txn struct {
txnInput
// This mutex is required since the consumer may call the public API
// interface functions from different routines.
sync.Mutex
// finished indicates whether or not End() has been called. After
// finished has been set to true, no recording should occur.
finished bool
queuing time.Duration
start time.Time
name string // Work in progress name
isWeb bool
ignore bool
errors txnErrors // Lazily initialized.
errorsSeen uint64
attrs *attributes
// Fields relating to tracing and breakdown metrics/segments.
tracer tracer
// wroteHeader prevents capturing multiple response code errors if the
// user erroneously calls WriteHeader multiple times.
wroteHeader bool
// Fields assigned at completion
stop time.Time
duration time.Duration
finalName string // Full finalized metric name
zone apdexZone
apdexThreshold time.Duration
}
func newTxn(input txnInput, name string) *txn {
txn := &txn{
txnInput: input,
start: time.Now(),
name: name,
isWeb: nil != input.Request,
attrs: newAttributes(input.attrConfig),
}
if nil != txn.Request {
h := input.Request.Header
txn.attrs.agent.RequestMethod = input.Request.Method
txn.attrs.agent.RequestAcceptHeader = h.Get("Accept")
txn.attrs.agent.RequestContentType = h.Get("Content-Type")
txn.attrs.agent.RequestHeadersHost = h.Get("Host")
txn.attrs.agent.RequestHeadersUserAgent = h.Get("User-Agent")
txn.attrs.agent.RequestHeadersReferer = safeURLFromString(h.Get("Referer"))
if cl := h.Get("Content-Length"); "" != cl {
if x, err := strconv.Atoi(cl); nil == err {
txn.attrs.agent.RequestContentLength = x
}
}
txn.queuing = queueDuration(h, txn.start)
}
txn.attrs.agent.HostDisplayName = txn.Config.HostDisplayName
return txn
}
func (txn *txn) txnEventsEnabled() bool {
return txn.Config.TransactionEvents.Enabled &&
txn.Reply.CollectAnalyticsEvents
}
func (txn *txn) errorEventsEnabled() bool {
return txn.Config.ErrorCollector.CaptureEvents &&
txn.Reply.CollectErrorEvents
}
func (txn *txn) freezeName() {
if txn.ignore || ("" != txn.finalName) {
return
}
txn.finalName = CreateFullTxnName(txn.name, txn.Reply, txn.isWeb)
if "" == txn.finalName {
txn.ignore = true
}
}
func (txn *txn) getsApdex() bool {
return txn.isWeb
}
type createTxnMetricsArgs struct {
isWeb bool
duration time.Duration
exclusive time.Duration
name string
zone apdexZone
apdexThreshold time.Duration
errorsSeen uint64
}
func createTxnMetrics(args createTxnMetricsArgs, metrics *metricTable) {
// Duration Metrics
rollup := backgroundRollup
if args.isWeb {
rollup = webRollup
metrics.addDuration(dispatcherMetric, "", args.duration, 0, forced)
}
metrics.addDuration(args.name, "", args.duration, args.exclusive, forced)
metrics.addDuration(rollup, "", args.duration, args.exclusive, forced)
// Apdex Metrics
if args.zone != apdexNone {
metrics.addApdex(apdexRollup, "", args.apdexThreshold, args.zone, forced)
mname := apdexPrefix + removeFirstSegment(args.name)
metrics.addApdex(mname, "", args.apdexThreshold, args.zone, unforced)
}
// Error Metrics
if args.errorsSeen > 0 {
metrics.addSingleCount(errorsAll, forced)
if args.isWeb {
metrics.addSingleCount(errorsWeb, forced)
} else {
metrics.addSingleCount(errorsBackground, forced)
}
metrics.addSingleCount(errorsPrefix+args.name, forced)
}
}
func (txn *txn) mergeIntoHarvest(h *harvest) {
exclusive := time.Duration(0)
children := tracerRootChildren(&txn.tracer)
if txn.duration > children {
exclusive = txn.duration - children
}
createTxnMetrics(createTxnMetricsArgs{
isWeb: txn.isWeb,
duration: txn.duration,
exclusive: exclusive,
name: txn.finalName,
zone: txn.zone,
apdexThreshold: txn.apdexThreshold,
errorsSeen: txn.errorsSeen,
}, h.metrics)
if txn.queuing > 0 {
h.metrics.addDuration(queueMetric, "", txn.queuing, txn.queuing, forced)
}
mergeBreakdownMetrics(&txn.tracer, h.metrics, txn.finalName, txn.isWeb)
if txn.txnEventsEnabled() {
h.txnEvents.AddTxnEvent(&txnEvent{
Name: txn.finalName,
Timestamp: txn.start,
Duration: txn.duration,
queuing: txn.queuing,
zone: txn.zone,
attrs: txn.attrs,
datastoreExternalTotals: txn.tracer.datastoreExternalTotals,
})
}
requestURI := ""
if nil != txn.Request && nil != txn.Request.URL {
requestURI = safeURL(txn.Request.URL)
}
mergeTxnErrors(h.errorTraces, txn.errors, txn.finalName, requestURI, txn.attrs)
if txn.errorEventsEnabled() {
for _, e := range txn.errors {
h.errorEvents.Add(&errorEvent{
klass: e.klass,
msg: e.msg,
when: e.when,
txnName: txn.finalName,
duration: txn.duration,
queuing: txn.queuing,
attrs: txn.attrs,
datastoreExternalTotals: txn.tracer.datastoreExternalTotals,
})
}
}
}
func responseCodeIsError(cfg *api.Config, code int) bool {
if code < http.StatusBadRequest { // 400
return false
}
for _, ignoreCode := range cfg.ErrorCollector.IgnoreStatusCodes {
if code == ignoreCode {
return false
}
}
return true
}
var (
// statusCodeLookup avoids a strconv.Itoa call.
statusCodeLookup = map[int]string{
100: "100", 101: "101",
200: "200", 201: "201", 202: "202", 203: "203", 204: "204", 205: "205", 206: "206",
300: "300", 301: "301", 302: "302", 303: "303", 304: "304", 305: "305", 307: "307",
400: "400", 401: "401", 402: "402", 403: "403", 404: "404", 405: "405", 406: "406",
407: "407", 408: "408", 409: "409", 410: "410", 411: "411", 412: "412", 413: "413",
414: "414", 415: "415", 416: "416", 417: "417", 418: "418", 428: "428", 429: "429",
431: "431", 451: "451",
500: "500", 501: "501", 502: "502", 503: "503", 504: "504", 505: "505", 511: "511",
}
)
func headersJustWritten(txn *txn, code int) {
if txn.finished {
return
}
if txn.wroteHeader {
return
}
txn.wroteHeader = true
h := txn.W.Header()
txn.attrs.agent.ResponseHeadersContentType = h.Get("Content-Type") | }
txn.attrs.agent.ResponseCode = statusCodeLookup[code]
if txn.attrs.agent.ResponseCode == "" {
txn.attrs.agent.ResponseCode = strconv.Itoa(code)
}
if responseCodeIsError(&txn.Config, code) {
e := txnErrorFromResponseCode(code)
e.stack = getStackTrace(1)
txn.noticeErrorInternal(e)
}
}
func (txn *txn) Header() http.Header { return txn.W.Header() }
func (txn *txn) Write(b []byte) (int, error) {
n, err := txn.W.Write(b)
txn.Lock()
defer txn.Unlock()
headersJustWritten(txn, http.StatusOK)
return n, err
}
func (txn *txn) WriteHeader(code int) {
txn.W.WriteHeader(code)
txn.Lock()
defer txn.Unlock()
headersJustWritten(txn, code)
}
var (
// ErrAlreadyEnded is returned by public txn methods if End() has
// already been called.
ErrAlreadyEnded = errors.New("transaction has already ended")
)
func (txn *txn) End() error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
txn.finished = true
r := recover()
if nil != r {
e := txnErrorFromPanic(r)
e.stack = getStackTrace(0)
txn.noticeErrorInternal(e)
}
txn.stop = time.Now()
txn.duration = txn.stop.Sub(txn.start)
txn.freezeName()
if txn.getsApdex() {
txn.apdexThreshold = calculateApdexThreshold(txn.Reply, txn.finalName)
if txn.errorsSeen > 0 {
txn.zone = apdexFailing
} else {
txn.zone = calculateApdexZone(txn.apdexThreshold, txn.duration)
}
} else {
txn.zone = apdexNone
}
if log.DebugEnabled() {
log.Debug("transaction ended", log.Context{
"name": txn.finalName,
"duration_ms": txn.duration.Seconds() * 1000.0,
"ignored": txn.ignore,
"run": txn.Reply.RunID,
})
}
if !txn.ignore {
txn.Consumer.consume(txn.Reply.RunID, txn)
}
// Note that if a consumer uses `panic(nil)`, the panic will not
// propogate.
if nil != r {
panic(r)
}
return nil
}
func (txn *txn) AddAttribute(name string, value interface{}) error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
return addUserAttribute(txn.attrs, name, value, destAll)
}
var (
// ErrorsLocallyDisabled is returned if error capture is disabled by
// local configuration.
ErrorsLocallyDisabled = errors.New("errors locally disabled")
// ErrorsRemotelyDisabled is returned if error capture is disabled
// by remote configuration.
ErrorsRemotelyDisabled = errors.New("errors remotely disabled")
// ErrNilError is returned if the provided error is nil.
ErrNilError = errors.New("nil error")
)
const (
// HighSecurityErrorMsg is used in place of the error's message
// (err.String()) when high security moed is enabled.
HighSecurityErrorMsg = "message removed by high security setting"
)
func (txn *txn) noticeErrorInternal(err txnError) error {
// Increment errorsSeen even if errors are disabled: Error metrics do
// not depend on whether or not errors are enabled.
txn.errorsSeen++
if !txn.Config.ErrorCollector.Enabled {
return ErrorsLocallyDisabled
}
if !txn.Reply.CollectErrors {
return ErrorsRemotelyDisabled
}
if nil == txn.errors {
txn.errors = newTxnErrors(maxTxnErrors)
}
if txn.Config.HighSecurity {
err.msg = HighSecurityErrorMsg
}
err.when = time.Now()
txn.errors.Add(&err)
return nil
}
func (txn *txn) NoticeError(err error) error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
if nil == err {
return ErrNilError
}
e := txnErrorFromError(err)
e.stack = getStackTrace(2)
return txn.noticeErrorInternal(e)
}
func (txn *txn) SetName(name string) error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
txn.name = name
return nil
}
func (txn *txn) Ignore() error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
txn.ignore = true
return nil
}
func (txn *txn) StartSegment() api.Token {
token := invalidToken
txn.Lock()
if !txn.finished {
token = startSegment(&txn.tracer, time.Now())
}
txn.Unlock()
return token
}
func (txn *txn) EndSegment(token api.Token, name string) {
txn.Lock()
if !txn.finished {
endBasicSegment(&txn.tracer, token, time.Now(), name)
}
txn.Unlock()
}
func (txn *txn) EndDatastore(token api.Token, s datastore.Segment) {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return
}
endDatastoreSegment(&txn.tracer, token, time.Now(), s)
}
func (txn *txn) EndExternal(token api.Token, url string) {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return
}
endExternalSegment(&txn.tracer, token, time.Now(), hostFromExternalURL(url))
}
func (txn *txn) PrepareRequest(token api.Token, request *http.Request) {
txn.Lock()
defer txn.Unlock()
// TODO: handle request CAT headers
}
func hostFromRequestResponse(request *http.Request, response *http.Response) string {
if nil != response && nil != response.Request {
request = response.Request
}
if nil == request || nil == request.URL {
return ""
}
if "" != request.URL.Opaque {
return "opaque"
}
return request.URL.Host
}
func (txn *txn) EndRequest(token api.Token, request *http.Request, response *http.Response) {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return
}
// TODO: handle response CAT headers
host := hostFromRequestResponse(request, response)
endExternalSegment(&txn.tracer, token, time.Now(), host)
} |
if val := h.Get("Content-Length"); "" != val {
if x, err := strconv.Atoi(val); nil == err {
txn.attrs.agent.ResponseHeadersContentLength = x
} | random_line_split |
txn.go | package internal
import (
"errors"
"net/http"
"strconv"
"sync"
"time"
"github.com/newrelic/go-agent/api"
"github.com/newrelic/go-agent/api/datastore"
"github.com/newrelic/go-agent/log"
)
type txnInput struct {
W http.ResponseWriter
Request *http.Request
Config api.Config
Reply *ConnectReply
Consumer dataConsumer
attrConfig *attributeConfig
}
type txn struct {
txnInput
// This mutex is required since the consumer may call the public API
// interface functions from different routines.
sync.Mutex
// finished indicates whether or not End() has been called. After
// finished has been set to true, no recording should occur.
finished bool
queuing time.Duration
start time.Time
name string // Work in progress name
isWeb bool
ignore bool
errors txnErrors // Lazily initialized.
errorsSeen uint64
attrs *attributes
// Fields relating to tracing and breakdown metrics/segments.
tracer tracer
// wroteHeader prevents capturing multiple response code errors if the
// user erroneously calls WriteHeader multiple times.
wroteHeader bool
// Fields assigned at completion
stop time.Time
duration time.Duration
finalName string // Full finalized metric name
zone apdexZone
apdexThreshold time.Duration
}
func newTxn(input txnInput, name string) *txn {
txn := &txn{
txnInput: input,
start: time.Now(),
name: name,
isWeb: nil != input.Request,
attrs: newAttributes(input.attrConfig),
}
if nil != txn.Request {
h := input.Request.Header
txn.attrs.agent.RequestMethod = input.Request.Method
txn.attrs.agent.RequestAcceptHeader = h.Get("Accept")
txn.attrs.agent.RequestContentType = h.Get("Content-Type")
txn.attrs.agent.RequestHeadersHost = h.Get("Host")
txn.attrs.agent.RequestHeadersUserAgent = h.Get("User-Agent")
txn.attrs.agent.RequestHeadersReferer = safeURLFromString(h.Get("Referer"))
if cl := h.Get("Content-Length"); "" != cl {
if x, err := strconv.Atoi(cl); nil == err {
txn.attrs.agent.RequestContentLength = x
}
}
txn.queuing = queueDuration(h, txn.start)
}
txn.attrs.agent.HostDisplayName = txn.Config.HostDisplayName
return txn
}
func (txn *txn) txnEventsEnabled() bool {
return txn.Config.TransactionEvents.Enabled &&
txn.Reply.CollectAnalyticsEvents
}
func (txn *txn) errorEventsEnabled() bool {
return txn.Config.ErrorCollector.CaptureEvents &&
txn.Reply.CollectErrorEvents
}
func (txn *txn) freezeName() {
if txn.ignore || ("" != txn.finalName) {
return
}
txn.finalName = CreateFullTxnName(txn.name, txn.Reply, txn.isWeb)
if "" == txn.finalName {
txn.ignore = true
}
}
func (txn *txn) getsApdex() bool {
return txn.isWeb
}
type createTxnMetricsArgs struct {
isWeb bool
duration time.Duration
exclusive time.Duration
name string
zone apdexZone
apdexThreshold time.Duration
errorsSeen uint64
}
func createTxnMetrics(args createTxnMetricsArgs, metrics *metricTable) {
// Duration Metrics
rollup := backgroundRollup
if args.isWeb {
rollup = webRollup
metrics.addDuration(dispatcherMetric, "", args.duration, 0, forced)
}
metrics.addDuration(args.name, "", args.duration, args.exclusive, forced)
metrics.addDuration(rollup, "", args.duration, args.exclusive, forced)
// Apdex Metrics
if args.zone != apdexNone {
metrics.addApdex(apdexRollup, "", args.apdexThreshold, args.zone, forced)
mname := apdexPrefix + removeFirstSegment(args.name)
metrics.addApdex(mname, "", args.apdexThreshold, args.zone, unforced)
}
// Error Metrics
if args.errorsSeen > 0 {
metrics.addSingleCount(errorsAll, forced)
if args.isWeb {
metrics.addSingleCount(errorsWeb, forced)
} else {
metrics.addSingleCount(errorsBackground, forced)
}
metrics.addSingleCount(errorsPrefix+args.name, forced)
}
}
func (txn *txn) mergeIntoHarvest(h *harvest) {
exclusive := time.Duration(0)
children := tracerRootChildren(&txn.tracer)
if txn.duration > children {
exclusive = txn.duration - children
}
createTxnMetrics(createTxnMetricsArgs{
isWeb: txn.isWeb,
duration: txn.duration,
exclusive: exclusive,
name: txn.finalName,
zone: txn.zone,
apdexThreshold: txn.apdexThreshold,
errorsSeen: txn.errorsSeen,
}, h.metrics)
if txn.queuing > 0 {
h.metrics.addDuration(queueMetric, "", txn.queuing, txn.queuing, forced)
}
mergeBreakdownMetrics(&txn.tracer, h.metrics, txn.finalName, txn.isWeb)
if txn.txnEventsEnabled() {
h.txnEvents.AddTxnEvent(&txnEvent{
Name: txn.finalName,
Timestamp: txn.start,
Duration: txn.duration,
queuing: txn.queuing,
zone: txn.zone,
attrs: txn.attrs,
datastoreExternalTotals: txn.tracer.datastoreExternalTotals,
})
}
requestURI := ""
if nil != txn.Request && nil != txn.Request.URL {
requestURI = safeURL(txn.Request.URL)
}
mergeTxnErrors(h.errorTraces, txn.errors, txn.finalName, requestURI, txn.attrs)
if txn.errorEventsEnabled() {
for _, e := range txn.errors {
h.errorEvents.Add(&errorEvent{
klass: e.klass,
msg: e.msg,
when: e.when,
txnName: txn.finalName,
duration: txn.duration,
queuing: txn.queuing,
attrs: txn.attrs,
datastoreExternalTotals: txn.tracer.datastoreExternalTotals,
})
}
}
}
func responseCodeIsError(cfg *api.Config, code int) bool {
if code < http.StatusBadRequest { // 400
return false
}
for _, ignoreCode := range cfg.ErrorCollector.IgnoreStatusCodes {
if code == ignoreCode {
return false
}
}
return true
}
var (
// statusCodeLookup avoids a strconv.Itoa call.
statusCodeLookup = map[int]string{
100: "100", 101: "101",
200: "200", 201: "201", 202: "202", 203: "203", 204: "204", 205: "205", 206: "206",
300: "300", 301: "301", 302: "302", 303: "303", 304: "304", 305: "305", 307: "307",
400: "400", 401: "401", 402: "402", 403: "403", 404: "404", 405: "405", 406: "406",
407: "407", 408: "408", 409: "409", 410: "410", 411: "411", 412: "412", 413: "413",
414: "414", 415: "415", 416: "416", 417: "417", 418: "418", 428: "428", 429: "429",
431: "431", 451: "451",
500: "500", 501: "501", 502: "502", 503: "503", 504: "504", 505: "505", 511: "511",
}
)
func headersJustWritten(txn *txn, code int) {
if txn.finished {
return
}
if txn.wroteHeader {
return
}
txn.wroteHeader = true
h := txn.W.Header()
txn.attrs.agent.ResponseHeadersContentType = h.Get("Content-Type")
if val := h.Get("Content-Length"); "" != val {
if x, err := strconv.Atoi(val); nil == err {
txn.attrs.agent.ResponseHeadersContentLength = x
}
}
txn.attrs.agent.ResponseCode = statusCodeLookup[code]
if txn.attrs.agent.ResponseCode == "" {
txn.attrs.agent.ResponseCode = strconv.Itoa(code)
}
if responseCodeIsError(&txn.Config, code) {
e := txnErrorFromResponseCode(code)
e.stack = getStackTrace(1)
txn.noticeErrorInternal(e)
}
}
func (txn *txn) Header() http.Header { return txn.W.Header() }
func (txn *txn) Write(b []byte) (int, error) {
n, err := txn.W.Write(b)
txn.Lock()
defer txn.Unlock()
headersJustWritten(txn, http.StatusOK)
return n, err
}
func (txn *txn) WriteHeader(code int) {
txn.W.WriteHeader(code)
txn.Lock()
defer txn.Unlock()
headersJustWritten(txn, code)
}
var (
// ErrAlreadyEnded is returned by public txn methods if End() has
// already been called.
ErrAlreadyEnded = errors.New("transaction has already ended")
)
func (txn *txn) End() error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
txn.finished = true
r := recover()
if nil != r {
e := txnErrorFromPanic(r)
e.stack = getStackTrace(0)
txn.noticeErrorInternal(e)
}
txn.stop = time.Now()
txn.duration = txn.stop.Sub(txn.start)
txn.freezeName()
if txn.getsApdex() {
txn.apdexThreshold = calculateApdexThreshold(txn.Reply, txn.finalName)
if txn.errorsSeen > 0 {
txn.zone = apdexFailing
} else {
txn.zone = calculateApdexZone(txn.apdexThreshold, txn.duration)
}
} else {
txn.zone = apdexNone
}
if log.DebugEnabled() {
log.Debug("transaction ended", log.Context{
"name": txn.finalName,
"duration_ms": txn.duration.Seconds() * 1000.0,
"ignored": txn.ignore,
"run": txn.Reply.RunID,
})
}
if !txn.ignore {
txn.Consumer.consume(txn.Reply.RunID, txn)
}
// Note that if a consumer uses `panic(nil)`, the panic will not
// propogate.
if nil != r {
panic(r)
}
return nil
}
func (txn *txn) AddAttribute(name string, value interface{}) error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
return addUserAttribute(txn.attrs, name, value, destAll)
}
var (
// ErrorsLocallyDisabled is returned if error capture is disabled by
// local configuration.
ErrorsLocallyDisabled = errors.New("errors locally disabled")
// ErrorsRemotelyDisabled is returned if error capture is disabled
// by remote configuration.
ErrorsRemotelyDisabled = errors.New("errors remotely disabled")
// ErrNilError is returned if the provided error is nil.
ErrNilError = errors.New("nil error")
)
const (
// HighSecurityErrorMsg is used in place of the error's message
// (err.String()) when high security moed is enabled.
HighSecurityErrorMsg = "message removed by high security setting"
)
func (txn *txn) noticeErrorInternal(err txnError) error {
// Increment errorsSeen even if errors are disabled: Error metrics do
// not depend on whether or not errors are enabled.
txn.errorsSeen++
if !txn.Config.ErrorCollector.Enabled {
return ErrorsLocallyDisabled
}
if !txn.Reply.CollectErrors {
return ErrorsRemotelyDisabled
}
if nil == txn.errors {
txn.errors = newTxnErrors(maxTxnErrors)
}
if txn.Config.HighSecurity {
err.msg = HighSecurityErrorMsg
}
err.when = time.Now()
txn.errors.Add(&err)
return nil
}
func (txn *txn) NoticeError(err error) error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
if nil == err {
return ErrNilError
}
e := txnErrorFromError(err)
e.stack = getStackTrace(2)
return txn.noticeErrorInternal(e)
}
func (txn *txn) SetName(name string) error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
txn.name = name
return nil
}
func (txn *txn) Ignore() error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
txn.ignore = true
return nil
}
func (txn *txn) | () api.Token {
token := invalidToken
txn.Lock()
if !txn.finished {
token = startSegment(&txn.tracer, time.Now())
}
txn.Unlock()
return token
}
func (txn *txn) EndSegment(token api.Token, name string) {
txn.Lock()
if !txn.finished {
endBasicSegment(&txn.tracer, token, time.Now(), name)
}
txn.Unlock()
}
func (txn *txn) EndDatastore(token api.Token, s datastore.Segment) {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return
}
endDatastoreSegment(&txn.tracer, token, time.Now(), s)
}
func (txn *txn) EndExternal(token api.Token, url string) {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return
}
endExternalSegment(&txn.tracer, token, time.Now(), hostFromExternalURL(url))
}
func (txn *txn) PrepareRequest(token api.Token, request *http.Request) {
txn.Lock()
defer txn.Unlock()
// TODO: handle request CAT headers
}
func hostFromRequestResponse(request *http.Request, response *http.Response) string {
if nil != response && nil != response.Request {
request = response.Request
}
if nil == request || nil == request.URL {
return ""
}
if "" != request.URL.Opaque {
return "opaque"
}
return request.URL.Host
}
func (txn *txn) EndRequest(token api.Token, request *http.Request, response *http.Response) {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return
}
// TODO: handle response CAT headers
host := hostFromRequestResponse(request, response)
endExternalSegment(&txn.tracer, token, time.Now(), host)
}
| StartSegment | identifier_name |
txn.go | package internal
import (
"errors"
"net/http"
"strconv"
"sync"
"time"
"github.com/newrelic/go-agent/api"
"github.com/newrelic/go-agent/api/datastore"
"github.com/newrelic/go-agent/log"
)
type txnInput struct {
W http.ResponseWriter
Request *http.Request
Config api.Config
Reply *ConnectReply
Consumer dataConsumer
attrConfig *attributeConfig
}
type txn struct {
txnInput
// This mutex is required since the consumer may call the public API
// interface functions from different routines.
sync.Mutex
// finished indicates whether or not End() has been called. After
// finished has been set to true, no recording should occur.
finished bool
queuing time.Duration
start time.Time
name string // Work in progress name
isWeb bool
ignore bool
errors txnErrors // Lazily initialized.
errorsSeen uint64
attrs *attributes
// Fields relating to tracing and breakdown metrics/segments.
tracer tracer
// wroteHeader prevents capturing multiple response code errors if the
// user erroneously calls WriteHeader multiple times.
wroteHeader bool
// Fields assigned at completion
stop time.Time
duration time.Duration
finalName string // Full finalized metric name
zone apdexZone
apdexThreshold time.Duration
}
func newTxn(input txnInput, name string) *txn {
txn := &txn{
txnInput: input,
start: time.Now(),
name: name,
isWeb: nil != input.Request,
attrs: newAttributes(input.attrConfig),
}
if nil != txn.Request {
h := input.Request.Header
txn.attrs.agent.RequestMethod = input.Request.Method
txn.attrs.agent.RequestAcceptHeader = h.Get("Accept")
txn.attrs.agent.RequestContentType = h.Get("Content-Type")
txn.attrs.agent.RequestHeadersHost = h.Get("Host")
txn.attrs.agent.RequestHeadersUserAgent = h.Get("User-Agent")
txn.attrs.agent.RequestHeadersReferer = safeURLFromString(h.Get("Referer"))
if cl := h.Get("Content-Length"); "" != cl {
if x, err := strconv.Atoi(cl); nil == err {
txn.attrs.agent.RequestContentLength = x
}
}
txn.queuing = queueDuration(h, txn.start)
}
txn.attrs.agent.HostDisplayName = txn.Config.HostDisplayName
return txn
}
func (txn *txn) txnEventsEnabled() bool {
return txn.Config.TransactionEvents.Enabled &&
txn.Reply.CollectAnalyticsEvents
}
func (txn *txn) errorEventsEnabled() bool {
return txn.Config.ErrorCollector.CaptureEvents &&
txn.Reply.CollectErrorEvents
}
func (txn *txn) freezeName() {
if txn.ignore || ("" != txn.finalName) {
return
}
txn.finalName = CreateFullTxnName(txn.name, txn.Reply, txn.isWeb)
if "" == txn.finalName {
txn.ignore = true
}
}
func (txn *txn) getsApdex() bool {
return txn.isWeb
}
type createTxnMetricsArgs struct {
isWeb bool
duration time.Duration
exclusive time.Duration
name string
zone apdexZone
apdexThreshold time.Duration
errorsSeen uint64
}
func createTxnMetrics(args createTxnMetricsArgs, metrics *metricTable) {
// Duration Metrics
rollup := backgroundRollup
if args.isWeb {
rollup = webRollup
metrics.addDuration(dispatcherMetric, "", args.duration, 0, forced)
}
metrics.addDuration(args.name, "", args.duration, args.exclusive, forced)
metrics.addDuration(rollup, "", args.duration, args.exclusive, forced)
// Apdex Metrics
if args.zone != apdexNone {
metrics.addApdex(apdexRollup, "", args.apdexThreshold, args.zone, forced)
mname := apdexPrefix + removeFirstSegment(args.name)
metrics.addApdex(mname, "", args.apdexThreshold, args.zone, unforced)
}
// Error Metrics
if args.errorsSeen > 0 {
metrics.addSingleCount(errorsAll, forced)
if args.isWeb | else {
metrics.addSingleCount(errorsBackground, forced)
}
metrics.addSingleCount(errorsPrefix+args.name, forced)
}
}
func (txn *txn) mergeIntoHarvest(h *harvest) {
exclusive := time.Duration(0)
children := tracerRootChildren(&txn.tracer)
if txn.duration > children {
exclusive = txn.duration - children
}
createTxnMetrics(createTxnMetricsArgs{
isWeb: txn.isWeb,
duration: txn.duration,
exclusive: exclusive,
name: txn.finalName,
zone: txn.zone,
apdexThreshold: txn.apdexThreshold,
errorsSeen: txn.errorsSeen,
}, h.metrics)
if txn.queuing > 0 {
h.metrics.addDuration(queueMetric, "", txn.queuing, txn.queuing, forced)
}
mergeBreakdownMetrics(&txn.tracer, h.metrics, txn.finalName, txn.isWeb)
if txn.txnEventsEnabled() {
h.txnEvents.AddTxnEvent(&txnEvent{
Name: txn.finalName,
Timestamp: txn.start,
Duration: txn.duration,
queuing: txn.queuing,
zone: txn.zone,
attrs: txn.attrs,
datastoreExternalTotals: txn.tracer.datastoreExternalTotals,
})
}
requestURI := ""
if nil != txn.Request && nil != txn.Request.URL {
requestURI = safeURL(txn.Request.URL)
}
mergeTxnErrors(h.errorTraces, txn.errors, txn.finalName, requestURI, txn.attrs)
if txn.errorEventsEnabled() {
for _, e := range txn.errors {
h.errorEvents.Add(&errorEvent{
klass: e.klass,
msg: e.msg,
when: e.when,
txnName: txn.finalName,
duration: txn.duration,
queuing: txn.queuing,
attrs: txn.attrs,
datastoreExternalTotals: txn.tracer.datastoreExternalTotals,
})
}
}
}
func responseCodeIsError(cfg *api.Config, code int) bool {
if code < http.StatusBadRequest { // 400
return false
}
for _, ignoreCode := range cfg.ErrorCollector.IgnoreStatusCodes {
if code == ignoreCode {
return false
}
}
return true
}
var (
// statusCodeLookup avoids a strconv.Itoa call.
statusCodeLookup = map[int]string{
100: "100", 101: "101",
200: "200", 201: "201", 202: "202", 203: "203", 204: "204", 205: "205", 206: "206",
300: "300", 301: "301", 302: "302", 303: "303", 304: "304", 305: "305", 307: "307",
400: "400", 401: "401", 402: "402", 403: "403", 404: "404", 405: "405", 406: "406",
407: "407", 408: "408", 409: "409", 410: "410", 411: "411", 412: "412", 413: "413",
414: "414", 415: "415", 416: "416", 417: "417", 418: "418", 428: "428", 429: "429",
431: "431", 451: "451",
500: "500", 501: "501", 502: "502", 503: "503", 504: "504", 505: "505", 511: "511",
}
)
func headersJustWritten(txn *txn, code int) {
if txn.finished {
return
}
if txn.wroteHeader {
return
}
txn.wroteHeader = true
h := txn.W.Header()
txn.attrs.agent.ResponseHeadersContentType = h.Get("Content-Type")
if val := h.Get("Content-Length"); "" != val {
if x, err := strconv.Atoi(val); nil == err {
txn.attrs.agent.ResponseHeadersContentLength = x
}
}
txn.attrs.agent.ResponseCode = statusCodeLookup[code]
if txn.attrs.agent.ResponseCode == "" {
txn.attrs.agent.ResponseCode = strconv.Itoa(code)
}
if responseCodeIsError(&txn.Config, code) {
e := txnErrorFromResponseCode(code)
e.stack = getStackTrace(1)
txn.noticeErrorInternal(e)
}
}
func (txn *txn) Header() http.Header { return txn.W.Header() }
func (txn *txn) Write(b []byte) (int, error) {
n, err := txn.W.Write(b)
txn.Lock()
defer txn.Unlock()
headersJustWritten(txn, http.StatusOK)
return n, err
}
func (txn *txn) WriteHeader(code int) {
txn.W.WriteHeader(code)
txn.Lock()
defer txn.Unlock()
headersJustWritten(txn, code)
}
var (
// ErrAlreadyEnded is returned by public txn methods if End() has
// already been called.
ErrAlreadyEnded = errors.New("transaction has already ended")
)
func (txn *txn) End() error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
txn.finished = true
r := recover()
if nil != r {
e := txnErrorFromPanic(r)
e.stack = getStackTrace(0)
txn.noticeErrorInternal(e)
}
txn.stop = time.Now()
txn.duration = txn.stop.Sub(txn.start)
txn.freezeName()
if txn.getsApdex() {
txn.apdexThreshold = calculateApdexThreshold(txn.Reply, txn.finalName)
if txn.errorsSeen > 0 {
txn.zone = apdexFailing
} else {
txn.zone = calculateApdexZone(txn.apdexThreshold, txn.duration)
}
} else {
txn.zone = apdexNone
}
if log.DebugEnabled() {
log.Debug("transaction ended", log.Context{
"name": txn.finalName,
"duration_ms": txn.duration.Seconds() * 1000.0,
"ignored": txn.ignore,
"run": txn.Reply.RunID,
})
}
if !txn.ignore {
txn.Consumer.consume(txn.Reply.RunID, txn)
}
// Note that if a consumer uses `panic(nil)`, the panic will not
// propogate.
if nil != r {
panic(r)
}
return nil
}
func (txn *txn) AddAttribute(name string, value interface{}) error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
return addUserAttribute(txn.attrs, name, value, destAll)
}
var (
// ErrorsLocallyDisabled is returned if error capture is disabled by
// local configuration.
ErrorsLocallyDisabled = errors.New("errors locally disabled")
// ErrorsRemotelyDisabled is returned if error capture is disabled
// by remote configuration.
ErrorsRemotelyDisabled = errors.New("errors remotely disabled")
// ErrNilError is returned if the provided error is nil.
ErrNilError = errors.New("nil error")
)
const (
// HighSecurityErrorMsg is used in place of the error's message
// (err.String()) when high security moed is enabled.
HighSecurityErrorMsg = "message removed by high security setting"
)
func (txn *txn) noticeErrorInternal(err txnError) error {
// Increment errorsSeen even if errors are disabled: Error metrics do
// not depend on whether or not errors are enabled.
txn.errorsSeen++
if !txn.Config.ErrorCollector.Enabled {
return ErrorsLocallyDisabled
}
if !txn.Reply.CollectErrors {
return ErrorsRemotelyDisabled
}
if nil == txn.errors {
txn.errors = newTxnErrors(maxTxnErrors)
}
if txn.Config.HighSecurity {
err.msg = HighSecurityErrorMsg
}
err.when = time.Now()
txn.errors.Add(&err)
return nil
}
func (txn *txn) NoticeError(err error) error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
if nil == err {
return ErrNilError
}
e := txnErrorFromError(err)
e.stack = getStackTrace(2)
return txn.noticeErrorInternal(e)
}
func (txn *txn) SetName(name string) error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
txn.name = name
return nil
}
func (txn *txn) Ignore() error {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return ErrAlreadyEnded
}
txn.ignore = true
return nil
}
func (txn *txn) StartSegment() api.Token {
token := invalidToken
txn.Lock()
if !txn.finished {
token = startSegment(&txn.tracer, time.Now())
}
txn.Unlock()
return token
}
func (txn *txn) EndSegment(token api.Token, name string) {
txn.Lock()
if !txn.finished {
endBasicSegment(&txn.tracer, token, time.Now(), name)
}
txn.Unlock()
}
func (txn *txn) EndDatastore(token api.Token, s datastore.Segment) {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return
}
endDatastoreSegment(&txn.tracer, token, time.Now(), s)
}
func (txn *txn) EndExternal(token api.Token, url string) {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return
}
endExternalSegment(&txn.tracer, token, time.Now(), hostFromExternalURL(url))
}
func (txn *txn) PrepareRequest(token api.Token, request *http.Request) {
txn.Lock()
defer txn.Unlock()
// TODO: handle request CAT headers
}
func hostFromRequestResponse(request *http.Request, response *http.Response) string {
if nil != response && nil != response.Request {
request = response.Request
}
if nil == request || nil == request.URL {
return ""
}
if "" != request.URL.Opaque {
return "opaque"
}
return request.URL.Host
}
func (txn *txn) EndRequest(token api.Token, request *http.Request, response *http.Response) {
txn.Lock()
defer txn.Unlock()
if txn.finished {
return
}
// TODO: handle response CAT headers
host := hostFromRequestResponse(request, response)
endExternalSegment(&txn.tracer, token, time.Now(), host)
}
| {
metrics.addSingleCount(errorsWeb, forced)
} | conditional_block |
tools.py | import torch
import torch.nn as nn
import copy
class View(nn.Module):
def __init__(self, size):
super(View, self).__init__()
self.size = size
def forward(self, tensor):
return tensor.view(self.size)
#########################################################
# image encoders #
"Any image encoders could replace my implementation here"
#########################################################
class ImageEncoder(nn.Module):
def __init__(self, input_channel_num=3, layer_params=None):
# {'filter num': [16, 16, 32, 32], 'kernel sizes': [7, 3, 3, 3], 'strides': [1, 1, 2, 1]}
super(ImageEncoder, self).__init__()
layers = []
layer_params['filter num'] = [input_channel_num] + list(layer_params['filter num'])
for i in range(len(layer_params['filter num'])-1):
layers.append(nn.Conv2d(layer_params['filter num'][i], layer_params['filter num'][i+1],
kernel_size=layer_params['kernel sizes'][i], stride=layer_params['strides'][i]))
# layers.append(nn.BatchNorm2d(layer_params['filter num'][i+1]))
layers.append(nn.LeakyReLU(inplace=True))
self.encoder = nn.Sequential(*layers)
def forward(self, batch_image_tensors):
return self.encoder(batch_image_tensors)
class KeyPointHeatmapEncoder(nn.Module):
def __init__(self, layer_params, input_channel_num=1):
# layer_params {'filter num': [1, 2], 'operator':['conv2d','max_pool'], 'kernel sizes': [3, 3], 'strides': [1, 2]}
super(KeyPointHeatmapEncoder, self).__init__()
layers = []
layer_params['filter num'] = [input_channel_num] + layer_params['filter num']
for i in range(len(layer_params['filter num']) - 1):
if layer_params['operator'] == 'conv2d':
layers.append(nn.Conv2d(layer_params['filter num'][i], layer_params['filter num'][i + 1],
kernel_size=layer_params['kernel sizes'][i], stride=layer_params['strides'][i]))
layers.append(nn.BatchNorm2d(layer_params['filter num'][i+1]))
layers.append(nn.ReLU(inplace=True))
else:
layers.append(nn.MaxPool2d(kernel_size=layer_params['kernel sizes'][i], stride=layer_params['strides'][i]))
layers.append(View(-1, ))
self.encoder_conv = nn.Sequential(*layers)
def forward(self, batch_heatmap_tensor):
return self.encoder_conv(batch_heatmap_tensor)
#########################################################
# Graph Neural Network Library, a simple implementation #
"Any other graph neural network library could be used "
"TODO: use pytorchGeometrics lib"
"https://pytorch-geometric.readthedocs.io/en/latest/modules/nn.html"
#########################################################
class PairMessageGenerator(nn.Module):
def __init__(self, dim_hv, dim_hw, msg_dim):
"""
generate pair message between node Hv and Hw.
since the cat operation, msgs from hv -> hw and hw -> hv are different
"""
super(PairMessageGenerator, self).__init__()
self.dim_hv, self.dim_hw, self.msg_dim = dim_hv, dim_hw, msg_dim
self.in_dim = dim_hv + dim_hw # row * feature_dim, 2048
self.mlp = nn.Sequential(
nn.LayerNorm(self.in_dim), # this layer norm is important to create diversity
nn.Linear(self.in_dim, self.msg_dim),
nn.LeakyReLU(0.2)
)
def forward(self, Hv, Hw):
"""
Hv: m v nodes : node feature
Hw: m w nodes : node feature
"""
inputs = torch.cat((Hv, Hw), 1)
m_vw = self.mlp(inputs)
return m_vw
class MessagePassing(nn.Module):
def __init__(self, dim_h, msg_dim, msg_aggrgt='AVG'):
"""
input:
1 generate pair message between all connected nodes
2 do message aggregate
3 gru update, output all nodes' next h, only do one step
"""
super(MessagePassing, self).__init__()
self.dim_h = dim_h
self.msg_aggrgt = msg_aggrgt
self.msg_dim = msg_dim
self.msg_generator = PairMessageGenerator(dim_h, dim_h, msg_dim) # parameters shared
self.update = nn.GRUCell(msg_dim, dim_h) # parameters shared
def forward(self, Ht_batch, A):
"""
intput: Ht, hidden state of all nodes at time t, n instances
Ht, 3D matrix, instances : nodes : node vectors (dim_h)
A, Adjacent matrix, assuming all have the same adjacent matrix as all represent in one task kernel
steps: 1 generate pair message stored in a hash table (for undirected graph here)
2 aggregate msgs mt+1 for each node.
3 feed ht and mt+1 in GRU update module
output: Ht+1, hidden state of all nodes at time t+1, n instances
: 3D matrix, instance entries : nodes: node vectors
"""
# generate pair message
pair_msgs = {} ## hash msgs
device = Ht_batch.device
node_Ht_next_step = torch.zeros(Ht_batch.size()).to(device) # n instances : nodes_num : node vectors (dim_h)
# scan adjacent matrix
for i in range(A.shape[0]): # all the nodes
pair_msgs[i] = [] # connected_msg_num * n * msg_dim
Hv = Ht_batch[:, i, :] # n*dim_h
for j in range(A.shape[1]): # scan the other nodes
if A[i, j] == 1: ## connected nodeds
Hw = Ht_batch[:, j, :] # n*dim_h
# msg from Hv to Hw
msg_i_j = self.msg_generator(Hv, Hw) # n * dim_msgs
pair_msgs[i].append(msg_i_j)
# aggregate all connected msgs
msg_next_step = self.aggregate_msgs(pair_msgs[i]).to(device) # n*msg_dim
# update function, get next hidden state
Ht_next_step = self.update(msg_next_step, Hv) # n * dim_h
node_Ht_next_step[:, i, :] = Ht_next_step
return node_Ht_next_step
def aggregate_msgs(self, connected_msgs_list):
|
class GraphReadOut(nn.Module):
"""
that's the readout function
input: all nodes final hidden state
output: readout vector representing the graph
"""
def __init__(self, input_dim, node_num, output_dim):
super(GraphReadOut, self).__init__()
self.input_dim = input_dim # 1024
self.output_dim = output_dim
self.node_num = node_num
self.mlp = nn.Sequential(
View((-1, self.node_num * self.input_dim)),
nn.LayerNorm(self.node_num*self.input_dim), # layer norm is good
nn.Linear(self.node_num * self.input_dim, self.output_dim),
nn.LeakyReLU(0.2),
)
def forward(self, nodes_final_hidden):
"""
nodes_final_hidden: n graphs : node_num (as the sequence) : node_hidden_state_dim
output: n scalar values representing weight of each graph
"""
return self.mlp(nodes_final_hidden)
# ****************************************************************
# --Test-- : Fri, 16:02:00, Jun 7, 2019, MDT
# --Result-- : PASS / NG, Jun Jin, 16:02:00, Jun 7, 2019, MDT
# ****************************************************************
# Ht = torch.randn((120, 2, 128))
# readout = GraphReadOut(128, 2)
# outputs = readout(Ht)
# print (outputs.shape)
# error_vec = torch.ones(120)
# outputs.backward(error_vec)
# print(list(readout.parameters())[0].grad)
# # when include lstm, forward function is OK. but after backward, grad is None
# images = np.load('../raw/sample_img.npy')
# transform = T.Compose([
# T.ToPILImage(),
# T.ToTensor(),
# T.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))])
# images = transform(images).to(device).unsqueeze(0)
# images = torch.randn((10,3,128,128)).to(device)
# deep_geometry_set = deep_geometry_set.to(device)
# basis_weighted_layer = deep_geometry_set(images) # dim N * (7*_gnn_output_dim)
def init_weights(m):
if type(m) == nn.Linear:
# torch.nn.init.xavier_uniform(m.weight)
torch.nn.init.kaiming_uniform_(m.weight, mode='fan_in', nonlinearity='relu')
def tie_weights_of_two_networks(src, tgt):
i = 0
params = list(tgt.parameters())
assert len(list(src.parameters())) == len(params), "failed, length not match!"
for f in src.parameters(): # set weights
f.data = params[i].data
i += 1
#########################################################
# baseline encoders #
"baseline encoders for ablation study"
#########################################################
class PixelE2E(nn.Module):
def __init__(self, input_channel_num=3, layer_params=None, output_dim=896):
# {'filter num': [16, 16, 32, 32], 'kernel sizes': [7, 3, 3, 3], 'strides': [1, 1, 2, 1]}
super(PixelE2E, self).__init__()
self.conv_encoder = nn.Sequential(
ImageEncoder(input_channel_num=input_channel_num, layer_params=layer_params),
View(-1, ),
nn.Linear(169, output_dim), # for a fair comparison 896 is exactly the dim of geometry set output dim
nn.ReLU())
def forward(self, batch_image_tensors):
return self.conv_encoder(batch_image_tensors)
class M6EKViEncoder(nn.Module):
"""
M6 baseline, Ours - G: E+k+Vi
"""
def __init__(self, _conv_encoder=None, _encoder_out_channels=32, _vi_key_pointer=None, key_point_num=20, _debug_tool=None, _debug_frequency=None, _vi_mode=True):
"""
deep geometric feature set as state representation
:param _conv_encoder:
:param _encoder_out_channels:
:param _vi_key_pointer:
:param key_point_num: default 20
"""
super(M6EKViEncoder, self).__init__()
self.encoder = _conv_encoder
self.k_heatmaps_layer = nn.Sequential(
nn.Conv2d(_encoder_out_channels, key_point_num, kernel_size=(1, 1), stride=(1, 1)),
nn.BatchNorm2d(key_point_num),
nn.ReLU())
self.vi_key_pointer = _vi_key_pointer
self.debug_tool = _debug_tool
self.debug_frequency = _debug_frequency
self.it_count = 0
self.vi_mode = _vi_mode
def forward(self, batch_image_tensors):
self.it_count += 1 # this is only for debug purpose
x = self.encoder(batch_image_tensors)
x = self.k_heatmaps_layer(x) # x: k=20 heat maps
print('conv heatmap size')
print(x.shape)
if self.debug_tool is not None and self.it_count % self.debug_frequency == 0: # if debug mode, output more info
conv_heatmaps = copy.deepcopy(x.detach().to('cpu'))
x, gauss_mu, gauss_maps, vi_key_point_heatmaps = self.vi_key_pointer(x, self.vi_mode)
self.debug_tool.vis_debugger(batch_image_tensors.detach().to('cpu'),
conv_heatmaps,
gauss_maps.detach().to('cpu'),
vi_key_point_heatmaps.detach().to('cpu'),
gauss_mu[:, :, 0].detach().to('cpu'),
gauss_mu[:, :, 1].detach().to('cpu'),
show_graphs=True
)
else:
x, _, _, _ = self.vi_key_pointer(x) # x: k=20 key points with visual features
return x
# class M7EKGEncoder(nn.Module): # that's DeepGeometricSet with vi_mode = False
# class M8: keypoint bottle neck: E + K, # that's M6EKViEncoder with vi_mode = False
| """
# for n graph instances
# given edge index number
# this connected_msgs_list contains all connnected edges msg, say m connected edges
# connected_msgs_list: m items, each item is n*msg_dim matrix
# return n*msg_dim matrix, representing next step msg of this edge index
:param connected_msgs_list:
:return:
"""
msg_num = len(connected_msgs_list)
agg_msg = connected_msgs_list[0]
for i in range(1, msg_num):
agg_msg += connected_msgs_list[i]
if self.msg_aggrgt == 'AVG':
return agg_msg / msg_num
elif self.msg_aggrgt == 'SUM':
return agg_msg | identifier_body |
tools.py | import torch
import torch.nn as nn
import copy
class View(nn.Module):
def __init__(self, size):
super(View, self).__init__()
self.size = size
def forward(self, tensor):
return tensor.view(self.size)
#########################################################
# image encoders #
"Any image encoders could replace my implementation here"
#########################################################
class ImageEncoder(nn.Module):
def __init__(self, input_channel_num=3, layer_params=None):
# {'filter num': [16, 16, 32, 32], 'kernel sizes': [7, 3, 3, 3], 'strides': [1, 1, 2, 1]}
super(ImageEncoder, self).__init__()
layers = []
layer_params['filter num'] = [input_channel_num] + list(layer_params['filter num'])
for i in range(len(layer_params['filter num'])-1):
layers.append(nn.Conv2d(layer_params['filter num'][i], layer_params['filter num'][i+1],
kernel_size=layer_params['kernel sizes'][i], stride=layer_params['strides'][i]))
# layers.append(nn.BatchNorm2d(layer_params['filter num'][i+1]))
layers.append(nn.LeakyReLU(inplace=True))
self.encoder = nn.Sequential(*layers)
def forward(self, batch_image_tensors):
return self.encoder(batch_image_tensors)
class | (nn.Module):
def __init__(self, layer_params, input_channel_num=1):
# layer_params {'filter num': [1, 2], 'operator':['conv2d','max_pool'], 'kernel sizes': [3, 3], 'strides': [1, 2]}
super(KeyPointHeatmapEncoder, self).__init__()
layers = []
layer_params['filter num'] = [input_channel_num] + layer_params['filter num']
for i in range(len(layer_params['filter num']) - 1):
if layer_params['operator'] == 'conv2d':
layers.append(nn.Conv2d(layer_params['filter num'][i], layer_params['filter num'][i + 1],
kernel_size=layer_params['kernel sizes'][i], stride=layer_params['strides'][i]))
layers.append(nn.BatchNorm2d(layer_params['filter num'][i+1]))
layers.append(nn.ReLU(inplace=True))
else:
layers.append(nn.MaxPool2d(kernel_size=layer_params['kernel sizes'][i], stride=layer_params['strides'][i]))
layers.append(View(-1, ))
self.encoder_conv = nn.Sequential(*layers)
def forward(self, batch_heatmap_tensor):
return self.encoder_conv(batch_heatmap_tensor)
#########################################################
# Graph Neural Network Library, a simple implementation #
"Any other graph neural network library could be used "
"TODO: use pytorchGeometrics lib"
"https://pytorch-geometric.readthedocs.io/en/latest/modules/nn.html"
#########################################################
class PairMessageGenerator(nn.Module):
def __init__(self, dim_hv, dim_hw, msg_dim):
"""
generate pair message between node Hv and Hw.
since the cat operation, msgs from hv -> hw and hw -> hv are different
"""
super(PairMessageGenerator, self).__init__()
self.dim_hv, self.dim_hw, self.msg_dim = dim_hv, dim_hw, msg_dim
self.in_dim = dim_hv + dim_hw # row * feature_dim, 2048
self.mlp = nn.Sequential(
nn.LayerNorm(self.in_dim), # this layer norm is important to create diversity
nn.Linear(self.in_dim, self.msg_dim),
nn.LeakyReLU(0.2)
)
def forward(self, Hv, Hw):
"""
Hv: m v nodes : node feature
Hw: m w nodes : node feature
"""
inputs = torch.cat((Hv, Hw), 1)
m_vw = self.mlp(inputs)
return m_vw
class MessagePassing(nn.Module):
def __init__(self, dim_h, msg_dim, msg_aggrgt='AVG'):
"""
input:
1 generate pair message between all connected nodes
2 do message aggregate
3 gru update, output all nodes' next h, only do one step
"""
super(MessagePassing, self).__init__()
self.dim_h = dim_h
self.msg_aggrgt = msg_aggrgt
self.msg_dim = msg_dim
self.msg_generator = PairMessageGenerator(dim_h, dim_h, msg_dim) # parameters shared
self.update = nn.GRUCell(msg_dim, dim_h) # parameters shared
def forward(self, Ht_batch, A):
"""
intput: Ht, hidden state of all nodes at time t, n instances
Ht, 3D matrix, instances : nodes : node vectors (dim_h)
A, Adjacent matrix, assuming all have the same adjacent matrix as all represent in one task kernel
steps: 1 generate pair message stored in a hash table (for undirected graph here)
2 aggregate msgs mt+1 for each node.
3 feed ht and mt+1 in GRU update module
output: Ht+1, hidden state of all nodes at time t+1, n instances
: 3D matrix, instance entries : nodes: node vectors
"""
# generate pair message
pair_msgs = {} ## hash msgs
device = Ht_batch.device
node_Ht_next_step = torch.zeros(Ht_batch.size()).to(device) # n instances : nodes_num : node vectors (dim_h)
# scan adjacent matrix
for i in range(A.shape[0]): # all the nodes
pair_msgs[i] = [] # connected_msg_num * n * msg_dim
Hv = Ht_batch[:, i, :] # n*dim_h
for j in range(A.shape[1]): # scan the other nodes
if A[i, j] == 1: ## connected nodeds
Hw = Ht_batch[:, j, :] # n*dim_h
# msg from Hv to Hw
msg_i_j = self.msg_generator(Hv, Hw) # n * dim_msgs
pair_msgs[i].append(msg_i_j)
# aggregate all connected msgs
msg_next_step = self.aggregate_msgs(pair_msgs[i]).to(device) # n*msg_dim
# update function, get next hidden state
Ht_next_step = self.update(msg_next_step, Hv) # n * dim_h
node_Ht_next_step[:, i, :] = Ht_next_step
return node_Ht_next_step
def aggregate_msgs(self, connected_msgs_list):
"""
# for n graph instances
# given edge index number
# this connected_msgs_list contains all connnected edges msg, say m connected edges
# connected_msgs_list: m items, each item is n*msg_dim matrix
# return n*msg_dim matrix, representing next step msg of this edge index
:param connected_msgs_list:
:return:
"""
msg_num = len(connected_msgs_list)
agg_msg = connected_msgs_list[0]
for i in range(1, msg_num):
agg_msg += connected_msgs_list[i]
if self.msg_aggrgt == 'AVG':
return agg_msg / msg_num
elif self.msg_aggrgt == 'SUM':
return agg_msg
class GraphReadOut(nn.Module):
"""
that's the readout function
input: all nodes final hidden state
output: readout vector representing the graph
"""
def __init__(self, input_dim, node_num, output_dim):
super(GraphReadOut, self).__init__()
self.input_dim = input_dim # 1024
self.output_dim = output_dim
self.node_num = node_num
self.mlp = nn.Sequential(
View((-1, self.node_num * self.input_dim)),
nn.LayerNorm(self.node_num*self.input_dim), # layer norm is good
nn.Linear(self.node_num * self.input_dim, self.output_dim),
nn.LeakyReLU(0.2),
)
def forward(self, nodes_final_hidden):
"""
nodes_final_hidden: n graphs : node_num (as the sequence) : node_hidden_state_dim
output: n scalar values representing weight of each graph
"""
return self.mlp(nodes_final_hidden)
# ****************************************************************
# --Test-- : Fri, 16:02:00, Jun 7, 2019, MDT
# --Result-- : PASS / NG, Jun Jin, 16:02:00, Jun 7, 2019, MDT
# ****************************************************************
# Ht = torch.randn((120, 2, 128))
# readout = GraphReadOut(128, 2)
# outputs = readout(Ht)
# print (outputs.shape)
# error_vec = torch.ones(120)
# outputs.backward(error_vec)
# print(list(readout.parameters())[0].grad)
# # when include lstm, forward function is OK. but after backward, grad is None
# images = np.load('../raw/sample_img.npy')
# transform = T.Compose([
# T.ToPILImage(),
# T.ToTensor(),
# T.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))])
# images = transform(images).to(device).unsqueeze(0)
# images = torch.randn((10,3,128,128)).to(device)
# deep_geometry_set = deep_geometry_set.to(device)
# basis_weighted_layer = deep_geometry_set(images) # dim N * (7*_gnn_output_dim)
def init_weights(m):
if type(m) == nn.Linear:
# torch.nn.init.xavier_uniform(m.weight)
torch.nn.init.kaiming_uniform_(m.weight, mode='fan_in', nonlinearity='relu')
def tie_weights_of_two_networks(src, tgt):
i = 0
params = list(tgt.parameters())
assert len(list(src.parameters())) == len(params), "failed, length not match!"
for f in src.parameters(): # set weights
f.data = params[i].data
i += 1
#########################################################
# baseline encoders #
"baseline encoders for ablation study"
#########################################################
class PixelE2E(nn.Module):
def __init__(self, input_channel_num=3, layer_params=None, output_dim=896):
# {'filter num': [16, 16, 32, 32], 'kernel sizes': [7, 3, 3, 3], 'strides': [1, 1, 2, 1]}
super(PixelE2E, self).__init__()
self.conv_encoder = nn.Sequential(
ImageEncoder(input_channel_num=input_channel_num, layer_params=layer_params),
View(-1, ),
nn.Linear(169, output_dim), # for a fair comparison 896 is exactly the dim of geometry set output dim
nn.ReLU())
def forward(self, batch_image_tensors):
return self.conv_encoder(batch_image_tensors)
class M6EKViEncoder(nn.Module):
"""
M6 baseline, Ours - G: E+k+Vi
"""
def __init__(self, _conv_encoder=None, _encoder_out_channels=32, _vi_key_pointer=None, key_point_num=20, _debug_tool=None, _debug_frequency=None, _vi_mode=True):
"""
deep geometric feature set as state representation
:param _conv_encoder:
:param _encoder_out_channels:
:param _vi_key_pointer:
:param key_point_num: default 20
"""
super(M6EKViEncoder, self).__init__()
self.encoder = _conv_encoder
self.k_heatmaps_layer = nn.Sequential(
nn.Conv2d(_encoder_out_channels, key_point_num, kernel_size=(1, 1), stride=(1, 1)),
nn.BatchNorm2d(key_point_num),
nn.ReLU())
self.vi_key_pointer = _vi_key_pointer
self.debug_tool = _debug_tool
self.debug_frequency = _debug_frequency
self.it_count = 0
self.vi_mode = _vi_mode
def forward(self, batch_image_tensors):
self.it_count += 1 # this is only for debug purpose
x = self.encoder(batch_image_tensors)
x = self.k_heatmaps_layer(x) # x: k=20 heat maps
print('conv heatmap size')
print(x.shape)
if self.debug_tool is not None and self.it_count % self.debug_frequency == 0: # if debug mode, output more info
conv_heatmaps = copy.deepcopy(x.detach().to('cpu'))
x, gauss_mu, gauss_maps, vi_key_point_heatmaps = self.vi_key_pointer(x, self.vi_mode)
self.debug_tool.vis_debugger(batch_image_tensors.detach().to('cpu'),
conv_heatmaps,
gauss_maps.detach().to('cpu'),
vi_key_point_heatmaps.detach().to('cpu'),
gauss_mu[:, :, 0].detach().to('cpu'),
gauss_mu[:, :, 1].detach().to('cpu'),
show_graphs=True
)
else:
x, _, _, _ = self.vi_key_pointer(x) # x: k=20 key points with visual features
return x
# class M7EKGEncoder(nn.Module): # that's DeepGeometricSet with vi_mode = False
# class M8: keypoint bottle neck: E + K, # that's M6EKViEncoder with vi_mode = False
| KeyPointHeatmapEncoder | identifier_name |
tools.py | import torch
import torch.nn as nn
import copy
class View(nn.Module):
def __init__(self, size):
super(View, self).__init__()
self.size = size
def forward(self, tensor):
return tensor.view(self.size)
#########################################################
# image encoders #
"Any image encoders could replace my implementation here"
#########################################################
class ImageEncoder(nn.Module):
def __init__(self, input_channel_num=3, layer_params=None):
# {'filter num': [16, 16, 32, 32], 'kernel sizes': [7, 3, 3, 3], 'strides': [1, 1, 2, 1]}
super(ImageEncoder, self).__init__()
layers = []
layer_params['filter num'] = [input_channel_num] + list(layer_params['filter num'])
for i in range(len(layer_params['filter num'])-1):
layers.append(nn.Conv2d(layer_params['filter num'][i], layer_params['filter num'][i+1],
kernel_size=layer_params['kernel sizes'][i], stride=layer_params['strides'][i]))
# layers.append(nn.BatchNorm2d(layer_params['filter num'][i+1]))
layers.append(nn.LeakyReLU(inplace=True))
self.encoder = nn.Sequential(*layers)
def forward(self, batch_image_tensors):
return self.encoder(batch_image_tensors)
class KeyPointHeatmapEncoder(nn.Module):
def __init__(self, layer_params, input_channel_num=1):
# layer_params {'filter num': [1, 2], 'operator':['conv2d','max_pool'], 'kernel sizes': [3, 3], 'strides': [1, 2]}
super(KeyPointHeatmapEncoder, self).__init__()
layers = []
layer_params['filter num'] = [input_channel_num] + layer_params['filter num']
for i in range(len(layer_params['filter num']) - 1):
if layer_params['operator'] == 'conv2d':
|
else:
layers.append(nn.MaxPool2d(kernel_size=layer_params['kernel sizes'][i], stride=layer_params['strides'][i]))
layers.append(View(-1, ))
self.encoder_conv = nn.Sequential(*layers)
def forward(self, batch_heatmap_tensor):
return self.encoder_conv(batch_heatmap_tensor)
#########################################################
# Graph Neural Network Library, a simple implementation #
"Any other graph neural network library could be used "
"TODO: use pytorchGeometrics lib"
"https://pytorch-geometric.readthedocs.io/en/latest/modules/nn.html"
#########################################################
class PairMessageGenerator(nn.Module):
def __init__(self, dim_hv, dim_hw, msg_dim):
"""
generate pair message between node Hv and Hw.
since the cat operation, msgs from hv -> hw and hw -> hv are different
"""
super(PairMessageGenerator, self).__init__()
self.dim_hv, self.dim_hw, self.msg_dim = dim_hv, dim_hw, msg_dim
self.in_dim = dim_hv + dim_hw # row * feature_dim, 2048
self.mlp = nn.Sequential(
nn.LayerNorm(self.in_dim), # this layer norm is important to create diversity
nn.Linear(self.in_dim, self.msg_dim),
nn.LeakyReLU(0.2)
)
def forward(self, Hv, Hw):
"""
Hv: m v nodes : node feature
Hw: m w nodes : node feature
"""
inputs = torch.cat((Hv, Hw), 1)
m_vw = self.mlp(inputs)
return m_vw
class MessagePassing(nn.Module):
def __init__(self, dim_h, msg_dim, msg_aggrgt='AVG'):
"""
input:
1 generate pair message between all connected nodes
2 do message aggregate
3 gru update, output all nodes' next h, only do one step
"""
super(MessagePassing, self).__init__()
self.dim_h = dim_h
self.msg_aggrgt = msg_aggrgt
self.msg_dim = msg_dim
self.msg_generator = PairMessageGenerator(dim_h, dim_h, msg_dim) # parameters shared
self.update = nn.GRUCell(msg_dim, dim_h) # parameters shared
def forward(self, Ht_batch, A):
"""
intput: Ht, hidden state of all nodes at time t, n instances
Ht, 3D matrix, instances : nodes : node vectors (dim_h)
A, Adjacent matrix, assuming all have the same adjacent matrix as all represent in one task kernel
steps: 1 generate pair message stored in a hash table (for undirected graph here)
2 aggregate msgs mt+1 for each node.
3 feed ht and mt+1 in GRU update module
output: Ht+1, hidden state of all nodes at time t+1, n instances
: 3D matrix, instance entries : nodes: node vectors
"""
# generate pair message
pair_msgs = {} ## hash msgs
device = Ht_batch.device
node_Ht_next_step = torch.zeros(Ht_batch.size()).to(device) # n instances : nodes_num : node vectors (dim_h)
# scan adjacent matrix
for i in range(A.shape[0]): # all the nodes
pair_msgs[i] = [] # connected_msg_num * n * msg_dim
Hv = Ht_batch[:, i, :] # n*dim_h
for j in range(A.shape[1]): # scan the other nodes
if A[i, j] == 1: ## connected nodeds
Hw = Ht_batch[:, j, :] # n*dim_h
# msg from Hv to Hw
msg_i_j = self.msg_generator(Hv, Hw) # n * dim_msgs
pair_msgs[i].append(msg_i_j)
# aggregate all connected msgs
msg_next_step = self.aggregate_msgs(pair_msgs[i]).to(device) # n*msg_dim
# update function, get next hidden state
Ht_next_step = self.update(msg_next_step, Hv) # n * dim_h
node_Ht_next_step[:, i, :] = Ht_next_step
return node_Ht_next_step
def aggregate_msgs(self, connected_msgs_list):
"""
# for n graph instances
# given edge index number
# this connected_msgs_list contains all connnected edges msg, say m connected edges
# connected_msgs_list: m items, each item is n*msg_dim matrix
# return n*msg_dim matrix, representing next step msg of this edge index
:param connected_msgs_list:
:return:
"""
msg_num = len(connected_msgs_list)
agg_msg = connected_msgs_list[0]
for i in range(1, msg_num):
agg_msg += connected_msgs_list[i]
if self.msg_aggrgt == 'AVG':
return agg_msg / msg_num
elif self.msg_aggrgt == 'SUM':
return agg_msg
class GraphReadOut(nn.Module):
"""
that's the readout function
input: all nodes final hidden state
output: readout vector representing the graph
"""
def __init__(self, input_dim, node_num, output_dim):
super(GraphReadOut, self).__init__()
self.input_dim = input_dim # 1024
self.output_dim = output_dim
self.node_num = node_num
self.mlp = nn.Sequential(
View((-1, self.node_num * self.input_dim)),
nn.LayerNorm(self.node_num*self.input_dim), # layer norm is good
nn.Linear(self.node_num * self.input_dim, self.output_dim),
nn.LeakyReLU(0.2),
)
def forward(self, nodes_final_hidden):
"""
nodes_final_hidden: n graphs : node_num (as the sequence) : node_hidden_state_dim
output: n scalar values representing weight of each graph
"""
return self.mlp(nodes_final_hidden)
# ****************************************************************
# --Test-- : Fri, 16:02:00, Jun 7, 2019, MDT
# --Result-- : PASS / NG, Jun Jin, 16:02:00, Jun 7, 2019, MDT
# ****************************************************************
# Ht = torch.randn((120, 2, 128))
# readout = GraphReadOut(128, 2)
# outputs = readout(Ht)
# print (outputs.shape)
# error_vec = torch.ones(120)
# outputs.backward(error_vec)
# print(list(readout.parameters())[0].grad)
# # when include lstm, forward function is OK. but after backward, grad is None
# images = np.load('../raw/sample_img.npy')
# transform = T.Compose([
# T.ToPILImage(),
# T.ToTensor(),
# T.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))])
# images = transform(images).to(device).unsqueeze(0)
# images = torch.randn((10,3,128,128)).to(device)
# deep_geometry_set = deep_geometry_set.to(device)
# basis_weighted_layer = deep_geometry_set(images) # dim N * (7*_gnn_output_dim)
def init_weights(m):
if type(m) == nn.Linear:
# torch.nn.init.xavier_uniform(m.weight)
torch.nn.init.kaiming_uniform_(m.weight, mode='fan_in', nonlinearity='relu')
def tie_weights_of_two_networks(src, tgt):
i = 0
params = list(tgt.parameters())
assert len(list(src.parameters())) == len(params), "failed, length not match!"
for f in src.parameters(): # set weights
f.data = params[i].data
i += 1
#########################################################
# baseline encoders #
"baseline encoders for ablation study"
#########################################################
class PixelE2E(nn.Module):
def __init__(self, input_channel_num=3, layer_params=None, output_dim=896):
# {'filter num': [16, 16, 32, 32], 'kernel sizes': [7, 3, 3, 3], 'strides': [1, 1, 2, 1]}
super(PixelE2E, self).__init__()
self.conv_encoder = nn.Sequential(
ImageEncoder(input_channel_num=input_channel_num, layer_params=layer_params),
View(-1, ),
nn.Linear(169, output_dim), # for a fair comparison 896 is exactly the dim of geometry set output dim
nn.ReLU())
def forward(self, batch_image_tensors):
return self.conv_encoder(batch_image_tensors)
class M6EKViEncoder(nn.Module):
"""
M6 baseline, Ours - G: E+k+Vi
"""
def __init__(self, _conv_encoder=None, _encoder_out_channels=32, _vi_key_pointer=None, key_point_num=20, _debug_tool=None, _debug_frequency=None, _vi_mode=True):
"""
deep geometric feature set as state representation
:param _conv_encoder:
:param _encoder_out_channels:
:param _vi_key_pointer:
:param key_point_num: default 20
"""
super(M6EKViEncoder, self).__init__()
self.encoder = _conv_encoder
self.k_heatmaps_layer = nn.Sequential(
nn.Conv2d(_encoder_out_channels, key_point_num, kernel_size=(1, 1), stride=(1, 1)),
nn.BatchNorm2d(key_point_num),
nn.ReLU())
self.vi_key_pointer = _vi_key_pointer
self.debug_tool = _debug_tool
self.debug_frequency = _debug_frequency
self.it_count = 0
self.vi_mode = _vi_mode
def forward(self, batch_image_tensors):
self.it_count += 1 # this is only for debug purpose
x = self.encoder(batch_image_tensors)
x = self.k_heatmaps_layer(x) # x: k=20 heat maps
print('conv heatmap size')
print(x.shape)
if self.debug_tool is not None and self.it_count % self.debug_frequency == 0: # if debug mode, output more info
conv_heatmaps = copy.deepcopy(x.detach().to('cpu'))
x, gauss_mu, gauss_maps, vi_key_point_heatmaps = self.vi_key_pointer(x, self.vi_mode)
self.debug_tool.vis_debugger(batch_image_tensors.detach().to('cpu'),
conv_heatmaps,
gauss_maps.detach().to('cpu'),
vi_key_point_heatmaps.detach().to('cpu'),
gauss_mu[:, :, 0].detach().to('cpu'),
gauss_mu[:, :, 1].detach().to('cpu'),
show_graphs=True
)
else:
x, _, _, _ = self.vi_key_pointer(x) # x: k=20 key points with visual features
return x
# class M7EKGEncoder(nn.Module): # that's DeepGeometricSet with vi_mode = False
# class M8: keypoint bottle neck: E + K, # that's M6EKViEncoder with vi_mode = False
| layers.append(nn.Conv2d(layer_params['filter num'][i], layer_params['filter num'][i + 1],
kernel_size=layer_params['kernel sizes'][i], stride=layer_params['strides'][i]))
layers.append(nn.BatchNorm2d(layer_params['filter num'][i+1]))
layers.append(nn.ReLU(inplace=True)) | conditional_block |
tools.py | import torch
import torch.nn as nn
import copy
class View(nn.Module): | def __init__(self, size):
super(View, self).__init__()
self.size = size
def forward(self, tensor):
return tensor.view(self.size)
#########################################################
# image encoders #
"Any image encoders could replace my implementation here"
#########################################################
class ImageEncoder(nn.Module):
def __init__(self, input_channel_num=3, layer_params=None):
# {'filter num': [16, 16, 32, 32], 'kernel sizes': [7, 3, 3, 3], 'strides': [1, 1, 2, 1]}
super(ImageEncoder, self).__init__()
layers = []
layer_params['filter num'] = [input_channel_num] + list(layer_params['filter num'])
for i in range(len(layer_params['filter num'])-1):
layers.append(nn.Conv2d(layer_params['filter num'][i], layer_params['filter num'][i+1],
kernel_size=layer_params['kernel sizes'][i], stride=layer_params['strides'][i]))
# layers.append(nn.BatchNorm2d(layer_params['filter num'][i+1]))
layers.append(nn.LeakyReLU(inplace=True))
self.encoder = nn.Sequential(*layers)
def forward(self, batch_image_tensors):
return self.encoder(batch_image_tensors)
class KeyPointHeatmapEncoder(nn.Module):
def __init__(self, layer_params, input_channel_num=1):
# layer_params {'filter num': [1, 2], 'operator':['conv2d','max_pool'], 'kernel sizes': [3, 3], 'strides': [1, 2]}
super(KeyPointHeatmapEncoder, self).__init__()
layers = []
layer_params['filter num'] = [input_channel_num] + layer_params['filter num']
for i in range(len(layer_params['filter num']) - 1):
if layer_params['operator'] == 'conv2d':
layers.append(nn.Conv2d(layer_params['filter num'][i], layer_params['filter num'][i + 1],
kernel_size=layer_params['kernel sizes'][i], stride=layer_params['strides'][i]))
layers.append(nn.BatchNorm2d(layer_params['filter num'][i+1]))
layers.append(nn.ReLU(inplace=True))
else:
layers.append(nn.MaxPool2d(kernel_size=layer_params['kernel sizes'][i], stride=layer_params['strides'][i]))
layers.append(View(-1, ))
self.encoder_conv = nn.Sequential(*layers)
def forward(self, batch_heatmap_tensor):
return self.encoder_conv(batch_heatmap_tensor)
#########################################################
# Graph Neural Network Library, a simple implementation #
"Any other graph neural network library could be used "
"TODO: use pytorchGeometrics lib"
"https://pytorch-geometric.readthedocs.io/en/latest/modules/nn.html"
#########################################################
class PairMessageGenerator(nn.Module):
def __init__(self, dim_hv, dim_hw, msg_dim):
"""
generate pair message between node Hv and Hw.
since the cat operation, msgs from hv -> hw and hw -> hv are different
"""
super(PairMessageGenerator, self).__init__()
self.dim_hv, self.dim_hw, self.msg_dim = dim_hv, dim_hw, msg_dim
self.in_dim = dim_hv + dim_hw # row * feature_dim, 2048
self.mlp = nn.Sequential(
nn.LayerNorm(self.in_dim), # this layer norm is important to create diversity
nn.Linear(self.in_dim, self.msg_dim),
nn.LeakyReLU(0.2)
)
def forward(self, Hv, Hw):
"""
Hv: m v nodes : node feature
Hw: m w nodes : node feature
"""
inputs = torch.cat((Hv, Hw), 1)
m_vw = self.mlp(inputs)
return m_vw
class MessagePassing(nn.Module):
def __init__(self, dim_h, msg_dim, msg_aggrgt='AVG'):
"""
input:
1 generate pair message between all connected nodes
2 do message aggregate
3 gru update, output all nodes' next h, only do one step
"""
super(MessagePassing, self).__init__()
self.dim_h = dim_h
self.msg_aggrgt = msg_aggrgt
self.msg_dim = msg_dim
self.msg_generator = PairMessageGenerator(dim_h, dim_h, msg_dim) # parameters shared
self.update = nn.GRUCell(msg_dim, dim_h) # parameters shared
def forward(self, Ht_batch, A):
"""
intput: Ht, hidden state of all nodes at time t, n instances
Ht, 3D matrix, instances : nodes : node vectors (dim_h)
A, Adjacent matrix, assuming all have the same adjacent matrix as all represent in one task kernel
steps: 1 generate pair message stored in a hash table (for undirected graph here)
2 aggregate msgs mt+1 for each node.
3 feed ht and mt+1 in GRU update module
output: Ht+1, hidden state of all nodes at time t+1, n instances
: 3D matrix, instance entries : nodes: node vectors
"""
# generate pair message
pair_msgs = {} ## hash msgs
device = Ht_batch.device
node_Ht_next_step = torch.zeros(Ht_batch.size()).to(device) # n instances : nodes_num : node vectors (dim_h)
# scan adjacent matrix
for i in range(A.shape[0]): # all the nodes
pair_msgs[i] = [] # connected_msg_num * n * msg_dim
Hv = Ht_batch[:, i, :] # n*dim_h
for j in range(A.shape[1]): # scan the other nodes
if A[i, j] == 1: ## connected nodeds
Hw = Ht_batch[:, j, :] # n*dim_h
# msg from Hv to Hw
msg_i_j = self.msg_generator(Hv, Hw) # n * dim_msgs
pair_msgs[i].append(msg_i_j)
# aggregate all connected msgs
msg_next_step = self.aggregate_msgs(pair_msgs[i]).to(device) # n*msg_dim
# update function, get next hidden state
Ht_next_step = self.update(msg_next_step, Hv) # n * dim_h
node_Ht_next_step[:, i, :] = Ht_next_step
return node_Ht_next_step
def aggregate_msgs(self, connected_msgs_list):
"""
# for n graph instances
# given edge index number
# this connected_msgs_list contains all connnected edges msg, say m connected edges
# connected_msgs_list: m items, each item is n*msg_dim matrix
# return n*msg_dim matrix, representing next step msg of this edge index
:param connected_msgs_list:
:return:
"""
msg_num = len(connected_msgs_list)
agg_msg = connected_msgs_list[0]
for i in range(1, msg_num):
agg_msg += connected_msgs_list[i]
if self.msg_aggrgt == 'AVG':
return agg_msg / msg_num
elif self.msg_aggrgt == 'SUM':
return agg_msg
class GraphReadOut(nn.Module):
"""
that's the readout function
input: all nodes final hidden state
output: readout vector representing the graph
"""
def __init__(self, input_dim, node_num, output_dim):
super(GraphReadOut, self).__init__()
self.input_dim = input_dim # 1024
self.output_dim = output_dim
self.node_num = node_num
self.mlp = nn.Sequential(
View((-1, self.node_num * self.input_dim)),
nn.LayerNorm(self.node_num*self.input_dim), # layer norm is good
nn.Linear(self.node_num * self.input_dim, self.output_dim),
nn.LeakyReLU(0.2),
)
def forward(self, nodes_final_hidden):
"""
nodes_final_hidden: n graphs : node_num (as the sequence) : node_hidden_state_dim
output: n scalar values representing weight of each graph
"""
return self.mlp(nodes_final_hidden)
# ****************************************************************
# --Test-- : Fri, 16:02:00, Jun 7, 2019, MDT
# --Result-- : PASS / NG, Jun Jin, 16:02:00, Jun 7, 2019, MDT
# ****************************************************************
# Ht = torch.randn((120, 2, 128))
# readout = GraphReadOut(128, 2)
# outputs = readout(Ht)
# print (outputs.shape)
# error_vec = torch.ones(120)
# outputs.backward(error_vec)
# print(list(readout.parameters())[0].grad)
# # when include lstm, forward function is OK. but after backward, grad is None
# images = np.load('../raw/sample_img.npy')
# transform = T.Compose([
# T.ToPILImage(),
# T.ToTensor(),
# T.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))])
# images = transform(images).to(device).unsqueeze(0)
# images = torch.randn((10,3,128,128)).to(device)
# deep_geometry_set = deep_geometry_set.to(device)
# basis_weighted_layer = deep_geometry_set(images) # dim N * (7*_gnn_output_dim)
def init_weights(m):
if type(m) == nn.Linear:
# torch.nn.init.xavier_uniform(m.weight)
torch.nn.init.kaiming_uniform_(m.weight, mode='fan_in', nonlinearity='relu')
def tie_weights_of_two_networks(src, tgt):
i = 0
params = list(tgt.parameters())
assert len(list(src.parameters())) == len(params), "failed, length not match!"
for f in src.parameters(): # set weights
f.data = params[i].data
i += 1
#########################################################
# baseline encoders #
"baseline encoders for ablation study"
#########################################################
class PixelE2E(nn.Module):
def __init__(self, input_channel_num=3, layer_params=None, output_dim=896):
# {'filter num': [16, 16, 32, 32], 'kernel sizes': [7, 3, 3, 3], 'strides': [1, 1, 2, 1]}
super(PixelE2E, self).__init__()
self.conv_encoder = nn.Sequential(
ImageEncoder(input_channel_num=input_channel_num, layer_params=layer_params),
View(-1, ),
nn.Linear(169, output_dim), # for a fair comparison 896 is exactly the dim of geometry set output dim
nn.ReLU())
def forward(self, batch_image_tensors):
return self.conv_encoder(batch_image_tensors)
class M6EKViEncoder(nn.Module):
"""
M6 baseline, Ours - G: E+k+Vi
"""
def __init__(self, _conv_encoder=None, _encoder_out_channels=32, _vi_key_pointer=None, key_point_num=20, _debug_tool=None, _debug_frequency=None, _vi_mode=True):
"""
deep geometric feature set as state representation
:param _conv_encoder:
:param _encoder_out_channels:
:param _vi_key_pointer:
:param key_point_num: default 20
"""
super(M6EKViEncoder, self).__init__()
self.encoder = _conv_encoder
self.k_heatmaps_layer = nn.Sequential(
nn.Conv2d(_encoder_out_channels, key_point_num, kernel_size=(1, 1), stride=(1, 1)),
nn.BatchNorm2d(key_point_num),
nn.ReLU())
self.vi_key_pointer = _vi_key_pointer
self.debug_tool = _debug_tool
self.debug_frequency = _debug_frequency
self.it_count = 0
self.vi_mode = _vi_mode
def forward(self, batch_image_tensors):
self.it_count += 1 # this is only for debug purpose
x = self.encoder(batch_image_tensors)
x = self.k_heatmaps_layer(x) # x: k=20 heat maps
print('conv heatmap size')
print(x.shape)
if self.debug_tool is not None and self.it_count % self.debug_frequency == 0: # if debug mode, output more info
conv_heatmaps = copy.deepcopy(x.detach().to('cpu'))
x, gauss_mu, gauss_maps, vi_key_point_heatmaps = self.vi_key_pointer(x, self.vi_mode)
self.debug_tool.vis_debugger(batch_image_tensors.detach().to('cpu'),
conv_heatmaps,
gauss_maps.detach().to('cpu'),
vi_key_point_heatmaps.detach().to('cpu'),
gauss_mu[:, :, 0].detach().to('cpu'),
gauss_mu[:, :, 1].detach().to('cpu'),
show_graphs=True
)
else:
x, _, _, _ = self.vi_key_pointer(x) # x: k=20 key points with visual features
return x
# class M7EKGEncoder(nn.Module): # that's DeepGeometricSet with vi_mode = False
# class M8: keypoint bottle neck: E + K, # that's M6EKViEncoder with vi_mode = False | random_line_split | |
Project4.py | ########################################################################################################
##################################################### Imports ##########################################
########################################################################################################
import re
import os
from nltk import sent_tokenize, word_tokenize
from IPython.display import clear_output
from collections import Counter
import gc
import pickle
from nltk.tokenize import RegexpTokenizer, TweetTokenizer
from nltk.util import ngrams
import pandas as pd
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
import nltk
nltk.download('stopwords')
nltk.download('punkt')
from nltk.corpus import stopwords
import matplotlib.pyplot as plt
from keras import layers
from keras.layers import Input, Dense, Activation, BatchNormalization, Flatten, Conv2D
from keras.layers import MaxPooling2D, Dropout, concatenate
from keras.models import Model
import pandas as pd
import keras.backend as K
import tensorflow as tf
import os
from keras.preprocessing.image import ImageDataGenerator
from sklearn.model_selection import train_test_split
from keras.layers import Activation
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
########################################################################################################
##################################### Declarations #####################################################
########################################################################################################
def Score_Classifier(y_train_pred, y_train_true, y_pred, y_true, labels = ['Negative','Positive'], Classifier_Title = None
, evaluation_type = 'Validation'):
cm = confusion_matrix(y_true = y_true, y_pred = y_pred)
print()
if Classifier_Title is not None:
print('************************',Classifier_Title,'************************')
print('--------------------------------------------------------------')
print('Training Accuracy:')
pretty_percentage(accuracy_score(y_pred = y_train_pred, y_true = y_train_true))
print('--------------------------------------------------------------')
print(evaluation_type +' Accuracy:')
pretty_percentage(accuracy_score(y_pred = y_pred, y_true = y_true))
print('--------------------------------------------------------------')
print(evaluation_type +' Precision:')
pretty_percentage(precision_score(y_pred = y_pred, y_true = y_true))
print('--------------------------------------------------------------')
print(evaluation_type +' Recall:')
pretty_percentage(recall_score(y_pred = y_pred, y_true = y_true))
print('--------------------------------------------------------------')
print(evaluation_type +' F1 Score:')
pretty_percentage(f1_score(y_pred = y_pred, y_true = y_true))
print('--------------------------------------------------------------')
print(evaluation_type +' Confusion Matrix:')
print_cm(cm, labels)
print('--------------------------------------------------------------')
def plot_history(hs, epochs, title, upper = 0.9):
#figure(num=None, figsize=(6, 6), dpi=100, facecolor='w', edgecolor='k')
plt.close()
plt.plot(hs.history['acc'])
plt.plot(hs.history['val_acc'])
plt.title('Model Accuracy')
plt.ylabel('accuracy')
plt.xticks(range(0,epochs,2))
plt.ylim(top = upper)
plt.xlabel('epoch')
plt.legend(['Train Accuracy',
'Validation Accuracy'], loc = 4)
plt.savefig(title + '_Acc.png')
plt.close()
plt.plot(hs.history['loss'])
plt.plot(hs.history['val_loss'])
plt.xticks(range(0,epochs,2))
plt.title('Model Loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['Train Loss','Validation Loss'], loc = 1)
plt.savefig(title + '_Loss.png')
def print_cm(cm, labels, hide_zeroes=False, hide_diagonal=False, hide_threshold=None):
"""pretty print for confusion matrixes"""
columnwidth = max([len(x) for x in labels] + [5]) # 5 is value length
empty_cell = " " * columnwidth
# Print header
print(" " + empty_cell, end=" ")
for label in labels:
print("%{0}s".format(columnwidth) % label, end=" ")
print()
# Print rows
for i, label1 in enumerate(labels):
print(" %{0}s".format(columnwidth) % label1, end=" ")
for j in range(len(labels)):
cell = "%{0}.1f".format(columnwidth) % cm[i, j]
if hide_zeroes:
cell = cell if float(cm[i, j]) != 0 else empty_cell
if hide_diagonal:
cell = cell if i != j else empty_cell
if hide_threshold:
cell = cell if cm[i, j] > hide_threshold else empty_cell
print(cell, end=" ")
print()
def pretty_percentage(amount):
print(str(np.round(amount*100,2)) + '%')
def clean_text(text):
"""
1. Remove html like text from europarl e.g. <Chapter 1>
2. Remove line breaks
3. Reduce all whitespaces to 1
4. turn everything to lower case
""" | regex = re.compile('[\.|\-|\,|\?|\_|\:|\"|\)|\(\)\/|\\|\>|\<]')
text = text.lower() # Turn everything to lower case
text = regex.sub(' ', text).strip()
out = re.sub(' +', ' ', text) # Reduce whitespace down to one
return out
########################################################################################################
##################################### Preprocessing ####################################################
########################################################################################################
tok = TweetTokenizer()
path = '.'
os.chdir(path)
raw = pd.read_csv('imdb_master.csv',encoding='iso-8859-1')
raw = raw[raw['label'] != 'unsup']
data = list(raw.review)
labels = raw.label
del raw
labels = list(labels.replace({'pos': 1, 'neg': 0}))
for i in range(0,len(data)):
clean = tok.tokenize(clean_text(data[i]))
clean = [word for word in clean if word != 'br']
clean = ' '.join(clean)
data[i] = clean
print('Review ' + str(i+1) + ' cleaned. Completed ' + str(round(i * 100 / len(data), 2)) + '%')
with open('data', 'wb') as f:
pickle.dump(data, f)
with open('labels', 'wb') as f:
pickle.dump(labels, f)
"""
with open('data', 'rb') as f:
data = pickle.load(f)
with open('labels', 'rb') as f:
labels = pickle.load(f)
"""
########################################################################################################
######################################## Split into Sets ##############################################
########################################################################################################
X_Train, X_Tune, Y_Train, Y_Tune = train_test_split(data,
labels,
test_size=0.10,
random_state = 40)
X_Validation, X_Test, Y_Validation, Y_Test = train_test_split(X_Tune,
Y_Tune,
test_size=0.5,
random_state = 40)
print('Training set size:', len(X_Train))
print('Validation set size:', len(X_Validation))
print('Test set size:', len(X_Test))
del X_Tune, Y_Tune
gc.collect()
########################################################################################################
########################################## Create Grams ################################################
########################################################################################################
Unigram_vectorizer = TfidfVectorizer(ngram_range = (1, 1),
min_df = 10,
analyzer = 'word',
stop_words = stopwords.words('english'))
Uni_X_Train = Unigram_vectorizer.fit_transform(X_Train)
Uni_X_Validation = Unigram_vectorizer.transform(X_Validation)
Uni_X_Test = Unigram_vectorizer.transform(X_Test)
print('Unigram Training Dataset:',Uni_X_Train.shape)
print('Unigram Validation Dataset:',Uni_X_Validation.shape)
print('Unigram Test Dataset:',Uni_X_Test.shape)
########################################################################################################
######################## Perform Truncated SVD to reduce dimensions ####################################
########################################################################################################
from sklearn.decomposition import TruncatedSVD
tsvd1 = TruncatedSVD(n_components=10000, random_state=42)
svd_model_uni = tsvd1.fit(Uni_X_Train)
uni_ex_var = np.sum(svd_model_uni.explained_variance_ratio_)
reduced_uni_train = svd_model_uni.transform(Uni_X_Train)
reduced_uni_validation = svd_model_uni.transform(Uni_X_Validation)
reduced_uni_test = svd_model_uni.transform(Uni_X_Test)
print('Initial Shape of Unigram Data:',Uni_X_Train.shape)
print('Explained Variance of Unigram model: ')
pretty_percentage(uni_ex_var)
print('Reduced Shape of Unigram Data:',reduced_uni_train.shape)
with open('reduced_uni_train', 'wb') as f:
pickle.dump(reduced_uni_train, f)
with open('reduced_uni_validation', 'wb') as f:
pickle.dump(reduced_uni_validation, f)
with open('reduced_uni_test', 'wb') as f:
pickle.dump(reduced_uni_test, f)
with open('Y_Train', 'wb') as f:
pickle.dump(Y_Train, f)
with open('Y_Validation', 'wb') as f:
pickle.dump(Y_Validation, f)
with open('Y_Test', 'wb') as f:
pickle.dump(Y_Test, f)
"""
with open('reduced_uni_train', 'rb') as f:
reduced_uni_train = pickle.load(f)
with open('reduced_uni_validation', 'rb') as f:
reduced_uni_validation = pickle.load(f)
with open('reduced_uni_test', 'rb') as f:
reduced_uni_test = pickle.load(f)
with open('Y_Train', 'rb') as f:
Y_Train = pickle.load(f)
with open('Y_Validation', 'rb') as f:
Y_Validation = pickle.load(f)
with open('Y_Test', 'rb') as f:
Y_Test = pickle.load(f)
"""
########################################################################################################
###################################### Modelling #######################################################
########################################################################################################
#######################################################
## Baseline Classifier ##
#######################################################
Class_Freq_Train = pd.Series(Y_Train).value_counts()
print(Class_Freq_Train)
baseline_train = np.zeros((len(Y_Train)))
baseline_valid = np.zeros((len(Y_Validation)))
Score_Classifier(baseline_train, Y_Train, baseline_valid, Y_Validation, Classifier_Title = 'Baseline')
#######################################################
## MLP for Unigrams ##
#######################################################
from keras.callbacks import Callback
from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score
from keras.regularizers import l1
from keras.layers import LeakyReLU
class Metrics(Callback):
def on_train_begin(self, logs={}):
self.val_f1s = []
self.val_recalls = []
self.val_precisions = []
def on_epoch_end(self, epoch, logs={}):
val_predict = (np.asarray(self.model.predict(self.validation_data[0]))).round()
val_targ = self.validation_data[1]
_val_f1 = f1_score(Y_Validation, val_predict)
_val_recall = recall_score(val_targ, val_predict)
_val_precision = precision_score(val_targ, val_predict)
self.val_f1s.append(_val_f1)
self.val_recalls.append(_val_recall)
self.val_precisions.append(_val_precision)
print(' — val_f1: %f — val_precision: %f — val_recall %f' %(_val_f1, _val_precision, _val_recall))
print()
return
metrics = Metrics()
def Dense_Layer(input_tensor, n_neurons, l1_rate = 0.02, dropout_rate = 0):
X = Dense(n_neurons, kernel_regularizer= l1(l1_rate))(input_tensor)
X = BatchNormalization(axis = -1)(X)
X = LeakyReLU(alpha = 0.1)(X)
X = Dropout(dropout_rate)(X)
return X
def Create_Model(structure, l1_rate = 0, dropout_rate = 0, opt = 'adam', inpt = 10000):
X_input = Input((inpt,))
X = BatchNormalization(axis = -1)(X_input)
for i in range(0,len(structure)):
X = Dense_Layer(X, structure[i], l1_rate = l1_rate, dropout_rate = dropout_rate)
X = BatchNormalization(axis = -1)(X)
X = Dense(1, activation = 'sigmoid')(X)
model = Model(inputs = X_input, outputs = X, name='Sentiment Recognizer')
model.compile(optimizer = opt, loss = "binary_crossentropy", metrics = ['accuracy'])
return model
###############################################################################
###################### Structure Tuning ###################################
###############################################################################
scenarios = []
scenarios.append([10])
scenarios.append([50])
scenarios.append([10,10])
scenarios.append([50,50])
scenarios.append([10,10,10])
scenarios.append([50,50,50])
scenarios.append([10,10,10,10])
scenarios.append([50,50,50,50])
scenarios.append([10,10,10,10,10])
scenarios.append([50,50,50,50,50])
epochs = 15
cnt = 1
for scenario in scenarios:
structure1 = scenario
model1 = Create_Model(structure1, 0.005, 0.3, 'adam',10000)
model1.summary()
history1 = model1.fit(reduced_uni_train, Y_Train,
validation_data=(reduced_uni_validation, Y_Validation),
epochs=15,
batch_size=256,
callbacks=[metrics])
model1.evaluate(reduced_uni_test, Y_Test)
print('Number of Hidden Layers:',str(len(structure1)))
print('Number of Neurons per Layer:',str(structure1[0]))
plot_history(history1, epochs, 'Scenario' + str(cnt))
cnt+=1
final_structure1 = scenarios[9]
###############################################################################
###################### Optimizer Tuning ##############################
###############################################################################
model1 = Create_Model(final_structure1, 0.005, 0.3, 'adagrad',10000)
model1.summary()
history1 = model1.fit(reduced_uni_train, Y_Train,
validation_data=(reduced_uni_validation, Y_Validation),
epochs=epochs,
batch_size=256,
callbacks=[metrics])
plot_history(history1, epochs, 'adagrad', 1.0)
###############################################################################
###################### Regularization Tuning #########################
###############################################################################
epochs = 15
model1 = Create_Model(final_structure1, 0.011, 0, 'adagrad',10000)
model1.summary()
history1 = model1.fit(reduced_uni_train, Y_Train,
validation_data=(reduced_uni_validation, Y_Validation),
epochs=epochs,
batch_size=256,
callbacks=[metrics])
###############################################################################
############################# Final Model ############################
###############################################################################
epochs = 15
model1 = Create_Model(final_structure1, 0.011, 0, 'adagrad',10000)
model1.summary()
history1 = model1.fit(reduced_uni_train, Y_Train,
validation_data=(reduced_uni_validation, Y_Validation),
epochs=epochs,
batch_size=256,
callbacks=[metrics])
tr_pred = model1.predict(reduced_uni_train)
tr_pred[tr_pred>=0.5] = 1
tr_pred[tr_pred<0.5] = 0
ts_pred = model1.predict(reduced_uni_test)
ts_pred[ts_pred>=0.5] = 1
ts_pred[ts_pred<0.5] = 0
Score_Classifier(tr_pred, Y_Train, ts_pred, Y_Test,
labels = ['Negative','Positive'], Classifier_Title = 'Final Model',
evaluation_type = 'Test')
###############################################################################
################# Error Overview ####################
###############################################################################
true = np.array(Y_Test).reshape(2500,)/1.
predicted = ts_pred.reshape(2500,)/1.
# False Positive
fps = np.where((predicted== 1.)& (true ==0))[0]
index = np.random.choice(fps.shape[0], 1)[0]
X_Test[index]
# False Negative
fps = np.where((predicted== 0.)& (true ==1))[0]
index = np.random.choice(fps.shape[0], 1)[0]
X_Test[index]
#######################################################
## BIDIRECTIONAL RNN WITH MLP ON TOP ##
#######################################################
#Custom keras layer for linear attention over RNNs output states
from keras.engine.topology import Layer
from keras import initializers as initializers, regularizers, constraints
from keras import backend as K
from keras.layers import InputSpec
class AttentionWeightedAverage(Layer):
"""
Computes a weighted average attention mechanism
"""
def __init__(self, return_attention=False, **kwargs):
self.init = initializers.get('uniform')
self.supports_masking = True
self.return_attention = return_attention
super(AttentionWeightedAverage, self).__init__(** kwargs)
def build(self, input_shape):
self.input_spec = [InputSpec(ndim=3)]
assert len(input_shape) == 3
self.w = self.add_weight(shape=(input_shape[2], 1),
name='{}_w'.format(self.name),
initializer=self.init)
self.trainable_weights = [self.w]
super(AttentionWeightedAverage, self).build(input_shape)
def call(self, h, mask=None):
h_shape = K.shape(h)
d_w, T = h_shape[0], h_shape[1]
logits = K.dot(h, self.w) # w^T h
logits = K.reshape(logits, (d_w, T))
alpha = K.exp(logits - K.max(logits, axis=-1, keepdims=True)) # exp
# masked timesteps have zero weight
if mask is not None:
mask = K.cast(mask, K.floatx())
alpha = alpha * mask
alpha = alpha / K.sum(alpha, axis=1, keepdims=True) # softmax
r = K.sum(h * K.expand_dims(alpha), axis=1) # r = h*alpha^T
h_star = K.tanh(r) # h^* = tanh(r)
if self.return_attention:
return [h_star, alpha]
return h_star
def get_output_shape_for(self, input_shape):
return self.compute_output_shape(input_shape)
def compute_output_shape(self, input_shape):
output_len = input_shape[2]
if self.return_attention:
return [(input_shape[0], output_len), (input_shape[0], input_shape[1])]
return (input_shape[0], output_len)
def compute_mask(self, input, input_mask=None):
if isinstance(input_mask, list):
return [None] * len(input_mask)
else:
return None
# Set Maximum number of words to be embedded
NUM_WORDS = 20000
# load tokenizer from keras
from keras.preprocessing.text import Tokenizer
# Define/Load Tokenize text function
tokenizer = Tokenizer(num_words=NUM_WORDS,filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n\'',lower=True)
# Fit the function on the text
tokenizer.fit_on_texts(X_Train)
# Count number of unique tokens
word_index = tokenizer.word_index
print('Found %s unique tokens.' % len(word_index))
word_vectors = dict()
# load the whole embedding into memory
f = open('glove.6B.300d.txt', encoding="utf8")
for line in f:
values = line.split()
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
word_vectors[word] = coefs
f.close()
print('Loaded %s word vectors.' % len(word_vectors))
EMBEDDING_DIM=300
vocabulary_size=min(len(word_index)+1,(NUM_WORDS))
embedding_matrix = np.zeros((vocabulary_size, EMBEDDING_DIM))
for word, i in word_index.items():
if i>=NUM_WORDS:
continue
try:
embedding_vector = word_vectors[word]
embedding_matrix[i] = embedding_vector
except KeyError:
pass
del(word_vectors)
# load embedding library from keras
from keras.layers import Embedding
# map words into their unique id for train and test set
X_TrainSeq = tokenizer.texts_to_sequences(X_Train)
X_TestSeq = tokenizer.texts_to_sequences(X_Test)
# padding comments into sentences in order to get fixed length comments into batch
SentLen = [len(sent) for sent in X_TrainSeq]
MAXLENGTH = int(pd.DataFrame(SentLen ).quantile(0.95)[0]) ### gets the value 148
# load pad_sequences from keras
from keras.preprocessing.sequence import pad_sequences
# create batches of length MAXLENGTH
X_TrainModified = pad_sequences(X_TrainSeq, maxlen=MAXLENGTH)
X_TestModified = pad_sequences(X_TestSeq, maxlen=MAXLENGTH)
# automatically set the number of input
inp = Input(shape=(MAXLENGTH, ))
# define the vector space of the embendings
embeddings = Embedding(vocabulary_size,EMBEDDING_DIM,weights=[embedding_matrix],trainable=True)(inp)
del(embedding_matrix)
from keras.layers import Bidirectional, Input
from keras.layers.recurrent import LSTM
drop_emb = Dropout(0.2)(embeddings)
# feed Tensor into the LSTM layer
# LSTM takes in a tensor of [Batch Size, Time Steps, Number of Inputs]
BATCHSIZE = 60 # number of samples in a batch
bilstm = Bidirectional(LSTM(60, return_sequences=True,name='lstm_layer'))(drop_emb)
DENSE = 200
x, attn = AttentionWeightedAverage(return_attention=True)(bilstm)
out = Dense(units=DENSE, activation="relu")(x)
out = Dense(units=1, activation="sigmoid")(out)
model = Model(inp, out)
print(model.summary())
from keras.optimizers import Adam
from keras_tqdm import TQDMNotebookCallback
from keras.callbacks import ModelCheckpoint
model.compile(loss='binary_crossentropy',
optimizer=Adam(lr=0.001),
metrics=['accuracy'])
checkpoint = ModelCheckpoint('keras_BiLSTM+attn_model', monitor='val_f1', verbose=1, save_best_only=True, mode='max')
# define the model
Model = model.fit(X_TrainModified, Y_Train,
batch_size=32,
epochs=2,
verbose = 0,
callbacks=[checkpoint,TQDMNotebookCallback()],
validation_data=(X_TestModified, Y_Validation),
shuffle=True)
# run the model
model = Model(inputs=inp, outputs=x) | random_line_split | |
Project4.py | ########################################################################################################
##################################################### Imports ##########################################
########################################################################################################
import re
import os
from nltk import sent_tokenize, word_tokenize
from IPython.display import clear_output
from collections import Counter
import gc
import pickle
from nltk.tokenize import RegexpTokenizer, TweetTokenizer
from nltk.util import ngrams
import pandas as pd
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
import nltk
nltk.download('stopwords')
nltk.download('punkt')
from nltk.corpus import stopwords
import matplotlib.pyplot as plt
from keras import layers
from keras.layers import Input, Dense, Activation, BatchNormalization, Flatten, Conv2D
from keras.layers import MaxPooling2D, Dropout, concatenate
from keras.models import Model
import pandas as pd
import keras.backend as K
import tensorflow as tf
import os
from keras.preprocessing.image import ImageDataGenerator
from sklearn.model_selection import train_test_split
from keras.layers import Activation
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
########################################################################################################
##################################### Declarations #####################################################
########################################################################################################
def Score_Classifier(y_train_pred, y_train_true, y_pred, y_true, labels = ['Negative','Positive'], Classifier_Title = None
, evaluation_type = 'Validation'):
cm = confusion_matrix(y_true = y_true, y_pred = y_pred)
print()
if Classifier_Title is not None:
print('************************',Classifier_Title,'************************')
print('--------------------------------------------------------------')
print('Training Accuracy:')
pretty_percentage(accuracy_score(y_pred = y_train_pred, y_true = y_train_true))
print('--------------------------------------------------------------')
print(evaluation_type +' Accuracy:')
pretty_percentage(accuracy_score(y_pred = y_pred, y_true = y_true))
print('--------------------------------------------------------------')
print(evaluation_type +' Precision:')
pretty_percentage(precision_score(y_pred = y_pred, y_true = y_true))
print('--------------------------------------------------------------')
print(evaluation_type +' Recall:')
pretty_percentage(recall_score(y_pred = y_pred, y_true = y_true))
print('--------------------------------------------------------------')
print(evaluation_type +' F1 Score:')
pretty_percentage(f1_score(y_pred = y_pred, y_true = y_true))
print('--------------------------------------------------------------')
print(evaluation_type +' Confusion Matrix:')
print_cm(cm, labels)
print('--------------------------------------------------------------')
def plot_history(hs, epochs, title, upper = 0.9):
#figure(num=None, figsize=(6, 6), dpi=100, facecolor='w', edgecolor='k')
plt.close()
plt.plot(hs.history['acc'])
plt.plot(hs.history['val_acc'])
plt.title('Model Accuracy')
plt.ylabel('accuracy')
plt.xticks(range(0,epochs,2))
plt.ylim(top = upper)
plt.xlabel('epoch')
plt.legend(['Train Accuracy',
'Validation Accuracy'], loc = 4)
plt.savefig(title + '_Acc.png')
plt.close()
plt.plot(hs.history['loss'])
plt.plot(hs.history['val_loss'])
plt.xticks(range(0,epochs,2))
plt.title('Model Loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['Train Loss','Validation Loss'], loc = 1)
plt.savefig(title + '_Loss.png')
def print_cm(cm, labels, hide_zeroes=False, hide_diagonal=False, hide_threshold=None):
"""pretty print for confusion matrixes"""
columnwidth = max([len(x) for x in labels] + [5]) # 5 is value length
empty_cell = " " * columnwidth
# Print header
print(" " + empty_cell, end=" ")
for label in labels:
print("%{0}s".format(columnwidth) % label, end=" ")
print()
# Print rows
for i, label1 in enumerate(labels):
print(" %{0}s".format(columnwidth) % label1, end=" ")
for j in range(len(labels)):
cell = "%{0}.1f".format(columnwidth) % cm[i, j]
if hide_zeroes:
cell = cell if float(cm[i, j]) != 0 else empty_cell
if hide_diagonal:
cell = cell if i != j else empty_cell
if hide_threshold:
cell = cell if cm[i, j] > hide_threshold else empty_cell
print(cell, end=" ")
print()
def pretty_percentage(amount):
print(str(np.round(amount*100,2)) + '%')
def clean_text(text):
"""
1. Remove html like text from europarl e.g. <Chapter 1>
2. Remove line breaks
3. Reduce all whitespaces to 1
4. turn everything to lower case
"""
regex = re.compile('[\.|\-|\,|\?|\_|\:|\"|\)|\(\)\/|\\|\>|\<]')
text = text.lower() # Turn everything to lower case
text = regex.sub(' ', text).strip()
out = re.sub(' +', ' ', text) # Reduce whitespace down to one
return out
########################################################################################################
##################################### Preprocessing ####################################################
########################################################################################################
tok = TweetTokenizer()
path = '.'
os.chdir(path)
raw = pd.read_csv('imdb_master.csv',encoding='iso-8859-1')
raw = raw[raw['label'] != 'unsup']
data = list(raw.review)
labels = raw.label
del raw
labels = list(labels.replace({'pos': 1, 'neg': 0}))
for i in range(0,len(data)):
clean = tok.tokenize(clean_text(data[i]))
clean = [word for word in clean if word != 'br']
clean = ' '.join(clean)
data[i] = clean
print('Review ' + str(i+1) + ' cleaned. Completed ' + str(round(i * 100 / len(data), 2)) + '%')
with open('data', 'wb') as f:
pickle.dump(data, f)
with open('labels', 'wb') as f:
pickle.dump(labels, f)
"""
with open('data', 'rb') as f:
data = pickle.load(f)
with open('labels', 'rb') as f:
labels = pickle.load(f)
"""
########################################################################################################
######################################## Split into Sets ##############################################
########################################################################################################
X_Train, X_Tune, Y_Train, Y_Tune = train_test_split(data,
labels,
test_size=0.10,
random_state = 40)
X_Validation, X_Test, Y_Validation, Y_Test = train_test_split(X_Tune,
Y_Tune,
test_size=0.5,
random_state = 40)
print('Training set size:', len(X_Train))
print('Validation set size:', len(X_Validation))
print('Test set size:', len(X_Test))
del X_Tune, Y_Tune
gc.collect()
########################################################################################################
########################################## Create Grams ################################################
########################################################################################################
Unigram_vectorizer = TfidfVectorizer(ngram_range = (1, 1),
min_df = 10,
analyzer = 'word',
stop_words = stopwords.words('english'))
Uni_X_Train = Unigram_vectorizer.fit_transform(X_Train)
Uni_X_Validation = Unigram_vectorizer.transform(X_Validation)
Uni_X_Test = Unigram_vectorizer.transform(X_Test)
print('Unigram Training Dataset:',Uni_X_Train.shape)
print('Unigram Validation Dataset:',Uni_X_Validation.shape)
print('Unigram Test Dataset:',Uni_X_Test.shape)
########################################################################################################
######################## Perform Truncated SVD to reduce dimensions ####################################
########################################################################################################
from sklearn.decomposition import TruncatedSVD
tsvd1 = TruncatedSVD(n_components=10000, random_state=42)
svd_model_uni = tsvd1.fit(Uni_X_Train)
uni_ex_var = np.sum(svd_model_uni.explained_variance_ratio_)
reduced_uni_train = svd_model_uni.transform(Uni_X_Train)
reduced_uni_validation = svd_model_uni.transform(Uni_X_Validation)
reduced_uni_test = svd_model_uni.transform(Uni_X_Test)
print('Initial Shape of Unigram Data:',Uni_X_Train.shape)
print('Explained Variance of Unigram model: ')
pretty_percentage(uni_ex_var)
print('Reduced Shape of Unigram Data:',reduced_uni_train.shape)
with open('reduced_uni_train', 'wb') as f:
pickle.dump(reduced_uni_train, f)
with open('reduced_uni_validation', 'wb') as f:
pickle.dump(reduced_uni_validation, f)
with open('reduced_uni_test', 'wb') as f:
pickle.dump(reduced_uni_test, f)
with open('Y_Train', 'wb') as f:
pickle.dump(Y_Train, f)
with open('Y_Validation', 'wb') as f:
pickle.dump(Y_Validation, f)
with open('Y_Test', 'wb') as f:
pickle.dump(Y_Test, f)
"""
with open('reduced_uni_train', 'rb') as f:
reduced_uni_train = pickle.load(f)
with open('reduced_uni_validation', 'rb') as f:
reduced_uni_validation = pickle.load(f)
with open('reduced_uni_test', 'rb') as f:
reduced_uni_test = pickle.load(f)
with open('Y_Train', 'rb') as f:
Y_Train = pickle.load(f)
with open('Y_Validation', 'rb') as f:
Y_Validation = pickle.load(f)
with open('Y_Test', 'rb') as f:
Y_Test = pickle.load(f)
"""
########################################################################################################
###################################### Modelling #######################################################
########################################################################################################
#######################################################
## Baseline Classifier ##
#######################################################
Class_Freq_Train = pd.Series(Y_Train).value_counts()
print(Class_Freq_Train)
baseline_train = np.zeros((len(Y_Train)))
baseline_valid = np.zeros((len(Y_Validation)))
Score_Classifier(baseline_train, Y_Train, baseline_valid, Y_Validation, Classifier_Title = 'Baseline')
#######################################################
## MLP for Unigrams ##
#######################################################
from keras.callbacks import Callback
from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score
from keras.regularizers import l1
from keras.layers import LeakyReLU
class Metrics(Callback):
def on_train_begin(self, logs={}):
self.val_f1s = []
self.val_recalls = []
self.val_precisions = []
def on_epoch_end(self, epoch, logs={}):
val_predict = (np.asarray(self.model.predict(self.validation_data[0]))).round()
val_targ = self.validation_data[1]
_val_f1 = f1_score(Y_Validation, val_predict)
_val_recall = recall_score(val_targ, val_predict)
_val_precision = precision_score(val_targ, val_predict)
self.val_f1s.append(_val_f1)
self.val_recalls.append(_val_recall)
self.val_precisions.append(_val_precision)
print(' — val_f1: %f — val_precision: %f — val_recall %f' %(_val_f1, _val_precision, _val_recall))
print()
return
metrics = Metrics()
def Dense_Layer(input_tensor, n_neurons, l1_rate = 0.02, dropout_rate = 0):
X = Dense(n_neurons, kernel_regularizer= l1(l1_rate))(input_tensor)
X = BatchNormalization(axis = -1)(X)
X = LeakyReLU(alpha = 0.1)(X)
X = Dropout(dropout_rate)(X)
return X
def Create_Model(structure, l1_rate = 0, dropout_rate = 0, opt = 'adam', inpt = 10000):
X_input = Input((inpt,))
X = BatchNormalization(axis = -1)(X_input)
for i in range(0,len(structure)):
X = Dense_Layer(X, structure[i], l1_rate = l1_rate, dropout_rate = dropout_rate)
X = BatchNormalization(axis = -1)(X)
X = Dense(1, activation = 'sigmoid')(X)
model = Model(inputs = X_input, outputs = X, name='Sentiment Recognizer')
model.compile(optimizer = opt, loss = "binary_crossentropy", metrics = ['accuracy'])
return model
###############################################################################
###################### Structure Tuning ###################################
###############################################################################
scenarios = []
scenarios.append([10])
scenarios.append([50])
scenarios.append([10,10])
scenarios.append([50,50])
scenarios.append([10,10,10])
scenarios.append([50,50,50])
scenarios.append([10,10,10,10])
scenarios.append([50,50,50,50])
scenarios.append([10,10,10,10,10])
scenarios.append([50,50,50,50,50])
epochs = 15
cnt = 1
for scenario in scenarios:
structure1 = scenario
model1 = Create_Model(structure1, 0.005, 0.3, 'adam',10000)
model1.summary()
history1 = model1.fit(reduced_uni_train, Y_Train,
validation_data=(reduced_uni_validation, Y_Validation),
epochs=15,
batch_size=256,
callbacks=[metrics])
model1.evaluate(reduced_uni_test, Y_Test)
print('Number of Hidden Layers:',str(len(structure1)))
print('Number of Neurons per Layer:',str(structure1[0]))
plot_history(history1, epochs, 'Scenario' + str(cnt))
cnt+=1
final_structure1 = scenarios[9]
###############################################################################
###################### Optimizer Tuning ##############################
###############################################################################
model1 = Create_Model(final_structure1, 0.005, 0.3, 'adagrad',10000)
model1.summary()
history1 = model1.fit(reduced_uni_train, Y_Train,
validation_data=(reduced_uni_validation, Y_Validation),
epochs=epochs,
batch_size=256,
callbacks=[metrics])
plot_history(history1, epochs, 'adagrad', 1.0)
###############################################################################
###################### Regularization Tuning #########################
###############################################################################
epochs = 15
model1 = Create_Model(final_structure1, 0.011, 0, 'adagrad',10000)
model1.summary()
history1 = model1.fit(reduced_uni_train, Y_Train,
validation_data=(reduced_uni_validation, Y_Validation),
epochs=epochs,
batch_size=256,
callbacks=[metrics])
###############################################################################
############################# Final Model ############################
###############################################################################
epochs = 15
model1 = Create_Model(final_structure1, 0.011, 0, 'adagrad',10000)
model1.summary()
history1 = model1.fit(reduced_uni_train, Y_Train,
validation_data=(reduced_uni_validation, Y_Validation),
epochs=epochs,
batch_size=256,
callbacks=[metrics])
tr_pred = model1.predict(reduced_uni_train)
tr_pred[tr_pred>=0.5] = 1
tr_pred[tr_pred<0.5] = 0
ts_pred = model1.predict(reduced_uni_test)
ts_pred[ts_pred>=0.5] = 1
ts_pred[ts_pred<0.5] = 0
Score_Classifier(tr_pred, Y_Train, ts_pred, Y_Test,
labels = ['Negative','Positive'], Classifier_Title = 'Final Model',
evaluation_type = 'Test')
###############################################################################
################# Error Overview ####################
###############################################################################
true = np.array(Y_Test).reshape(2500,)/1.
predicted = ts_pred.reshape(2500,)/1.
# False Positive
fps = np.where((predicted== 1.)& (true ==0))[0]
index = np.random.choice(fps.shape[0], 1)[0]
X_Test[index]
# False Negative
fps = np.where((predicted== 0.)& (true ==1))[0]
index = np.random.choice(fps.shape[0], 1)[0]
X_Test[index]
#######################################################
## BIDIRECTIONAL RNN WITH MLP ON TOP ##
#######################################################
#Custom keras layer for linear attention over RNNs output states
from keras.engine.topology import Layer
from keras import initializers as initializers, regularizers, constraints
from keras import backend as K
from keras.layers import InputSpec
class AttentionWeightedAverage(Layer):
"""
| t Maximum number of words to be embedded
NUM_WORDS = 20000
# load tokenizer from keras
from keras.preprocessing.text import Tokenizer
# Define/Load Tokenize text function
tokenizer = Tokenizer(num_words=NUM_WORDS,filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n\'',lower=True)
# Fit the function on the text
tokenizer.fit_on_texts(X_Train)
# Count number of unique tokens
word_index = tokenizer.word_index
print('Found %s unique tokens.' % len(word_index))
word_vectors = dict()
# load the whole embedding into memory
f = open('glove.6B.300d.txt', encoding="utf8")
for line in f:
values = line.split()
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
word_vectors[word] = coefs
f.close()
print('Loaded %s word vectors.' % len(word_vectors))
EMBEDDING_DIM=300
vocabulary_size=min(len(word_index)+1,(NUM_WORDS))
embedding_matrix = np.zeros((vocabulary_size, EMBEDDING_DIM))
for word, i in word_index.items():
if i>=NUM_WORDS:
continue
try:
embedding_vector = word_vectors[word]
embedding_matrix[i] = embedding_vector
except KeyError:
pass
del(word_vectors)
# load embedding library from keras
from keras.layers import Embedding
# map words into their unique id for train and test set
X_TrainSeq = tokenizer.texts_to_sequences(X_Train)
X_TestSeq = tokenizer.texts_to_sequences(X_Test)
# padding comments into sentences in order to get fixed length comments into batch
SentLen = [len(sent) for sent in X_TrainSeq]
MAXLENGTH = int(pd.DataFrame(SentLen ).quantile(0.95)[0]) ### gets the value 148
# load pad_sequences from keras
from keras.preprocessing.sequence import pad_sequences
# create batches of length MAXLENGTH
X_TrainModified = pad_sequences(X_TrainSeq, maxlen=MAXLENGTH)
X_TestModified = pad_sequences(X_TestSeq, maxlen=MAXLENGTH)
# automatically set the number of input
inp = Input(shape=(MAXLENGTH, ))
# define the vector space of the embendings
embeddings = Embedding(vocabulary_size,EMBEDDING_DIM,weights=[embedding_matrix],trainable=True)(inp)
del(embedding_matrix)
from keras.layers import Bidirectional, Input
from keras.layers.recurrent import LSTM
drop_emb = Dropout(0.2)(embeddings)
# feed Tensor into the LSTM layer
# LSTM takes in a tensor of [Batch Size, Time Steps, Number of Inputs]
BATCHSIZE = 60 # number of samples in a batch
bilstm = Bidirectional(LSTM(60, return_sequences=True,name='lstm_layer'))(drop_emb)
DENSE = 200
x, attn = AttentionWeightedAverage(return_attention=True)(bilstm)
out = Dense(units=DENSE, activation="relu")(x)
out = Dense(units=1, activation="sigmoid")(out)
model = Model(inp, out)
print(model.summary())
from keras.optimizers import Adam
from keras_tqdm import TQDMNotebookCallback
from keras.callbacks import ModelCheckpoint
model.compile(loss='binary_crossentropy',
optimizer=Adam(lr=0.001),
metrics=['accuracy'])
checkpoint = ModelCheckpoint('keras_BiLSTM+attn_model', monitor='val_f1', verbose=1, save_best_only=True, mode='max')
# define the model
Model = model.fit(X_TrainModified, Y_Train,
batch_size=32,
epochs=2,
verbose = 0,
callbacks=[checkpoint,TQDMNotebookCallback()],
validation_data=(X_TestModified, Y_Validation),
shuffle=True)
# run the model
model = Model(inputs=inp, outputs=x)
| Computes a weighted average attention mechanism
"""
def __init__(self, return_attention=False, **kwargs):
self.init = initializers.get('uniform')
self.supports_masking = True
self.return_attention = return_attention
super(AttentionWeightedAverage, self).__init__(** kwargs)
def build(self, input_shape):
self.input_spec = [InputSpec(ndim=3)]
assert len(input_shape) == 3
self.w = self.add_weight(shape=(input_shape[2], 1),
name='{}_w'.format(self.name),
initializer=self.init)
self.trainable_weights = [self.w]
super(AttentionWeightedAverage, self).build(input_shape)
def call(self, h, mask=None):
h_shape = K.shape(h)
d_w, T = h_shape[0], h_shape[1]
logits = K.dot(h, self.w) # w^T h
logits = K.reshape(logits, (d_w, T))
alpha = K.exp(logits - K.max(logits, axis=-1, keepdims=True)) # exp
# masked timesteps have zero weight
if mask is not None:
mask = K.cast(mask, K.floatx())
alpha = alpha * mask
alpha = alpha / K.sum(alpha, axis=1, keepdims=True) # softmax
r = K.sum(h * K.expand_dims(alpha), axis=1) # r = h*alpha^T
h_star = K.tanh(r) # h^* = tanh(r)
if self.return_attention:
return [h_star, alpha]
return h_star
def get_output_shape_for(self, input_shape):
return self.compute_output_shape(input_shape)
def compute_output_shape(self, input_shape):
output_len = input_shape[2]
if self.return_attention:
return [(input_shape[0], output_len), (input_shape[0], input_shape[1])]
return (input_shape[0], output_len)
def compute_mask(self, input, input_mask=None):
if isinstance(input_mask, list):
return [None] * len(input_mask)
else:
return None
# Se | identifier_body |
Project4.py | ########################################################################################################
##################################################### Imports ##########################################
########################################################################################################
import re
import os
from nltk import sent_tokenize, word_tokenize
from IPython.display import clear_output
from collections import Counter
import gc
import pickle
from nltk.tokenize import RegexpTokenizer, TweetTokenizer
from nltk.util import ngrams
import pandas as pd
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
import nltk
nltk.download('stopwords')
nltk.download('punkt')
from nltk.corpus import stopwords
import matplotlib.pyplot as plt
from keras import layers
from keras.layers import Input, Dense, Activation, BatchNormalization, Flatten, Conv2D
from keras.layers import MaxPooling2D, Dropout, concatenate
from keras.models import Model
import pandas as pd
import keras.backend as K
import tensorflow as tf
import os
from keras.preprocessing.image import ImageDataGenerator
from sklearn.model_selection import train_test_split
from keras.layers import Activation
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
########################################################################################################
##################################### Declarations #####################################################
########################################################################################################
def Score_Classifier(y_train_pred, y_train_true, y_pred, y_true, labels = ['Negative','Positive'], Classifier_Title = None
, evaluation_type = 'Validation'):
cm = confusion_matrix(y_true = y_true, y_pred = y_pred)
print()
if Classifier_Title is not None:
print('************************',Classifier_Title,'************************')
print('--------------------------------------------------------------')
print('Training Accuracy:')
pretty_percentage(accuracy_score(y_pred = y_train_pred, y_true = y_train_true))
print('--------------------------------------------------------------')
print(evaluation_type +' Accuracy:')
pretty_percentage(accuracy_score(y_pred = y_pred, y_true = y_true))
print('--------------------------------------------------------------')
print(evaluation_type +' Precision:')
pretty_percentage(precision_score(y_pred = y_pred, y_true = y_true))
print('--------------------------------------------------------------')
print(evaluation_type +' Recall:')
pretty_percentage(recall_score(y_pred = y_pred, y_true = y_true))
print('--------------------------------------------------------------')
print(evaluation_type +' F1 Score:')
pretty_percentage(f1_score(y_pred = y_pred, y_true = y_true))
print('--------------------------------------------------------------')
print(evaluation_type +' Confusion Matrix:')
print_cm(cm, labels)
print('--------------------------------------------------------------')
def plot_history(hs, epochs, title, upper = 0.9):
#figure(num=None, figsize=(6, 6), dpi=100, facecolor='w', edgecolor='k')
plt.close()
plt.plot(hs.history['acc'])
plt.plot(hs.history['val_acc'])
plt.title('Model Accuracy')
plt.ylabel('accuracy')
plt.xticks(range(0,epochs,2))
plt.ylim(top = upper)
plt.xlabel('epoch')
plt.legend(['Train Accuracy',
'Validation Accuracy'], loc = 4)
plt.savefig(title + '_Acc.png')
plt.close()
plt.plot(hs.history['loss'])
plt.plot(hs.history['val_loss'])
plt.xticks(range(0,epochs,2))
plt.title('Model Loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['Train Loss','Validation Loss'], loc = 1)
plt.savefig(title + '_Loss.png')
def print_cm(cm, labels, hide_zeroes=False, hide_diagonal=False, hide_threshold=None):
"""pretty print for confusion matrixes"""
columnwidth = max([len(x) for x in labels] + [5]) # 5 is value length
empty_cell = " " * columnwidth
# Print header
print(" " + empty_cell, end=" ")
for label in labels:
print("%{0}s".format(columnwidth) % label, end=" ")
print()
# Print rows
for i, label1 in enumerate(labels):
print(" %{0}s".format(columnwidth) % label1, end=" ")
for j in range(len(labels)):
cell = "%{0}.1f".format(columnwidth) % cm[i, j]
if hide_zeroes:
cell = cell if float(cm[i, j]) != 0 else empty_cell
if hide_diagonal:
cell = cell if i != j else empty_cell
if hide_threshold:
cell = cell if cm[i, j] > hide_threshold else empty_cell
print(cell, end=" ")
print()
def pretty_percentage(amount):
print(str(np.round(amount*100,2)) + '%')
def clean_text(text):
"""
1. Remove html like text from europarl e.g. <Chapter 1>
2. Remove line breaks
3. Reduce all whitespaces to 1
4. turn everything to lower case
"""
regex = re.compile('[\.|\-|\,|\?|\_|\:|\"|\)|\(\)\/|\\|\>|\<]')
text = text.lower() # Turn everything to lower case
text = regex.sub(' ', text).strip()
out = re.sub(' +', ' ', text) # Reduce whitespace down to one
return out
########################################################################################################
##################################### Preprocessing ####################################################
########################################################################################################
tok = TweetTokenizer()
path = '.'
os.chdir(path)
raw = pd.read_csv('imdb_master.csv',encoding='iso-8859-1')
raw = raw[raw['label'] != 'unsup']
data = list(raw.review)
labels = raw.label
del raw
labels = list(labels.replace({'pos': 1, 'neg': 0}))
for i in range(0,len(data)):
clean = tok.tokenize(clean_text(data[i]))
clean = [word for word in clean if word != 'br']
clean = ' '.join(clean)
data[i] = clean
print('Review ' + str(i+1) + ' cleaned. Completed ' + str(round(i * 100 / len(data), 2)) + '%')
with open('data', 'wb') as f:
pickle.dump(data, f)
with open('labels', 'wb') as f:
pickle.dump(labels, f)
"""
with open('data', 'rb') as f:
data = pickle.load(f)
with open('labels', 'rb') as f:
labels = pickle.load(f)
"""
########################################################################################################
######################################## Split into Sets ##############################################
########################################################################################################
X_Train, X_Tune, Y_Train, Y_Tune = train_test_split(data,
labels,
test_size=0.10,
random_state = 40)
X_Validation, X_Test, Y_Validation, Y_Test = train_test_split(X_Tune,
Y_Tune,
test_size=0.5,
random_state = 40)
print('Training set size:', len(X_Train))
print('Validation set size:', len(X_Validation))
print('Test set size:', len(X_Test))
del X_Tune, Y_Tune
gc.collect()
########################################################################################################
########################################## Create Grams ################################################
########################################################################################################
Unigram_vectorizer = TfidfVectorizer(ngram_range = (1, 1),
min_df = 10,
analyzer = 'word',
stop_words = stopwords.words('english'))
Uni_X_Train = Unigram_vectorizer.fit_transform(X_Train)
Uni_X_Validation = Unigram_vectorizer.transform(X_Validation)
Uni_X_Test = Unigram_vectorizer.transform(X_Test)
print('Unigram Training Dataset:',Uni_X_Train.shape)
print('Unigram Validation Dataset:',Uni_X_Validation.shape)
print('Unigram Test Dataset:',Uni_X_Test.shape)
########################################################################################################
######################## Perform Truncated SVD to reduce dimensions ####################################
########################################################################################################
from sklearn.decomposition import TruncatedSVD
tsvd1 = TruncatedSVD(n_components=10000, random_state=42)
svd_model_uni = tsvd1.fit(Uni_X_Train)
uni_ex_var = np.sum(svd_model_uni.explained_variance_ratio_)
reduced_uni_train = svd_model_uni.transform(Uni_X_Train)
reduced_uni_validation = svd_model_uni.transform(Uni_X_Validation)
reduced_uni_test = svd_model_uni.transform(Uni_X_Test)
print('Initial Shape of Unigram Data:',Uni_X_Train.shape)
print('Explained Variance of Unigram model: ')
pretty_percentage(uni_ex_var)
print('Reduced Shape of Unigram Data:',reduced_uni_train.shape)
with open('reduced_uni_train', 'wb') as f:
pickle.dump(reduced_uni_train, f)
with open('reduced_uni_validation', 'wb') as f:
pickle.dump(reduced_uni_validation, f)
with open('reduced_uni_test', 'wb') as f:
pickle.dump(reduced_uni_test, f)
with open('Y_Train', 'wb') as f:
pickle.dump(Y_Train, f)
with open('Y_Validation', 'wb') as f:
pickle.dump(Y_Validation, f)
with open('Y_Test', 'wb') as f:
pickle.dump(Y_Test, f)
"""
with open('reduced_uni_train', 'rb') as f:
reduced_uni_train = pickle.load(f)
with open('reduced_uni_validation', 'rb') as f:
reduced_uni_validation = pickle.load(f)
with open('reduced_uni_test', 'rb') as f:
reduced_uni_test = pickle.load(f)
with open('Y_Train', 'rb') as f:
Y_Train = pickle.load(f)
with open('Y_Validation', 'rb') as f:
Y_Validation = pickle.load(f)
with open('Y_Test', 'rb') as f:
Y_Test = pickle.load(f)
"""
########################################################################################################
###################################### Modelling #######################################################
########################################################################################################
#######################################################
## Baseline Classifier ##
#######################################################
Class_Freq_Train = pd.Series(Y_Train).value_counts()
print(Class_Freq_Train)
baseline_train = np.zeros((len(Y_Train)))
baseline_valid = np.zeros((len(Y_Validation)))
Score_Classifier(baseline_train, Y_Train, baseline_valid, Y_Validation, Classifier_Title = 'Baseline')
#######################################################
## MLP for Unigrams ##
#######################################################
from keras.callbacks import Callback
from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score
from keras.regularizers import l1
from keras.layers import LeakyReLU
class | (Callback):
def on_train_begin(self, logs={}):
self.val_f1s = []
self.val_recalls = []
self.val_precisions = []
def on_epoch_end(self, epoch, logs={}):
val_predict = (np.asarray(self.model.predict(self.validation_data[0]))).round()
val_targ = self.validation_data[1]
_val_f1 = f1_score(Y_Validation, val_predict)
_val_recall = recall_score(val_targ, val_predict)
_val_precision = precision_score(val_targ, val_predict)
self.val_f1s.append(_val_f1)
self.val_recalls.append(_val_recall)
self.val_precisions.append(_val_precision)
print(' — val_f1: %f — val_precision: %f — val_recall %f' %(_val_f1, _val_precision, _val_recall))
print()
return
metrics = Metrics()
def Dense_Layer(input_tensor, n_neurons, l1_rate = 0.02, dropout_rate = 0):
X = Dense(n_neurons, kernel_regularizer= l1(l1_rate))(input_tensor)
X = BatchNormalization(axis = -1)(X)
X = LeakyReLU(alpha = 0.1)(X)
X = Dropout(dropout_rate)(X)
return X
def Create_Model(structure, l1_rate = 0, dropout_rate = 0, opt = 'adam', inpt = 10000):
X_input = Input((inpt,))
X = BatchNormalization(axis = -1)(X_input)
for i in range(0,len(structure)):
X = Dense_Layer(X, structure[i], l1_rate = l1_rate, dropout_rate = dropout_rate)
X = BatchNormalization(axis = -1)(X)
X = Dense(1, activation = 'sigmoid')(X)
model = Model(inputs = X_input, outputs = X, name='Sentiment Recognizer')
model.compile(optimizer = opt, loss = "binary_crossentropy", metrics = ['accuracy'])
return model
###############################################################################
###################### Structure Tuning ###################################
###############################################################################
scenarios = []
scenarios.append([10])
scenarios.append([50])
scenarios.append([10,10])
scenarios.append([50,50])
scenarios.append([10,10,10])
scenarios.append([50,50,50])
scenarios.append([10,10,10,10])
scenarios.append([50,50,50,50])
scenarios.append([10,10,10,10,10])
scenarios.append([50,50,50,50,50])
epochs = 15
cnt = 1
for scenario in scenarios:
structure1 = scenario
model1 = Create_Model(structure1, 0.005, 0.3, 'adam',10000)
model1.summary()
history1 = model1.fit(reduced_uni_train, Y_Train,
validation_data=(reduced_uni_validation, Y_Validation),
epochs=15,
batch_size=256,
callbacks=[metrics])
model1.evaluate(reduced_uni_test, Y_Test)
print('Number of Hidden Layers:',str(len(structure1)))
print('Number of Neurons per Layer:',str(structure1[0]))
plot_history(history1, epochs, 'Scenario' + str(cnt))
cnt+=1
final_structure1 = scenarios[9]
###############################################################################
###################### Optimizer Tuning ##############################
###############################################################################
model1 = Create_Model(final_structure1, 0.005, 0.3, 'adagrad',10000)
model1.summary()
history1 = model1.fit(reduced_uni_train, Y_Train,
validation_data=(reduced_uni_validation, Y_Validation),
epochs=epochs,
batch_size=256,
callbacks=[metrics])
plot_history(history1, epochs, 'adagrad', 1.0)
###############################################################################
###################### Regularization Tuning #########################
###############################################################################
epochs = 15
model1 = Create_Model(final_structure1, 0.011, 0, 'adagrad',10000)
model1.summary()
history1 = model1.fit(reduced_uni_train, Y_Train,
validation_data=(reduced_uni_validation, Y_Validation),
epochs=epochs,
batch_size=256,
callbacks=[metrics])
###############################################################################
############################# Final Model ############################
###############################################################################
epochs = 15
model1 = Create_Model(final_structure1, 0.011, 0, 'adagrad',10000)
model1.summary()
history1 = model1.fit(reduced_uni_train, Y_Train,
validation_data=(reduced_uni_validation, Y_Validation),
epochs=epochs,
batch_size=256,
callbacks=[metrics])
tr_pred = model1.predict(reduced_uni_train)
tr_pred[tr_pred>=0.5] = 1
tr_pred[tr_pred<0.5] = 0
ts_pred = model1.predict(reduced_uni_test)
ts_pred[ts_pred>=0.5] = 1
ts_pred[ts_pred<0.5] = 0
Score_Classifier(tr_pred, Y_Train, ts_pred, Y_Test,
labels = ['Negative','Positive'], Classifier_Title = 'Final Model',
evaluation_type = 'Test')
###############################################################################
################# Error Overview ####################
###############################################################################
true = np.array(Y_Test).reshape(2500,)/1.
predicted = ts_pred.reshape(2500,)/1.
# False Positive
fps = np.where((predicted== 1.)& (true ==0))[0]
index = np.random.choice(fps.shape[0], 1)[0]
X_Test[index]
# False Negative
fps = np.where((predicted== 0.)& (true ==1))[0]
index = np.random.choice(fps.shape[0], 1)[0]
X_Test[index]
#######################################################
## BIDIRECTIONAL RNN WITH MLP ON TOP ##
#######################################################
#Custom keras layer for linear attention over RNNs output states
from keras.engine.topology import Layer
from keras import initializers as initializers, regularizers, constraints
from keras import backend as K
from keras.layers import InputSpec
class AttentionWeightedAverage(Layer):
"""
Computes a weighted average attention mechanism
"""
def __init__(self, return_attention=False, **kwargs):
self.init = initializers.get('uniform')
self.supports_masking = True
self.return_attention = return_attention
super(AttentionWeightedAverage, self).__init__(** kwargs)
def build(self, input_shape):
self.input_spec = [InputSpec(ndim=3)]
assert len(input_shape) == 3
self.w = self.add_weight(shape=(input_shape[2], 1),
name='{}_w'.format(self.name),
initializer=self.init)
self.trainable_weights = [self.w]
super(AttentionWeightedAverage, self).build(input_shape)
def call(self, h, mask=None):
h_shape = K.shape(h)
d_w, T = h_shape[0], h_shape[1]
logits = K.dot(h, self.w) # w^T h
logits = K.reshape(logits, (d_w, T))
alpha = K.exp(logits - K.max(logits, axis=-1, keepdims=True)) # exp
# masked timesteps have zero weight
if mask is not None:
mask = K.cast(mask, K.floatx())
alpha = alpha * mask
alpha = alpha / K.sum(alpha, axis=1, keepdims=True) # softmax
r = K.sum(h * K.expand_dims(alpha), axis=1) # r = h*alpha^T
h_star = K.tanh(r) # h^* = tanh(r)
if self.return_attention:
return [h_star, alpha]
return h_star
def get_output_shape_for(self, input_shape):
return self.compute_output_shape(input_shape)
def compute_output_shape(self, input_shape):
output_len = input_shape[2]
if self.return_attention:
return [(input_shape[0], output_len), (input_shape[0], input_shape[1])]
return (input_shape[0], output_len)
def compute_mask(self, input, input_mask=None):
if isinstance(input_mask, list):
return [None] * len(input_mask)
else:
return None
# Set Maximum number of words to be embedded
NUM_WORDS = 20000
# load tokenizer from keras
from keras.preprocessing.text import Tokenizer
# Define/Load Tokenize text function
tokenizer = Tokenizer(num_words=NUM_WORDS,filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n\'',lower=True)
# Fit the function on the text
tokenizer.fit_on_texts(X_Train)
# Count number of unique tokens
word_index = tokenizer.word_index
print('Found %s unique tokens.' % len(word_index))
word_vectors = dict()
# load the whole embedding into memory
f = open('glove.6B.300d.txt', encoding="utf8")
for line in f:
values = line.split()
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
word_vectors[word] = coefs
f.close()
print('Loaded %s word vectors.' % len(word_vectors))
EMBEDDING_DIM=300
vocabulary_size=min(len(word_index)+1,(NUM_WORDS))
embedding_matrix = np.zeros((vocabulary_size, EMBEDDING_DIM))
for word, i in word_index.items():
if i>=NUM_WORDS:
continue
try:
embedding_vector = word_vectors[word]
embedding_matrix[i] = embedding_vector
except KeyError:
pass
del(word_vectors)
# load embedding library from keras
from keras.layers import Embedding
# map words into their unique id for train and test set
X_TrainSeq = tokenizer.texts_to_sequences(X_Train)
X_TestSeq = tokenizer.texts_to_sequences(X_Test)
# padding comments into sentences in order to get fixed length comments into batch
SentLen = [len(sent) for sent in X_TrainSeq]
MAXLENGTH = int(pd.DataFrame(SentLen ).quantile(0.95)[0]) ### gets the value 148
# load pad_sequences from keras
from keras.preprocessing.sequence import pad_sequences
# create batches of length MAXLENGTH
X_TrainModified = pad_sequences(X_TrainSeq, maxlen=MAXLENGTH)
X_TestModified = pad_sequences(X_TestSeq, maxlen=MAXLENGTH)
# automatically set the number of input
inp = Input(shape=(MAXLENGTH, ))
# define the vector space of the embendings
embeddings = Embedding(vocabulary_size,EMBEDDING_DIM,weights=[embedding_matrix],trainable=True)(inp)
del(embedding_matrix)
from keras.layers import Bidirectional, Input
from keras.layers.recurrent import LSTM
drop_emb = Dropout(0.2)(embeddings)
# feed Tensor into the LSTM layer
# LSTM takes in a tensor of [Batch Size, Time Steps, Number of Inputs]
BATCHSIZE = 60 # number of samples in a batch
bilstm = Bidirectional(LSTM(60, return_sequences=True,name='lstm_layer'))(drop_emb)
DENSE = 200
x, attn = AttentionWeightedAverage(return_attention=True)(bilstm)
out = Dense(units=DENSE, activation="relu")(x)
out = Dense(units=1, activation="sigmoid")(out)
model = Model(inp, out)
print(model.summary())
from keras.optimizers import Adam
from keras_tqdm import TQDMNotebookCallback
from keras.callbacks import ModelCheckpoint
model.compile(loss='binary_crossentropy',
optimizer=Adam(lr=0.001),
metrics=['accuracy'])
checkpoint = ModelCheckpoint('keras_BiLSTM+attn_model', monitor='val_f1', verbose=1, save_best_only=True, mode='max')
# define the model
Model = model.fit(X_TrainModified, Y_Train,
batch_size=32,
epochs=2,
verbose = 0,
callbacks=[checkpoint,TQDMNotebookCallback()],
validation_data=(X_TestModified, Y_Validation),
shuffle=True)
# run the model
model = Model(inputs=inp, outputs=x)
| Metrics | identifier_name |
Project4.py | ########################################################################################################
##################################################### Imports ##########################################
########################################################################################################
import re
import os
from nltk import sent_tokenize, word_tokenize
from IPython.display import clear_output
from collections import Counter
import gc
import pickle
from nltk.tokenize import RegexpTokenizer, TweetTokenizer
from nltk.util import ngrams
import pandas as pd
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
import nltk
nltk.download('stopwords')
nltk.download('punkt')
from nltk.corpus import stopwords
import matplotlib.pyplot as plt
from keras import layers
from keras.layers import Input, Dense, Activation, BatchNormalization, Flatten, Conv2D
from keras.layers import MaxPooling2D, Dropout, concatenate
from keras.models import Model
import pandas as pd
import keras.backend as K
import tensorflow as tf
import os
from keras.preprocessing.image import ImageDataGenerator
from sklearn.model_selection import train_test_split
from keras.layers import Activation
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
########################################################################################################
##################################### Declarations #####################################################
########################################################################################################
def Score_Classifier(y_train_pred, y_train_true, y_pred, y_true, labels = ['Negative','Positive'], Classifier_Title = None
, evaluation_type = 'Validation'):
cm = confusion_matrix(y_true = y_true, y_pred = y_pred)
print()
if Classifier_Title is not None:
print('************************',Classifier_Title,'************************')
print('--------------------------------------------------------------')
print('Training Accuracy:')
pretty_percentage(accuracy_score(y_pred = y_train_pred, y_true = y_train_true))
print('--------------------------------------------------------------')
print(evaluation_type +' Accuracy:')
pretty_percentage(accuracy_score(y_pred = y_pred, y_true = y_true))
print('--------------------------------------------------------------')
print(evaluation_type +' Precision:')
pretty_percentage(precision_score(y_pred = y_pred, y_true = y_true))
print('--------------------------------------------------------------')
print(evaluation_type +' Recall:')
pretty_percentage(recall_score(y_pred = y_pred, y_true = y_true))
print('--------------------------------------------------------------')
print(evaluation_type +' F1 Score:')
pretty_percentage(f1_score(y_pred = y_pred, y_true = y_true))
print('--------------------------------------------------------------')
print(evaluation_type +' Confusion Matrix:')
print_cm(cm, labels)
print('--------------------------------------------------------------')
def plot_history(hs, epochs, title, upper = 0.9):
#figure(num=None, figsize=(6, 6), dpi=100, facecolor='w', edgecolor='k')
plt.close()
plt.plot(hs.history['acc'])
plt.plot(hs.history['val_acc'])
plt.title('Model Accuracy')
plt.ylabel('accuracy')
plt.xticks(range(0,epochs,2))
plt.ylim(top = upper)
plt.xlabel('epoch')
plt.legend(['Train Accuracy',
'Validation Accuracy'], loc = 4)
plt.savefig(title + '_Acc.png')
plt.close()
plt.plot(hs.history['loss'])
plt.plot(hs.history['val_loss'])
plt.xticks(range(0,epochs,2))
plt.title('Model Loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['Train Loss','Validation Loss'], loc = 1)
plt.savefig(title + '_Loss.png')
def print_cm(cm, labels, hide_zeroes=False, hide_diagonal=False, hide_threshold=None):
"""pretty print for confusion matrixes"""
columnwidth = max([len(x) for x in labels] + [5]) # 5 is value length
empty_cell = " " * columnwidth
# Print header
print(" " + empty_cell, end=" ")
for label in labels:
print("%{0}s".format(columnwidth) % label, end=" ")
print()
# Print rows
for i, label1 in enumerate(labels):
print(" %{0}s".format(columnwidth) % label1, end=" ")
for j in range(len(labels)):
cell = "%{0}.1f".format(columnwidth) % cm[i, j]
if hide_zeroes:
cell = cell if float(cm[i, j]) != 0 else empty_cell
if hide_diagonal:
cell = cell if i != j else empty_cell
if hide_threshold:
cell = cell if cm[i, j] > hide_threshold else empty_cell
print(cell, end=" ")
print()
def pretty_percentage(amount):
print(str(np.round(amount*100,2)) + '%')
def clean_text(text):
"""
1. Remove html like text from europarl e.g. <Chapter 1>
2. Remove line breaks
3. Reduce all whitespaces to 1
4. turn everything to lower case
"""
regex = re.compile('[\.|\-|\,|\?|\_|\:|\"|\)|\(\)\/|\\|\>|\<]')
text = text.lower() # Turn everything to lower case
text = regex.sub(' ', text).strip()
out = re.sub(' +', ' ', text) # Reduce whitespace down to one
return out
########################################################################################################
##################################### Preprocessing ####################################################
########################################################################################################
tok = TweetTokenizer()
path = '.'
os.chdir(path)
raw = pd.read_csv('imdb_master.csv',encoding='iso-8859-1')
raw = raw[raw['label'] != 'unsup']
data = list(raw.review)
labels = raw.label
del raw
labels = list(labels.replace({'pos': 1, 'neg': 0}))
for i in range(0,len(data)):
clean = tok.tokenize(clean_text(data[i]))
clean = [word for word in clean if word != 'br']
clean = ' '.join(clean)
data[i] = clean
print('Review ' + str(i+1) + ' cleaned. Completed ' + str(round(i * 100 / len(data), 2)) + '%')
with open('data', 'wb') as f:
pickle.dump(data, f)
with open('labels', 'wb') as f:
pickle.dump(labels, f)
"""
with open('data', 'rb') as f:
data = pickle.load(f)
with open('labels', 'rb') as f:
labels = pickle.load(f)
"""
########################################################################################################
######################################## Split into Sets ##############################################
########################################################################################################
X_Train, X_Tune, Y_Train, Y_Tune = train_test_split(data,
labels,
test_size=0.10,
random_state = 40)
X_Validation, X_Test, Y_Validation, Y_Test = train_test_split(X_Tune,
Y_Tune,
test_size=0.5,
random_state = 40)
print('Training set size:', len(X_Train))
print('Validation set size:', len(X_Validation))
print('Test set size:', len(X_Test))
del X_Tune, Y_Tune
gc.collect()
########################################################################################################
########################################## Create Grams ################################################
########################################################################################################
Unigram_vectorizer = TfidfVectorizer(ngram_range = (1, 1),
min_df = 10,
analyzer = 'word',
stop_words = stopwords.words('english'))
Uni_X_Train = Unigram_vectorizer.fit_transform(X_Train)
Uni_X_Validation = Unigram_vectorizer.transform(X_Validation)
Uni_X_Test = Unigram_vectorizer.transform(X_Test)
print('Unigram Training Dataset:',Uni_X_Train.shape)
print('Unigram Validation Dataset:',Uni_X_Validation.shape)
print('Unigram Test Dataset:',Uni_X_Test.shape)
########################################################################################################
######################## Perform Truncated SVD to reduce dimensions ####################################
########################################################################################################
from sklearn.decomposition import TruncatedSVD
tsvd1 = TruncatedSVD(n_components=10000, random_state=42)
svd_model_uni = tsvd1.fit(Uni_X_Train)
uni_ex_var = np.sum(svd_model_uni.explained_variance_ratio_)
reduced_uni_train = svd_model_uni.transform(Uni_X_Train)
reduced_uni_validation = svd_model_uni.transform(Uni_X_Validation)
reduced_uni_test = svd_model_uni.transform(Uni_X_Test)
print('Initial Shape of Unigram Data:',Uni_X_Train.shape)
print('Explained Variance of Unigram model: ')
pretty_percentage(uni_ex_var)
print('Reduced Shape of Unigram Data:',reduced_uni_train.shape)
with open('reduced_uni_train', 'wb') as f:
pickle.dump(reduced_uni_train, f)
with open('reduced_uni_validation', 'wb') as f:
pickle.dump(reduced_uni_validation, f)
with open('reduced_uni_test', 'wb') as f:
pickle.dump(reduced_uni_test, f)
with open('Y_Train', 'wb') as f:
pickle.dump(Y_Train, f)
with open('Y_Validation', 'wb') as f:
pickle.dump(Y_Validation, f)
with open('Y_Test', 'wb') as f:
pickle.dump(Y_Test, f)
"""
with open('reduced_uni_train', 'rb') as f:
reduced_uni_train = pickle.load(f)
with open('reduced_uni_validation', 'rb') as f:
reduced_uni_validation = pickle.load(f)
with open('reduced_uni_test', 'rb') as f:
reduced_uni_test = pickle.load(f)
with open('Y_Train', 'rb') as f:
Y_Train = pickle.load(f)
with open('Y_Validation', 'rb') as f:
Y_Validation = pickle.load(f)
with open('Y_Test', 'rb') as f:
Y_Test = pickle.load(f)
"""
########################################################################################################
###################################### Modelling #######################################################
########################################################################################################
#######################################################
## Baseline Classifier ##
#######################################################
Class_Freq_Train = pd.Series(Y_Train).value_counts()
print(Class_Freq_Train)
baseline_train = np.zeros((len(Y_Train)))
baseline_valid = np.zeros((len(Y_Validation)))
Score_Classifier(baseline_train, Y_Train, baseline_valid, Y_Validation, Classifier_Title = 'Baseline')
#######################################################
## MLP for Unigrams ##
#######################################################
from keras.callbacks import Callback
from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score
from keras.regularizers import l1
from keras.layers import LeakyReLU
class Metrics(Callback):
def on_train_begin(self, logs={}):
self.val_f1s = []
self.val_recalls = []
self.val_precisions = []
def on_epoch_end(self, epoch, logs={}):
val_predict = (np.asarray(self.model.predict(self.validation_data[0]))).round()
val_targ = self.validation_data[1]
_val_f1 = f1_score(Y_Validation, val_predict)
_val_recall = recall_score(val_targ, val_predict)
_val_precision = precision_score(val_targ, val_predict)
self.val_f1s.append(_val_f1)
self.val_recalls.append(_val_recall)
self.val_precisions.append(_val_precision)
print(' — val_f1: %f — val_precision: %f — val_recall %f' %(_val_f1, _val_precision, _val_recall))
print()
return
metrics = Metrics()
def Dense_Layer(input_tensor, n_neurons, l1_rate = 0.02, dropout_rate = 0):
X = Dense(n_neurons, kernel_regularizer= l1(l1_rate))(input_tensor)
X = BatchNormalization(axis = -1)(X)
X = LeakyReLU(alpha = 0.1)(X)
X = Dropout(dropout_rate)(X)
return X
def Create_Model(structure, l1_rate = 0, dropout_rate = 0, opt = 'adam', inpt = 10000):
X_input = Input((inpt,))
X = BatchNormalization(axis = -1)(X_input)
for i in range(0,len(structure)):
X = Dense_Layer(X, structure[i], l1_rate = l1_rate, dropout_rate = dropout_rate)
X = BatchNormalization(axis = -1)(X)
X = Dense(1, activation = 'sigmoid')(X)
model = Model(inputs = X_input, outputs = X, name='Sentiment Recognizer')
model.compile(optimizer = opt, loss = "binary_crossentropy", metrics = ['accuracy'])
return model
###############################################################################
###################### Structure Tuning ###################################
###############################################################################
scenarios = []
scenarios.append([10])
scenarios.append([50])
scenarios.append([10,10])
scenarios.append([50,50])
scenarios.append([10,10,10])
scenarios.append([50,50,50])
scenarios.append([10,10,10,10])
scenarios.append([50,50,50,50])
scenarios.append([10,10,10,10,10])
scenarios.append([50,50,50,50,50])
epochs = 15
cnt = 1
for scenario in scenarios:
structure1 = scenario
model1 = Create_Model(structure1, 0.005, 0.3, 'adam',10000)
model1.summary()
history1 = model1.fit(reduced_uni_train, Y_Train,
validation_data=(reduced_uni_validation, Y_Validation),
epochs=15,
batch_size=256,
callbacks=[metrics])
model1.evaluate(reduced_uni_test, Y_Test)
print('Number of Hidden Layers:',str(len(structure1)))
print('Number of Neurons per Layer:',str(structure1[0]))
plot_history(history1, epochs, 'Scenario' + str(cnt))
cnt+=1
final_structure1 = scenarios[9]
###############################################################################
###################### Optimizer Tuning ##############################
###############################################################################
model1 = Create_Model(final_structure1, 0.005, 0.3, 'adagrad',10000)
model1.summary()
history1 = model1.fit(reduced_uni_train, Y_Train,
validation_data=(reduced_uni_validation, Y_Validation),
epochs=epochs,
batch_size=256,
callbacks=[metrics])
plot_history(history1, epochs, 'adagrad', 1.0)
###############################################################################
###################### Regularization Tuning #########################
###############################################################################
epochs = 15
model1 = Create_Model(final_structure1, 0.011, 0, 'adagrad',10000)
model1.summary()
history1 = model1.fit(reduced_uni_train, Y_Train,
validation_data=(reduced_uni_validation, Y_Validation),
epochs=epochs,
batch_size=256,
callbacks=[metrics])
###############################################################################
############################# Final Model ############################
###############################################################################
epochs = 15
model1 = Create_Model(final_structure1, 0.011, 0, 'adagrad',10000)
model1.summary()
history1 = model1.fit(reduced_uni_train, Y_Train,
validation_data=(reduced_uni_validation, Y_Validation),
epochs=epochs,
batch_size=256,
callbacks=[metrics])
tr_pred = model1.predict(reduced_uni_train)
tr_pred[tr_pred>=0.5] = 1
tr_pred[tr_pred<0.5] = 0
ts_pred = model1.predict(reduced_uni_test)
ts_pred[ts_pred>=0.5] = 1
ts_pred[ts_pred<0.5] = 0
Score_Classifier(tr_pred, Y_Train, ts_pred, Y_Test,
labels = ['Negative','Positive'], Classifier_Title = 'Final Model',
evaluation_type = 'Test')
###############################################################################
################# Error Overview ####################
###############################################################################
true = np.array(Y_Test).reshape(2500,)/1.
predicted = ts_pred.reshape(2500,)/1.
# False Positive
fps = np.where((predicted== 1.)& (true ==0))[0]
index = np.random.choice(fps.shape[0], 1)[0]
X_Test[index]
# False Negative
fps = np.where((predicted== 0.)& (true ==1))[0]
index = np.random.choice(fps.shape[0], 1)[0]
X_Test[index]
#######################################################
## BIDIRECTIONAL RNN WITH MLP ON TOP ##
#######################################################
#Custom keras layer for linear attention over RNNs output states
from keras.engine.topology import Layer
from keras import initializers as initializers, regularizers, constraints
from keras import backend as K
from keras.layers import InputSpec
class AttentionWeightedAverage(Layer):
"""
Computes a weighted average attention mechanism
"""
def __init__(self, return_attention=False, **kwargs):
self.init = initializers.get('uniform')
self.supports_masking = True
self.return_attention = return_attention
super(AttentionWeightedAverage, self).__init__(** kwargs)
def build(self, input_shape):
self.input_spec = [InputSpec(ndim=3)]
assert len(input_shape) == 3
self.w = self.add_weight(shape=(input_shape[2], 1),
name='{}_w'.format(self.name),
initializer=self.init)
self.trainable_weights = [self.w]
super(AttentionWeightedAverage, self).build(input_shape)
def call(self, h, mask=None):
h_shape = K.shape(h)
d_w, T = h_shape[0], h_shape[1]
logits = K.dot(h, self.w) # w^T h
logits = K.reshape(logits, (d_w, T))
alpha = K.exp(logits - K.max(logits, axis=-1, keepdims=True)) # exp
# masked timesteps have zero weight
if mask is not None:
mask = K.cast(mask, K.floatx())
alpha = alpha * mask
alpha = alpha / K.sum(alpha, axis=1, keepdims=True) # softmax
r = K.sum(h * K.expand_dims(alpha), axis=1) # r = h*alpha^T
h_star = K.tanh(r) # h^* = tanh(r)
if self.return_attention:
return [h_star, alpha]
return h_star
def get_output_shape_for(self, input_shape):
return self.compute_output_shape(input_shape)
def compute_output_shape(self, input_shape):
output_len = input_shape[2]
if self.return_attention:
return [(input_shape[0], output_len), (input_shape[0], input_shape[1])]
return (input_shape[0], output_len)
def compute_mask(self, input, input_mask=None):
if isinstance(input_mask, list):
return [None] * len(input_mask)
else:
return None
# Set Maximum number of words to be embedded
NUM_WORDS = 20000
# load tokenizer from keras
from keras.preprocessing.text import Tokenizer
# Define/Load Tokenize text function
tokenizer = Tokenizer(num_words=NUM_WORDS,filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n\'',lower=True)
# Fit the function on the text
tokenizer.fit_on_texts(X_Train)
# Count number of unique tokens
word_index = tokenizer.word_index
print('Found %s unique tokens.' % len(word_index))
word_vectors = dict()
# load the whole embedding into memory
f = open('glove.6B.300d.txt', encoding="utf8")
for line in f:
values = line.split()
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
word_vectors[word] = coefs
f.close()
print('Loaded %s word vectors.' % len(word_vectors))
EMBEDDING_DIM=300
vocabulary_size=min(len(word_index)+1,(NUM_WORDS))
embedding_matrix = np.zeros((vocabulary_size, EMBEDDING_DIM))
for word, i in word_index.items():
if i>=NUM_WORDS:
contin | ry:
embedding_vector = word_vectors[word]
embedding_matrix[i] = embedding_vector
except KeyError:
pass
del(word_vectors)
# load embedding library from keras
from keras.layers import Embedding
# map words into their unique id for train and test set
X_TrainSeq = tokenizer.texts_to_sequences(X_Train)
X_TestSeq = tokenizer.texts_to_sequences(X_Test)
# padding comments into sentences in order to get fixed length comments into batch
SentLen = [len(sent) for sent in X_TrainSeq]
MAXLENGTH = int(pd.DataFrame(SentLen ).quantile(0.95)[0]) ### gets the value 148
# load pad_sequences from keras
from keras.preprocessing.sequence import pad_sequences
# create batches of length MAXLENGTH
X_TrainModified = pad_sequences(X_TrainSeq, maxlen=MAXLENGTH)
X_TestModified = pad_sequences(X_TestSeq, maxlen=MAXLENGTH)
# automatically set the number of input
inp = Input(shape=(MAXLENGTH, ))
# define the vector space of the embendings
embeddings = Embedding(vocabulary_size,EMBEDDING_DIM,weights=[embedding_matrix],trainable=True)(inp)
del(embedding_matrix)
from keras.layers import Bidirectional, Input
from keras.layers.recurrent import LSTM
drop_emb = Dropout(0.2)(embeddings)
# feed Tensor into the LSTM layer
# LSTM takes in a tensor of [Batch Size, Time Steps, Number of Inputs]
BATCHSIZE = 60 # number of samples in a batch
bilstm = Bidirectional(LSTM(60, return_sequences=True,name='lstm_layer'))(drop_emb)
DENSE = 200
x, attn = AttentionWeightedAverage(return_attention=True)(bilstm)
out = Dense(units=DENSE, activation="relu")(x)
out = Dense(units=1, activation="sigmoid")(out)
model = Model(inp, out)
print(model.summary())
from keras.optimizers import Adam
from keras_tqdm import TQDMNotebookCallback
from keras.callbacks import ModelCheckpoint
model.compile(loss='binary_crossentropy',
optimizer=Adam(lr=0.001),
metrics=['accuracy'])
checkpoint = ModelCheckpoint('keras_BiLSTM+attn_model', monitor='val_f1', verbose=1, save_best_only=True, mode='max')
# define the model
Model = model.fit(X_TrainModified, Y_Train,
batch_size=32,
epochs=2,
verbose = 0,
callbacks=[checkpoint,TQDMNotebookCallback()],
validation_data=(X_TestModified, Y_Validation),
shuffle=True)
# run the model
model = Model(inputs=inp, outputs=x)
| ue
t | conditional_block |
transformer.go | package feast
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/antonmedv/expr"
"github.com/antonmedv/expr/vm"
"math"
"strings"
"time"
"github.com/buger/jsonparser"
feast "github.com/feast-dev/feast/sdk/go"
"github.com/feast-dev/feast/sdk/go/protos/feast/serving"
"github.com/feast-dev/feast/sdk/go/protos/feast/types"
"github.com/oliveagle/jsonpath"
"github.com/opentracing/opentracing-go"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"go.uber.org/zap"
"github.com/gojek/merlin/pkg/transformer"
)
var (
feastError = promauto.NewCounter(prometheus.CounterOpts{
Namespace: transformer.PromNamespace,
Name: "feast_serving_error_count",
Help: "The total number of error returned by feast serving",
})
feastLatency = promauto.NewHistogramVec(prometheus.HistogramOpts{
Namespace: transformer.PromNamespace,
Name: "feast_serving_request_duration_ms",
Help: "Feast serving latency histogram",
Buckets: prometheus.ExponentialBuckets(1, 2, 10), // 1,2,4,8,16,32,64,128,256,512,+Inf
}, []string{"result"})
feastFeatureStatus = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: transformer.PromNamespace,
Name: "feast_feature_status_count",
Help: "Feature status by feature",
}, []string{"feature", "status"})
feastFeatureSummary = promauto.NewSummaryVec(prometheus.SummaryOpts{
Namespace: transformer.PromNamespace,
Name: "feast_feature_value",
Help: "Summary of feature value",
AgeBuckets: 1,
}, []string{"feature"})
)
// Options for the Feast transformer.
type Options struct {
ServingURL string `envconfig:"FEAST_SERVING_URL" required:"true"`
StatusMonitoringEnabled bool `envconfig:"FEAST_FEATURE_STATUS_MONITORING_ENABLED" default:"false"`
ValueMonitoringEnabled bool `envconfig:"FEAST_FEATURE_VALUE_MONITORING_ENABLED" default:"false"`
}
// Transformer wraps feast serving client to retrieve features.
type Transformer struct {
feastClient feast.Client
config *transformer.StandardTransformerConfig
logger *zap.Logger
options *Options
defaultValues map[string]*types.Value
compiledJsonPath map[string]*jsonpath.Compiled
compiledUdf map[string]*vm.Program
}
// NewTransformer initializes a new Transformer.
func NewTransformer(feastClient feast.Client, config *transformer.StandardTransformerConfig, options *Options, logger *zap.Logger) (*Transformer, error) {
defaultValues := make(map[string]*types.Value)
// populate default values
for _, ft := range config.TransformerConfig.Feast {
for _, f := range ft.Features {
if len(f.DefaultValue) != 0 {
feastValType := types.ValueType_Enum(types.ValueType_Enum_value[f.ValueType])
defVal, err := getValue(f.DefaultValue, feastValType)
if err != nil {
logger.Warn(fmt.Sprintf("invalid default value for %s : %v, %v", f.Name, f.DefaultValue, err))
continue
}
defaultValues[f.Name] = defVal
}
}
}
compiledJsonPath := make(map[string]*jsonpath.Compiled)
compiledUdf := make(map[string]*vm.Program)
for _, ft := range config.TransformerConfig.Feast {
for _, configEntity := range ft.Entities {
switch configEntity.Extractor.(type) {
case *transformer.Entity_JsonPath:
c, err := jsonpath.Compile(configEntity.GetJsonPath())
if err != nil {
return nil, fmt.Errorf("unable to compile jsonpath for entity %s: %s", configEntity.Name, configEntity.GetJsonPath())
}
compiledJsonPath[configEntity.GetJsonPath()] = c
case *transformer.Entity_Udf:
c, err := expr.Compile(configEntity.GetUdf(), expr.Env(UdfEnv{}))
if err != nil {
return nil, err
}
compiledUdf[configEntity.GetUdf()] = c
}
}
}
return &Transformer{
feastClient: feastClient,
config: config,
options: options,
logger: logger,
defaultValues: defaultValues,
compiledJsonPath: compiledJsonPath,
compiledUdf: compiledUdf,
}, nil
}
type FeastFeature struct {
Columns []string `json:"columns"`
Data [][]interface{} `json:"data"`
}
type result struct {
tableName string
feastFeature *FeastFeature
err error
}
// Transform retrieves the Feast features values and add them into the request.
func (t *Transformer) Transform(ctx context.Context, request []byte) ([]byte, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.Transform")
defer span.Finish()
feastFeatures := make(map[string]*FeastFeature, len(t.config.TransformerConfig.Feast))
// parallelize feast call per feature table
resChan := make(chan result, len(t.config.TransformerConfig.Feast))
for _, config := range t.config.TransformerConfig.Feast {
go func(cfg *transformer.FeatureTable) {
tableName := createTableName(cfg.Entities)
val, err := t.getFeastFeature(ctx, tableName, request, cfg)
resChan <- result{tableName, val, err}
}(config)
}
// collect result
for i := 0; i < cap(resChan); i++ {
res := <-resChan
if res.err != nil {
return nil, res.err
}
feastFeatures[res.tableName] = res.feastFeature
}
out, err := enrichRequest(ctx, request, feastFeatures)
if err != nil {
return nil, err
}
return out, err
}
func (t *Transformer) getFeastFeature(ctx context.Context, tableName string, request []byte, config *transformer.FeatureTable) (*FeastFeature, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.getFeastFeature")
span.SetTag("table.name", tableName)
defer span.Finish()
entities, err := t.buildEntitiesRequest(ctx, request, config.Entities)
if err != nil {
return nil, err
}
var features []string
for _, feature := range config.Features {
features = append(features, feature.Name)
}
feastRequest := feast.OnlineFeaturesRequest{
Project: config.Project,
Entities: entities,
Features: features,
}
t.logger.Debug("feast_request", zap.Any("feast_request", feastRequest))
startTime := time.Now()
feastResponse, err := t.feastClient.GetOnlineFeatures(ctx, &feastRequest)
durationMs := time.Now().Sub(startTime).Milliseconds()
if err != nil {
feastLatency.WithLabelValues("error").Observe(float64(durationMs))
feastError.Inc()
return nil, err
}
feastLatency.WithLabelValues("success").Observe(float64(durationMs))
t.logger.Debug("feast_response", zap.Any("feast_response", feastResponse.Rows()))
feastFeature, err := t.buildFeastFeatures(ctx, feastResponse, config)
if err != nil {
return nil, err
}
return feastFeature, nil
}
func (t *Transformer) buildEntitiesRequest(ctx context.Context, request []byte, configEntities []*transformer.Entity) ([]feast.Row, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.buildEntitiesRequest")
defer span.Finish()
var entities []feast.Row
var nodesBody interface{}
err := json.Unmarshal(request, &nodesBody)
if err != nil {
return nil, err
}
for _, configEntity := range configEntities {
switch configEntity.Extractor.(type) {
case *transformer.Entity_JsonPath:
_, ok := t.compiledJsonPath[configEntity.GetJsonPath()]
if !ok {
c, err := jsonpath.Compile(configEntity.GetJsonPath())
if err != nil {
return nil, fmt.Errorf("unable to compile jsonpath for entity %s: %s", configEntity.Name, configEntity.GetJsonPath())
}
t.compiledJsonPath[configEntity.GetJsonPath()] = c
}
}
vals, err := getValuesFromJSONPayload(nodesBody, configEntity, t.compiledJsonPath[configEntity.GetJsonPath()], t.compiledUdf[configEntity.GetUdf()])
if err != nil {
return nil, fmt.Errorf("unable to extract entity %s: %v", configEntity.Name, err)
}
if len(entities) == 0 { | for _, val := range vals {
entities = append(entities, feast.Row{
configEntity.Name: val,
})
}
} else {
newEntities := []feast.Row{}
for _, entity := range entities {
for _, val := range vals {
newFeastRow := feast.Row{}
for k, v := range entity {
newFeastRow[k] = v
}
newFeastRow[configEntity.Name] = val
newEntities = append(newEntities, newFeastRow)
}
}
entities = newEntities
}
}
return entities, nil
}
func (t *Transformer) buildFeastFeatures(ctx context.Context, feastResponse *feast.OnlineFeaturesResponse, config *transformer.FeatureTable) (*FeastFeature, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.buildFeastFeatures")
defer span.Finish()
var columns []string
for _, entity := range config.Entities {
columns = append(columns, entity.Name)
}
for _, feature := range config.Features {
columns = append(columns, feature.Name)
}
var data [][]interface{}
status := feastResponse.Statuses()
for i, feastRow := range feastResponse.Rows() {
var row []interface{}
for _, column := range columns {
featureStatus := status[i][column]
switch featureStatus {
case serving.GetOnlineFeaturesResponse_PRESENT:
rawValue := feastRow[column]
featVal, err := getFeatureValue(rawValue)
if err != nil {
return nil, err
}
row = append(row, featVal)
// put behind feature toggle since it will generate high cardinality metrics
if t.options.ValueMonitoringEnabled {
v, err := getFloatValue(featVal)
if err != nil {
continue
}
feastFeatureSummary.WithLabelValues(column).Observe(v)
}
case serving.GetOnlineFeaturesResponse_NOT_FOUND, serving.GetOnlineFeaturesResponse_NULL_VALUE, serving.GetOnlineFeaturesResponse_OUTSIDE_MAX_AGE:
defVal, ok := t.defaultValues[column]
if !ok {
row = append(row, nil)
continue
}
featVal, err := getFeatureValue(defVal)
if err != nil {
return nil, err
}
row = append(row, featVal)
default:
return nil, fmt.Errorf("Unsupported feature retrieval status: %s", featureStatus)
}
// put behind feature toggle since it will generate high cardinality metrics
if t.options.StatusMonitoringEnabled {
feastFeatureStatus.WithLabelValues(column, featureStatus.String()).Inc()
}
}
data = append(data, row)
}
return &FeastFeature{
Columns: columns,
Data: data,
}, nil
}
func getFloatValue(val interface{}) (float64, error) {
switch i := val.(type) {
case float64:
return i, nil
case float32:
return float64(i), nil
case int64:
return float64(i), nil
case int32:
return float64(i), nil
default:
return math.NaN(), errors.New("getFloat: unknown value is of incompatible type")
}
}
func createTableName(entities []*transformer.Entity) string {
entityNames := make([]string, 0)
for _, n := range entities {
entityNames = append(entityNames, n.Name)
}
return strings.Join(entityNames, "_")
}
func getFeatureValue(val *types.Value) (interface{}, error) {
switch val.Val.(type) {
case *types.Value_StringVal:
return val.GetStringVal(), nil
case *types.Value_DoubleVal:
return val.GetDoubleVal(), nil
case *types.Value_FloatVal:
return val.GetFloatVal(), nil
case *types.Value_Int32Val:
return val.GetInt32Val(), nil
case *types.Value_Int64Val:
return val.GetInt64Val(), nil
case *types.Value_BoolVal:
return val.GetBoolVal(), nil
case *types.Value_StringListVal:
return val.GetStringListVal(), nil
case *types.Value_DoubleListVal:
return val.GetDoubleListVal(), nil
case *types.Value_FloatListVal:
return val.GetFloatListVal(), nil
case *types.Value_Int32ListVal:
return val.GetInt32ListVal(), nil
case *types.Value_Int64ListVal:
return val.GetInt64ListVal(), nil
case *types.Value_BoolListVal:
return val.GetBoolListVal(), nil
case *types.Value_BytesVal:
return val.GetBytesVal(), nil
case *types.Value_BytesListVal:
return val.GetBytesListVal(), nil
default:
return nil, fmt.Errorf("unknown feature value type: %T", val.Val)
}
}
func enrichRequest(ctx context.Context, request []byte, feastFeatures map[string]*FeastFeature) ([]byte, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.enrichRequest")
defer span.Finish()
feastFeatureJSON, err := json.Marshal(feastFeatures)
if err != nil {
return nil, err
}
out, err := jsonparser.Set(request, feastFeatureJSON, transformer.FeastFeatureJSONField)
if err != nil {
return nil, err
}
return out, err
} | random_line_split | |
transformer.go | package feast
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/antonmedv/expr"
"github.com/antonmedv/expr/vm"
"math"
"strings"
"time"
"github.com/buger/jsonparser"
feast "github.com/feast-dev/feast/sdk/go"
"github.com/feast-dev/feast/sdk/go/protos/feast/serving"
"github.com/feast-dev/feast/sdk/go/protos/feast/types"
"github.com/oliveagle/jsonpath"
"github.com/opentracing/opentracing-go"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"go.uber.org/zap"
"github.com/gojek/merlin/pkg/transformer"
)
var (
feastError = promauto.NewCounter(prometheus.CounterOpts{
Namespace: transformer.PromNamespace,
Name: "feast_serving_error_count",
Help: "The total number of error returned by feast serving",
})
feastLatency = promauto.NewHistogramVec(prometheus.HistogramOpts{
Namespace: transformer.PromNamespace,
Name: "feast_serving_request_duration_ms",
Help: "Feast serving latency histogram",
Buckets: prometheus.ExponentialBuckets(1, 2, 10), // 1,2,4,8,16,32,64,128,256,512,+Inf
}, []string{"result"})
feastFeatureStatus = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: transformer.PromNamespace,
Name: "feast_feature_status_count",
Help: "Feature status by feature",
}, []string{"feature", "status"})
feastFeatureSummary = promauto.NewSummaryVec(prometheus.SummaryOpts{
Namespace: transformer.PromNamespace,
Name: "feast_feature_value",
Help: "Summary of feature value",
AgeBuckets: 1,
}, []string{"feature"})
)
// Options for the Feast transformer.
type Options struct {
ServingURL string `envconfig:"FEAST_SERVING_URL" required:"true"`
StatusMonitoringEnabled bool `envconfig:"FEAST_FEATURE_STATUS_MONITORING_ENABLED" default:"false"`
ValueMonitoringEnabled bool `envconfig:"FEAST_FEATURE_VALUE_MONITORING_ENABLED" default:"false"`
}
// Transformer wraps feast serving client to retrieve features.
type Transformer struct {
feastClient feast.Client
config *transformer.StandardTransformerConfig
logger *zap.Logger
options *Options
defaultValues map[string]*types.Value
compiledJsonPath map[string]*jsonpath.Compiled
compiledUdf map[string]*vm.Program
}
// NewTransformer initializes a new Transformer.
func NewTransformer(feastClient feast.Client, config *transformer.StandardTransformerConfig, options *Options, logger *zap.Logger) (*Transformer, error) {
defaultValues := make(map[string]*types.Value)
// populate default values
for _, ft := range config.TransformerConfig.Feast {
for _, f := range ft.Features {
if len(f.DefaultValue) != 0 {
feastValType := types.ValueType_Enum(types.ValueType_Enum_value[f.ValueType])
defVal, err := getValue(f.DefaultValue, feastValType)
if err != nil {
logger.Warn(fmt.Sprintf("invalid default value for %s : %v, %v", f.Name, f.DefaultValue, err))
continue
}
defaultValues[f.Name] = defVal
}
}
}
compiledJsonPath := make(map[string]*jsonpath.Compiled)
compiledUdf := make(map[string]*vm.Program)
for _, ft := range config.TransformerConfig.Feast {
for _, configEntity := range ft.Entities {
switch configEntity.Extractor.(type) {
case *transformer.Entity_JsonPath:
c, err := jsonpath.Compile(configEntity.GetJsonPath())
if err != nil {
return nil, fmt.Errorf("unable to compile jsonpath for entity %s: %s", configEntity.Name, configEntity.GetJsonPath())
}
compiledJsonPath[configEntity.GetJsonPath()] = c
case *transformer.Entity_Udf:
c, err := expr.Compile(configEntity.GetUdf(), expr.Env(UdfEnv{}))
if err != nil {
return nil, err
}
compiledUdf[configEntity.GetUdf()] = c
}
}
}
return &Transformer{
feastClient: feastClient,
config: config,
options: options,
logger: logger,
defaultValues: defaultValues,
compiledJsonPath: compiledJsonPath,
compiledUdf: compiledUdf,
}, nil
}
type FeastFeature struct {
Columns []string `json:"columns"`
Data [][]interface{} `json:"data"`
}
type result struct {
tableName string
feastFeature *FeastFeature
err error
}
// Transform retrieves the Feast features values and add them into the request.
func (t *Transformer) Transform(ctx context.Context, request []byte) ([]byte, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.Transform")
defer span.Finish()
feastFeatures := make(map[string]*FeastFeature, len(t.config.TransformerConfig.Feast))
// parallelize feast call per feature table
resChan := make(chan result, len(t.config.TransformerConfig.Feast))
for _, config := range t.config.TransformerConfig.Feast {
go func(cfg *transformer.FeatureTable) {
tableName := createTableName(cfg.Entities)
val, err := t.getFeastFeature(ctx, tableName, request, cfg)
resChan <- result{tableName, val, err}
}(config)
}
// collect result
for i := 0; i < cap(resChan); i++ {
res := <-resChan
if res.err != nil {
return nil, res.err
}
feastFeatures[res.tableName] = res.feastFeature
}
out, err := enrichRequest(ctx, request, feastFeatures)
if err != nil {
return nil, err
}
return out, err
}
func (t *Transformer) getFeastFeature(ctx context.Context, tableName string, request []byte, config *transformer.FeatureTable) (*FeastFeature, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.getFeastFeature")
span.SetTag("table.name", tableName)
defer span.Finish()
entities, err := t.buildEntitiesRequest(ctx, request, config.Entities)
if err != nil {
return nil, err
}
var features []string
for _, feature := range config.Features {
features = append(features, feature.Name)
}
feastRequest := feast.OnlineFeaturesRequest{
Project: config.Project,
Entities: entities,
Features: features,
}
t.logger.Debug("feast_request", zap.Any("feast_request", feastRequest))
startTime := time.Now()
feastResponse, err := t.feastClient.GetOnlineFeatures(ctx, &feastRequest)
durationMs := time.Now().Sub(startTime).Milliseconds()
if err != nil {
feastLatency.WithLabelValues("error").Observe(float64(durationMs))
feastError.Inc()
return nil, err
}
feastLatency.WithLabelValues("success").Observe(float64(durationMs))
t.logger.Debug("feast_response", zap.Any("feast_response", feastResponse.Rows()))
feastFeature, err := t.buildFeastFeatures(ctx, feastResponse, config)
if err != nil {
return nil, err
}
return feastFeature, nil
}
func (t *Transformer) buildEntitiesRequest(ctx context.Context, request []byte, configEntities []*transformer.Entity) ([]feast.Row, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.buildEntitiesRequest")
defer span.Finish()
var entities []feast.Row
var nodesBody interface{}
err := json.Unmarshal(request, &nodesBody)
if err != nil {
return nil, err
}
for _, configEntity := range configEntities {
switch configEntity.Extractor.(type) {
case *transformer.Entity_JsonPath:
_, ok := t.compiledJsonPath[configEntity.GetJsonPath()]
if !ok {
c, err := jsonpath.Compile(configEntity.GetJsonPath())
if err != nil {
return nil, fmt.Errorf("unable to compile jsonpath for entity %s: %s", configEntity.Name, configEntity.GetJsonPath())
}
t.compiledJsonPath[configEntity.GetJsonPath()] = c
}
}
vals, err := getValuesFromJSONPayload(nodesBody, configEntity, t.compiledJsonPath[configEntity.GetJsonPath()], t.compiledUdf[configEntity.GetUdf()])
if err != nil {
return nil, fmt.Errorf("unable to extract entity %s: %v", configEntity.Name, err)
}
if len(entities) == 0 {
for _, val := range vals {
entities = append(entities, feast.Row{
configEntity.Name: val,
})
}
} else {
newEntities := []feast.Row{}
for _, entity := range entities {
for _, val := range vals {
newFeastRow := feast.Row{}
for k, v := range entity {
newFeastRow[k] = v
}
newFeastRow[configEntity.Name] = val
newEntities = append(newEntities, newFeastRow)
}
}
entities = newEntities
}
}
return entities, nil
}
func (t *Transformer) buildFeastFeatures(ctx context.Context, feastResponse *feast.OnlineFeaturesResponse, config *transformer.FeatureTable) (*FeastFeature, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.buildFeastFeatures")
defer span.Finish()
var columns []string
for _, entity := range config.Entities {
columns = append(columns, entity.Name)
}
for _, feature := range config.Features {
columns = append(columns, feature.Name)
}
var data [][]interface{}
status := feastResponse.Statuses()
for i, feastRow := range feastResponse.Rows() {
var row []interface{}
for _, column := range columns {
featureStatus := status[i][column]
switch featureStatus {
case serving.GetOnlineFeaturesResponse_PRESENT:
rawValue := feastRow[column]
featVal, err := getFeatureValue(rawValue)
if err != nil {
return nil, err
}
row = append(row, featVal)
// put behind feature toggle since it will generate high cardinality metrics
if t.options.ValueMonitoringEnabled {
v, err := getFloatValue(featVal)
if err != nil {
continue
}
feastFeatureSummary.WithLabelValues(column).Observe(v)
}
case serving.GetOnlineFeaturesResponse_NOT_FOUND, serving.GetOnlineFeaturesResponse_NULL_VALUE, serving.GetOnlineFeaturesResponse_OUTSIDE_MAX_AGE:
defVal, ok := t.defaultValues[column]
if !ok {
row = append(row, nil)
continue
}
featVal, err := getFeatureValue(defVal)
if err != nil {
return nil, err
}
row = append(row, featVal)
default:
return nil, fmt.Errorf("Unsupported feature retrieval status: %s", featureStatus)
}
// put behind feature toggle since it will generate high cardinality metrics
if t.options.StatusMonitoringEnabled {
feastFeatureStatus.WithLabelValues(column, featureStatus.String()).Inc()
}
}
data = append(data, row)
}
return &FeastFeature{
Columns: columns,
Data: data,
}, nil
}
func getFloatValue(val interface{}) (float64, error) {
switch i := val.(type) {
case float64:
return i, nil
case float32:
return float64(i), nil
case int64:
return float64(i), nil
case int32:
return float64(i), nil
default:
return math.NaN(), errors.New("getFloat: unknown value is of incompatible type")
}
}
func createTableName(entities []*transformer.Entity) string |
func getFeatureValue(val *types.Value) (interface{}, error) {
switch val.Val.(type) {
case *types.Value_StringVal:
return val.GetStringVal(), nil
case *types.Value_DoubleVal:
return val.GetDoubleVal(), nil
case *types.Value_FloatVal:
return val.GetFloatVal(), nil
case *types.Value_Int32Val:
return val.GetInt32Val(), nil
case *types.Value_Int64Val:
return val.GetInt64Val(), nil
case *types.Value_BoolVal:
return val.GetBoolVal(), nil
case *types.Value_StringListVal:
return val.GetStringListVal(), nil
case *types.Value_DoubleListVal:
return val.GetDoubleListVal(), nil
case *types.Value_FloatListVal:
return val.GetFloatListVal(), nil
case *types.Value_Int32ListVal:
return val.GetInt32ListVal(), nil
case *types.Value_Int64ListVal:
return val.GetInt64ListVal(), nil
case *types.Value_BoolListVal:
return val.GetBoolListVal(), nil
case *types.Value_BytesVal:
return val.GetBytesVal(), nil
case *types.Value_BytesListVal:
return val.GetBytesListVal(), nil
default:
return nil, fmt.Errorf("unknown feature value type: %T", val.Val)
}
}
func enrichRequest(ctx context.Context, request []byte, feastFeatures map[string]*FeastFeature) ([]byte, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.enrichRequest")
defer span.Finish()
feastFeatureJSON, err := json.Marshal(feastFeatures)
if err != nil {
return nil, err
}
out, err := jsonparser.Set(request, feastFeatureJSON, transformer.FeastFeatureJSONField)
if err != nil {
return nil, err
}
return out, err
}
| {
entityNames := make([]string, 0)
for _, n := range entities {
entityNames = append(entityNames, n.Name)
}
return strings.Join(entityNames, "_")
} | identifier_body |
transformer.go | package feast
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/antonmedv/expr"
"github.com/antonmedv/expr/vm"
"math"
"strings"
"time"
"github.com/buger/jsonparser"
feast "github.com/feast-dev/feast/sdk/go"
"github.com/feast-dev/feast/sdk/go/protos/feast/serving"
"github.com/feast-dev/feast/sdk/go/protos/feast/types"
"github.com/oliveagle/jsonpath"
"github.com/opentracing/opentracing-go"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"go.uber.org/zap"
"github.com/gojek/merlin/pkg/transformer"
)
var (
feastError = promauto.NewCounter(prometheus.CounterOpts{
Namespace: transformer.PromNamespace,
Name: "feast_serving_error_count",
Help: "The total number of error returned by feast serving",
})
feastLatency = promauto.NewHistogramVec(prometheus.HistogramOpts{
Namespace: transformer.PromNamespace,
Name: "feast_serving_request_duration_ms",
Help: "Feast serving latency histogram",
Buckets: prometheus.ExponentialBuckets(1, 2, 10), // 1,2,4,8,16,32,64,128,256,512,+Inf
}, []string{"result"})
feastFeatureStatus = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: transformer.PromNamespace,
Name: "feast_feature_status_count",
Help: "Feature status by feature",
}, []string{"feature", "status"})
feastFeatureSummary = promauto.NewSummaryVec(prometheus.SummaryOpts{
Namespace: transformer.PromNamespace,
Name: "feast_feature_value",
Help: "Summary of feature value",
AgeBuckets: 1,
}, []string{"feature"})
)
// Options for the Feast transformer.
type Options struct {
ServingURL string `envconfig:"FEAST_SERVING_URL" required:"true"`
StatusMonitoringEnabled bool `envconfig:"FEAST_FEATURE_STATUS_MONITORING_ENABLED" default:"false"`
ValueMonitoringEnabled bool `envconfig:"FEAST_FEATURE_VALUE_MONITORING_ENABLED" default:"false"`
}
// Transformer wraps feast serving client to retrieve features.
type Transformer struct {
feastClient feast.Client
config *transformer.StandardTransformerConfig
logger *zap.Logger
options *Options
defaultValues map[string]*types.Value
compiledJsonPath map[string]*jsonpath.Compiled
compiledUdf map[string]*vm.Program
}
// NewTransformer initializes a new Transformer.
func NewTransformer(feastClient feast.Client, config *transformer.StandardTransformerConfig, options *Options, logger *zap.Logger) (*Transformer, error) {
defaultValues := make(map[string]*types.Value)
// populate default values
for _, ft := range config.TransformerConfig.Feast {
for _, f := range ft.Features {
if len(f.DefaultValue) != 0 {
feastValType := types.ValueType_Enum(types.ValueType_Enum_value[f.ValueType])
defVal, err := getValue(f.DefaultValue, feastValType)
if err != nil {
logger.Warn(fmt.Sprintf("invalid default value for %s : %v, %v", f.Name, f.DefaultValue, err))
continue
}
defaultValues[f.Name] = defVal
}
}
}
compiledJsonPath := make(map[string]*jsonpath.Compiled)
compiledUdf := make(map[string]*vm.Program)
for _, ft := range config.TransformerConfig.Feast {
for _, configEntity := range ft.Entities {
switch configEntity.Extractor.(type) {
case *transformer.Entity_JsonPath:
c, err := jsonpath.Compile(configEntity.GetJsonPath())
if err != nil {
return nil, fmt.Errorf("unable to compile jsonpath for entity %s: %s", configEntity.Name, configEntity.GetJsonPath())
}
compiledJsonPath[configEntity.GetJsonPath()] = c
case *transformer.Entity_Udf:
c, err := expr.Compile(configEntity.GetUdf(), expr.Env(UdfEnv{}))
if err != nil {
return nil, err
}
compiledUdf[configEntity.GetUdf()] = c
}
}
}
return &Transformer{
feastClient: feastClient,
config: config,
options: options,
logger: logger,
defaultValues: defaultValues,
compiledJsonPath: compiledJsonPath,
compiledUdf: compiledUdf,
}, nil
}
type FeastFeature struct {
Columns []string `json:"columns"`
Data [][]interface{} `json:"data"`
}
type result struct {
tableName string
feastFeature *FeastFeature
err error
}
// Transform retrieves the Feast features values and add them into the request.
func (t *Transformer) Transform(ctx context.Context, request []byte) ([]byte, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.Transform")
defer span.Finish()
feastFeatures := make(map[string]*FeastFeature, len(t.config.TransformerConfig.Feast))
// parallelize feast call per feature table
resChan := make(chan result, len(t.config.TransformerConfig.Feast))
for _, config := range t.config.TransformerConfig.Feast {
go func(cfg *transformer.FeatureTable) {
tableName := createTableName(cfg.Entities)
val, err := t.getFeastFeature(ctx, tableName, request, cfg)
resChan <- result{tableName, val, err}
}(config)
}
// collect result
for i := 0; i < cap(resChan); i++ {
res := <-resChan
if res.err != nil {
return nil, res.err
}
feastFeatures[res.tableName] = res.feastFeature
}
out, err := enrichRequest(ctx, request, feastFeatures)
if err != nil {
return nil, err
}
return out, err
}
func (t *Transformer) getFeastFeature(ctx context.Context, tableName string, request []byte, config *transformer.FeatureTable) (*FeastFeature, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.getFeastFeature")
span.SetTag("table.name", tableName)
defer span.Finish()
entities, err := t.buildEntitiesRequest(ctx, request, config.Entities)
if err != nil {
return nil, err
}
var features []string
for _, feature := range config.Features {
features = append(features, feature.Name)
}
feastRequest := feast.OnlineFeaturesRequest{
Project: config.Project,
Entities: entities,
Features: features,
}
t.logger.Debug("feast_request", zap.Any("feast_request", feastRequest))
startTime := time.Now()
feastResponse, err := t.feastClient.GetOnlineFeatures(ctx, &feastRequest)
durationMs := time.Now().Sub(startTime).Milliseconds()
if err != nil {
feastLatency.WithLabelValues("error").Observe(float64(durationMs))
feastError.Inc()
return nil, err
}
feastLatency.WithLabelValues("success").Observe(float64(durationMs))
t.logger.Debug("feast_response", zap.Any("feast_response", feastResponse.Rows()))
feastFeature, err := t.buildFeastFeatures(ctx, feastResponse, config)
if err != nil {
return nil, err
}
return feastFeature, nil
}
func (t *Transformer) buildEntitiesRequest(ctx context.Context, request []byte, configEntities []*transformer.Entity) ([]feast.Row, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.buildEntitiesRequest")
defer span.Finish()
var entities []feast.Row
var nodesBody interface{}
err := json.Unmarshal(request, &nodesBody)
if err != nil {
return nil, err
}
for _, configEntity := range configEntities {
switch configEntity.Extractor.(type) {
case *transformer.Entity_JsonPath:
_, ok := t.compiledJsonPath[configEntity.GetJsonPath()]
if !ok {
c, err := jsonpath.Compile(configEntity.GetJsonPath())
if err != nil {
return nil, fmt.Errorf("unable to compile jsonpath for entity %s: %s", configEntity.Name, configEntity.GetJsonPath())
}
t.compiledJsonPath[configEntity.GetJsonPath()] = c
}
}
vals, err := getValuesFromJSONPayload(nodesBody, configEntity, t.compiledJsonPath[configEntity.GetJsonPath()], t.compiledUdf[configEntity.GetUdf()])
if err != nil {
return nil, fmt.Errorf("unable to extract entity %s: %v", configEntity.Name, err)
}
if len(entities) == 0 {
for _, val := range vals {
entities = append(entities, feast.Row{
configEntity.Name: val,
})
}
} else {
newEntities := []feast.Row{}
for _, entity := range entities {
for _, val := range vals {
newFeastRow := feast.Row{}
for k, v := range entity {
newFeastRow[k] = v
}
newFeastRow[configEntity.Name] = val
newEntities = append(newEntities, newFeastRow)
}
}
entities = newEntities
}
}
return entities, nil
}
func (t *Transformer) buildFeastFeatures(ctx context.Context, feastResponse *feast.OnlineFeaturesResponse, config *transformer.FeatureTable) (*FeastFeature, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.buildFeastFeatures")
defer span.Finish()
var columns []string
for _, entity := range config.Entities {
columns = append(columns, entity.Name)
}
for _, feature := range config.Features {
columns = append(columns, feature.Name)
}
var data [][]interface{}
status := feastResponse.Statuses()
for i, feastRow := range feastResponse.Rows() {
var row []interface{}
for _, column := range columns {
featureStatus := status[i][column]
switch featureStatus {
case serving.GetOnlineFeaturesResponse_PRESENT:
rawValue := feastRow[column]
featVal, err := getFeatureValue(rawValue)
if err != nil {
return nil, err
}
row = append(row, featVal)
// put behind feature toggle since it will generate high cardinality metrics
if t.options.ValueMonitoringEnabled {
v, err := getFloatValue(featVal)
if err != nil {
continue
}
feastFeatureSummary.WithLabelValues(column).Observe(v)
}
case serving.GetOnlineFeaturesResponse_NOT_FOUND, serving.GetOnlineFeaturesResponse_NULL_VALUE, serving.GetOnlineFeaturesResponse_OUTSIDE_MAX_AGE:
defVal, ok := t.defaultValues[column]
if !ok {
row = append(row, nil)
continue
}
featVal, err := getFeatureValue(defVal)
if err != nil {
return nil, err
}
row = append(row, featVal)
default:
return nil, fmt.Errorf("Unsupported feature retrieval status: %s", featureStatus)
}
// put behind feature toggle since it will generate high cardinality metrics
if t.options.StatusMonitoringEnabled {
feastFeatureStatus.WithLabelValues(column, featureStatus.String()).Inc()
}
}
data = append(data, row)
}
return &FeastFeature{
Columns: columns,
Data: data,
}, nil
}
func | (val interface{}) (float64, error) {
switch i := val.(type) {
case float64:
return i, nil
case float32:
return float64(i), nil
case int64:
return float64(i), nil
case int32:
return float64(i), nil
default:
return math.NaN(), errors.New("getFloat: unknown value is of incompatible type")
}
}
func createTableName(entities []*transformer.Entity) string {
entityNames := make([]string, 0)
for _, n := range entities {
entityNames = append(entityNames, n.Name)
}
return strings.Join(entityNames, "_")
}
func getFeatureValue(val *types.Value) (interface{}, error) {
switch val.Val.(type) {
case *types.Value_StringVal:
return val.GetStringVal(), nil
case *types.Value_DoubleVal:
return val.GetDoubleVal(), nil
case *types.Value_FloatVal:
return val.GetFloatVal(), nil
case *types.Value_Int32Val:
return val.GetInt32Val(), nil
case *types.Value_Int64Val:
return val.GetInt64Val(), nil
case *types.Value_BoolVal:
return val.GetBoolVal(), nil
case *types.Value_StringListVal:
return val.GetStringListVal(), nil
case *types.Value_DoubleListVal:
return val.GetDoubleListVal(), nil
case *types.Value_FloatListVal:
return val.GetFloatListVal(), nil
case *types.Value_Int32ListVal:
return val.GetInt32ListVal(), nil
case *types.Value_Int64ListVal:
return val.GetInt64ListVal(), nil
case *types.Value_BoolListVal:
return val.GetBoolListVal(), nil
case *types.Value_BytesVal:
return val.GetBytesVal(), nil
case *types.Value_BytesListVal:
return val.GetBytesListVal(), nil
default:
return nil, fmt.Errorf("unknown feature value type: %T", val.Val)
}
}
func enrichRequest(ctx context.Context, request []byte, feastFeatures map[string]*FeastFeature) ([]byte, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.enrichRequest")
defer span.Finish()
feastFeatureJSON, err := json.Marshal(feastFeatures)
if err != nil {
return nil, err
}
out, err := jsonparser.Set(request, feastFeatureJSON, transformer.FeastFeatureJSONField)
if err != nil {
return nil, err
}
return out, err
}
| getFloatValue | identifier_name |
transformer.go | package feast
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/antonmedv/expr"
"github.com/antonmedv/expr/vm"
"math"
"strings"
"time"
"github.com/buger/jsonparser"
feast "github.com/feast-dev/feast/sdk/go"
"github.com/feast-dev/feast/sdk/go/protos/feast/serving"
"github.com/feast-dev/feast/sdk/go/protos/feast/types"
"github.com/oliveagle/jsonpath"
"github.com/opentracing/opentracing-go"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"go.uber.org/zap"
"github.com/gojek/merlin/pkg/transformer"
)
var (
feastError = promauto.NewCounter(prometheus.CounterOpts{
Namespace: transformer.PromNamespace,
Name: "feast_serving_error_count",
Help: "The total number of error returned by feast serving",
})
feastLatency = promauto.NewHistogramVec(prometheus.HistogramOpts{
Namespace: transformer.PromNamespace,
Name: "feast_serving_request_duration_ms",
Help: "Feast serving latency histogram",
Buckets: prometheus.ExponentialBuckets(1, 2, 10), // 1,2,4,8,16,32,64,128,256,512,+Inf
}, []string{"result"})
feastFeatureStatus = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: transformer.PromNamespace,
Name: "feast_feature_status_count",
Help: "Feature status by feature",
}, []string{"feature", "status"})
feastFeatureSummary = promauto.NewSummaryVec(prometheus.SummaryOpts{
Namespace: transformer.PromNamespace,
Name: "feast_feature_value",
Help: "Summary of feature value",
AgeBuckets: 1,
}, []string{"feature"})
)
// Options for the Feast transformer.
type Options struct {
ServingURL string `envconfig:"FEAST_SERVING_URL" required:"true"`
StatusMonitoringEnabled bool `envconfig:"FEAST_FEATURE_STATUS_MONITORING_ENABLED" default:"false"`
ValueMonitoringEnabled bool `envconfig:"FEAST_FEATURE_VALUE_MONITORING_ENABLED" default:"false"`
}
// Transformer wraps feast serving client to retrieve features.
type Transformer struct {
feastClient feast.Client
config *transformer.StandardTransformerConfig
logger *zap.Logger
options *Options
defaultValues map[string]*types.Value
compiledJsonPath map[string]*jsonpath.Compiled
compiledUdf map[string]*vm.Program
}
// NewTransformer initializes a new Transformer.
func NewTransformer(feastClient feast.Client, config *transformer.StandardTransformerConfig, options *Options, logger *zap.Logger) (*Transformer, error) {
defaultValues := make(map[string]*types.Value)
// populate default values
for _, ft := range config.TransformerConfig.Feast {
for _, f := range ft.Features {
if len(f.DefaultValue) != 0 {
feastValType := types.ValueType_Enum(types.ValueType_Enum_value[f.ValueType])
defVal, err := getValue(f.DefaultValue, feastValType)
if err != nil {
logger.Warn(fmt.Sprintf("invalid default value for %s : %v, %v", f.Name, f.DefaultValue, err))
continue
}
defaultValues[f.Name] = defVal
}
}
}
compiledJsonPath := make(map[string]*jsonpath.Compiled)
compiledUdf := make(map[string]*vm.Program)
for _, ft := range config.TransformerConfig.Feast {
for _, configEntity := range ft.Entities {
switch configEntity.Extractor.(type) {
case *transformer.Entity_JsonPath:
c, err := jsonpath.Compile(configEntity.GetJsonPath())
if err != nil {
return nil, fmt.Errorf("unable to compile jsonpath for entity %s: %s", configEntity.Name, configEntity.GetJsonPath())
}
compiledJsonPath[configEntity.GetJsonPath()] = c
case *transformer.Entity_Udf:
c, err := expr.Compile(configEntity.GetUdf(), expr.Env(UdfEnv{}))
if err != nil {
return nil, err
}
compiledUdf[configEntity.GetUdf()] = c
}
}
}
return &Transformer{
feastClient: feastClient,
config: config,
options: options,
logger: logger,
defaultValues: defaultValues,
compiledJsonPath: compiledJsonPath,
compiledUdf: compiledUdf,
}, nil
}
type FeastFeature struct {
Columns []string `json:"columns"`
Data [][]interface{} `json:"data"`
}
type result struct {
tableName string
feastFeature *FeastFeature
err error
}
// Transform retrieves the Feast features values and add them into the request.
func (t *Transformer) Transform(ctx context.Context, request []byte) ([]byte, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.Transform")
defer span.Finish()
feastFeatures := make(map[string]*FeastFeature, len(t.config.TransformerConfig.Feast))
// parallelize feast call per feature table
resChan := make(chan result, len(t.config.TransformerConfig.Feast))
for _, config := range t.config.TransformerConfig.Feast {
go func(cfg *transformer.FeatureTable) {
tableName := createTableName(cfg.Entities)
val, err := t.getFeastFeature(ctx, tableName, request, cfg)
resChan <- result{tableName, val, err}
}(config)
}
// collect result
for i := 0; i < cap(resChan); i++ {
res := <-resChan
if res.err != nil {
return nil, res.err
}
feastFeatures[res.tableName] = res.feastFeature
}
out, err := enrichRequest(ctx, request, feastFeatures)
if err != nil {
return nil, err
}
return out, err
}
func (t *Transformer) getFeastFeature(ctx context.Context, tableName string, request []byte, config *transformer.FeatureTable) (*FeastFeature, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.getFeastFeature")
span.SetTag("table.name", tableName)
defer span.Finish()
entities, err := t.buildEntitiesRequest(ctx, request, config.Entities)
if err != nil {
return nil, err
}
var features []string
for _, feature := range config.Features {
features = append(features, feature.Name)
}
feastRequest := feast.OnlineFeaturesRequest{
Project: config.Project,
Entities: entities,
Features: features,
}
t.logger.Debug("feast_request", zap.Any("feast_request", feastRequest))
startTime := time.Now()
feastResponse, err := t.feastClient.GetOnlineFeatures(ctx, &feastRequest)
durationMs := time.Now().Sub(startTime).Milliseconds()
if err != nil {
feastLatency.WithLabelValues("error").Observe(float64(durationMs))
feastError.Inc()
return nil, err
}
feastLatency.WithLabelValues("success").Observe(float64(durationMs))
t.logger.Debug("feast_response", zap.Any("feast_response", feastResponse.Rows()))
feastFeature, err := t.buildFeastFeatures(ctx, feastResponse, config)
if err != nil {
return nil, err
}
return feastFeature, nil
}
func (t *Transformer) buildEntitiesRequest(ctx context.Context, request []byte, configEntities []*transformer.Entity) ([]feast.Row, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.buildEntitiesRequest")
defer span.Finish()
var entities []feast.Row
var nodesBody interface{}
err := json.Unmarshal(request, &nodesBody)
if err != nil {
return nil, err
}
for _, configEntity := range configEntities {
switch configEntity.Extractor.(type) {
case *transformer.Entity_JsonPath:
_, ok := t.compiledJsonPath[configEntity.GetJsonPath()]
if !ok {
c, err := jsonpath.Compile(configEntity.GetJsonPath())
if err != nil {
return nil, fmt.Errorf("unable to compile jsonpath for entity %s: %s", configEntity.Name, configEntity.GetJsonPath())
}
t.compiledJsonPath[configEntity.GetJsonPath()] = c
}
}
vals, err := getValuesFromJSONPayload(nodesBody, configEntity, t.compiledJsonPath[configEntity.GetJsonPath()], t.compiledUdf[configEntity.GetUdf()])
if err != nil {
return nil, fmt.Errorf("unable to extract entity %s: %v", configEntity.Name, err)
}
if len(entities) == 0 {
for _, val := range vals {
entities = append(entities, feast.Row{
configEntity.Name: val,
})
}
} else {
newEntities := []feast.Row{}
for _, entity := range entities {
for _, val := range vals {
newFeastRow := feast.Row{}
for k, v := range entity {
newFeastRow[k] = v
}
newFeastRow[configEntity.Name] = val
newEntities = append(newEntities, newFeastRow)
}
}
entities = newEntities
}
}
return entities, nil
}
func (t *Transformer) buildFeastFeatures(ctx context.Context, feastResponse *feast.OnlineFeaturesResponse, config *transformer.FeatureTable) (*FeastFeature, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.buildFeastFeatures")
defer span.Finish()
var columns []string
for _, entity := range config.Entities {
columns = append(columns, entity.Name)
}
for _, feature := range config.Features {
columns = append(columns, feature.Name)
}
var data [][]interface{}
status := feastResponse.Statuses()
for i, feastRow := range feastResponse.Rows() |
return &FeastFeature{
Columns: columns,
Data: data,
}, nil
}
func getFloatValue(val interface{}) (float64, error) {
switch i := val.(type) {
case float64:
return i, nil
case float32:
return float64(i), nil
case int64:
return float64(i), nil
case int32:
return float64(i), nil
default:
return math.NaN(), errors.New("getFloat: unknown value is of incompatible type")
}
}
func createTableName(entities []*transformer.Entity) string {
entityNames := make([]string, 0)
for _, n := range entities {
entityNames = append(entityNames, n.Name)
}
return strings.Join(entityNames, "_")
}
func getFeatureValue(val *types.Value) (interface{}, error) {
switch val.Val.(type) {
case *types.Value_StringVal:
return val.GetStringVal(), nil
case *types.Value_DoubleVal:
return val.GetDoubleVal(), nil
case *types.Value_FloatVal:
return val.GetFloatVal(), nil
case *types.Value_Int32Val:
return val.GetInt32Val(), nil
case *types.Value_Int64Val:
return val.GetInt64Val(), nil
case *types.Value_BoolVal:
return val.GetBoolVal(), nil
case *types.Value_StringListVal:
return val.GetStringListVal(), nil
case *types.Value_DoubleListVal:
return val.GetDoubleListVal(), nil
case *types.Value_FloatListVal:
return val.GetFloatListVal(), nil
case *types.Value_Int32ListVal:
return val.GetInt32ListVal(), nil
case *types.Value_Int64ListVal:
return val.GetInt64ListVal(), nil
case *types.Value_BoolListVal:
return val.GetBoolListVal(), nil
case *types.Value_BytesVal:
return val.GetBytesVal(), nil
case *types.Value_BytesListVal:
return val.GetBytesListVal(), nil
default:
return nil, fmt.Errorf("unknown feature value type: %T", val.Val)
}
}
func enrichRequest(ctx context.Context, request []byte, feastFeatures map[string]*FeastFeature) ([]byte, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "feast.enrichRequest")
defer span.Finish()
feastFeatureJSON, err := json.Marshal(feastFeatures)
if err != nil {
return nil, err
}
out, err := jsonparser.Set(request, feastFeatureJSON, transformer.FeastFeatureJSONField)
if err != nil {
return nil, err
}
return out, err
}
| {
var row []interface{}
for _, column := range columns {
featureStatus := status[i][column]
switch featureStatus {
case serving.GetOnlineFeaturesResponse_PRESENT:
rawValue := feastRow[column]
featVal, err := getFeatureValue(rawValue)
if err != nil {
return nil, err
}
row = append(row, featVal)
// put behind feature toggle since it will generate high cardinality metrics
if t.options.ValueMonitoringEnabled {
v, err := getFloatValue(featVal)
if err != nil {
continue
}
feastFeatureSummary.WithLabelValues(column).Observe(v)
}
case serving.GetOnlineFeaturesResponse_NOT_FOUND, serving.GetOnlineFeaturesResponse_NULL_VALUE, serving.GetOnlineFeaturesResponse_OUTSIDE_MAX_AGE:
defVal, ok := t.defaultValues[column]
if !ok {
row = append(row, nil)
continue
}
featVal, err := getFeatureValue(defVal)
if err != nil {
return nil, err
}
row = append(row, featVal)
default:
return nil, fmt.Errorf("Unsupported feature retrieval status: %s", featureStatus)
}
// put behind feature toggle since it will generate high cardinality metrics
if t.options.StatusMonitoringEnabled {
feastFeatureStatus.WithLabelValues(column, featureStatus.String()).Inc()
}
}
data = append(data, row)
} | conditional_block |
start.py | import argparse
import os
from time import time
from PIL import Image
import align.detect_face as detect_face
import cv2
import numpy as np
import tensorflow as tf
from lib.face_utils import judge_side_face
from lib.utils import Logger, mkdir
from project_root_dir import project_dir
from src.sort import Sort
from load_model.tensorflow_loader import load_tf_model, tf_inference
from utils.anchor_generator import generate_anchors
from utils.anchor_decode import decode_bbox
from utils.nms import single_class_non_max_suppression
logger = Logger()
# 开始人脸对齐
sess, graph = load_tf_model('models/face_mask_detection.pb')
# anchor configuration
feature_map_sizes = [[33, 33], [17, 17], [9, 9], [5, 5], [3, 3]]
anchor_sizes = [[0.04, 0.056], [0.08, 0.11], [0.16, 0.22], [0.32, 0.45], [0.64, 0.72]]
anchor_ratios = [[1, 0.62, 0.42]] * 5
# generate anchors
anchors = generate_anchors(feature_map_sizes, anchor_sizes, anchor_ratios)
# for inference , the batch size is 1, the model output shape is [1, N, 4],
# so we expand dim for anchors to [1, anchor_num, 4]
anchors_exp = np.expand_dims(anchors, axis=0)
id2class = {0: 'Mask', 1: 'NoMask'}
# 人脸对齐方法
def inference(image,
conf_thresh=0.5,
iou_thresh=0.4,
target_shape=(160, 160),
draw_result=True,
show_result=True
):
'''
Main function of detection inference
:param image: 3D numpy array of image
:param conf_thresh: the min threshold of classification probabity.
:param iou_thresh: the IOU threshold of NMS
:param target_shape: the model input size.
:param draw_result: whether to daw bounding box to the image.
:param show_result: whether to display the image.
:return:
'''
output_info = []
height, width, _ = image.shape
image_resized = cv2.resize(image, target_shape)
image_np = image_resized / 255.0 # 归一化到0~1
image_exp = np.expand_dims(image_np, axis=0)
# 输出回归框和人脸得分
y_bboxes_output, y_cls_output = tf_inference(sess, graph, image_exp)
# remove the batch dimension, for batch is always 1 for inference.
y_bboxes = decode_bbox(anchors_exp, y_bboxes_output)[0]
y_cls = y_cls_output[0]
# To speed up, do single class NMS, not multiple classes NMS.
bbox_max_scores = np.max(y_cls, axis=1)
bbox_max_score_classes = np.argmax(y_cls, axis=1)
# 对单个人脸进行非极大抑制
keep_idxs = single_class_non_max_suppression(y_bboxes,
bbox_max_scores,
conf_thresh=conf_thresh,
iou_thresh=iou_thresh,
)
for idx in keep_idxs:
conf = float(bbox_max_scores[idx])
class_id = bbox_max_score_classes[idx]
bbox = y_bboxes[idx]
# clip the coordinate, avoid the value exceed the image boundary.
xmin = max(0, int(bbox[0] * width))
ymin = max(0, int(bbox[1] * height))
xmax = min(int(bbox[2] * width), width)
ymax = min(int(bbox[3] * height), height)
if draw_result:
if class_id == 0:
color = (0, 255, 0)
else:
color = (255, 0, 0)
cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, 2)
cv2.putText(image, "%s: %.2f" % (id2class[class_id], conf), (xmin + 2, ymin - 2),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, color)
output_info.append([class_id, conf, xmin, ymin, xmax, ymax])
print(output_info)
if show_result:
Image.fromarray(image).show()
return output_info
def main():
global colours, img_size
args = parse_args()
videos_dir = args.video | ory containing aligned your face patches.', default='videos')
parser.add_argument('--output_path', type=str,
help='Path to save face',
default='facepics')
parser.add_argument('--detect_interval',
help='how many frames to make a detection',
type=int, default=1)
parser.add_argument('--margin',
help='add margin for face',
type=int, default=10)
parser.add_argument('--scale_rate',
help='Scale down or enlarge the original video img',
type=float, default=0.7)
parser.add_argument('--show_rate',
help='Scale down or enlarge the imgs drawn by opencv',
type=float, default=1)
parser.add_argument('--face_score_threshold',
help='The threshold of the extracted faces,range 0<x<=1',
type=float, default=0.85)
parser.add_argument('--face_landmarks',
help='Draw five face landmarks on extracted face or not ', action="store_true")
parser.add_argument('--no_display',
help='Display or not', action='store_true')
args = parser.parse_args()
return args
| s_dir
output_path = args.output_path
no_display = args.no_display
detect_interval = args.detect_interval # 间隔一帧检测一次
margin = args.margin # 脸边距(默认10)
scale_rate = args.scale_rate # 检测图像的尺寸设置
show_rate = args.show_rate # 展示图像的尺寸设置
face_score_threshold = args.face_score_threshold # 人脸判别阈值
mkdir(output_path)
# for display
if not no_display:
colours = np.random.rand(32, 3)
# 初始化追踪器
tracker = Sort() # create instance of the SORT tracker
logger.info('Start track and extract......')
# 影像处理
for filename in os.listdir(videos_dir):
logger.info('All files:{}'.format(filename))
for filename in os.listdir(videos_dir):
suffix = filename.split('.')[1]
if suffix != 'mp4' and suffix != 'avi': # you can specify more video formats if you need
continue
video_name = os.path.join(videos_dir, filename)
directoryname = os.path.join(output_path, filename.split('.')[0])
logger.info('Video_name:{}'.format(video_name))
cam = cv2.VideoCapture(video_name)
c = 0
while True:
final_faces = []
addtional_attribute_list = []
ret, frame = cam.read()
if not ret:
logger.warning("ret false")
break
if frame is None:
logger.warning("frame drop")
break
frame = cv2.resize(frame, (0, 0), fx=scale_rate, fy=scale_rate)
r_g_b_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 间隔取帧,默认每帧都取
# if c % detect_interval == 0:
# img_size = np.asarray(frame.shape)[0:2]
# faces = inference(r_g_b_frame, show_result=True, target_shape=(260, 260))
with tf.Graph().as_default():
with tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True),
log_device_placement=False)) as sess:
pnet, rnet, onet = detect_face.create_mtcnn(sess, os.path.join(project_dir, "align"))
minsize = 40 # minimum size of face for mtcnn to detect
threshold = [0.6, 0.7, 0.7] # three steps's threshold
factor = 0.709 # scale factor
for filename in os.listdir(videos_dir):
logger.info('All files:{}'.format(filename))
for filename in os.listdir(videos_dir):
suffix = filename.split('.')[1]
if suffix != 'mp4' and suffix != 'avi': # you can specify more video formats if you need
continue
video_name = os.path.join(videos_dir, filename)
directoryname = os.path.join(output_path, filename.split('.')[0])
logger.info('Video_name:{}'.format(video_name))
cam = cv2.VideoCapture(video_name)
c = 0
while True:
final_faces = []
addtional_attribute_list = []
ret, frame = cam.read()
if not ret:
logger.warning("ret false")
break
if frame is None:
logger.warning("frame drop")
break
frame = cv2.resize(frame, (0, 0), fx=scale_rate, fy=scale_rate)
r_g_b_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
if c % detect_interval == 0:
img_size = np.asarray(frame.shape)[0:2]
mtcnn_starttime = time()
faces, points = detect_face.detect_face(r_g_b_frame, minsize, pnet, rnet, onet, threshold,
factor)
logger.info("MTCNN detect face cost time : {} s".format(
round(time() - mtcnn_starttime, 3))) # mtcnn detect ,slow
print('testttttt')
print(type(faces))
face_sums = faces.shape[0]
if face_sums > 0:
face_list = []
for i, item in enumerate(faces):
print(item)
score = round(faces[i, 4], 6)
if score > face_score_threshold:
det = np.squeeze(faces[i, 0:4])
# face rectangle
det[0] = np.maximum(det[0] - margin, 0)
det[1] = np.maximum(det[1] - margin, 0)
det[2] = np.minimum(det[2] + margin, img_size[1])
det[3] = np.minimum(det[3] + margin, img_size[0])
face_list.append(item)
# face cropped
bb = np.array(det, dtype=np.int32)
# use 5 face landmarks to judge the face is front or side
squeeze_points = np.squeeze(points[:, i])
tolist = squeeze_points.tolist()
facial_landmarks = []
for j in range(5):
item = [tolist[j], tolist[(j + 5)]]
facial_landmarks.append(item)
if args.face_landmarks:
for (x, y) in facial_landmarks:
cv2.circle(frame, (int(x), int(y)), 3, (0, 255, 0), -1)
cropped = frame[bb[1]:bb[3], bb[0]:bb[2], :].copy()
dist_rate, high_ratio_variance, width_rate = judge_side_face(
np.array(facial_landmarks))
# face addtional attribute(index 0:face score; index 1:0 represents front face and 1 for side face )
item_list = [cropped, score, dist_rate, high_ratio_variance, width_rate]
addtional_attribute_list.append(item_list)
final_faces = np.array(face_list)
trackers = tracker.update(final_faces, img_size, directoryname, addtional_attribute_list, detect_interval)
c += 1
for d in trackers:
if not no_display:
d = d.astype(np.int32)
cv2.rectangle(frame, (d[0], d[1]), (d[2], d[3]), colours[d[4] % 32, :] * 255, 3)
if final_faces != []:
cv2.putText(frame, 'ID : %d DETECT' % (d[4]), (d[0] - 10, d[1] - 10),
cv2.FONT_HERSHEY_SIMPLEX,
0.75,
colours[d[4] % 32, :] * 255, 2)
cv2.putText(frame, 'DETECTOR', (5, 45), cv2.FONT_HERSHEY_SIMPLEX, 0.75,
(1, 1, 1), 2)
else:
cv2.putText(frame, 'ID : %d' % (d[4]), (d[0] - 10, d[1] - 10), cv2.FONT_HERSHEY_SIMPLEX,
0.75,
colours[d[4] % 32, :] * 255, 2)
if not no_display:
frame = cv2.resize(frame, (0, 0), fx=show_rate, fy=show_rate)
cv2.imshow("Frame", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("--videos_dir", type=str,
help='Path to the data direct | identifier_body |
start.py | import argparse
import os
from time import time
from PIL import Image
import align.detect_face as detect_face
import cv2
import numpy as np
import tensorflow as tf
from lib.face_utils import judge_side_face
from lib.utils import Logger, mkdir
from project_root_dir import project_dir
from src.sort import Sort
from load_model.tensorflow_loader import load_tf_model, tf_inference
from utils.anchor_generator import generate_anchors
from utils.anchor_decode import decode_bbox
from utils.nms import single_class_non_max_suppression
logger = Logger()
# 开始人脸对齐
sess, graph = load_tf_model('models/face_mask_detection.pb')
# anchor configuration
feature_map_sizes = [[33, 33], [17, 17], [9, 9], [5, 5], [3, 3]]
anchor_sizes = [[0.04, 0.056], [0.08, 0.11], [0.16, 0.22], [0.32, 0.45], [0.64, 0.72]]
anchor_ratios = [[1, 0.62, 0.42]] * 5
# generate anchors
anchors = generate_anchors(feature_map_sizes, anchor_sizes, anchor_ratios)
# for inference , the batch size is 1, the model output shape is [1, N, 4],
# so we expand dim for anchors to [1, anchor_num, 4]
anchors_exp = np.expand_dims(anchors, axis=0)
id2class = {0: 'Mask', 1: 'NoMask'}
# 人脸对齐方法
def inference(image,
conf_thresh=0.5,
iou_thresh=0.4,
target_shape=(160, 160),
draw_result=True, | :param image: 3D numpy array of image
:param conf_thresh: the min threshold of classification probabity.
:param iou_thresh: the IOU threshold of NMS
:param target_shape: the model input size.
:param draw_result: whether to daw bounding box to the image.
:param show_result: whether to display the image.
:return:
'''
output_info = []
height, width, _ = image.shape
image_resized = cv2.resize(image, target_shape)
image_np = image_resized / 255.0 # 归一化到0~1
image_exp = np.expand_dims(image_np, axis=0)
# 输出回归框和人脸得分
y_bboxes_output, y_cls_output = tf_inference(sess, graph, image_exp)
# remove the batch dimension, for batch is always 1 for inference.
y_bboxes = decode_bbox(anchors_exp, y_bboxes_output)[0]
y_cls = y_cls_output[0]
# To speed up, do single class NMS, not multiple classes NMS.
bbox_max_scores = np.max(y_cls, axis=1)
bbox_max_score_classes = np.argmax(y_cls, axis=1)
# 对单个人脸进行非极大抑制
keep_idxs = single_class_non_max_suppression(y_bboxes,
bbox_max_scores,
conf_thresh=conf_thresh,
iou_thresh=iou_thresh,
)
for idx in keep_idxs:
conf = float(bbox_max_scores[idx])
class_id = bbox_max_score_classes[idx]
bbox = y_bboxes[idx]
# clip the coordinate, avoid the value exceed the image boundary.
xmin = max(0, int(bbox[0] * width))
ymin = max(0, int(bbox[1] * height))
xmax = min(int(bbox[2] * width), width)
ymax = min(int(bbox[3] * height), height)
if draw_result:
if class_id == 0:
color = (0, 255, 0)
else:
color = (255, 0, 0)
cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, 2)
cv2.putText(image, "%s: %.2f" % (id2class[class_id], conf), (xmin + 2, ymin - 2),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, color)
output_info.append([class_id, conf, xmin, ymin, xmax, ymax])
print(output_info)
if show_result:
Image.fromarray(image).show()
return output_info
def main():
global colours, img_size
args = parse_args()
videos_dir = args.videos_dir
output_path = args.output_path
no_display = args.no_display
detect_interval = args.detect_interval # 间隔一帧检测一次
margin = args.margin # 脸边距(默认10)
scale_rate = args.scale_rate # 检测图像的尺寸设置
show_rate = args.show_rate # 展示图像的尺寸设置
face_score_threshold = args.face_score_threshold # 人脸判别阈值
mkdir(output_path)
# for display
if not no_display:
colours = np.random.rand(32, 3)
# 初始化追踪器
tracker = Sort() # create instance of the SORT tracker
logger.info('Start track and extract......')
# 影像处理
for filename in os.listdir(videos_dir):
logger.info('All files:{}'.format(filename))
for filename in os.listdir(videos_dir):
suffix = filename.split('.')[1]
if suffix != 'mp4' and suffix != 'avi': # you can specify more video formats if you need
continue
video_name = os.path.join(videos_dir, filename)
directoryname = os.path.join(output_path, filename.split('.')[0])
logger.info('Video_name:{}'.format(video_name))
cam = cv2.VideoCapture(video_name)
c = 0
while True:
final_faces = []
addtional_attribute_list = []
ret, frame = cam.read()
if not ret:
logger.warning("ret false")
break
if frame is None:
logger.warning("frame drop")
break
frame = cv2.resize(frame, (0, 0), fx=scale_rate, fy=scale_rate)
r_g_b_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 间隔取帧,默认每帧都取
# if c % detect_interval == 0:
# img_size = np.asarray(frame.shape)[0:2]
# faces = inference(r_g_b_frame, show_result=True, target_shape=(260, 260))
with tf.Graph().as_default():
with tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True),
log_device_placement=False)) as sess:
pnet, rnet, onet = detect_face.create_mtcnn(sess, os.path.join(project_dir, "align"))
minsize = 40 # minimum size of face for mtcnn to detect
threshold = [0.6, 0.7, 0.7] # three steps's threshold
factor = 0.709 # scale factor
for filename in os.listdir(videos_dir):
logger.info('All files:{}'.format(filename))
for filename in os.listdir(videos_dir):
suffix = filename.split('.')[1]
if suffix != 'mp4' and suffix != 'avi': # you can specify more video formats if you need
continue
video_name = os.path.join(videos_dir, filename)
directoryname = os.path.join(output_path, filename.split('.')[0])
logger.info('Video_name:{}'.format(video_name))
cam = cv2.VideoCapture(video_name)
c = 0
while True:
final_faces = []
addtional_attribute_list = []
ret, frame = cam.read()
if not ret:
logger.warning("ret false")
break
if frame is None:
logger.warning("frame drop")
break
frame = cv2.resize(frame, (0, 0), fx=scale_rate, fy=scale_rate)
r_g_b_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
if c % detect_interval == 0:
img_size = np.asarray(frame.shape)[0:2]
mtcnn_starttime = time()
faces, points = detect_face.detect_face(r_g_b_frame, minsize, pnet, rnet, onet, threshold,
factor)
logger.info("MTCNN detect face cost time : {} s".format(
round(time() - mtcnn_starttime, 3))) # mtcnn detect ,slow
print('testttttt')
print(type(faces))
face_sums = faces.shape[0]
if face_sums > 0:
face_list = []
for i, item in enumerate(faces):
print(item)
score = round(faces[i, 4], 6)
if score > face_score_threshold:
det = np.squeeze(faces[i, 0:4])
# face rectangle
det[0] = np.maximum(det[0] - margin, 0)
det[1] = np.maximum(det[1] - margin, 0)
det[2] = np.minimum(det[2] + margin, img_size[1])
det[3] = np.minimum(det[3] + margin, img_size[0])
face_list.append(item)
# face cropped
bb = np.array(det, dtype=np.int32)
# use 5 face landmarks to judge the face is front or side
squeeze_points = np.squeeze(points[:, i])
tolist = squeeze_points.tolist()
facial_landmarks = []
for j in range(5):
item = [tolist[j], tolist[(j + 5)]]
facial_landmarks.append(item)
if args.face_landmarks:
for (x, y) in facial_landmarks:
cv2.circle(frame, (int(x), int(y)), 3, (0, 255, 0), -1)
cropped = frame[bb[1]:bb[3], bb[0]:bb[2], :].copy()
dist_rate, high_ratio_variance, width_rate = judge_side_face(
np.array(facial_landmarks))
# face addtional attribute(index 0:face score; index 1:0 represents front face and 1 for side face )
item_list = [cropped, score, dist_rate, high_ratio_variance, width_rate]
addtional_attribute_list.append(item_list)
final_faces = np.array(face_list)
trackers = tracker.update(final_faces, img_size, directoryname, addtional_attribute_list, detect_interval)
c += 1
for d in trackers:
if not no_display:
d = d.astype(np.int32)
cv2.rectangle(frame, (d[0], d[1]), (d[2], d[3]), colours[d[4] % 32, :] * 255, 3)
if final_faces != []:
cv2.putText(frame, 'ID : %d DETECT' % (d[4]), (d[0] - 10, d[1] - 10),
cv2.FONT_HERSHEY_SIMPLEX,
0.75,
colours[d[4] % 32, :] * 255, 2)
cv2.putText(frame, 'DETECTOR', (5, 45), cv2.FONT_HERSHEY_SIMPLEX, 0.75,
(1, 1, 1), 2)
else:
cv2.putText(frame, 'ID : %d' % (d[4]), (d[0] - 10, d[1] - 10), cv2.FONT_HERSHEY_SIMPLEX,
0.75,
colours[d[4] % 32, :] * 255, 2)
if not no_display:
frame = cv2.resize(frame, (0, 0), fx=show_rate, fy=show_rate)
cv2.imshow("Frame", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("--videos_dir", type=str,
help='Path to the data directory containing aligned your face patches.', default='videos')
parser.add_argument('--output_path', type=str,
help='Path to save face',
default='facepics')
parser.add_argument('--detect_interval',
help='how many frames to make a detection',
type=int, default=1)
parser.add_argument('--margin',
help='add margin for face',
type=int, default=10)
parser.add_argument('--scale_rate',
help='Scale down or enlarge the original video img',
type=float, default=0.7)
parser.add_argument('--show_rate',
help='Scale down or enlarge the imgs drawn by opencv',
type=float, default=1)
parser.add_argument('--face_score_threshold',
help='The threshold of the extracted faces,range 0<x<=1',
type=float, default=0.85)
parser.add_argument('--face_landmarks',
help='Draw five face landmarks on extracted face or not ', action="store_true")
parser.add_argument('--no_display',
help='Display or not', action='store_true')
args = parser.parse_args()
return args | show_result=True
):
'''
Main function of detection inference | random_line_split |
start.py | import argparse
import os
from time import time
from PIL import Image
import align.detect_face as detect_face
import cv2
import numpy as np
import tensorflow as tf
from lib.face_utils import judge_side_face
from lib.utils import Logger, mkdir
from project_root_dir import project_dir
from src.sort import Sort
from load_model.tensorflow_loader import load_tf_model, tf_inference
from utils.anchor_generator import generate_anchors
from utils.anchor_decode import decode_bbox
from utils.nms import single_class_non_max_suppression
logger = Logger()
# 开始人脸对齐
sess, graph = load_tf_model('models/face_mask_detection.pb')
# anchor configuration
feature_map_sizes = [[33, 33], [17, 17], [9, 9], [5, 5], [3, 3]]
anchor_sizes = [[0.04, 0.056], [0.08, 0.11], [0.16, 0.22], [0.32, 0.45], [0.64, 0.72]]
anchor_ratios = [[1, 0.62, 0.42]] * 5
# generate anchors
anchors = generate_anchors(feature_map_sizes, anchor_sizes, anchor_ratios)
# for inference , the batch size is 1, the model output shape is [1, N, 4],
# so we expand dim for anchors to [1, anchor_num, 4]
anchors_exp = np.expand_dims(anchors, axis=0)
id2class = {0: 'Mask', 1: 'NoMask'}
# 人脸对齐方法
def inference(image,
| nf_thresh=0.5,
iou_thresh=0.4,
target_shape=(160, 160),
draw_result=True,
show_result=True
):
'''
Main function of detection inference
:param image: 3D numpy array of image
:param conf_thresh: the min threshold of classification probabity.
:param iou_thresh: the IOU threshold of NMS
:param target_shape: the model input size.
:param draw_result: whether to daw bounding box to the image.
:param show_result: whether to display the image.
:return:
'''
output_info = []
height, width, _ = image.shape
image_resized = cv2.resize(image, target_shape)
image_np = image_resized / 255.0 # 归一化到0~1
image_exp = np.expand_dims(image_np, axis=0)
# 输出回归框和人脸得分
y_bboxes_output, y_cls_output = tf_inference(sess, graph, image_exp)
# remove the batch dimension, for batch is always 1 for inference.
y_bboxes = decode_bbox(anchors_exp, y_bboxes_output)[0]
y_cls = y_cls_output[0]
# To speed up, do single class NMS, not multiple classes NMS.
bbox_max_scores = np.max(y_cls, axis=1)
bbox_max_score_classes = np.argmax(y_cls, axis=1)
# 对单个人脸进行非极大抑制
keep_idxs = single_class_non_max_suppression(y_bboxes,
bbox_max_scores,
conf_thresh=conf_thresh,
iou_thresh=iou_thresh,
)
for idx in keep_idxs:
conf = float(bbox_max_scores[idx])
class_id = bbox_max_score_classes[idx]
bbox = y_bboxes[idx]
# clip the coordinate, avoid the value exceed the image boundary.
xmin = max(0, int(bbox[0] * width))
ymin = max(0, int(bbox[1] * height))
xmax = min(int(bbox[2] * width), width)
ymax = min(int(bbox[3] * height), height)
if draw_result:
if class_id == 0:
color = (0, 255, 0)
else:
color = (255, 0, 0)
cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, 2)
cv2.putText(image, "%s: %.2f" % (id2class[class_id], conf), (xmin + 2, ymin - 2),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, color)
output_info.append([class_id, conf, xmin, ymin, xmax, ymax])
print(output_info)
if show_result:
Image.fromarray(image).show()
return output_info
def main():
global colours, img_size
args = parse_args()
videos_dir = args.videos_dir
output_path = args.output_path
no_display = args.no_display
detect_interval = args.detect_interval # 间隔一帧检测一次
margin = args.margin # 脸边距(默认10)
scale_rate = args.scale_rate # 检测图像的尺寸设置
show_rate = args.show_rate # 展示图像的尺寸设置
face_score_threshold = args.face_score_threshold # 人脸判别阈值
mkdir(output_path)
# for display
if not no_display:
colours = np.random.rand(32, 3)
# 初始化追踪器
tracker = Sort() # create instance of the SORT tracker
logger.info('Start track and extract......')
# 影像处理
for filename in os.listdir(videos_dir):
logger.info('All files:{}'.format(filename))
for filename in os.listdir(videos_dir):
suffix = filename.split('.')[1]
if suffix != 'mp4' and suffix != 'avi': # you can specify more video formats if you need
continue
video_name = os.path.join(videos_dir, filename)
directoryname = os.path.join(output_path, filename.split('.')[0])
logger.info('Video_name:{}'.format(video_name))
cam = cv2.VideoCapture(video_name)
c = 0
while True:
final_faces = []
addtional_attribute_list = []
ret, frame = cam.read()
if not ret:
logger.warning("ret false")
break
if frame is None:
logger.warning("frame drop")
break
frame = cv2.resize(frame, (0, 0), fx=scale_rate, fy=scale_rate)
r_g_b_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 间隔取帧,默认每帧都取
# if c % detect_interval == 0:
# img_size = np.asarray(frame.shape)[0:2]
# faces = inference(r_g_b_frame, show_result=True, target_shape=(260, 260))
with tf.Graph().as_default():
with tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True),
log_device_placement=False)) as sess:
pnet, rnet, onet = detect_face.create_mtcnn(sess, os.path.join(project_dir, "align"))
minsize = 40 # minimum size of face for mtcnn to detect
threshold = [0.6, 0.7, 0.7] # three steps's threshold
factor = 0.709 # scale factor
for filename in os.listdir(videos_dir):
logger.info('All files:{}'.format(filename))
for filename in os.listdir(videos_dir):
suffix = filename.split('.')[1]
if suffix != 'mp4' and suffix != 'avi': # you can specify more video formats if you need
continue
video_name = os.path.join(videos_dir, filename)
directoryname = os.path.join(output_path, filename.split('.')[0])
logger.info('Video_name:{}'.format(video_name))
cam = cv2.VideoCapture(video_name)
c = 0
while True:
final_faces = []
addtional_attribute_list = []
ret, frame = cam.read()
if not ret:
logger.warning("ret false")
break
if frame is None:
logger.warning("frame drop")
break
frame = cv2.resize(frame, (0, 0), fx=scale_rate, fy=scale_rate)
r_g_b_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
if c % detect_interval == 0:
img_size = np.asarray(frame.shape)[0:2]
mtcnn_starttime = time()
faces, points = detect_face.detect_face(r_g_b_frame, minsize, pnet, rnet, onet, threshold,
factor)
logger.info("MTCNN detect face cost time : {} s".format(
round(time() - mtcnn_starttime, 3))) # mtcnn detect ,slow
print('testttttt')
print(type(faces))
face_sums = faces.shape[0]
if face_sums > 0:
face_list = []
for i, item in enumerate(faces):
print(item)
score = round(faces[i, 4], 6)
if score > face_score_threshold:
det = np.squeeze(faces[i, 0:4])
# face rectangle
det[0] = np.maximum(det[0] - margin, 0)
det[1] = np.maximum(det[1] - margin, 0)
det[2] = np.minimum(det[2] + margin, img_size[1])
det[3] = np.minimum(det[3] + margin, img_size[0])
face_list.append(item)
# face cropped
bb = np.array(det, dtype=np.int32)
# use 5 face landmarks to judge the face is front or side
squeeze_points = np.squeeze(points[:, i])
tolist = squeeze_points.tolist()
facial_landmarks = []
for j in range(5):
item = [tolist[j], tolist[(j + 5)]]
facial_landmarks.append(item)
if args.face_landmarks:
for (x, y) in facial_landmarks:
cv2.circle(frame, (int(x), int(y)), 3, (0, 255, 0), -1)
cropped = frame[bb[1]:bb[3], bb[0]:bb[2], :].copy()
dist_rate, high_ratio_variance, width_rate = judge_side_face(
np.array(facial_landmarks))
# face addtional attribute(index 0:face score; index 1:0 represents front face and 1 for side face )
item_list = [cropped, score, dist_rate, high_ratio_variance, width_rate]
addtional_attribute_list.append(item_list)
final_faces = np.array(face_list)
trackers = tracker.update(final_faces, img_size, directoryname, addtional_attribute_list, detect_interval)
c += 1
for d in trackers:
if not no_display:
d = d.astype(np.int32)
cv2.rectangle(frame, (d[0], d[1]), (d[2], d[3]), colours[d[4] % 32, :] * 255, 3)
if final_faces != []:
cv2.putText(frame, 'ID : %d DETECT' % (d[4]), (d[0] - 10, d[1] - 10),
cv2.FONT_HERSHEY_SIMPLEX,
0.75,
colours[d[4] % 32, :] * 255, 2)
cv2.putText(frame, 'DETECTOR', (5, 45), cv2.FONT_HERSHEY_SIMPLEX, 0.75,
(1, 1, 1), 2)
else:
cv2.putText(frame, 'ID : %d' % (d[4]), (d[0] - 10, d[1] - 10), cv2.FONT_HERSHEY_SIMPLEX,
0.75,
colours[d[4] % 32, :] * 255, 2)
if not no_display:
frame = cv2.resize(frame, (0, 0), fx=show_rate, fy=show_rate)
cv2.imshow("Frame", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("--videos_dir", type=str,
help='Path to the data directory containing aligned your face patches.', default='videos')
parser.add_argument('--output_path', type=str,
help='Path to save face',
default='facepics')
parser.add_argument('--detect_interval',
help='how many frames to make a detection',
type=int, default=1)
parser.add_argument('--margin',
help='add margin for face',
type=int, default=10)
parser.add_argument('--scale_rate',
help='Scale down or enlarge the original video img',
type=float, default=0.7)
parser.add_argument('--show_rate',
help='Scale down or enlarge the imgs drawn by opencv',
type=float, default=1)
parser.add_argument('--face_score_threshold',
help='The threshold of the extracted faces,range 0<x<=1',
type=float, default=0.85)
parser.add_argument('--face_landmarks',
help='Draw five face landmarks on extracted face or not ', action="store_true")
parser.add_argument('--no_display',
help='Display or not', action='store_true')
args = parser.parse_args()
return args
| co | identifier_name |
start.py | import argparse
import os
from time import time
from PIL import Image
import align.detect_face as detect_face
import cv2
import numpy as np
import tensorflow as tf
from lib.face_utils import judge_side_face
from lib.utils import Logger, mkdir
from project_root_dir import project_dir
from src.sort import Sort
from load_model.tensorflow_loader import load_tf_model, tf_inference
from utils.anchor_generator import generate_anchors
from utils.anchor_decode import decode_bbox
from utils.nms import single_class_non_max_suppression
logger = Logger()
# 开始人脸对齐
sess, graph = load_tf_model('models/face_mask_detection.pb')
# anchor configuration
feature_map_sizes = [[33, 33], [17, 17], [9, 9], [5, 5], [3, 3]]
anchor_sizes = [[0.04, 0.056], [0.08, 0.11], [0.16, 0.22], [0.32, 0.45], [0.64, 0.72]]
anchor_ratios = [[1, 0.62, 0.42]] * 5
# generate anchors
anchors = generate_anchors(feature_map_sizes, anchor_sizes, anchor_ratios)
# for inference , the batch size is 1, the model output shape is [1, N, 4],
# so we expand dim for anchors to [1, anchor_num, 4]
anchors_exp = np.expand_dims(anchors, axis=0)
id2class = {0: 'Mask', 1: 'NoMask'}
# 人脸对齐方法
def inference(image,
conf_thresh=0.5,
iou_thresh=0.4,
target_shape=(160, 160),
draw_result=True,
show_result=True
):
'''
Main function of detection inference
:param image: 3D numpy array of image
:param conf_thresh: the min threshold of classification probabity.
:param iou_thresh: the IOU threshold of NMS
:param target_shape: the model input size.
:param draw_result: whether to daw bounding box to the image.
:param show_result: whether to display the image.
:return:
'''
output_info = []
height, width, _ = image.shape
image_resized = cv2.resize(image, target_shape)
image_np = image_resized / 255.0 # 归一化到0~1
image_exp = np.expand_dims(image_np, axis=0)
# 输出回归框和人脸得分
y_bboxes_output, y_cls_output = tf_inference(sess, graph, image_exp)
# remove the batch dimension, for batch is always 1 for inference.
y_bboxes = decode_bbox(anchors_exp, y_bboxes_output)[0]
y_cls = y_cls_output[0]
# To speed up, do single class NMS, not multiple classes NMS.
bbox_max_scores = np.max(y_cls, axis=1)
bbox_max_score_classes = np.argmax(y_cls, axis=1)
# 对单个人脸进行非极大抑制
keep_idxs = single_class_non_max_suppression(y_bboxes,
bbox_max_scores,
conf_thresh=conf_thresh,
iou_thresh=iou_thresh,
)
for idx in keep_idxs:
conf = float(bbox_max_scores[idx])
class_id = bbox_max_score_classes[idx]
bbox = y_bboxes[idx]
# clip the coordinate, avoid the value exceed the image boundary.
xmin = max(0, int(bbox[0] * width))
ymin = max(0, int(bbox[1] * height))
xmax = min(int(bbox[2] * width), width)
ymax = min(int(bbox[3] * height), height)
if draw_result:
if class_id == 0:
color = (0, 255, 0)
else:
color = (255, 0, 0)
cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, 2)
cv2.putText(image, "%s: %.2f" % (id2class[class_id], conf), (xmin + 2, ymin - 2),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, color)
output_info.append([class_id, conf, xmin, ymin, xmax, ymax])
print(output_info)
if show_result:
Image.fromarray(image).show()
return output_info
def main():
global colours, img_size
args = parse_args()
videos_dir = args.videos_dir
output_path = args.output_path
no_display = args.no_display
detect_interval = args.detect_interval # 间隔一帧检测一次
margin = args.margin # 脸边距(默认10)
scale_rate = args.scale_rate # 检测图像的尺寸设置
show_rate = args.show_rate # 展示图像的尺寸设置
face_score_threshold = args.face_score_threshold # 人脸判别阈值
mkdir(output_path)
# for display
if not no_display:
colours = np.random.rand(32, 3)
# 初始化追踪器
tracker = Sort() # create instance of the SORT tracker
logger.info('Start track and extract......')
# 影像处理
for filename in os.listdir(videos_dir):
logger.info('All files:{}'.format(filename))
for filename in os.listdir(videos_dir):
suffix = filename.split('.')[1]
if suffix != 'mp4' and suffix != 'avi': # you can specify more video formats if you need
continue
video_name = os.path.join(videos_dir, filename)
directoryname = os.path.join(output_path, filename.split('.')[0])
logger.info('Video_name:{}'.format(video_name))
cam = cv2.VideoCapture(video_name)
c = 0
while True:
final_faces = []
addtional_attribute_list = []
ret, frame = cam.read()
if not ret:
logger.warning("ret false")
break
if frame is None:
logger.warning("frame drop")
break
frame = cv2.resize(frame, (0, 0), fx=scale_rate, fy=scale_rate)
r_g_b_frame = cv2.cvtColor(frame, | # if c % detect_interval == 0:
# img_size = np.asarray(frame.shape)[0:2]
# faces = inference(r_g_b_frame, show_result=True, target_shape=(260, 260))
with tf.Graph().as_default():
with tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True),
log_device_placement=False)) as sess:
pnet, rnet, onet = detect_face.create_mtcnn(sess, os.path.join(project_dir, "align"))
minsize = 40 # minimum size of face for mtcnn to detect
threshold = [0.6, 0.7, 0.7] # three steps's threshold
factor = 0.709 # scale factor
for filename in os.listdir(videos_dir):
logger.info('All files:{}'.format(filename))
for filename in os.listdir(videos_dir):
suffix = filename.split('.')[1]
if suffix != 'mp4' and suffix != 'avi': # you can specify more video formats if you need
continue
video_name = os.path.join(videos_dir, filename)
directoryname = os.path.join(output_path, filename.split('.')[0])
logger.info('Video_name:{}'.format(video_name))
cam = cv2.VideoCapture(video_name)
c = 0
while True:
final_faces = []
addtional_attribute_list = []
ret, frame = cam.read()
if not ret:
logger.warning("ret false")
break
if frame is None:
logger.warning("frame drop")
break
frame = cv2.resize(frame, (0, 0), fx=scale_rate, fy=scale_rate)
r_g_b_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
if c % detect_interval == 0:
img_size = np.asarray(frame.shape)[0:2]
mtcnn_starttime = time()
faces, points = detect_face.detect_face(r_g_b_frame, minsize, pnet, rnet, onet, threshold,
factor)
logger.info("MTCNN detect face cost time : {} s".format(
round(time() - mtcnn_starttime, 3))) # mtcnn detect ,slow
print('testttttt')
print(type(faces))
face_sums = faces.shape[0]
if face_sums > 0:
face_list = []
for i, item in enumerate(faces):
print(item)
score = round(faces[i, 4], 6)
if score > face_score_threshold:
det = np.squeeze(faces[i, 0:4])
# face rectangle
det[0] = np.maximum(det[0] - margin, 0)
det[1] = np.maximum(det[1] - margin, 0)
det[2] = np.minimum(det[2] + margin, img_size[1])
det[3] = np.minimum(det[3] + margin, img_size[0])
face_list.append(item)
# face cropped
bb = np.array(det, dtype=np.int32)
# use 5 face landmarks to judge the face is front or side
squeeze_points = np.squeeze(points[:, i])
tolist = squeeze_points.tolist()
facial_landmarks = []
for j in range(5):
item = [tolist[j], tolist[(j + 5)]]
facial_landmarks.append(item)
if args.face_landmarks:
for (x, y) in facial_landmarks:
cv2.circle(frame, (int(x), int(y)), 3, (0, 255, 0), -1)
cropped = frame[bb[1]:bb[3], bb[0]:bb[2], :].copy()
dist_rate, high_ratio_variance, width_rate = judge_side_face(
np.array(facial_landmarks))
# face addtional attribute(index 0:face score; index 1:0 represents front face and 1 for side face )
item_list = [cropped, score, dist_rate, high_ratio_variance, width_rate]
addtional_attribute_list.append(item_list)
final_faces = np.array(face_list)
trackers = tracker.update(final_faces, img_size, directoryname, addtional_attribute_list, detect_interval)
c += 1
for d in trackers:
if not no_display:
d = d.astype(np.int32)
cv2.rectangle(frame, (d[0], d[1]), (d[2], d[3]), colours[d[4] % 32, :] * 255, 3)
if final_faces != []:
cv2.putText(frame, 'ID : %d DETECT' % (d[4]), (d[0] - 10, d[1] - 10),
cv2.FONT_HERSHEY_SIMPLEX,
0.75,
colours[d[4] % 32, :] * 255, 2)
cv2.putText(frame, 'DETECTOR', (5, 45), cv2.FONT_HERSHEY_SIMPLEX, 0.75,
(1, 1, 1), 2)
else:
cv2.putText(frame, 'ID : %d' % (d[4]), (d[0] - 10, d[1] - 10), cv2.FONT_HERSHEY_SIMPLEX,
0.75,
colours[d[4] % 32, :] * 255, 2)
if not no_display:
frame = cv2.resize(frame, (0, 0), fx=show_rate, fy=show_rate)
cv2.imshow("Frame", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("--videos_dir", type=str,
help='Path to the data directory containing aligned your face patches.', default='videos')
parser.add_argument('--output_path', type=str,
help='Path to save face',
default='facepics')
parser.add_argument('--detect_interval',
help='how many frames to make a detection',
type=int, default=1)
parser.add_argument('--margin',
help='add margin for face',
type=int, default=10)
parser.add_argument('--scale_rate',
help='Scale down or enlarge the original video img',
type=float, default=0.7)
parser.add_argument('--show_rate',
help='Scale down or enlarge the imgs drawn by opencv',
type=float, default=1)
parser.add_argument('--face_score_threshold',
help='The threshold of the extracted faces,range 0<x<=1',
type=float, default=0.85)
parser.add_argument('--face_landmarks',
help='Draw five face landmarks on extracted face or not ', action="store_true")
parser.add_argument('--no_display',
help='Display or not', action='store_true')
args = parser.parse_args()
return args
| cv2.COLOR_BGR2RGB)
# 间隔取帧,默认每帧都取
| conditional_block |
h5t.go | package hdf5
// #include "hdf5.h"
// #include <stdlib.h>
// #include <string.h>
import "C"
import (
"unsafe"
//"runtime"
"fmt"
"reflect"
)
// ---- H5T: Datatype Interface ----
type DataType struct {
id C.hid_t
rt reflect.Type
}
type TypeClass C.H5T_class_t
const (
// Error
T_NO_CLASS TypeClass = -1
// integer types
T_INTEGER TypeClass = 0
// floating-point types
T_FLOAT TypeClass = 1
// date and time types
T_TIME TypeClass = 2
// character string types
T_STRING TypeClass = 3
// bit field types
T_BITFIELD TypeClass = 4
// opaque types
T_OPAQUE TypeClass = 5
// compound types
T_COMPOUND TypeClass = 6
// reference types
T_REFERENCE TypeClass = 7
// enumeration types
T_ENUM TypeClass = 8
// variable-length types
T_VLEN TypeClass = 9
// array types
T_ARRAY TypeClass = 10
// nbr of classes -- MUST BE LAST
T_NCLASSES TypeClass = 11
)
type dummy_struct struct{}
// list of go types
var (
_go_string_t reflect.Type = reflect.TypeOf(string(""))
_go_int_t reflect.Type = reflect.TypeOf(int(0))
_go_int8_t reflect.Type = reflect.TypeOf(int8(0))
_go_int16_t reflect.Type = reflect.TypeOf(int16(0))
_go_int32_t reflect.Type = reflect.TypeOf(int32(0))
_go_int64_t reflect.Type = reflect.TypeOf(int64(0))
_go_uint_t reflect.Type = reflect.TypeOf(uint(0))
_go_uint8_t reflect.Type = reflect.TypeOf(uint8(0))
_go_uint16_t reflect.Type = reflect.TypeOf(uint16(0))
_go_uint32_t reflect.Type = reflect.TypeOf(uint32(0))
_go_uint64_t reflect.Type = reflect.TypeOf(uint64(0))
_go_float32_t reflect.Type = reflect.TypeOf(float32(0))
_go_float64_t reflect.Type = reflect.TypeOf(float64(0))
_go_array_t reflect.Type = reflect.TypeOf([1]int{0})
_go_slice_t reflect.Type = reflect.TypeOf([]int{0})
_go_struct_t reflect.Type = reflect.TypeOf(dummy_struct{})
_go_ptr_t reflect.Type = reflect.PtrTo(_go_int_t)
)
type typeClassToType map[TypeClass]reflect.Type
var (
// mapping of type-class to go-type
_type_cls_to_go_type typeClassToType = typeClassToType{
T_NO_CLASS: nil,
T_INTEGER: _go_int_t,
T_FLOAT: _go_float32_t,
T_TIME: nil,
T_STRING: _go_string_t,
T_BITFIELD: nil,
T_OPAQUE: nil,
T_COMPOUND: _go_struct_t,
T_REFERENCE: _go_ptr_t,
T_ENUM: _go_int_t,
T_VLEN: _go_slice_t,
T_ARRAY: _go_array_t,
}
)
func new_dtype(id C.hid_t, rt reflect.Type) *DataType {
t := &DataType{id: id, rt: rt}
//runtime.SetFinalizer(t, (*DataType).h5t_finalizer)
return t
}
// Creates a new datatype.
// hid_t H5Tcreate( H5T_class_t class, size_tsize )
func CreateDataType(class TypeClass, size int) (t *DataType, err error) {
t = nil
err = nil
hid := C.H5Tcreate(C.H5T_class_t(class), C.size_t(size))
err = togo_err(C.herr_t(int(hid)))
if err != nil {
return
}
t = new_dtype(hid, _type_cls_to_go_type[class])
return
}
func (t *DataType) h5t_finalizer() {
err := t.Close()
if err != nil {
panic(fmt.Sprintf("error closing datatype: %s", err))
}
}
// Releases a datatype.
// herr_t H5Tclose( hid_t dtype_id )
func (t *DataType) Close() error {
if t.id > 0 {
fmt.Printf("--- closing dtype [%d]...\n", t.id)
err := togo_err(C.H5Tclose(t.id))
t.id = 0
return err
}
return nil
}
// Commits a transient datatype, linking it into the file and creating a new named datatype.
// herr_t H5Tcommit( hid_t loc_id, const char *name, hid_t dtype_id, hid_t lcpl_id, hid_t tcpl_id, hid_t tapl_id )
//func (t *DataType) Commit()
// Determines whether a datatype is a named type or a transient type.
// htri_tH5Tcommitted( hid_t dtype_id )
func (t *DataType) Committed() bool {
o := int(C.H5Tcommitted(t.id))
if o > 0 {
return true
}
return false
}
// Copies an existing datatype.
// hid_t H5Tcopy( hid_t dtype_id )
func (t *DataType) Copy() (*DataType, error) {
hid := C.H5Tcopy(t.id)
err := togo_err(C.herr_t(int(hid)))
if err != nil {
return nil, err
}
o := new_dtype(hid, t.rt)
return o, err
}
// Determines whether two datatype identifiers refer to the same datatype.
// htri_t H5Tequal( hid_t dtype_id1, hid_t dtype_id2 )
func (t *DataType) Equal(o *DataType) bool {
v := int(C.H5Tequal(t.id, o.id))
if v > 0 {
return true
}
return false
}
// Locks a datatype.
// herr_t H5Tlock( hid_t dtype_id )
func (t *DataType) Lock() error {
return togo_err(C.H5Tlock(t.id))
}
// Returns the size of a datatype.
// size_t H5Tget_size( hid_t dtype_id )
func (t *DataType) Size() int {
return int(C.H5Tget_size(t.id))
}
// Sets the total size for an atomic datatype.
// herr_t H5Tset_size( hid_t dtype_id, size_tsize )
func (t *DataType) SetSize(sz int) error {
err := C.H5Tset_size(t.id, C.size_t(sz))
return togo_err(err)
}
// ---------------------------------------------------------------------------
// array data type
type ArrayType struct {
DataType
}
func new_array_type(id C.hid_t) *ArrayType {
t := &ArrayType{DataType{id: id}}
//runtime.SetFinalizer(t, (*DataType).h5t_finalizer)
return t
}
func NewArrayType(base_type *DataType, dims []int) (*ArrayType, error) {
ndims := C.uint(len(dims))
c_dims := (*C.hsize_t)(unsafe.Pointer(&dims[0]))
hid := C.H5Tarray_create2(base_type.id, ndims, c_dims)
err := togo_err(C.herr_t(int(hid)))
if err != nil {
return nil, err
}
t := new_array_type(hid)
return t, err
}
// Returns the rank of an array datatype.
// int H5Tget_array_ndims( hid_t adtype_id )
func (t *ArrayType) NDims() int {
return int(C.H5Tget_array_ndims(t.id))
}
// Retrieves sizes of array dimensions.
// int H5Tget_array_dims2( hid_t adtype_id, hsize_t dims[] )
func (t *ArrayType) ArrayDims() []int {
rank := t.NDims()
dims := make([]int, rank)
// fixme: int/hsize_t size!
c_dims := (*C.hsize_t)(unsafe.Pointer(&dims[0]))
c_rank := int(C.H5Tget_array_dims2(t.id, c_dims))
if c_rank == rank {
return dims
}
return nil
}
// ---------------------------------------------------------------------------
// variable length array data type
type VarLenType struct {
DataType
}
func NewVarLenType(base_type *DataType) (*VarLenType, error) {
hid := C.H5Tvlen_create(base_type.id)
err := togo_err(C.herr_t(int(hid)))
if err != nil {
return nil, err
}
dt := new_vltype(hid)
return dt, err
}
func new_vltype(id C.hid_t) *VarLenType {
t := &VarLenType{DataType{id: id}}
//runtime.SetFinalizer(t, (*DataType).h5t_finalizer)
return t
}
// Determines whether datatype is a variable-length string.
// htri_t H5Tis_variable_str( hid_t dtype_id )
func (vl *VarLenType) IsVariableStr() bool {
o := int(C.H5Tis_variable_str(vl.id))
if o > 0 {
return true
}
return false
}
// ---------------------------------------------------------------------------
// compound data type
type CompType struct {
DataType
}
// Retrieves the number of elements in a compound or enumeration datatype.
// int H5Tget_nmembers( hid_t dtype_id )
func (t *CompType) NMembers() int {
return int(C.H5Tget_nmembers(t.id))
}
// Returns datatype class of compound datatype member.
// H5T_class_t H5Tget_member_class( hid_t cdtype_id, unsigned member_no )
func (t *CompType) MemberClass(mbr_idx int) TypeClass {
return TypeClass(C.H5Tget_member_class(t.id, C.uint(mbr_idx)))
}
// Retrieves the name of a compound or enumeration datatype member.
// char * H5Tget_member_name( hid_t dtype_id, unsigned field_idx )
func (t *CompType) MemberName(mbr_idx int) string {
c_name := C.H5Tget_member_name(t.id, C.uint(mbr_idx))
return C.GoString(c_name)
}
// Retrieves the index of a compound or enumeration datatype member.
// int H5Tget_member_index( hid_t dtype_id, const char * field_name )
func (t *CompType) MemberIndex(name string) int {
c_name := C.CString(name)
defer C.free(unsafe.Pointer(c_name))
return int(C.H5Tget_member_index(t.id, c_name))
}
// Retrieves the offset of a field of a compound datatype.
// size_t H5Tget_member_offset( hid_t dtype_id, unsigned memb_no )
func (t *CompType) MemberOffset(mbr_idx int) int {
return int(C.H5Tget_member_offset(t.id, C.uint(mbr_idx)))
}
// Returns the datatype of the specified member.
// hid_t H5Tget_member_type( hid_t dtype_id, unsigned field_idx )
func (t *CompType) MemberType(mbr_idx int) (*DataType, error) {
hid := C.H5Tget_member_type(t.id, C.uint(mbr_idx))
err := togo_err(C.herr_t(int(hid)))
if err != nil {
return nil, err
}
dt := new_dtype(hid, t.rt.Field(mbr_idx).Type)
return dt, nil
}
// Adds a new member to a compound datatype.
// herr_t H5Tinsert( hid_t dtype_id, const char * name, size_t offset, hid_t field_id )
func (t *CompType) Insert(name string, offset int, field *DataType) error {
c_name := C.CString(name)
defer C.free(unsafe.Pointer(c_name))
//fmt.Printf("inserting [%s] at offset:%d (id=%d)...\n", name, offset, field.id)
err := C.H5Tinsert(t.id, c_name, C.size_t(offset), field.id)
return togo_err(err)
}
// Recursively removes padding from within a compound datatype.
// herr_t H5Tpack( hid_t dtype_id )
func (t *CompType) Pack() error {
err := C.H5Tpack(t.id)
return togo_err(err)
}
// --- opaque type ---
type OpaqueDataType struct {
DataType
}
// Tags an opaque datatype.
// herr_t H5Tset_tag( hid_t dtype_id const char *tag )
func (t *OpaqueDataType) SetTag(tag string) error {
c_tag := C.CString(tag)
defer C.free(unsafe.Pointer(c_tag))
err := C.H5Tset_tag(t.id, c_tag)
return togo_err(err)
}
// Gets the tag associated with an opaque datatype.
// char *H5Tget_tag( hid_t dtype_id )
func (t *OpaqueDataType) Tag() string {
c_name := C.H5Tget_tag(t.id)
if c_name != nil {
return C.GoString(c_name)
}
return ""
}
// -----------------------------------------
// create a data-type from a golang value
func NewDataTypeFromValue(v interface{}) *DataType {
t := reflect.TypeOf(v)
return new_dataTypeFromType(t)
}
func new_dataTypeFromType(t reflect.Type) *DataType {
var dt *DataType = nil
switch t.Kind() {
case reflect.Int:
dt = T_NATIVE_INT // FIXME: .Copy() instead ?
case reflect.Int8:
dt = T_NATIVE_INT8
case reflect.Int16:
dt = T_NATIVE_INT16
case reflect.Int32:
dt = T_NATIVE_INT32
case reflect.Int64:
dt = T_NATIVE_INT64
case reflect.Uint:
dt = T_NATIVE_UINT // FIXME: .Copy() instead ?
case reflect.Uint8:
dt = T_NATIVE_UINT8
case reflect.Uint16:
dt = T_NATIVE_UINT16
case reflect.Uint32:
dt = T_NATIVE_UINT32
case reflect.Uint64:
dt = T_NATIVE_UINT64
case reflect.Float32:
dt = T_NATIVE_FLOAT
case reflect.Float64:
dt = T_NATIVE_DOUBLE
case reflect.String:
dt = T_GO_STRING
//dt = T_C_S1
case reflect.Array:
elem_type := new_dataTypeFromType(t.Elem())
n := t.Len()
dims := []int{n}
adt, err := NewArrayType(elem_type, dims)
if err != nil {
panic(err)
}
dt, err = adt.Copy()
if err != nil {
panic(err)
}
case reflect.Slice:
elem_type := new_dataTypeFromType(t.Elem())
vlen_dt, err := NewVarLenType(elem_type)
if err != nil {
panic(err)
}
dt, err = vlen_dt.Copy()
if err != nil {
panic(err)
}
case reflect.Struct:
sz := int(t.Size())
hdf_dt, err := CreateDataType(T_COMPOUND, sz)
if err != nil {
panic(err)
}
cdt := &CompType{*hdf_dt}
n := t.NumField()
for i := 0; i < n; i++ |
cdt.Lock()
dt, err = cdt.Copy()
if err != nil {
panic(err)
}
case reflect.Ptr:
panic("sorry, pointers not yet supported")
default:
panic(fmt.Sprintf("unhandled kind (%d)", t.Kind()))
}
return dt
}
// EOF
| {
f := t.Field(i)
var field_dt *DataType = nil
field_dt = new_dataTypeFromType(f.Type)
offset := int(f.Offset + 0)
if field_dt == nil {
panic(fmt.Sprintf("pb with field [%d-%s]", i, f.Name))
}
field_name := string(f.Tag)
if len(field_name) == 0 {
field_name = f.Name
}
err = cdt.Insert(field_name, offset, field_dt)
if err != nil {
panic(fmt.Sprintf("pb with field [%d-%s]: %s", i, f.Name, err))
}
} | conditional_block |
h5t.go | package hdf5
// #include "hdf5.h"
// #include <stdlib.h>
// #include <string.h>
import "C"
import (
"unsafe"
//"runtime"
"fmt"
"reflect"
)
// ---- H5T: Datatype Interface ----
type DataType struct {
id C.hid_t
rt reflect.Type
}
type TypeClass C.H5T_class_t
const (
// Error
T_NO_CLASS TypeClass = -1
// integer types
T_INTEGER TypeClass = 0
// floating-point types
T_FLOAT TypeClass = 1
// date and time types
T_TIME TypeClass = 2
// character string types
T_STRING TypeClass = 3
// bit field types
T_BITFIELD TypeClass = 4
// opaque types
T_OPAQUE TypeClass = 5
// compound types
T_COMPOUND TypeClass = 6
// reference types
T_REFERENCE TypeClass = 7
// enumeration types
T_ENUM TypeClass = 8
// variable-length types
T_VLEN TypeClass = 9
// array types
T_ARRAY TypeClass = 10
// nbr of classes -- MUST BE LAST
T_NCLASSES TypeClass = 11
)
type dummy_struct struct{}
// list of go types
var (
_go_string_t reflect.Type = reflect.TypeOf(string(""))
_go_int_t reflect.Type = reflect.TypeOf(int(0))
_go_int8_t reflect.Type = reflect.TypeOf(int8(0))
_go_int16_t reflect.Type = reflect.TypeOf(int16(0))
_go_int32_t reflect.Type = reflect.TypeOf(int32(0))
_go_int64_t reflect.Type = reflect.TypeOf(int64(0))
_go_uint_t reflect.Type = reflect.TypeOf(uint(0))
_go_uint8_t reflect.Type = reflect.TypeOf(uint8(0))
_go_uint16_t reflect.Type = reflect.TypeOf(uint16(0))
_go_uint32_t reflect.Type = reflect.TypeOf(uint32(0))
_go_uint64_t reflect.Type = reflect.TypeOf(uint64(0))
_go_float32_t reflect.Type = reflect.TypeOf(float32(0))
_go_float64_t reflect.Type = reflect.TypeOf(float64(0))
_go_array_t reflect.Type = reflect.TypeOf([1]int{0})
_go_slice_t reflect.Type = reflect.TypeOf([]int{0})
_go_struct_t reflect.Type = reflect.TypeOf(dummy_struct{})
_go_ptr_t reflect.Type = reflect.PtrTo(_go_int_t)
)
type typeClassToType map[TypeClass]reflect.Type
var (
// mapping of type-class to go-type
_type_cls_to_go_type typeClassToType = typeClassToType{
T_NO_CLASS: nil,
T_INTEGER: _go_int_t,
T_FLOAT: _go_float32_t,
T_TIME: nil,
T_STRING: _go_string_t,
T_BITFIELD: nil,
T_OPAQUE: nil,
T_COMPOUND: _go_struct_t,
T_REFERENCE: _go_ptr_t,
T_ENUM: _go_int_t,
T_VLEN: _go_slice_t,
T_ARRAY: _go_array_t,
}
)
func new_dtype(id C.hid_t, rt reflect.Type) *DataType {
t := &DataType{id: id, rt: rt}
//runtime.SetFinalizer(t, (*DataType).h5t_finalizer)
return t
}
// Creates a new datatype.
// hid_t H5Tcreate( H5T_class_t class, size_tsize )
func CreateDataType(class TypeClass, size int) (t *DataType, err error) {
t = nil
err = nil
hid := C.H5Tcreate(C.H5T_class_t(class), C.size_t(size))
err = togo_err(C.herr_t(int(hid)))
if err != nil {
return
}
t = new_dtype(hid, _type_cls_to_go_type[class])
return
}
func (t *DataType) h5t_finalizer() {
err := t.Close()
if err != nil {
panic(fmt.Sprintf("error closing datatype: %s", err))
}
}
// Releases a datatype.
// herr_t H5Tclose( hid_t dtype_id )
func (t *DataType) Close() error {
if t.id > 0 {
fmt.Printf("--- closing dtype [%d]...\n", t.id)
err := togo_err(C.H5Tclose(t.id))
t.id = 0
return err
}
return nil
}
// Commits a transient datatype, linking it into the file and creating a new named datatype.
// herr_t H5Tcommit( hid_t loc_id, const char *name, hid_t dtype_id, hid_t lcpl_id, hid_t tcpl_id, hid_t tapl_id )
//func (t *DataType) Commit()
// Determines whether a datatype is a named type or a transient type.
// htri_tH5Tcommitted( hid_t dtype_id )
func (t *DataType) Committed() bool {
o := int(C.H5Tcommitted(t.id))
if o > 0 {
return true
}
return false
}
// Copies an existing datatype.
// hid_t H5Tcopy( hid_t dtype_id )
func (t *DataType) Copy() (*DataType, error) {
hid := C.H5Tcopy(t.id)
err := togo_err(C.herr_t(int(hid)))
if err != nil {
return nil, err
}
o := new_dtype(hid, t.rt)
return o, err
}
// Determines whether two datatype identifiers refer to the same datatype.
// htri_t H5Tequal( hid_t dtype_id1, hid_t dtype_id2 )
func (t *DataType) Equal(o *DataType) bool {
v := int(C.H5Tequal(t.id, o.id))
if v > 0 {
return true
}
return false
}
// Locks a datatype.
// herr_t H5Tlock( hid_t dtype_id )
func (t *DataType) Lock() error {
return togo_err(C.H5Tlock(t.id))
}
// Returns the size of a datatype.
// size_t H5Tget_size( hid_t dtype_id )
func (t *DataType) Size() int {
return int(C.H5Tget_size(t.id))
}
// Sets the total size for an atomic datatype.
// herr_t H5Tset_size( hid_t dtype_id, size_tsize )
func (t *DataType) SetSize(sz int) error {
err := C.H5Tset_size(t.id, C.size_t(sz))
return togo_err(err)
}
// ---------------------------------------------------------------------------
// array data type
type ArrayType struct {
DataType
}
func new_array_type(id C.hid_t) *ArrayType {
t := &ArrayType{DataType{id: id}}
//runtime.SetFinalizer(t, (*DataType).h5t_finalizer)
return t
}
func NewArrayType(base_type *DataType, dims []int) (*ArrayType, error) {
ndims := C.uint(len(dims))
c_dims := (*C.hsize_t)(unsafe.Pointer(&dims[0]))
hid := C.H5Tarray_create2(base_type.id, ndims, c_dims)
err := togo_err(C.herr_t(int(hid)))
if err != nil {
return nil, err
}
t := new_array_type(hid)
return t, err
}
// Returns the rank of an array datatype.
// int H5Tget_array_ndims( hid_t adtype_id )
func (t *ArrayType) NDims() int {
return int(C.H5Tget_array_ndims(t.id))
}
// Retrieves sizes of array dimensions.
// int H5Tget_array_dims2( hid_t adtype_id, hsize_t dims[] )
func (t *ArrayType) ArrayDims() []int {
rank := t.NDims()
dims := make([]int, rank)
// fixme: int/hsize_t size!
c_dims := (*C.hsize_t)(unsafe.Pointer(&dims[0]))
c_rank := int(C.H5Tget_array_dims2(t.id, c_dims))
if c_rank == rank {
return dims
}
return nil
}
// ---------------------------------------------------------------------------
// variable length array data type
type VarLenType struct {
DataType
}
func NewVarLenType(base_type *DataType) (*VarLenType, error) {
hid := C.H5Tvlen_create(base_type.id)
err := togo_err(C.herr_t(int(hid)))
if err != nil {
return nil, err
}
dt := new_vltype(hid)
return dt, err
}
func new_vltype(id C.hid_t) *VarLenType {
t := &VarLenType{DataType{id: id}}
//runtime.SetFinalizer(t, (*DataType).h5t_finalizer)
return t
}
// Determines whether datatype is a variable-length string.
// htri_t H5Tis_variable_str( hid_t dtype_id )
func (vl *VarLenType) IsVariableStr() bool {
o := int(C.H5Tis_variable_str(vl.id))
if o > 0 {
return true
}
return false
}
// ---------------------------------------------------------------------------
// compound data type
type CompType struct {
DataType
}
// Retrieves the number of elements in a compound or enumeration datatype.
// int H5Tget_nmembers( hid_t dtype_id )
func (t *CompType) NMembers() int {
return int(C.H5Tget_nmembers(t.id))
}
// Returns datatype class of compound datatype member.
// H5T_class_t H5Tget_member_class( hid_t cdtype_id, unsigned member_no )
func (t *CompType) MemberClass(mbr_idx int) TypeClass {
return TypeClass(C.H5Tget_member_class(t.id, C.uint(mbr_idx)))
}
// Retrieves the name of a compound or enumeration datatype member.
// char * H5Tget_member_name( hid_t dtype_id, unsigned field_idx )
func (t *CompType) MemberName(mbr_idx int) string {
c_name := C.H5Tget_member_name(t.id, C.uint(mbr_idx))
return C.GoString(c_name)
}
// Retrieves the index of a compound or enumeration datatype member.
// int H5Tget_member_index( hid_t dtype_id, const char * field_name )
func (t *CompType) MemberIndex(name string) int {
c_name := C.CString(name)
defer C.free(unsafe.Pointer(c_name))
return int(C.H5Tget_member_index(t.id, c_name))
}
// Retrieves the offset of a field of a compound datatype.
// size_t H5Tget_member_offset( hid_t dtype_id, unsigned memb_no )
func (t *CompType) MemberOffset(mbr_idx int) int {
return int(C.H5Tget_member_offset(t.id, C.uint(mbr_idx)))
}
// Returns the datatype of the specified member.
// hid_t H5Tget_member_type( hid_t dtype_id, unsigned field_idx )
func (t *CompType) MemberType(mbr_idx int) (*DataType, error) {
hid := C.H5Tget_member_type(t.id, C.uint(mbr_idx))
err := togo_err(C.herr_t(int(hid)))
if err != nil {
return nil, err
}
dt := new_dtype(hid, t.rt.Field(mbr_idx).Type)
return dt, nil
}
// Adds a new member to a compound datatype.
// herr_t H5Tinsert( hid_t dtype_id, const char * name, size_t offset, hid_t field_id )
func (t *CompType) Insert(name string, offset int, field *DataType) error {
c_name := C.CString(name)
defer C.free(unsafe.Pointer(c_name))
//fmt.Printf("inserting [%s] at offset:%d (id=%d)...\n", name, offset, field.id)
err := C.H5Tinsert(t.id, c_name, C.size_t(offset), field.id)
return togo_err(err)
}
// Recursively removes padding from within a compound datatype.
// herr_t H5Tpack( hid_t dtype_id )
func (t *CompType) Pack() error {
err := C.H5Tpack(t.id)
return togo_err(err)
}
// --- opaque type ---
type OpaqueDataType struct {
DataType
}
// Tags an opaque datatype.
// herr_t H5Tset_tag( hid_t dtype_id const char *tag )
func (t *OpaqueDataType) SetTag(tag string) error |
// Gets the tag associated with an opaque datatype.
// char *H5Tget_tag( hid_t dtype_id )
func (t *OpaqueDataType) Tag() string {
c_name := C.H5Tget_tag(t.id)
if c_name != nil {
return C.GoString(c_name)
}
return ""
}
// -----------------------------------------
// create a data-type from a golang value
func NewDataTypeFromValue(v interface{}) *DataType {
t := reflect.TypeOf(v)
return new_dataTypeFromType(t)
}
func new_dataTypeFromType(t reflect.Type) *DataType {
var dt *DataType = nil
switch t.Kind() {
case reflect.Int:
dt = T_NATIVE_INT // FIXME: .Copy() instead ?
case reflect.Int8:
dt = T_NATIVE_INT8
case reflect.Int16:
dt = T_NATIVE_INT16
case reflect.Int32:
dt = T_NATIVE_INT32
case reflect.Int64:
dt = T_NATIVE_INT64
case reflect.Uint:
dt = T_NATIVE_UINT // FIXME: .Copy() instead ?
case reflect.Uint8:
dt = T_NATIVE_UINT8
case reflect.Uint16:
dt = T_NATIVE_UINT16
case reflect.Uint32:
dt = T_NATIVE_UINT32
case reflect.Uint64:
dt = T_NATIVE_UINT64
case reflect.Float32:
dt = T_NATIVE_FLOAT
case reflect.Float64:
dt = T_NATIVE_DOUBLE
case reflect.String:
dt = T_GO_STRING
//dt = T_C_S1
case reflect.Array:
elem_type := new_dataTypeFromType(t.Elem())
n := t.Len()
dims := []int{n}
adt, err := NewArrayType(elem_type, dims)
if err != nil {
panic(err)
}
dt, err = adt.Copy()
if err != nil {
panic(err)
}
case reflect.Slice:
elem_type := new_dataTypeFromType(t.Elem())
vlen_dt, err := NewVarLenType(elem_type)
if err != nil {
panic(err)
}
dt, err = vlen_dt.Copy()
if err != nil {
panic(err)
}
case reflect.Struct:
sz := int(t.Size())
hdf_dt, err := CreateDataType(T_COMPOUND, sz)
if err != nil {
panic(err)
}
cdt := &CompType{*hdf_dt}
n := t.NumField()
for i := 0; i < n; i++ {
f := t.Field(i)
var field_dt *DataType = nil
field_dt = new_dataTypeFromType(f.Type)
offset := int(f.Offset + 0)
if field_dt == nil {
panic(fmt.Sprintf("pb with field [%d-%s]", i, f.Name))
}
field_name := string(f.Tag)
if len(field_name) == 0 {
field_name = f.Name
}
err = cdt.Insert(field_name, offset, field_dt)
if err != nil {
panic(fmt.Sprintf("pb with field [%d-%s]: %s", i, f.Name, err))
}
}
cdt.Lock()
dt, err = cdt.Copy()
if err != nil {
panic(err)
}
case reflect.Ptr:
panic("sorry, pointers not yet supported")
default:
panic(fmt.Sprintf("unhandled kind (%d)", t.Kind()))
}
return dt
}
// EOF
| {
c_tag := C.CString(tag)
defer C.free(unsafe.Pointer(c_tag))
err := C.H5Tset_tag(t.id, c_tag)
return togo_err(err)
} | identifier_body |
h5t.go | package hdf5
// #include "hdf5.h"
// #include <stdlib.h>
// #include <string.h>
import "C"
import (
"unsafe"
//"runtime"
"fmt"
"reflect"
)
// ---- H5T: Datatype Interface ----
type DataType struct {
id C.hid_t
rt reflect.Type
}
type TypeClass C.H5T_class_t
const (
// Error
T_NO_CLASS TypeClass = -1
// integer types
T_INTEGER TypeClass = 0
// floating-point types
T_FLOAT TypeClass = 1
// date and time types
T_TIME TypeClass = 2
// character string types
T_STRING TypeClass = 3
// bit field types
T_BITFIELD TypeClass = 4
// opaque types
T_OPAQUE TypeClass = 5
// compound types
T_COMPOUND TypeClass = 6
// reference types
T_REFERENCE TypeClass = 7
// enumeration types
T_ENUM TypeClass = 8
// variable-length types
T_VLEN TypeClass = 9
// array types
T_ARRAY TypeClass = 10
// nbr of classes -- MUST BE LAST
T_NCLASSES TypeClass = 11
)
type dummy_struct struct{}
// list of go types
var (
_go_string_t reflect.Type = reflect.TypeOf(string(""))
_go_int_t reflect.Type = reflect.TypeOf(int(0))
_go_int8_t reflect.Type = reflect.TypeOf(int8(0))
_go_int16_t reflect.Type = reflect.TypeOf(int16(0))
_go_int32_t reflect.Type = reflect.TypeOf(int32(0))
_go_int64_t reflect.Type = reflect.TypeOf(int64(0))
_go_uint_t reflect.Type = reflect.TypeOf(uint(0))
_go_uint8_t reflect.Type = reflect.TypeOf(uint8(0))
_go_uint16_t reflect.Type = reflect.TypeOf(uint16(0))
_go_uint32_t reflect.Type = reflect.TypeOf(uint32(0))
_go_uint64_t reflect.Type = reflect.TypeOf(uint64(0))
_go_float32_t reflect.Type = reflect.TypeOf(float32(0))
_go_float64_t reflect.Type = reflect.TypeOf(float64(0))
_go_array_t reflect.Type = reflect.TypeOf([1]int{0})
_go_slice_t reflect.Type = reflect.TypeOf([]int{0})
_go_struct_t reflect.Type = reflect.TypeOf(dummy_struct{})
_go_ptr_t reflect.Type = reflect.PtrTo(_go_int_t)
)
type typeClassToType map[TypeClass]reflect.Type
var (
// mapping of type-class to go-type
_type_cls_to_go_type typeClassToType = typeClassToType{
T_NO_CLASS: nil,
T_INTEGER: _go_int_t,
T_FLOAT: _go_float32_t,
T_TIME: nil,
T_STRING: _go_string_t,
T_BITFIELD: nil,
T_OPAQUE: nil,
T_COMPOUND: _go_struct_t,
T_REFERENCE: _go_ptr_t,
T_ENUM: _go_int_t,
T_VLEN: _go_slice_t,
T_ARRAY: _go_array_t,
}
)
func new_dtype(id C.hid_t, rt reflect.Type) *DataType {
t := &DataType{id: id, rt: rt}
//runtime.SetFinalizer(t, (*DataType).h5t_finalizer)
return t
}
// Creates a new datatype.
// hid_t H5Tcreate( H5T_class_t class, size_tsize )
func CreateDataType(class TypeClass, size int) (t *DataType, err error) {
t = nil
err = nil
hid := C.H5Tcreate(C.H5T_class_t(class), C.size_t(size))
err = togo_err(C.herr_t(int(hid)))
if err != nil {
return
}
t = new_dtype(hid, _type_cls_to_go_type[class])
return
}
func (t *DataType) | () {
err := t.Close()
if err != nil {
panic(fmt.Sprintf("error closing datatype: %s", err))
}
}
// Releases a datatype.
// herr_t H5Tclose( hid_t dtype_id )
func (t *DataType) Close() error {
if t.id > 0 {
fmt.Printf("--- closing dtype [%d]...\n", t.id)
err := togo_err(C.H5Tclose(t.id))
t.id = 0
return err
}
return nil
}
// Commits a transient datatype, linking it into the file and creating a new named datatype.
// herr_t H5Tcommit( hid_t loc_id, const char *name, hid_t dtype_id, hid_t lcpl_id, hid_t tcpl_id, hid_t tapl_id )
//func (t *DataType) Commit()
// Determines whether a datatype is a named type or a transient type.
// htri_tH5Tcommitted( hid_t dtype_id )
func (t *DataType) Committed() bool {
o := int(C.H5Tcommitted(t.id))
if o > 0 {
return true
}
return false
}
// Copies an existing datatype.
// hid_t H5Tcopy( hid_t dtype_id )
func (t *DataType) Copy() (*DataType, error) {
hid := C.H5Tcopy(t.id)
err := togo_err(C.herr_t(int(hid)))
if err != nil {
return nil, err
}
o := new_dtype(hid, t.rt)
return o, err
}
// Determines whether two datatype identifiers refer to the same datatype.
// htri_t H5Tequal( hid_t dtype_id1, hid_t dtype_id2 )
func (t *DataType) Equal(o *DataType) bool {
v := int(C.H5Tequal(t.id, o.id))
if v > 0 {
return true
}
return false
}
// Locks a datatype.
// herr_t H5Tlock( hid_t dtype_id )
func (t *DataType) Lock() error {
return togo_err(C.H5Tlock(t.id))
}
// Returns the size of a datatype.
// size_t H5Tget_size( hid_t dtype_id )
func (t *DataType) Size() int {
return int(C.H5Tget_size(t.id))
}
// Sets the total size for an atomic datatype.
// herr_t H5Tset_size( hid_t dtype_id, size_tsize )
func (t *DataType) SetSize(sz int) error {
err := C.H5Tset_size(t.id, C.size_t(sz))
return togo_err(err)
}
// ---------------------------------------------------------------------------
// array data type
type ArrayType struct {
DataType
}
func new_array_type(id C.hid_t) *ArrayType {
t := &ArrayType{DataType{id: id}}
//runtime.SetFinalizer(t, (*DataType).h5t_finalizer)
return t
}
func NewArrayType(base_type *DataType, dims []int) (*ArrayType, error) {
ndims := C.uint(len(dims))
c_dims := (*C.hsize_t)(unsafe.Pointer(&dims[0]))
hid := C.H5Tarray_create2(base_type.id, ndims, c_dims)
err := togo_err(C.herr_t(int(hid)))
if err != nil {
return nil, err
}
t := new_array_type(hid)
return t, err
}
// Returns the rank of an array datatype.
// int H5Tget_array_ndims( hid_t adtype_id )
func (t *ArrayType) NDims() int {
return int(C.H5Tget_array_ndims(t.id))
}
// Retrieves sizes of array dimensions.
// int H5Tget_array_dims2( hid_t adtype_id, hsize_t dims[] )
func (t *ArrayType) ArrayDims() []int {
rank := t.NDims()
dims := make([]int, rank)
// fixme: int/hsize_t size!
c_dims := (*C.hsize_t)(unsafe.Pointer(&dims[0]))
c_rank := int(C.H5Tget_array_dims2(t.id, c_dims))
if c_rank == rank {
return dims
}
return nil
}
// ---------------------------------------------------------------------------
// variable length array data type
type VarLenType struct {
DataType
}
func NewVarLenType(base_type *DataType) (*VarLenType, error) {
hid := C.H5Tvlen_create(base_type.id)
err := togo_err(C.herr_t(int(hid)))
if err != nil {
return nil, err
}
dt := new_vltype(hid)
return dt, err
}
func new_vltype(id C.hid_t) *VarLenType {
t := &VarLenType{DataType{id: id}}
//runtime.SetFinalizer(t, (*DataType).h5t_finalizer)
return t
}
// Determines whether datatype is a variable-length string.
// htri_t H5Tis_variable_str( hid_t dtype_id )
func (vl *VarLenType) IsVariableStr() bool {
o := int(C.H5Tis_variable_str(vl.id))
if o > 0 {
return true
}
return false
}
// ---------------------------------------------------------------------------
// compound data type
type CompType struct {
DataType
}
// Retrieves the number of elements in a compound or enumeration datatype.
// int H5Tget_nmembers( hid_t dtype_id )
func (t *CompType) NMembers() int {
return int(C.H5Tget_nmembers(t.id))
}
// Returns datatype class of compound datatype member.
// H5T_class_t H5Tget_member_class( hid_t cdtype_id, unsigned member_no )
func (t *CompType) MemberClass(mbr_idx int) TypeClass {
return TypeClass(C.H5Tget_member_class(t.id, C.uint(mbr_idx)))
}
// Retrieves the name of a compound or enumeration datatype member.
// char * H5Tget_member_name( hid_t dtype_id, unsigned field_idx )
func (t *CompType) MemberName(mbr_idx int) string {
c_name := C.H5Tget_member_name(t.id, C.uint(mbr_idx))
return C.GoString(c_name)
}
// Retrieves the index of a compound or enumeration datatype member.
// int H5Tget_member_index( hid_t dtype_id, const char * field_name )
func (t *CompType) MemberIndex(name string) int {
c_name := C.CString(name)
defer C.free(unsafe.Pointer(c_name))
return int(C.H5Tget_member_index(t.id, c_name))
}
// Retrieves the offset of a field of a compound datatype.
// size_t H5Tget_member_offset( hid_t dtype_id, unsigned memb_no )
func (t *CompType) MemberOffset(mbr_idx int) int {
return int(C.H5Tget_member_offset(t.id, C.uint(mbr_idx)))
}
// Returns the datatype of the specified member.
// hid_t H5Tget_member_type( hid_t dtype_id, unsigned field_idx )
func (t *CompType) MemberType(mbr_idx int) (*DataType, error) {
hid := C.H5Tget_member_type(t.id, C.uint(mbr_idx))
err := togo_err(C.herr_t(int(hid)))
if err != nil {
return nil, err
}
dt := new_dtype(hid, t.rt.Field(mbr_idx).Type)
return dt, nil
}
// Adds a new member to a compound datatype.
// herr_t H5Tinsert( hid_t dtype_id, const char * name, size_t offset, hid_t field_id )
func (t *CompType) Insert(name string, offset int, field *DataType) error {
c_name := C.CString(name)
defer C.free(unsafe.Pointer(c_name))
//fmt.Printf("inserting [%s] at offset:%d (id=%d)...\n", name, offset, field.id)
err := C.H5Tinsert(t.id, c_name, C.size_t(offset), field.id)
return togo_err(err)
}
// Recursively removes padding from within a compound datatype.
// herr_t H5Tpack( hid_t dtype_id )
func (t *CompType) Pack() error {
err := C.H5Tpack(t.id)
return togo_err(err)
}
// --- opaque type ---
type OpaqueDataType struct {
DataType
}
// Tags an opaque datatype.
// herr_t H5Tset_tag( hid_t dtype_id const char *tag )
func (t *OpaqueDataType) SetTag(tag string) error {
c_tag := C.CString(tag)
defer C.free(unsafe.Pointer(c_tag))
err := C.H5Tset_tag(t.id, c_tag)
return togo_err(err)
}
// Gets the tag associated with an opaque datatype.
// char *H5Tget_tag( hid_t dtype_id )
func (t *OpaqueDataType) Tag() string {
c_name := C.H5Tget_tag(t.id)
if c_name != nil {
return C.GoString(c_name)
}
return ""
}
// -----------------------------------------
// create a data-type from a golang value
func NewDataTypeFromValue(v interface{}) *DataType {
t := reflect.TypeOf(v)
return new_dataTypeFromType(t)
}
func new_dataTypeFromType(t reflect.Type) *DataType {
var dt *DataType = nil
switch t.Kind() {
case reflect.Int:
dt = T_NATIVE_INT // FIXME: .Copy() instead ?
case reflect.Int8:
dt = T_NATIVE_INT8
case reflect.Int16:
dt = T_NATIVE_INT16
case reflect.Int32:
dt = T_NATIVE_INT32
case reflect.Int64:
dt = T_NATIVE_INT64
case reflect.Uint:
dt = T_NATIVE_UINT // FIXME: .Copy() instead ?
case reflect.Uint8:
dt = T_NATIVE_UINT8
case reflect.Uint16:
dt = T_NATIVE_UINT16
case reflect.Uint32:
dt = T_NATIVE_UINT32
case reflect.Uint64:
dt = T_NATIVE_UINT64
case reflect.Float32:
dt = T_NATIVE_FLOAT
case reflect.Float64:
dt = T_NATIVE_DOUBLE
case reflect.String:
dt = T_GO_STRING
//dt = T_C_S1
case reflect.Array:
elem_type := new_dataTypeFromType(t.Elem())
n := t.Len()
dims := []int{n}
adt, err := NewArrayType(elem_type, dims)
if err != nil {
panic(err)
}
dt, err = adt.Copy()
if err != nil {
panic(err)
}
case reflect.Slice:
elem_type := new_dataTypeFromType(t.Elem())
vlen_dt, err := NewVarLenType(elem_type)
if err != nil {
panic(err)
}
dt, err = vlen_dt.Copy()
if err != nil {
panic(err)
}
case reflect.Struct:
sz := int(t.Size())
hdf_dt, err := CreateDataType(T_COMPOUND, sz)
if err != nil {
panic(err)
}
cdt := &CompType{*hdf_dt}
n := t.NumField()
for i := 0; i < n; i++ {
f := t.Field(i)
var field_dt *DataType = nil
field_dt = new_dataTypeFromType(f.Type)
offset := int(f.Offset + 0)
if field_dt == nil {
panic(fmt.Sprintf("pb with field [%d-%s]", i, f.Name))
}
field_name := string(f.Tag)
if len(field_name) == 0 {
field_name = f.Name
}
err = cdt.Insert(field_name, offset, field_dt)
if err != nil {
panic(fmt.Sprintf("pb with field [%d-%s]: %s", i, f.Name, err))
}
}
cdt.Lock()
dt, err = cdt.Copy()
if err != nil {
panic(err)
}
case reflect.Ptr:
panic("sorry, pointers not yet supported")
default:
panic(fmt.Sprintf("unhandled kind (%d)", t.Kind()))
}
return dt
}
// EOF
| h5t_finalizer | identifier_name |
h5t.go | package hdf5
// #include "hdf5.h"
// #include <stdlib.h>
// #include <string.h>
import "C"
import (
"unsafe"
//"runtime"
"fmt"
"reflect"
)
// ---- H5T: Datatype Interface ----
type DataType struct {
id C.hid_t
rt reflect.Type
}
type TypeClass C.H5T_class_t
const (
// Error
T_NO_CLASS TypeClass = -1
// integer types
T_INTEGER TypeClass = 0
// floating-point types
T_FLOAT TypeClass = 1
// date and time types
T_TIME TypeClass = 2
// character string types
T_STRING TypeClass = 3
// bit field types
T_BITFIELD TypeClass = 4
// opaque types
T_OPAQUE TypeClass = 5
// compound types
T_COMPOUND TypeClass = 6
// reference types
T_REFERENCE TypeClass = 7
// enumeration types
T_ENUM TypeClass = 8
// variable-length types
T_VLEN TypeClass = 9
// array types
T_ARRAY TypeClass = 10
// nbr of classes -- MUST BE LAST
T_NCLASSES TypeClass = 11
)
type dummy_struct struct{}
// list of go types
var (
_go_string_t reflect.Type = reflect.TypeOf(string(""))
_go_int_t reflect.Type = reflect.TypeOf(int(0))
_go_int8_t reflect.Type = reflect.TypeOf(int8(0))
_go_int16_t reflect.Type = reflect.TypeOf(int16(0))
_go_int32_t reflect.Type = reflect.TypeOf(int32(0))
_go_int64_t reflect.Type = reflect.TypeOf(int64(0))
_go_uint_t reflect.Type = reflect.TypeOf(uint(0))
_go_uint8_t reflect.Type = reflect.TypeOf(uint8(0))
_go_uint16_t reflect.Type = reflect.TypeOf(uint16(0))
_go_uint32_t reflect.Type = reflect.TypeOf(uint32(0))
_go_uint64_t reflect.Type = reflect.TypeOf(uint64(0))
_go_float32_t reflect.Type = reflect.TypeOf(float32(0))
_go_float64_t reflect.Type = reflect.TypeOf(float64(0))
_go_array_t reflect.Type = reflect.TypeOf([1]int{0})
_go_slice_t reflect.Type = reflect.TypeOf([]int{0})
_go_struct_t reflect.Type = reflect.TypeOf(dummy_struct{})
_go_ptr_t reflect.Type = reflect.PtrTo(_go_int_t)
)
type typeClassToType map[TypeClass]reflect.Type
var (
// mapping of type-class to go-type
_type_cls_to_go_type typeClassToType = typeClassToType{
T_NO_CLASS: nil,
T_INTEGER: _go_int_t,
T_FLOAT: _go_float32_t,
T_TIME: nil,
T_STRING: _go_string_t,
T_BITFIELD: nil,
T_OPAQUE: nil,
T_COMPOUND: _go_struct_t,
T_REFERENCE: _go_ptr_t,
T_ENUM: _go_int_t,
T_VLEN: _go_slice_t,
T_ARRAY: _go_array_t,
}
)
func new_dtype(id C.hid_t, rt reflect.Type) *DataType {
t := &DataType{id: id, rt: rt}
//runtime.SetFinalizer(t, (*DataType).h5t_finalizer)
return t
}
// Creates a new datatype.
// hid_t H5Tcreate( H5T_class_t class, size_tsize )
func CreateDataType(class TypeClass, size int) (t *DataType, err error) {
t = nil
err = nil
hid := C.H5Tcreate(C.H5T_class_t(class), C.size_t(size))
err = togo_err(C.herr_t(int(hid)))
if err != nil {
return
}
t = new_dtype(hid, _type_cls_to_go_type[class])
return
}
func (t *DataType) h5t_finalizer() {
err := t.Close()
if err != nil {
panic(fmt.Sprintf("error closing datatype: %s", err))
}
}
// Releases a datatype.
// herr_t H5Tclose( hid_t dtype_id )
func (t *DataType) Close() error {
if t.id > 0 {
fmt.Printf("--- closing dtype [%d]...\n", t.id)
err := togo_err(C.H5Tclose(t.id))
t.id = 0
return err
}
return nil
}
// Commits a transient datatype, linking it into the file and creating a new named datatype.
// herr_t H5Tcommit( hid_t loc_id, const char *name, hid_t dtype_id, hid_t lcpl_id, hid_t tcpl_id, hid_t tapl_id )
//func (t *DataType) Commit()
// Determines whether a datatype is a named type or a transient type.
// htri_tH5Tcommitted( hid_t dtype_id )
func (t *DataType) Committed() bool {
o := int(C.H5Tcommitted(t.id))
if o > 0 {
return true
}
return false
}
// Copies an existing datatype.
// hid_t H5Tcopy( hid_t dtype_id )
func (t *DataType) Copy() (*DataType, error) {
hid := C.H5Tcopy(t.id)
err := togo_err(C.herr_t(int(hid)))
if err != nil {
return nil, err
}
o := new_dtype(hid, t.rt)
return o, err
}
// Determines whether two datatype identifiers refer to the same datatype.
// htri_t H5Tequal( hid_t dtype_id1, hid_t dtype_id2 )
func (t *DataType) Equal(o *DataType) bool {
v := int(C.H5Tequal(t.id, o.id))
if v > 0 {
return true
}
return false
}
// Locks a datatype.
// herr_t H5Tlock( hid_t dtype_id )
func (t *DataType) Lock() error {
return togo_err(C.H5Tlock(t.id))
}
// Returns the size of a datatype.
// size_t H5Tget_size( hid_t dtype_id )
func (t *DataType) Size() int {
return int(C.H5Tget_size(t.id))
}
// Sets the total size for an atomic datatype.
// herr_t H5Tset_size( hid_t dtype_id, size_tsize )
func (t *DataType) SetSize(sz int) error {
err := C.H5Tset_size(t.id, C.size_t(sz))
return togo_err(err)
}
// ---------------------------------------------------------------------------
// array data type
type ArrayType struct {
DataType
}
func new_array_type(id C.hid_t) *ArrayType {
t := &ArrayType{DataType{id: id}}
//runtime.SetFinalizer(t, (*DataType).h5t_finalizer)
return t
}
func NewArrayType(base_type *DataType, dims []int) (*ArrayType, error) {
ndims := C.uint(len(dims))
c_dims := (*C.hsize_t)(unsafe.Pointer(&dims[0]))
hid := C.H5Tarray_create2(base_type.id, ndims, c_dims)
err := togo_err(C.herr_t(int(hid)))
if err != nil {
return nil, err
}
t := new_array_type(hid)
return t, err
}
// Returns the rank of an array datatype.
// int H5Tget_array_ndims( hid_t adtype_id )
func (t *ArrayType) NDims() int {
return int(C.H5Tget_array_ndims(t.id))
}
// Retrieves sizes of array dimensions.
// int H5Tget_array_dims2( hid_t adtype_id, hsize_t dims[] )
func (t *ArrayType) ArrayDims() []int {
rank := t.NDims()
dims := make([]int, rank)
// fixme: int/hsize_t size!
c_dims := (*C.hsize_t)(unsafe.Pointer(&dims[0]))
c_rank := int(C.H5Tget_array_dims2(t.id, c_dims))
if c_rank == rank {
return dims
}
return nil
}
// ---------------------------------------------------------------------------
// variable length array data type
type VarLenType struct {
DataType
}
func NewVarLenType(base_type *DataType) (*VarLenType, error) {
hid := C.H5Tvlen_create(base_type.id)
err := togo_err(C.herr_t(int(hid)))
if err != nil {
return nil, err
}
dt := new_vltype(hid)
return dt, err
}
func new_vltype(id C.hid_t) *VarLenType {
t := &VarLenType{DataType{id: id}}
//runtime.SetFinalizer(t, (*DataType).h5t_finalizer)
return t
}
// Determines whether datatype is a variable-length string.
// htri_t H5Tis_variable_str( hid_t dtype_id )
func (vl *VarLenType) IsVariableStr() bool {
o := int(C.H5Tis_variable_str(vl.id))
if o > 0 {
return true
}
return false
}
// ---------------------------------------------------------------------------
// compound data type
type CompType struct {
DataType
}
// Retrieves the number of elements in a compound or enumeration datatype.
// int H5Tget_nmembers( hid_t dtype_id )
func (t *CompType) NMembers() int {
return int(C.H5Tget_nmembers(t.id))
}
// Returns datatype class of compound datatype member.
// H5T_class_t H5Tget_member_class( hid_t cdtype_id, unsigned member_no )
func (t *CompType) MemberClass(mbr_idx int) TypeClass {
return TypeClass(C.H5Tget_member_class(t.id, C.uint(mbr_idx)))
}
// Retrieves the name of a compound or enumeration datatype member.
// char * H5Tget_member_name( hid_t dtype_id, unsigned field_idx )
func (t *CompType) MemberName(mbr_idx int) string {
c_name := C.H5Tget_member_name(t.id, C.uint(mbr_idx))
return C.GoString(c_name)
}
// Retrieves the index of a compound or enumeration datatype member.
// int H5Tget_member_index( hid_t dtype_id, const char * field_name )
func (t *CompType) MemberIndex(name string) int {
c_name := C.CString(name)
defer C.free(unsafe.Pointer(c_name))
return int(C.H5Tget_member_index(t.id, c_name))
}
// Retrieves the offset of a field of a compound datatype.
// size_t H5Tget_member_offset( hid_t dtype_id, unsigned memb_no )
func (t *CompType) MemberOffset(mbr_idx int) int {
return int(C.H5Tget_member_offset(t.id, C.uint(mbr_idx)))
}
// Returns the datatype of the specified member.
// hid_t H5Tget_member_type( hid_t dtype_id, unsigned field_idx )
func (t *CompType) MemberType(mbr_idx int) (*DataType, error) {
hid := C.H5Tget_member_type(t.id, C.uint(mbr_idx))
err := togo_err(C.herr_t(int(hid)))
if err != nil {
return nil, err
}
dt := new_dtype(hid, t.rt.Field(mbr_idx).Type)
return dt, nil
}
// Adds a new member to a compound datatype.
// herr_t H5Tinsert( hid_t dtype_id, const char * name, size_t offset, hid_t field_id )
func (t *CompType) Insert(name string, offset int, field *DataType) error {
c_name := C.CString(name)
defer C.free(unsafe.Pointer(c_name))
//fmt.Printf("inserting [%s] at offset:%d (id=%d)...\n", name, offset, field.id)
err := C.H5Tinsert(t.id, c_name, C.size_t(offset), field.id)
return togo_err(err)
}
// Recursively removes padding from within a compound datatype.
// herr_t H5Tpack( hid_t dtype_id )
func (t *CompType) Pack() error {
err := C.H5Tpack(t.id)
return togo_err(err)
} | // --- opaque type ---
type OpaqueDataType struct {
DataType
}
// Tags an opaque datatype.
// herr_t H5Tset_tag( hid_t dtype_id const char *tag )
func (t *OpaqueDataType) SetTag(tag string) error {
c_tag := C.CString(tag)
defer C.free(unsafe.Pointer(c_tag))
err := C.H5Tset_tag(t.id, c_tag)
return togo_err(err)
}
// Gets the tag associated with an opaque datatype.
// char *H5Tget_tag( hid_t dtype_id )
func (t *OpaqueDataType) Tag() string {
c_name := C.H5Tget_tag(t.id)
if c_name != nil {
return C.GoString(c_name)
}
return ""
}
// -----------------------------------------
// create a data-type from a golang value
func NewDataTypeFromValue(v interface{}) *DataType {
t := reflect.TypeOf(v)
return new_dataTypeFromType(t)
}
func new_dataTypeFromType(t reflect.Type) *DataType {
var dt *DataType = nil
switch t.Kind() {
case reflect.Int:
dt = T_NATIVE_INT // FIXME: .Copy() instead ?
case reflect.Int8:
dt = T_NATIVE_INT8
case reflect.Int16:
dt = T_NATIVE_INT16
case reflect.Int32:
dt = T_NATIVE_INT32
case reflect.Int64:
dt = T_NATIVE_INT64
case reflect.Uint:
dt = T_NATIVE_UINT // FIXME: .Copy() instead ?
case reflect.Uint8:
dt = T_NATIVE_UINT8
case reflect.Uint16:
dt = T_NATIVE_UINT16
case reflect.Uint32:
dt = T_NATIVE_UINT32
case reflect.Uint64:
dt = T_NATIVE_UINT64
case reflect.Float32:
dt = T_NATIVE_FLOAT
case reflect.Float64:
dt = T_NATIVE_DOUBLE
case reflect.String:
dt = T_GO_STRING
//dt = T_C_S1
case reflect.Array:
elem_type := new_dataTypeFromType(t.Elem())
n := t.Len()
dims := []int{n}
adt, err := NewArrayType(elem_type, dims)
if err != nil {
panic(err)
}
dt, err = adt.Copy()
if err != nil {
panic(err)
}
case reflect.Slice:
elem_type := new_dataTypeFromType(t.Elem())
vlen_dt, err := NewVarLenType(elem_type)
if err != nil {
panic(err)
}
dt, err = vlen_dt.Copy()
if err != nil {
panic(err)
}
case reflect.Struct:
sz := int(t.Size())
hdf_dt, err := CreateDataType(T_COMPOUND, sz)
if err != nil {
panic(err)
}
cdt := &CompType{*hdf_dt}
n := t.NumField()
for i := 0; i < n; i++ {
f := t.Field(i)
var field_dt *DataType = nil
field_dt = new_dataTypeFromType(f.Type)
offset := int(f.Offset + 0)
if field_dt == nil {
panic(fmt.Sprintf("pb with field [%d-%s]", i, f.Name))
}
field_name := string(f.Tag)
if len(field_name) == 0 {
field_name = f.Name
}
err = cdt.Insert(field_name, offset, field_dt)
if err != nil {
panic(fmt.Sprintf("pb with field [%d-%s]: %s", i, f.Name, err))
}
}
cdt.Lock()
dt, err = cdt.Copy()
if err != nil {
panic(err)
}
case reflect.Ptr:
panic("sorry, pointers not yet supported")
default:
panic(fmt.Sprintf("unhandled kind (%d)", t.Kind()))
}
return dt
}
// EOF | random_line_split | |
ai.py | """
The file contains one Ai class, which contains different ai functions,
and two other functions.
One converts an angle from cartesian to perpendicular and the other
calculates the periodic difference between two angles.
"""
import math
import pymunk
from pymunk import Vec2d
import gameobjects | def angle_between_vectors(vec1, vec2):
"""
Since Vec2d operates in a cartesian coordinate space we have to
convert the resulting vector to get the correct angle for our space.
"""
vec = vec1 - vec2
vec = vec.perpendicular()
return vec.angle
def periodic_difference_of_angles(angle1, angle2):
return (angle1 % (2*math.pi)) - (angle2 % (2*math.pi))
class Ai:
"""
A simple ai that finds the shortest path to the target using
a breadth first search. Also capable of shooting other tanks and or
wooden boxes.
"""
def __init__(self, tank, game_objects_list, tanks_list, space, currentmap):
self.tank = tank
self.game_objects_list = game_objects_list
self.tanks_list = tanks_list
self.space = space
self.currentmap = currentmap
self.flag = None
self.MAX_X = currentmap.width - 1
self.MAX_Y = currentmap.height - 1
self.last_distance = 1
self.path = deque()
self.move_cycle = self.move_cycle_gen()
self.update_grid_pos()
def update_grid_pos(self):
"""
This should only be called in the beginning, or at the
end of a move_cycle.
"""
self.grid_pos = self.get_tile_of_position(self.tank.body.position)
def decide(self):
"""
Main decision function that gets called on every
tick of the game.
"""
self.maybe_shoot()
next(self.move_cycle)
pass
def maybe_shoot(self):
"""
Makes a raycast query in front of the tank. If another tank
or a wooden box is found, then we shoot.
"""
res = self.space.segment_query_first((self.tank.body.position[0] - \
0.6 * math.sin(self.tank.body.angle), self.tank.body.position[1] +\
0.6 * math.cos(self.tank.body.angle)), (self.tank.body.position[0] -\
10*math.sin(self.tank.body.angle), self.tank.body.position[1] + \
10*math.cos(self.tank.body.angle)), 0, pymunk.ShapeFilter())
if res is not None:
try:
if hasattr(res, 'shape'):
if isinstance(res.shape.parent, gameobjects.Tank):
bullet = self.tank.shoot(self.space)
if bullet is not None:
self.game_objects_list.append(bullet)
elif isinstance(res.shape.parent, gameobjects.Box):
if res.shape.parent.boxmodel.destructable is True:
bullet = self.tank.shoot(self.space)
if bullet is not None:
self.game_objects_list.append(bullet)
except:
pass
def move_cycle_gen(self):
"""
A generator that iteratively goes through all the required
steps to move to our goal.
"""
while True:
self.update_grid_pos()
path = self.find_shortest_path("without_metalbox")
if not path:
path = self.find_shortest_path("metalbox")
yield
if not path:
continue
next_coord = path.pop()
next_coord += Vec2d(0.5, 0.5)
yield
target_angle = \
angle_between_vectors(Vec2d(self.tank.body.position), next_coord)
angle_tank = self.tank.body.angle
self.turn(angle_tank, target_angle)
while not self.correct_angle(angle_tank, target_angle):
angle_tank = self.tank.body.angle
target_angle = \
angle_between_vectors(Vec2d(self.tank.body.position),
next_coord)
yield
self.tank.accelerate()
while not self.correct_pos(next_coord, self.last_distance):
yield
yield
def correct_pos(self, target_pos, last_distance):
"""
Checks if the tank is on the correct position, compared from the
last one.
"""
tank_pos = Vec2d(self.tank.body.position)
current_distance = target_pos.get_distance(tank_pos)
self.last_distance = current_distance
if last_distance < current_distance:
return True
else:
return False
def turn(self, tank_angle, target_angle):
"""
Finds the angle closest to next tile, and turns accordingly.
WIP: Sometimes it turns to the other side.
"""
angle_diff = periodic_difference_of_angles(tank_angle, target_angle)
if ((angle_diff + 2 * math.pi) % 2
* math.pi >= math.pi and abs(angle_diff) > MIN_ANGLE_DIF):
self.tank.stop_moving()
self.tank.turn_left()
elif ((angle_diff + 2 * math.pi) % 2 * math.pi
< math.pi and abs(angle_diff) > MIN_ANGLE_DIF):
self.tank.stop_moving()
self.tank.turn_right()
def correct_angle(self, tank_angle, target_angle):
"""
If the tank has the correct angle to the next tile; stop turning.
"""
angle_diff = periodic_difference_of_angles(target_angle, tank_angle)
if abs(angle_diff) <= MIN_ANGLE_DIF:
self.tank.stop_turning()
return True
else:
return False
def find_shortest_path(self, box_indicator):
"""
A simple Breadth First Search using integer coordinates as our
nodes. Edges are calculated as we go, using an external function.
"""
# To be implemented
dict = {}
shortest_path = []
visited = set()
queue = deque()
queue.append(self.grid_pos)
goal_node = None
while queue:
node = Vec2d(queue.popleft())
if node == self.get_target_tile().int_tuple:
goal_node = node.int_tuple
break
for neighbor in self.get_tile_neighbors(node, box_indicator):
neighbor = neighbor.int_tuple
if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)
dict[neighbor] = node.int_tuple
if goal_node is None:
return deque([])
else:
key = goal_node
while key != self.grid_pos.int_tuple:
shortest_path.append(Vec2d(key))
parent_node = dict[key]
key = parent_node
return deque(shortest_path)
def get_target_tile(self):
"""
Returns position of the flag if we don't have it. If we
do have the flag, return the position of our home base.
"""
if self.tank.flag is not None:
x, y = self.tank.start_position
else:
self.get_flag() # Ensure that we have initialized it.
x, y = self.flag.x, self.flag.y
return Vec2d(int(x), int(y))
def get_flag(self):
"""
This has to be called to get the flag, since we don't know
where it is when the Ai object is initialized.
"""
if self.flag is None:
# Find the flag in the game objects list
for obj in self.game_objects_list:
if isinstance(obj, gameobjects.Flag):
self.flag = obj
break
return self.flag
def get_tile_of_position(self, position_vector):
"""
Converts and returns the float position of our tank to an
integer position.
"""
x, y = position_vector
return Vec2d(int(x), int(y))
def get_tile_neighbors(self, coord_vec, box_indicator):
"""
Returns all bordering grid squares of the input coordinate.
A bordering square is only considered accessible if it is grass
or a wooden box.
"""
neighbors = [] # Find the coordinates of the tiles' four neighbors
neighbors.append(coord_vec + Vec2d(1, 0))
neighbors.append(coord_vec + Vec2d(-1, 0))
neighbors.append(coord_vec + Vec2d(0, 1))
neighbors.append(coord_vec + Vec2d(0, -1))
if box_indicator == "without_metalbox":
return filter(self.filter_tile_neighbors, neighbors)
else:
return filter(self.filter_tile_neighbors_metalbox, neighbors)
def filter_tile_neighbors(self, coord):
"""
Filter for all the tiles around the tank. This filter removes
the immovable stones so we don't count those tiles to find the
shortest path.
"""
coord = coord.int_tuple
if coord[1] <= self.MAX_Y and coord[0] <= self.MAX_X and coord[1] >= \
0 and coord[0] >=\
0 and (self.currentmap.boxAt(coord[0], coord[1])
== 0 or self.currentmap.boxAt(coord[0], coord[1]) == 2):
return True
return False
def filter_tile_neighbors_metalbox(self, coord):
"""
Filter for all the tiles around the tank, metalboxes included. This
filter removes the immovable stones so we don't count those tiles to
find the shortest path.
"""
coord = coord.int_tuple
if coord[1] <= self.MAX_Y and coord[0] <= self.MAX_X and coord[1] >=\
0 and coord[0] >= 0 and (self.currentmap.boxAt(coord[0], coord[1])
== 0 or self.currentmap.boxAt(coord[0],
coord[1])
== 2 or self.currentmap.boxAt(coord[0],
coord[1])
== 3):
return True
return False
SimpleAi = Ai # Legacy | from collections import defaultdict, deque
MIN_ANGLE_DIF = math.radians(5)
| random_line_split |
ai.py | """
The file contains one Ai class, which contains different ai functions,
and two other functions.
One converts an angle from cartesian to perpendicular and the other
calculates the periodic difference between two angles.
"""
import math
import pymunk
from pymunk import Vec2d
import gameobjects
from collections import defaultdict, deque
MIN_ANGLE_DIF = math.radians(5)
def angle_between_vectors(vec1, vec2):
"""
Since Vec2d operates in a cartesian coordinate space we have to
convert the resulting vector to get the correct angle for our space.
"""
vec = vec1 - vec2
vec = vec.perpendicular()
return vec.angle
def periodic_difference_of_angles(angle1, angle2):
return (angle1 % (2*math.pi)) - (angle2 % (2*math.pi))
class Ai:
"""
A simple ai that finds the shortest path to the target using
a breadth first search. Also capable of shooting other tanks and or
wooden boxes.
"""
def __init__(self, tank, game_objects_list, tanks_list, space, currentmap):
self.tank = tank
self.game_objects_list = game_objects_list
self.tanks_list = tanks_list
self.space = space
self.currentmap = currentmap
self.flag = None
self.MAX_X = currentmap.width - 1
self.MAX_Y = currentmap.height - 1
self.last_distance = 1
self.path = deque()
self.move_cycle = self.move_cycle_gen()
self.update_grid_pos()
def update_grid_pos(self):
"""
This should only be called in the beginning, or at the
end of a move_cycle.
"""
self.grid_pos = self.get_tile_of_position(self.tank.body.position)
def decide(self):
"""
Main decision function that gets called on every
tick of the game.
"""
self.maybe_shoot()
next(self.move_cycle)
pass
def maybe_shoot(self):
"""
Makes a raycast query in front of the tank. If another tank
or a wooden box is found, then we shoot.
"""
res = self.space.segment_query_first((self.tank.body.position[0] - \
0.6 * math.sin(self.tank.body.angle), self.tank.body.position[1] +\
0.6 * math.cos(self.tank.body.angle)), (self.tank.body.position[0] -\
10*math.sin(self.tank.body.angle), self.tank.body.position[1] + \
10*math.cos(self.tank.body.angle)), 0, pymunk.ShapeFilter())
if res is not None:
try:
if hasattr(res, 'shape'):
if isinstance(res.shape.parent, gameobjects.Tank):
|
elif isinstance(res.shape.parent, gameobjects.Box):
if res.shape.parent.boxmodel.destructable is True:
bullet = self.tank.shoot(self.space)
if bullet is not None:
self.game_objects_list.append(bullet)
except:
pass
def move_cycle_gen(self):
"""
A generator that iteratively goes through all the required
steps to move to our goal.
"""
while True:
self.update_grid_pos()
path = self.find_shortest_path("without_metalbox")
if not path:
path = self.find_shortest_path("metalbox")
yield
if not path:
continue
next_coord = path.pop()
next_coord += Vec2d(0.5, 0.5)
yield
target_angle = \
angle_between_vectors(Vec2d(self.tank.body.position), next_coord)
angle_tank = self.tank.body.angle
self.turn(angle_tank, target_angle)
while not self.correct_angle(angle_tank, target_angle):
angle_tank = self.tank.body.angle
target_angle = \
angle_between_vectors(Vec2d(self.tank.body.position),
next_coord)
yield
self.tank.accelerate()
while not self.correct_pos(next_coord, self.last_distance):
yield
yield
def correct_pos(self, target_pos, last_distance):
"""
Checks if the tank is on the correct position, compared from the
last one.
"""
tank_pos = Vec2d(self.tank.body.position)
current_distance = target_pos.get_distance(tank_pos)
self.last_distance = current_distance
if last_distance < current_distance:
return True
else:
return False
def turn(self, tank_angle, target_angle):
"""
Finds the angle closest to next tile, and turns accordingly.
WIP: Sometimes it turns to the other side.
"""
angle_diff = periodic_difference_of_angles(tank_angle, target_angle)
if ((angle_diff + 2 * math.pi) % 2
* math.pi >= math.pi and abs(angle_diff) > MIN_ANGLE_DIF):
self.tank.stop_moving()
self.tank.turn_left()
elif ((angle_diff + 2 * math.pi) % 2 * math.pi
< math.pi and abs(angle_diff) > MIN_ANGLE_DIF):
self.tank.stop_moving()
self.tank.turn_right()
def correct_angle(self, tank_angle, target_angle):
"""
If the tank has the correct angle to the next tile; stop turning.
"""
angle_diff = periodic_difference_of_angles(target_angle, tank_angle)
if abs(angle_diff) <= MIN_ANGLE_DIF:
self.tank.stop_turning()
return True
else:
return False
def find_shortest_path(self, box_indicator):
"""
A simple Breadth First Search using integer coordinates as our
nodes. Edges are calculated as we go, using an external function.
"""
# To be implemented
dict = {}
shortest_path = []
visited = set()
queue = deque()
queue.append(self.grid_pos)
goal_node = None
while queue:
node = Vec2d(queue.popleft())
if node == self.get_target_tile().int_tuple:
goal_node = node.int_tuple
break
for neighbor in self.get_tile_neighbors(node, box_indicator):
neighbor = neighbor.int_tuple
if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)
dict[neighbor] = node.int_tuple
if goal_node is None:
return deque([])
else:
key = goal_node
while key != self.grid_pos.int_tuple:
shortest_path.append(Vec2d(key))
parent_node = dict[key]
key = parent_node
return deque(shortest_path)
def get_target_tile(self):
"""
Returns position of the flag if we don't have it. If we
do have the flag, return the position of our home base.
"""
if self.tank.flag is not None:
x, y = self.tank.start_position
else:
self.get_flag() # Ensure that we have initialized it.
x, y = self.flag.x, self.flag.y
return Vec2d(int(x), int(y))
def get_flag(self):
"""
This has to be called to get the flag, since we don't know
where it is when the Ai object is initialized.
"""
if self.flag is None:
# Find the flag in the game objects list
for obj in self.game_objects_list:
if isinstance(obj, gameobjects.Flag):
self.flag = obj
break
return self.flag
def get_tile_of_position(self, position_vector):
"""
Converts and returns the float position of our tank to an
integer position.
"""
x, y = position_vector
return Vec2d(int(x), int(y))
def get_tile_neighbors(self, coord_vec, box_indicator):
"""
Returns all bordering grid squares of the input coordinate.
A bordering square is only considered accessible if it is grass
or a wooden box.
"""
neighbors = [] # Find the coordinates of the tiles' four neighbors
neighbors.append(coord_vec + Vec2d(1, 0))
neighbors.append(coord_vec + Vec2d(-1, 0))
neighbors.append(coord_vec + Vec2d(0, 1))
neighbors.append(coord_vec + Vec2d(0, -1))
if box_indicator == "without_metalbox":
return filter(self.filter_tile_neighbors, neighbors)
else:
return filter(self.filter_tile_neighbors_metalbox, neighbors)
def filter_tile_neighbors(self, coord):
"""
Filter for all the tiles around the tank. This filter removes
the immovable stones so we don't count those tiles to find the
shortest path.
"""
coord = coord.int_tuple
if coord[1] <= self.MAX_Y and coord[0] <= self.MAX_X and coord[1] >= \
0 and coord[0] >=\
0 and (self.currentmap.boxAt(coord[0], coord[1])
== 0 or self.currentmap.boxAt(coord[0], coord[1]) == 2):
return True
return False
def filter_tile_neighbors_metalbox(self, coord):
"""
Filter for all the tiles around the tank, metalboxes included. This
filter removes the immovable stones so we don't count those tiles to
find the shortest path.
"""
coord = coord.int_tuple
if coord[1] <= self.MAX_Y and coord[0] <= self.MAX_X and coord[1] >=\
0 and coord[0] >= 0 and (self.currentmap.boxAt(coord[0], coord[1])
== 0 or self.currentmap.boxAt(coord[0],
coord[1])
== 2 or self.currentmap.boxAt(coord[0],
coord[1])
== 3):
return True
return False
SimpleAi = Ai # Legacy
| bullet = self.tank.shoot(self.space)
if bullet is not None:
self.game_objects_list.append(bullet) | conditional_block |
ai.py | """
The file contains one Ai class, which contains different ai functions,
and two other functions.
One converts an angle from cartesian to perpendicular and the other
calculates the periodic difference between two angles.
"""
import math
import pymunk
from pymunk import Vec2d
import gameobjects
from collections import defaultdict, deque
MIN_ANGLE_DIF = math.radians(5)
def angle_between_vectors(vec1, vec2):
"""
Since Vec2d operates in a cartesian coordinate space we have to
convert the resulting vector to get the correct angle for our space.
"""
vec = vec1 - vec2
vec = vec.perpendicular()
return vec.angle
def periodic_difference_of_angles(angle1, angle2):
return (angle1 % (2*math.pi)) - (angle2 % (2*math.pi))
class Ai:
"""
A simple ai that finds the shortest path to the target using
a breadth first search. Also capable of shooting other tanks and or
wooden boxes.
"""
def __init__(self, tank, game_objects_list, tanks_list, space, currentmap):
self.tank = tank
self.game_objects_list = game_objects_list
self.tanks_list = tanks_list
self.space = space
self.currentmap = currentmap
self.flag = None
self.MAX_X = currentmap.width - 1
self.MAX_Y = currentmap.height - 1
self.last_distance = 1
self.path = deque()
self.move_cycle = self.move_cycle_gen()
self.update_grid_pos()
def update_grid_pos(self):
"""
This should only be called in the beginning, or at the
end of a move_cycle.
"""
self.grid_pos = self.get_tile_of_position(self.tank.body.position)
def decide(self):
"""
Main decision function that gets called on every
tick of the game.
"""
self.maybe_shoot()
next(self.move_cycle)
pass
def maybe_shoot(self):
"""
Makes a raycast query in front of the tank. If another tank
or a wooden box is found, then we shoot.
"""
res = self.space.segment_query_first((self.tank.body.position[0] - \
0.6 * math.sin(self.tank.body.angle), self.tank.body.position[1] +\
0.6 * math.cos(self.tank.body.angle)), (self.tank.body.position[0] -\
10*math.sin(self.tank.body.angle), self.tank.body.position[1] + \
10*math.cos(self.tank.body.angle)), 0, pymunk.ShapeFilter())
if res is not None:
try:
if hasattr(res, 'shape'):
if isinstance(res.shape.parent, gameobjects.Tank):
bullet = self.tank.shoot(self.space)
if bullet is not None:
self.game_objects_list.append(bullet)
elif isinstance(res.shape.parent, gameobjects.Box):
if res.shape.parent.boxmodel.destructable is True:
bullet = self.tank.shoot(self.space)
if bullet is not None:
self.game_objects_list.append(bullet)
except:
pass
def move_cycle_gen(self):
|
def correct_pos(self, target_pos, last_distance):
"""
Checks if the tank is on the correct position, compared from the
last one.
"""
tank_pos = Vec2d(self.tank.body.position)
current_distance = target_pos.get_distance(tank_pos)
self.last_distance = current_distance
if last_distance < current_distance:
return True
else:
return False
def turn(self, tank_angle, target_angle):
"""
Finds the angle closest to next tile, and turns accordingly.
WIP: Sometimes it turns to the other side.
"""
angle_diff = periodic_difference_of_angles(tank_angle, target_angle)
if ((angle_diff + 2 * math.pi) % 2
* math.pi >= math.pi and abs(angle_diff) > MIN_ANGLE_DIF):
self.tank.stop_moving()
self.tank.turn_left()
elif ((angle_diff + 2 * math.pi) % 2 * math.pi
< math.pi and abs(angle_diff) > MIN_ANGLE_DIF):
self.tank.stop_moving()
self.tank.turn_right()
def correct_angle(self, tank_angle, target_angle):
"""
If the tank has the correct angle to the next tile; stop turning.
"""
angle_diff = periodic_difference_of_angles(target_angle, tank_angle)
if abs(angle_diff) <= MIN_ANGLE_DIF:
self.tank.stop_turning()
return True
else:
return False
def find_shortest_path(self, box_indicator):
"""
A simple Breadth First Search using integer coordinates as our
nodes. Edges are calculated as we go, using an external function.
"""
# To be implemented
dict = {}
shortest_path = []
visited = set()
queue = deque()
queue.append(self.grid_pos)
goal_node = None
while queue:
node = Vec2d(queue.popleft())
if node == self.get_target_tile().int_tuple:
goal_node = node.int_tuple
break
for neighbor in self.get_tile_neighbors(node, box_indicator):
neighbor = neighbor.int_tuple
if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)
dict[neighbor] = node.int_tuple
if goal_node is None:
return deque([])
else:
key = goal_node
while key != self.grid_pos.int_tuple:
shortest_path.append(Vec2d(key))
parent_node = dict[key]
key = parent_node
return deque(shortest_path)
def get_target_tile(self):
"""
Returns position of the flag if we don't have it. If we
do have the flag, return the position of our home base.
"""
if self.tank.flag is not None:
x, y = self.tank.start_position
else:
self.get_flag() # Ensure that we have initialized it.
x, y = self.flag.x, self.flag.y
return Vec2d(int(x), int(y))
def get_flag(self):
"""
This has to be called to get the flag, since we don't know
where it is when the Ai object is initialized.
"""
if self.flag is None:
# Find the flag in the game objects list
for obj in self.game_objects_list:
if isinstance(obj, gameobjects.Flag):
self.flag = obj
break
return self.flag
def get_tile_of_position(self, position_vector):
"""
Converts and returns the float position of our tank to an
integer position.
"""
x, y = position_vector
return Vec2d(int(x), int(y))
def get_tile_neighbors(self, coord_vec, box_indicator):
"""
Returns all bordering grid squares of the input coordinate.
A bordering square is only considered accessible if it is grass
or a wooden box.
"""
neighbors = [] # Find the coordinates of the tiles' four neighbors
neighbors.append(coord_vec + Vec2d(1, 0))
neighbors.append(coord_vec + Vec2d(-1, 0))
neighbors.append(coord_vec + Vec2d(0, 1))
neighbors.append(coord_vec + Vec2d(0, -1))
if box_indicator == "without_metalbox":
return filter(self.filter_tile_neighbors, neighbors)
else:
return filter(self.filter_tile_neighbors_metalbox, neighbors)
def filter_tile_neighbors(self, coord):
"""
Filter for all the tiles around the tank. This filter removes
the immovable stones so we don't count those tiles to find the
shortest path.
"""
coord = coord.int_tuple
if coord[1] <= self.MAX_Y and coord[0] <= self.MAX_X and coord[1] >= \
0 and coord[0] >=\
0 and (self.currentmap.boxAt(coord[0], coord[1])
== 0 or self.currentmap.boxAt(coord[0], coord[1]) == 2):
return True
return False
def filter_tile_neighbors_metalbox(self, coord):
"""
Filter for all the tiles around the tank, metalboxes included. This
filter removes the immovable stones so we don't count those tiles to
find the shortest path.
"""
coord = coord.int_tuple
if coord[1] <= self.MAX_Y and coord[0] <= self.MAX_X and coord[1] >=\
0 and coord[0] >= 0 and (self.currentmap.boxAt(coord[0], coord[1])
== 0 or self.currentmap.boxAt(coord[0],
coord[1])
== 2 or self.currentmap.boxAt(coord[0],
coord[1])
== 3):
return True
return False
SimpleAi = Ai # Legacy
| """
A generator that iteratively goes through all the required
steps to move to our goal.
"""
while True:
self.update_grid_pos()
path = self.find_shortest_path("without_metalbox")
if not path:
path = self.find_shortest_path("metalbox")
yield
if not path:
continue
next_coord = path.pop()
next_coord += Vec2d(0.5, 0.5)
yield
target_angle = \
angle_between_vectors(Vec2d(self.tank.body.position), next_coord)
angle_tank = self.tank.body.angle
self.turn(angle_tank, target_angle)
while not self.correct_angle(angle_tank, target_angle):
angle_tank = self.tank.body.angle
target_angle = \
angle_between_vectors(Vec2d(self.tank.body.position),
next_coord)
yield
self.tank.accelerate()
while not self.correct_pos(next_coord, self.last_distance):
yield
yield | identifier_body |
ai.py | """
The file contains one Ai class, which contains different ai functions,
and two other functions.
One converts an angle from cartesian to perpendicular and the other
calculates the periodic difference between two angles.
"""
import math
import pymunk
from pymunk import Vec2d
import gameobjects
from collections import defaultdict, deque
MIN_ANGLE_DIF = math.radians(5)
def angle_between_vectors(vec1, vec2):
"""
Since Vec2d operates in a cartesian coordinate space we have to
convert the resulting vector to get the correct angle for our space.
"""
vec = vec1 - vec2
vec = vec.perpendicular()
return vec.angle
def periodic_difference_of_angles(angle1, angle2):
return (angle1 % (2*math.pi)) - (angle2 % (2*math.pi))
class Ai:
"""
A simple ai that finds the shortest path to the target using
a breadth first search. Also capable of shooting other tanks and or
wooden boxes.
"""
def __init__(self, tank, game_objects_list, tanks_list, space, currentmap):
self.tank = tank
self.game_objects_list = game_objects_list
self.tanks_list = tanks_list
self.space = space
self.currentmap = currentmap
self.flag = None
self.MAX_X = currentmap.width - 1
self.MAX_Y = currentmap.height - 1
self.last_distance = 1
self.path = deque()
self.move_cycle = self.move_cycle_gen()
self.update_grid_pos()
def update_grid_pos(self):
"""
This should only be called in the beginning, or at the
end of a move_cycle.
"""
self.grid_pos = self.get_tile_of_position(self.tank.body.position)
def decide(self):
"""
Main decision function that gets called on every
tick of the game.
"""
self.maybe_shoot()
next(self.move_cycle)
pass
def maybe_shoot(self):
"""
Makes a raycast query in front of the tank. If another tank
or a wooden box is found, then we shoot.
"""
res = self.space.segment_query_first((self.tank.body.position[0] - \
0.6 * math.sin(self.tank.body.angle), self.tank.body.position[1] +\
0.6 * math.cos(self.tank.body.angle)), (self.tank.body.position[0] -\
10*math.sin(self.tank.body.angle), self.tank.body.position[1] + \
10*math.cos(self.tank.body.angle)), 0, pymunk.ShapeFilter())
if res is not None:
try:
if hasattr(res, 'shape'):
if isinstance(res.shape.parent, gameobjects.Tank):
bullet = self.tank.shoot(self.space)
if bullet is not None:
self.game_objects_list.append(bullet)
elif isinstance(res.shape.parent, gameobjects.Box):
if res.shape.parent.boxmodel.destructable is True:
bullet = self.tank.shoot(self.space)
if bullet is not None:
self.game_objects_list.append(bullet)
except:
pass
def move_cycle_gen(self):
"""
A generator that iteratively goes through all the required
steps to move to our goal.
"""
while True:
self.update_grid_pos()
path = self.find_shortest_path("without_metalbox")
if not path:
path = self.find_shortest_path("metalbox")
yield
if not path:
continue
next_coord = path.pop()
next_coord += Vec2d(0.5, 0.5)
yield
target_angle = \
angle_between_vectors(Vec2d(self.tank.body.position), next_coord)
angle_tank = self.tank.body.angle
self.turn(angle_tank, target_angle)
while not self.correct_angle(angle_tank, target_angle):
angle_tank = self.tank.body.angle
target_angle = \
angle_between_vectors(Vec2d(self.tank.body.position),
next_coord)
yield
self.tank.accelerate()
while not self.correct_pos(next_coord, self.last_distance):
yield
yield
def correct_pos(self, target_pos, last_distance):
"""
Checks if the tank is on the correct position, compared from the
last one.
"""
tank_pos = Vec2d(self.tank.body.position)
current_distance = target_pos.get_distance(tank_pos)
self.last_distance = current_distance
if last_distance < current_distance:
return True
else:
return False
def turn(self, tank_angle, target_angle):
"""
Finds the angle closest to next tile, and turns accordingly.
WIP: Sometimes it turns to the other side.
"""
angle_diff = periodic_difference_of_angles(tank_angle, target_angle)
if ((angle_diff + 2 * math.pi) % 2
* math.pi >= math.pi and abs(angle_diff) > MIN_ANGLE_DIF):
self.tank.stop_moving()
self.tank.turn_left()
elif ((angle_diff + 2 * math.pi) % 2 * math.pi
< math.pi and abs(angle_diff) > MIN_ANGLE_DIF):
self.tank.stop_moving()
self.tank.turn_right()
def correct_angle(self, tank_angle, target_angle):
"""
If the tank has the correct angle to the next tile; stop turning.
"""
angle_diff = periodic_difference_of_angles(target_angle, tank_angle)
if abs(angle_diff) <= MIN_ANGLE_DIF:
self.tank.stop_turning()
return True
else:
return False
def find_shortest_path(self, box_indicator):
"""
A simple Breadth First Search using integer coordinates as our
nodes. Edges are calculated as we go, using an external function.
"""
# To be implemented
dict = {}
shortest_path = []
visited = set()
queue = deque()
queue.append(self.grid_pos)
goal_node = None
while queue:
node = Vec2d(queue.popleft())
if node == self.get_target_tile().int_tuple:
goal_node = node.int_tuple
break
for neighbor in self.get_tile_neighbors(node, box_indicator):
neighbor = neighbor.int_tuple
if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)
dict[neighbor] = node.int_tuple
if goal_node is None:
return deque([])
else:
key = goal_node
while key != self.grid_pos.int_tuple:
shortest_path.append(Vec2d(key))
parent_node = dict[key]
key = parent_node
return deque(shortest_path)
def get_target_tile(self):
"""
Returns position of the flag if we don't have it. If we
do have the flag, return the position of our home base.
"""
if self.tank.flag is not None:
x, y = self.tank.start_position
else:
self.get_flag() # Ensure that we have initialized it.
x, y = self.flag.x, self.flag.y
return Vec2d(int(x), int(y))
def get_flag(self):
"""
This has to be called to get the flag, since we don't know
where it is when the Ai object is initialized.
"""
if self.flag is None:
# Find the flag in the game objects list
for obj in self.game_objects_list:
if isinstance(obj, gameobjects.Flag):
self.flag = obj
break
return self.flag
def get_tile_of_position(self, position_vector):
"""
Converts and returns the float position of our tank to an
integer position.
"""
x, y = position_vector
return Vec2d(int(x), int(y))
def get_tile_neighbors(self, coord_vec, box_indicator):
"""
Returns all bordering grid squares of the input coordinate.
A bordering square is only considered accessible if it is grass
or a wooden box.
"""
neighbors = [] # Find the coordinates of the tiles' four neighbors
neighbors.append(coord_vec + Vec2d(1, 0))
neighbors.append(coord_vec + Vec2d(-1, 0))
neighbors.append(coord_vec + Vec2d(0, 1))
neighbors.append(coord_vec + Vec2d(0, -1))
if box_indicator == "without_metalbox":
return filter(self.filter_tile_neighbors, neighbors)
else:
return filter(self.filter_tile_neighbors_metalbox, neighbors)
def filter_tile_neighbors(self, coord):
"""
Filter for all the tiles around the tank. This filter removes
the immovable stones so we don't count those tiles to find the
shortest path.
"""
coord = coord.int_tuple
if coord[1] <= self.MAX_Y and coord[0] <= self.MAX_X and coord[1] >= \
0 and coord[0] >=\
0 and (self.currentmap.boxAt(coord[0], coord[1])
== 0 or self.currentmap.boxAt(coord[0], coord[1]) == 2):
return True
return False
def | (self, coord):
"""
Filter for all the tiles around the tank, metalboxes included. This
filter removes the immovable stones so we don't count those tiles to
find the shortest path.
"""
coord = coord.int_tuple
if coord[1] <= self.MAX_Y and coord[0] <= self.MAX_X and coord[1] >=\
0 and coord[0] >= 0 and (self.currentmap.boxAt(coord[0], coord[1])
== 0 or self.currentmap.boxAt(coord[0],
coord[1])
== 2 or self.currentmap.boxAt(coord[0],
coord[1])
== 3):
return True
return False
SimpleAi = Ai # Legacy
| filter_tile_neighbors_metalbox | identifier_name |
mole.go | package mole
import (
"context"
"fmt"
"io/ioutil"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/davrodpin/mole/alias"
"github.com/davrodpin/mole/fsutils"
"github.com/davrodpin/mole/rpc"
"github.com/davrodpin/mole/tunnel"
"github.com/awnumar/memguard"
"github.com/gofrs/uuid"
"github.com/mitchellh/mapstructure"
daemon "github.com/sevlyar/go-daemon"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh/terminal"
)
const (
// IdFlagName is the name of the flag that carries the unique idenfier for a
// mole instance.
IdFlagName = "id"
)
// cli keeps a reference to the latest Client object created.
// This is mostly needed to introspect client states during runtime (e.g. a
// remote procedure call that needs to check certain runtime information)
var cli *Client
type Configuration struct {
Id string `json:"id" mapstructure:"id" toml:"id"`
TunnelType string `json:"tunnel-type" mapstructure:"tunnel-type" toml:"tunnel-type"`
Verbose bool `json:"verbose" mapstructure:"verbose" toml:"verbose"`
Insecure bool `json:"insecure" mapstructure:"insecure" toml:"insecure"`
Detach bool `json:"detach" mapstructure:"detach" toml:"detach"`
Source AddressInputList `json:"source" mapstructure:"source" toml:"source"`
Destination AddressInputList `json:"destination" mapstructure:"destination" toml:"destination"`
Server AddressInput `json:"server" mapstructure:"server" toml:"server"`
Key string `json:"key" mapstructure:"key" toml:"key"`
KeepAliveInterval time.Duration `json:"keep-alive-interval" mapstructure:"keep-alive-interva" toml:"keep-alive-interval"`
ConnectionRetries int `json:"connection-retries" mapstructure:"connection-retries" toml:"connection-retries"`
WaitAndRetry time.Duration `json:"wait-and-retry" mapstructure:"wait-and-retry" toml:"wait-and-retry"`
SshAgent string `json:"ssh-agent" mapstructure:"ssh-agent" toml:"ssh-agent"`
Timeout time.Duration `json:"timeout" mapstructure:"timeout" toml:"timeout"`
SshConfig string `json:"ssh-config" mapstructure:"ssh-config" toml:"ssh-config"`
Rpc bool `json:"rpc" mapstructure:"rpc" toml:"rpc"`
RpcAddress string `json:"rpc-address" mapstructure:"rpc-address" toml:"rpc-address"`
}
// ParseAlias translates a Configuration object to an Alias object.
func (c Configuration) ParseAlias(name string) *alias.Alias {
return &alias.Alias{
Name: name,
TunnelType: c.TunnelType,
Verbose: c.Verbose,
Insecure: c.Insecure,
Detach: c.Detach,
Source: c.Source.List(),
Destination: c.Destination.List(),
Server: c.Server.String(),
Key: c.Key,
KeepAliveInterval: c.KeepAliveInterval.String(),
ConnectionRetries: c.ConnectionRetries,
WaitAndRetry: c.WaitAndRetry.String(),
SshAgent: c.SshAgent,
Timeout: c.Timeout.String(),
SshConfig: c.SshConfig,
Rpc: c.Rpc,
RpcAddress: c.RpcAddress,
}
}
// Client manages the overall state of the application based on its configuration.
type Client struct {
Conf *Configuration
Tunnel *tunnel.Tunnel
sigs chan os.Signal
}
// New initializes a new mole's client.
func New(conf *Configuration) *Client {
cli = &Client{
Conf: conf,
sigs: make(chan os.Signal, 1),
}
return cli
}
// Start kicks off mole's client, establishing the tunnel and its channels
// based on the client configuration attributes.
func (c *Client) Start() error {
// memguard is used to securely keep sensitive information in memory.
// This call makes sure all data will be destroy when the program exits.
defer memguard.Purge()
if c.Conf.Id == "" {
u, err := uuid.NewV4()
if err != nil {
return fmt.Errorf("could not auto generate app instance id: %v", err)
}
c.Conf.Id = u.String()[:8]
}
r, err := c.Running()
if err != nil {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).WithError(err).Error("error while checking for another instance using the same id")
return err
}
if r {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).Error("can't start. Another instance is already using the same id")
return fmt.Errorf("can't start. Another instance is already using the same id %s", c.Conf.Id)
}
log.Infof("instance identifier is %s", c.Conf.Id)
if c.Conf.Detach {
var err error
ic, err := NewDetachedInstance(c.Conf.Id)
if err != nil {
log.WithError(err).Errorf("error while creating directory to store mole instance related files")
return err
}
err = startDaemonProcess(ic)
if err != nil {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).WithError(err).Error("error starting ssh tunnel")
return err
}
} else {
go c.handleSignals()
}
if c.Conf.Verbose {
log.SetLevel(log.DebugLevel)
}
d, err := fsutils.CreateInstanceDir(c.Conf.Id)
if err != nil {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).WithError(err).Error("error creating directory for mole instance")
return err
}
if c.Conf.Rpc {
addr, err := rpc.Start(c.Conf.RpcAddress)
if err != nil {
return err
}
rd := filepath.Join(d.Dir, "rpc")
err = ioutil.WriteFile(rd, []byte(addr.String()), 0644)
if err != nil {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).WithError(err).Error("error creating file with rpc address")
return err
}
c.Conf.RpcAddress = addr.String()
log.Infof("rpc server address saved on %s", rd)
}
t, err := createTunnel(c.Conf)
if err != nil {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).WithError(err).Error("error creating tunnel")
return err
}
c.Tunnel = t
if err = c.Tunnel.Start(); err != nil {
log.WithFields(log.Fields{
"tunnel": c.Tunnel.String(),
}).WithError(err).Error("error while starting tunnel")
return err
}
return nil
}
// Stop shuts down a detached mole's application instance.
func (c *Client) Stop() error {
pfp, err := fsutils.GetPidFileLocation(c.Conf.Id)
if err != nil {
return fmt.Errorf("error getting information about aliases directory: %v", err)
}
if _, err := os.Stat(pfp); os.IsNotExist(err) {
return fmt.Errorf("no instance of mole with id %s is running", c.Conf.Id)
}
cntxt := &daemon.Context{
PidFileName: pfp,
}
d, err := cntxt.Search()
if err != nil {
return err
}
if c.Conf.Detach {
err = os.RemoveAll(pfp)
if err != nil {
return err
}
} else {
d, err := fsutils.InstanceDir(c.Conf.Id)
if err != nil {
return err
}
err = os.RemoveAll(d.Dir)
if err != nil {
return err
}
}
err = d.Kill()
if err != nil {
return err
}
return nil
}
func (c *Client) handleSignals() {
signal.Notify(c.sigs, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
sig := <-c.sigs
log.Debugf("process signal %s received", sig)
err := c.Stop()
if err != nil {
log.WithError(err).Error("instance not properly stopped")
}
}
// Merge overwrites Configuration from the given Alias.
//
// Certain attributes like Verbose, Insecure and Detach will be overwritten
// only if they are found on the givenFlags which should contain the name of
// all flags given by the user through UI (e.g. CLI).
func (c *Configuration) Merge(al *alias.Alias, givenFlags []string) error {
var fl flags = givenFlags
if !fl.lookup("verbose") {
c.Verbose = al.Verbose
}
if !fl.lookup("insecure") {
c.Insecure = al.Insecure
}
if !fl.lookup("detach") {
c.Detach = al.Detach
}
c.Id = al.Name
c.TunnelType = al.TunnelType
srcl := AddressInputList{}
for _, src := range al.Source {
err := srcl.Set(src)
if err != nil {
return err
}
}
c.Source = srcl
dstl := AddressInputList{}
for _, dst := range al.Destination {
err := dstl.Set(dst)
if err != nil {
return err
}
}
c.Destination = dstl
srv := AddressInput{}
err := srv.Set(al.Server)
if err != nil {
return err
}
c.Server = srv
c.Key = al.Key
kai, err := time.ParseDuration(al.KeepAliveInterval)
if err != nil {
return err
}
c.KeepAliveInterval = kai
c.ConnectionRetries = al.ConnectionRetries
war, err := time.ParseDuration(al.WaitAndRetry)
if err != nil {
return err
}
c.WaitAndRetry = war
c.SshAgent = al.SshAgent
tim, err := time.ParseDuration(al.Timeout)
if err != nil {
return err
}
c.Timeout = tim
c.SshConfig = al.SshConfig
c.Rpc = al.Rpc
c.RpcAddress = al.RpcAddress
return nil
}
// ShowInstances returns the runtime information about all instances of mole
// running on the system with rpc enabled.
func ShowInstances() (*InstancesRuntime, error) {
ctx := context.Background()
data, err := rpc.ShowAll(ctx)
if err != nil {
return nil, err
}
var instances []Runtime
err = mapstructure.Decode(data, &instances)
if err != nil {
return nil, err
}
runtime := InstancesRuntime(instances)
if len(runtime) == 0 {
return nil, fmt.Errorf("no instances were found.")
}
return &runtime, nil
}
// ShowInstance returns the runtime information about an application instance
// from the given id or alias.
func ShowInstance(id string) (*Runtime, error) {
ctx := context.Background()
info, err := rpc.Show(ctx, id)
if err != nil {
return nil, err
}
var r Runtime
err = mapstructure.Decode(info, &r)
if err != nil {
return nil, err
}
return &r, nil
}
func startDaemonProcess(instanceConf *DetachedInstance) error {
args := appendIdArg(instanceConf.Id, os.Args)
cntxt := &daemon.Context{
PidFileName: instanceConf.PidFile,
PidFilePerm: 0644,
LogFileName: instanceConf.LogFile,
LogFilePerm: 0640,
Umask: 027,
Args: args,
}
d, err := cntxt.Reborn()
if err != nil {
return err
}
if d != nil {
err = os.Rename(instanceConf.PidFile, instanceConf.PidFile)
if err != nil {
return err
}
err = os.Rename(instanceConf.LogFile, instanceConf.LogFile)
if err != nil {
return err
}
log.Infof("execute \"mole stop %s\" if you like to stop it at any time", instanceConf.Id)
os.Exit(0)
}
defer func() {
err := cntxt.Release()
if err != nil {
log.WithFields(log.Fields{
"id": instanceConf.Id,
}).WithError(err).Error("error detaching the mole instance")
}
}()
return nil
}
type flags []string
func (fs flags) lookup(flag string) bool {
for _, f := range fs {
if flag == f {
return true
}
}
return false
}
func | (conf *Configuration) (*tunnel.Tunnel, error) {
s, err := tunnel.NewServer(conf.Server.User, conf.Server.Address(), conf.Key, conf.SshAgent, conf.SshConfig)
if err != nil {
log.Errorf("error processing server options: %v\n", err)
return nil, err
}
s.Insecure = conf.Insecure
s.Timeout = conf.Timeout
err = s.Key.HandlePassphrase(func() ([]byte, error) {
fmt.Printf("The key provided is secured by a password. Please provide it below:\n")
fmt.Printf("Password: ")
p, err := terminal.ReadPassword(int(syscall.Stdin))
fmt.Printf("\n")
return p, err
})
if err != nil {
log.WithError(err).Error("error setting up password handling function")
return nil, err
}
log.Debugf("server: %s", s)
source := make([]string, len(conf.Source))
for i, r := range conf.Source {
source[i] = r.String()
}
destination := make([]string, len(conf.Destination))
for i, r := range conf.Destination {
if r.Port == "" {
log.WithError(err).Errorf("missing port in destination address: %s", r.String())
return nil, err
}
destination[i] = r.String()
}
t, err := tunnel.New(conf.TunnelType, s, source, destination, conf.SshConfig)
if err != nil {
log.Error(err)
return nil, err
}
//TODO need to find a way to require the attributes below to be always set
// since they are not optional (functionality will break if they are not
// set and CLI parsing is the one setting the default values).
// That could be done by make them required in the constructor's signature or
// by creating a configuration struct for a tunnel object.
t.ConnectionRetries = conf.ConnectionRetries
t.WaitAndRetry = conf.WaitAndRetry
t.KeepAliveInterval = conf.KeepAliveInterval
return t, nil
}
// appendIdArg adds the id argument to the list of arguments passed by the user.
// This is helpful for scenarios where the process will be detached from the
// parent process and the new child process needs context about the instance.
func appendIdArg(id string, args []string) (newArgs []string) {
for _, arg := range args {
if arg == "--id" {
return args
}
}
newArgs = make([]string, len(args)+2)
copy(newArgs, args)
newArgs[len(args)-2] = fmt.Sprintf("--%s", IdFlagName)
newArgs[len(args)-1] = id
return
}
| createTunnel | identifier_name |
mole.go | package mole
import (
"context"
"fmt"
"io/ioutil"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/davrodpin/mole/alias"
"github.com/davrodpin/mole/fsutils"
"github.com/davrodpin/mole/rpc"
"github.com/davrodpin/mole/tunnel"
"github.com/awnumar/memguard"
"github.com/gofrs/uuid"
"github.com/mitchellh/mapstructure"
daemon "github.com/sevlyar/go-daemon"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh/terminal"
)
const (
// IdFlagName is the name of the flag that carries the unique idenfier for a
// mole instance.
IdFlagName = "id"
)
// cli keeps a reference to the latest Client object created.
// This is mostly needed to introspect client states during runtime (e.g. a
// remote procedure call that needs to check certain runtime information)
var cli *Client
type Configuration struct {
Id string `json:"id" mapstructure:"id" toml:"id"`
TunnelType string `json:"tunnel-type" mapstructure:"tunnel-type" toml:"tunnel-type"`
Verbose bool `json:"verbose" mapstructure:"verbose" toml:"verbose"`
Insecure bool `json:"insecure" mapstructure:"insecure" toml:"insecure"`
Detach bool `json:"detach" mapstructure:"detach" toml:"detach"`
Source AddressInputList `json:"source" mapstructure:"source" toml:"source"`
Destination AddressInputList `json:"destination" mapstructure:"destination" toml:"destination"`
Server AddressInput `json:"server" mapstructure:"server" toml:"server"`
Key string `json:"key" mapstructure:"key" toml:"key"`
KeepAliveInterval time.Duration `json:"keep-alive-interval" mapstructure:"keep-alive-interva" toml:"keep-alive-interval"`
ConnectionRetries int `json:"connection-retries" mapstructure:"connection-retries" toml:"connection-retries"`
WaitAndRetry time.Duration `json:"wait-and-retry" mapstructure:"wait-and-retry" toml:"wait-and-retry"`
SshAgent string `json:"ssh-agent" mapstructure:"ssh-agent" toml:"ssh-agent"`
Timeout time.Duration `json:"timeout" mapstructure:"timeout" toml:"timeout"`
SshConfig string `json:"ssh-config" mapstructure:"ssh-config" toml:"ssh-config"`
Rpc bool `json:"rpc" mapstructure:"rpc" toml:"rpc"`
RpcAddress string `json:"rpc-address" mapstructure:"rpc-address" toml:"rpc-address"`
}
// ParseAlias translates a Configuration object to an Alias object.
func (c Configuration) ParseAlias(name string) *alias.Alias {
return &alias.Alias{
Name: name,
TunnelType: c.TunnelType,
Verbose: c.Verbose,
Insecure: c.Insecure,
Detach: c.Detach,
Source: c.Source.List(),
Destination: c.Destination.List(),
Server: c.Server.String(),
Key: c.Key,
KeepAliveInterval: c.KeepAliveInterval.String(),
ConnectionRetries: c.ConnectionRetries,
WaitAndRetry: c.WaitAndRetry.String(),
SshAgent: c.SshAgent,
Timeout: c.Timeout.String(),
SshConfig: c.SshConfig,
Rpc: c.Rpc,
RpcAddress: c.RpcAddress,
}
}
// Client manages the overall state of the application based on its configuration.
type Client struct {
Conf *Configuration
Tunnel *tunnel.Tunnel
sigs chan os.Signal
}
// New initializes a new mole's client.
func New(conf *Configuration) *Client {
cli = &Client{
Conf: conf,
sigs: make(chan os.Signal, 1),
}
return cli
}
// Start kicks off mole's client, establishing the tunnel and its channels
// based on the client configuration attributes.
func (c *Client) Start() error {
// memguard is used to securely keep sensitive information in memory.
// This call makes sure all data will be destroy when the program exits.
defer memguard.Purge()
if c.Conf.Id == "" {
u, err := uuid.NewV4()
if err != nil {
return fmt.Errorf("could not auto generate app instance id: %v", err)
}
c.Conf.Id = u.String()[:8]
}
r, err := c.Running()
if err != nil {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).WithError(err).Error("error while checking for another instance using the same id")
return err
}
if r {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).Error("can't start. Another instance is already using the same id")
return fmt.Errorf("can't start. Another instance is already using the same id %s", c.Conf.Id)
}
log.Infof("instance identifier is %s", c.Conf.Id)
if c.Conf.Detach {
var err error
ic, err := NewDetachedInstance(c.Conf.Id)
if err != nil {
log.WithError(err).Errorf("error while creating directory to store mole instance related files")
return err
}
err = startDaemonProcess(ic)
if err != nil {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).WithError(err).Error("error starting ssh tunnel")
return err
}
} else {
go c.handleSignals()
}
if c.Conf.Verbose {
log.SetLevel(log.DebugLevel)
}
d, err := fsutils.CreateInstanceDir(c.Conf.Id)
if err != nil {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).WithError(err).Error("error creating directory for mole instance")
return err
}
if c.Conf.Rpc {
addr, err := rpc.Start(c.Conf.RpcAddress)
if err != nil {
return err
}
rd := filepath.Join(d.Dir, "rpc")
err = ioutil.WriteFile(rd, []byte(addr.String()), 0644)
if err != nil {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).WithError(err).Error("error creating file with rpc address")
return err
}
c.Conf.RpcAddress = addr.String()
log.Infof("rpc server address saved on %s", rd)
}
t, err := createTunnel(c.Conf)
if err != nil {
log.WithFields(log.Fields{
"id": c.Conf.Id,
}).WithError(err).Error("error creating tunnel")
return err
}
c.Tunnel = t
if err = c.Tunnel.Start(); err != nil {
log.WithFields(log.Fields{
"tunnel": c.Tunnel.String(),
}).WithError(err).Error("error while starting tunnel")
return err
}
return nil
}
// Stop shuts down a detached mole's application instance.
func (c *Client) Stop() error {
pfp, err := fsutils.GetPidFileLocation(c.Conf.Id)
if err != nil {
return fmt.Errorf("error getting information about aliases directory: %v", err)
}
if _, err := os.Stat(pfp); os.IsNotExist(err) {
return fmt.Errorf("no instance of mole with id %s is running", c.Conf.Id)
}
cntxt := &daemon.Context{
PidFileName: pfp,
}
d, err := cntxt.Search()
if err != nil {
return err
}
if c.Conf.Detach {
err = os.RemoveAll(pfp)
if err != nil {
return err
}
} else {
d, err := fsutils.InstanceDir(c.Conf.Id)
if err != nil {
return err
}
err = os.RemoveAll(d.Dir)
if err != nil {
return err
}
}
err = d.Kill()
if err != nil {
return err
}
return nil
}
func (c *Client) handleSignals() {
signal.Notify(c.sigs, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
sig := <-c.sigs
log.Debugf("process signal %s received", sig)
err := c.Stop()
if err != nil {
log.WithError(err).Error("instance not properly stopped")
}
}
// Merge overwrites Configuration from the given Alias.
//
// Certain attributes like Verbose, Insecure and Detach will be overwritten
// only if they are found on the givenFlags which should contain the name of
// all flags given by the user through UI (e.g. CLI).
func (c *Configuration) Merge(al *alias.Alias, givenFlags []string) error {
var fl flags = givenFlags
if !fl.lookup("verbose") {
c.Verbose = al.Verbose
}
if !fl.lookup("insecure") {
c.Insecure = al.Insecure
}
if !fl.lookup("detach") {
c.Detach = al.Detach
}
c.Id = al.Name
c.TunnelType = al.TunnelType
srcl := AddressInputList{}
for _, src := range al.Source {
err := srcl.Set(src)
if err != nil {
return err
}
}
c.Source = srcl
dstl := AddressInputList{}
for _, dst := range al.Destination {
err := dstl.Set(dst)
if err != nil {
return err
}
}
c.Destination = dstl
srv := AddressInput{}
err := srv.Set(al.Server)
if err != nil {
return err
}
c.Server = srv
c.Key = al.Key
kai, err := time.ParseDuration(al.KeepAliveInterval)
if err != nil {
return err
}
c.KeepAliveInterval = kai
c.ConnectionRetries = al.ConnectionRetries
war, err := time.ParseDuration(al.WaitAndRetry)
if err != nil {
return err
}
c.WaitAndRetry = war
c.SshAgent = al.SshAgent
tim, err := time.ParseDuration(al.Timeout)
if err != nil {
return err
}
c.Timeout = tim
c.SshConfig = al.SshConfig
c.Rpc = al.Rpc
c.RpcAddress = al.RpcAddress
return nil
}
// ShowInstances returns the runtime information about all instances of mole
// running on the system with rpc enabled.
func ShowInstances() (*InstancesRuntime, error) {
ctx := context.Background()
data, err := rpc.ShowAll(ctx)
if err != nil {
return nil, err
}
var instances []Runtime
err = mapstructure.Decode(data, &instances)
if err != nil {
return nil, err
}
runtime := InstancesRuntime(instances)
if len(runtime) == 0 {
return nil, fmt.Errorf("no instances were found.")
}
return &runtime, nil
}
// ShowInstance returns the runtime information about an application instance
// from the given id or alias.
func ShowInstance(id string) (*Runtime, error) {
ctx := context.Background()
info, err := rpc.Show(ctx, id)
if err != nil {
return nil, err
}
var r Runtime
err = mapstructure.Decode(info, &r)
if err != nil {
return nil, err
}
return &r, nil
}
func startDaemonProcess(instanceConf *DetachedInstance) error {
args := appendIdArg(instanceConf.Id, os.Args)
cntxt := &daemon.Context{
PidFileName: instanceConf.PidFile,
PidFilePerm: 0644,
LogFileName: instanceConf.LogFile,
LogFilePerm: 0640,
Umask: 027,
Args: args,
}
d, err := cntxt.Reborn()
if err != nil {
return err
}
if d != nil {
err = os.Rename(instanceConf.PidFile, instanceConf.PidFile)
if err != nil {
return err
}
err = os.Rename(instanceConf.LogFile, instanceConf.LogFile)
if err != nil {
return err
}
log.Infof("execute \"mole stop %s\" if you like to stop it at any time", instanceConf.Id)
os.Exit(0)
}
defer func() {
err := cntxt.Release()
if err != nil {
log.WithFields(log.Fields{
"id": instanceConf.Id,
}).WithError(err).Error("error detaching the mole instance")
}
}()
return nil
}
type flags []string
func (fs flags) lookup(flag string) bool |
func createTunnel(conf *Configuration) (*tunnel.Tunnel, error) {
s, err := tunnel.NewServer(conf.Server.User, conf.Server.Address(), conf.Key, conf.SshAgent, conf.SshConfig)
if err != nil {
log.Errorf("error processing server options: %v\n", err)
return nil, err
}
s.Insecure = conf.Insecure
s.Timeout = conf.Timeout
err = s.Key.HandlePassphrase(func() ([]byte, error) {
fmt.Printf("The key provided is secured by a password. Please provide it below:\n")
fmt.Printf("Password: ")
p, err := terminal.ReadPassword(int(syscall.Stdin))
fmt.Printf("\n")
return p, err
})
if err != nil {
log.WithError(err).Error("error setting up password handling function")
return nil, err
}
log.Debugf("server: %s", s)
source := make([]string, len(conf.Source))
for i, r := range conf.Source {
source[i] = r.String()
}
destination := make([]string, len(conf.Destination))
for i, r := range conf.Destination {
if r.Port == "" {
log.WithError(err).Errorf("missing port in destination address: %s", r.String())
return nil, err
}
destination[i] = r.String()
}
t, err := tunnel.New(conf.TunnelType, s, source, destination, conf.SshConfig)
if err != nil {
log.Error(err)
return nil, err
}
//TODO need to find a way to require the attributes below to be always set
// since they are not optional (functionality will break if they are not
// set and CLI parsing is the one setting the default values).
// That could be done by make them required in the constructor's signature or
// by creating a configuration struct for a tunnel object.
t.ConnectionRetries = conf.ConnectionRetries
t.WaitAndRetry = conf.WaitAndRetry
t.KeepAliveInterval = conf.KeepAliveInterval
return t, nil
}
// appendIdArg adds the id argument to the list of arguments passed by the user.
// This is helpful for scenarios where the process will be detached from the
// parent process and the new child process needs context about the instance.
func appendIdArg(id string, args []string) (newArgs []string) {
for _, arg := range args {
if arg == "--id" {
return args
}
}
newArgs = make([]string, len(args)+2)
copy(newArgs, args)
newArgs[len(args)-2] = fmt.Sprintf("--%s", IdFlagName)
newArgs[len(args)-1] = id
return
}
| {
for _, f := range fs {
if flag == f {
return true
}
}
return false
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.