repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
thhuang/notes-fcnd
[ "c5b0ec7d99df3cb60a850308d16ccc6c096c7931" ]
[ "Course04/19-8_Attitude estimation/helpers.py" ]
[ "import numpy as np\nfrom matplotlib import pyplot as plt\n\nclass IMU:\n def __init__(self, accel_sigma=0.1, gyro_sigma=0.5):\n self.accel_sigma = accel_sigma\n self.gyro_sigma = gyro_sigma\n \n def measure(self, true_state):\n \"\"\"true_state is [theta, phi, q, p]\"\"\"\n theta = true_state[0] + np.random.normal(0, self.accel_sigma)\n phi = true_state[1] + np.random.normal(0, self.accel_sigma) \n q = true_state[2] + np.random.normal(0, self.gyro_sigma)\n p = true_state[3] + np.random.normal(0, self.gyro_sigma)\n \n return np.array([theta,phi,q,p])\n \n def make_measurements(self, true_states):\n measurements = np.zeros((4, true_states.shape[1]))\n for i in range(true_states.shape[1]):\n measurements[:,i] = self.measure(true_states[:,i])\n return measurements\n \ndef plot_compare(truth, estimates, measurements, integrated, dt,index):\n N = truth.shape[1]\n t = np.arange(0,N*dt, dt)\n plt.plot(t, truth.T[:,index],linestyle='-', color='black',lw=4)\n plt.plot(t, measurements.T[:,index], linestyle='-', color='red',alpha=0.5)\n plt.plot(t,estimates.T[:,index],linestyle='-',color='blue')\n plt.plot(t,integrated.T[:,index],linestyle='-',color='green')\n plt.grid()\n if index == 0:\n title = \"Pitch\"\n else:\n title = \"Roll\"\n plt.title(title).set_fontsize(20)\n plt.xlabel('$t$ [sec]').set_fontsize(20)\n xlab = '$\\Theta - \\Theta_0$ [$^{\\circ}$]'\n if index == 1:\n xlab = '$\\Phi - \\Phi$ [$^{\\circ}$]'\n plt.ylabel(xlab).set_fontsize(20)\n plt.xticks(fontsize = 14)\n plt.yticks(fontsize = 14)\n plt.legend(['True', 'Measured','Estimated','Gyro integral'],fontsize = 18)\n fig =plt.gcf()\n fig.set_size_inches(10, 10)\n plt.show()" ]
[ [ "numpy.array", "matplotlib.pyplot.legend", "matplotlib.pyplot.yticks", "matplotlib.pyplot.title", "numpy.arange", "matplotlib.pyplot.gcf", "matplotlib.pyplot.plot", "numpy.random.normal", "matplotlib.pyplot.grid", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks", "matplotlib.pyplot.show", "numpy.zeros", "matplotlib.pyplot.ylabel" ] ]
sethdmay/dg-cv
[ "09eac355b11507b6d034eb209168cec820851e36" ]
[ "seth/background_extract.py" ]
[ "import cv2 as cv\nimport numpy as np\n\n\nwindow_name = \"FG Mask\"\npaused = False\n\n# Lucas kanade params\nlk_params = dict(\n winSize=(15, 15),\n maxLevel=4,\n criteria=(cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 0.03),\n)\n\n\nvideo = cv.VideoCapture(\"resources/putt.mov\")\nbg_extract = cv.createBackgroundSubtractorKNN(history=750, dist2Threshold=800)\nbg_extract.setNSamples(10)\n\navailable, frame = video.read()\nframe_num = 0\n\n\ncv.namedWindow(\n window_name, (cv.WINDOW_NORMAL | cv.WINDOW_KEEPRATIO | cv.WINDOW_GUI_EXPANDED)\n)\ncv.namedWindow(\n \"Original\", (cv.WINDOW_NORMAL | cv.WINDOW_KEEPRATIO | cv.WINDOW_GUI_EXPANDED)\n)\n\n\ndef pause(*args):\n global paused\n paused = not paused\n\n\ncv.createButton(\"Pause\", pause, None, cv.QT_PUSH_BUTTON)\n\npoint_selected = False\npoint = ()\nold_points = np.array([[]])\npath = []\n\n# Mouse function\ndef select_point(event, x, y, flags, params):\n global old_points, point, point_selected, path\n if event == cv.EVENT_LBUTTONDOWN:\n point = (x, y)\n point_selected = True\n old_points = np.array([[x, y]], dtype=np.float32)\n path = []\n\n\ndef mask_highlight(mask, original):\n pure_mask = cv.cvtColor(mask, cv.COLOR_GRAY2BGR)\n pure_mask = pure_mask == 255\n\n grey_original = cv.cvtColor(\n cv.cvtColor(original, cv.COLOR_BGR2GRAY), cv.COLOR_GRAY2BGR\n )\n grey_original //= 10\n grey_original[pure_mask != [0, 0, 0]] = 0\n\n masked = original * pure_mask.astype(original.dtype)\n\n merged = grey_original + masked\n return merged, masked\n\n\ndef get_gradient(fnum, current_length):\n red = np.interp(fnum, [0,current_length], [64,0])\n green = np.interp(fnum, [0,current_length], [255,128])\n blue = np.interp(fnum, [0,current_length], [0,255])\n\n\n return [int(blue), int(green), int(red)]\n\n\ncv.setMouseCallback(\"Original\", select_point)\n\nwhile available:\n fg_mask = bg_extract.apply(frame)\n\n fg_highlight, fg_alone = mask_highlight(fg_mask, frame)\n\n gray_frame = cv.cvtColor(fg_alone, cv.COLOR_BGR2GRAY)\n\n if point_selected:\n cv.circle(fg_alone, point, 5, (0, 0, 255), 2)\n\n new_points, status, error = cv.calcOpticalFlowPyrLK(\n old_gray, gray_frame, old_points, None, **lk_params\n )\n\n old_points = new_points\n\n x, y = new_points.ravel()\n cv.circle(fg_alone, (x, y), 5, (0, 255, 0), -1)\n\n path.append((int(x), int(y)))\n if key == ord('r'):\n point_selected = False\n\n old_gray = gray_frame.copy()\n\n\n\n \n\n if len(path) >= 2:\n path_canvas = np.zeros_like(frame)\n\n # draw gradient\n current_length = len(path)\n for i, location in enumerate(path[:-1]):\n cv.line(path_canvas, location, path[i+1], get_gradient(i, current_length), 3, cv.FILLED)\n\n\n path_canvas_blurred = cv.blur(path_canvas, (2,2), 0)\n\n\n frame = cv.addWeighted(src1=path_canvas_blurred, alpha=0.8, src2=frame, beta=1, gamma=0)\n\n #frame[path_canvas != [0,0,0]] = path_canvas[path_canvas != [0,0,0]]\n\n\n cv.imshow(window_name, fg_alone)\n cv.imshow(\"Original\", frame)\n key = cv.waitKey(1)\n \n if key == ord('q'):\n break\n if key == ord('p'):\n cv.waitKey(-1)\n \n\n frame_num += 1\n available, frame = video.read()\n\nvideo.release()\ncv.destroyAllWindows()\n" ]
[ [ "numpy.array", "numpy.zeros_like", "numpy.interp" ] ]
EuphoriaYan/Chinese-ancient-book-recognition-HSK
[ "865736d16389037f555f0eea7ec6c4ab7e4319c9" ]
[ "noise_util.py" ]
[ "from PIL import Image, ImageDraw\nimport numpy as np\nfrom tqdm import tqdm\nimport random\nimport math\nimport json\n\n\ndef cal_dis(pA, pB):\n return math.sqrt((pA[0] - pB[0]) ** 2 + (pA[1] - pB[1]) ** 2)\n\n\ndef add_noise(img, generate_ratio=0.003, generate_size=0.006):\n if not isinstance(img, np.ndarray):\n img = np.array(img)\n h, w = img.shape\n R_max = max(3, int(min(h, w) * generate_size))\n threshold = int(h * w * generate_ratio)\n random_choice_list = []\n for i in range(1, R_max + 1):\n random_choice_list.extend([i] * (R_max - i + 1))\n cnt = 0\n\n while True:\n R = random.choice(random_choice_list)\n P_noise_x = random.randint(R, w - 1 - R)\n P_noise_y = random.randint(R, h - 1 - R)\n for i in range(P_noise_x - R, P_noise_x + R):\n for j in range(P_noise_y - R, P_noise_y + R):\n if cal_dis((i, j), (P_noise_x, P_noise_y)) < R:\n if random.random() < 0.6:\n img[j][i] = random.randint(0, 255)\n cnt += 2 * R\n if cnt >= threshold:\n break\n\n R_max *= 2\n random_choice_list = []\n for i in range(1, R_max + 1):\n random_choice_list.extend([i] * (R_max - i + 1))\n cnt = 0\n while True:\n R = random.choice(random_choice_list)\n P_noise_x = random.randint(0, w - 1 - R)\n P_noise_y = random.randint(0, h - 1 - R)\n for i in range(P_noise_x + 1, P_noise_x + R):\n for j in range(P_noise_y + 1, P_noise_y + R):\n if random.random() < 0.6:\n img[j][i] = random.randint(0, 255)\n cnt += R\n if cnt >= threshold:\n break\n\n img = Image.fromarray(img)\n return img\n" ]
[ [ "numpy.array" ] ]
stephanedenis/donkeycar
[ "a0eb5df643f19c6ba51a864add5abdc4e13b9104" ]
[ "donkeycar/templates/complete.py" ]
[ "#!/usr/bin/env python3\n\"\"\"\nScripts to drive a donkey 2 car\n\nUsage:\n manage.py (drive) [--model=<model>] [--js] [--type=(linear|categorical)] [--camera=(single|stereo)] [--meta=<key:value> ...] [--myconfig=<filename>]\n manage.py (train) [--tubs=tubs] (--model=<model>) [--type=(linear|inferred|tensorrt_linear|tflite_linear)]\n\nOptions:\n -h --help Show this screen.\n --js Use physical joystick.\n -f --file=<file> A text file containing paths to tub files, one per line. Option may be used more than once.\n --meta=<key:value> Key/Value strings describing describing a piece of meta data about this drive. Option may be used more than once.\n --myconfig=filename Specify myconfig file to use. \n [default: myconfig.py]\n\"\"\"\nimport os\nimport time\nimport logging\nfrom docopt import docopt\n\n\nimport donkeycar as dk\nfrom donkeycar.parts import actuator, pins\nfrom donkeycar.parts.transform import TriggeredCallback, DelayedTrigger\nfrom donkeycar.parts.tub_v2 import TubWriter\nfrom donkeycar.parts.datastore import TubHandler\nfrom donkeycar.parts.controller import LocalWebController, WebFpv, JoystickController\nfrom donkeycar.parts.throttle_filter import ThrottleFilter\nfrom donkeycar.parts.behavior import BehaviorPart\nfrom donkeycar.parts.file_watcher import FileWatcher\nfrom donkeycar.parts.launch import AiLaunch\nfrom donkeycar.utils import *\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO)\n\n\ndef drive(cfg, model_path=None, use_joystick=False, model_type=None,\n camera_type='single', meta=[]):\n \"\"\"\n Construct a working robotic vehicle from many parts. Each part runs as a\n job in the Vehicle loop, calling either it's run or run_threaded method\n depending on the constructor flag `threaded`. All parts are updated one\n after another at the framerate given in cfg.DRIVE_LOOP_HZ assuming each\n part finishes processing in a timely manner. Parts may have named outputs\n and inputs. The framework handles passing named outputs to parts\n requesting the same named input.\n \"\"\"\n logger.info(f'PID: {os.getpid()}')\n if cfg.DONKEY_GYM:\n #the simulator will use cuda and then we usually run out of resources\n #if we also try to use cuda. so disable for donkey_gym.\n os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"-1\"\n\n if model_type is None:\n if cfg.TRAIN_LOCALIZER:\n model_type = \"localizer\"\n elif cfg.TRAIN_BEHAVIORS:\n model_type = \"behavior\"\n else:\n model_type = cfg.DEFAULT_MODEL_TYPE\n\n #Initialize car\n V = dk.vehicle.Vehicle()\n\n #Initialize logging before anything else to allow console logging\n if cfg.HAVE_CONSOLE_LOGGING:\n logger.setLevel(logging.getLevelName(cfg.LOGGING_LEVEL))\n ch = logging.StreamHandler()\n ch.setFormatter(logging.Formatter(cfg.LOGGING_FORMAT))\n logger.addHandler(ch)\n\n if cfg.HAVE_MQTT_TELEMETRY:\n from donkeycar.parts.telemetry import MqttTelemetry\n tel = MqttTelemetry(cfg)\n \n if cfg.HAVE_ODOM:\n if cfg.ENCODER_TYPE == \"GPIO\":\n from donkeycar.parts.encoder import RotaryEncoder\n enc = RotaryEncoder(mm_per_tick=cfg.MM_PER_TICK, pin=cfg.ODOM_PIN, poll_delay=1.0/(cfg.DRIVE_LOOP_HZ*3), debug=cfg.ODOM_DEBUG)\n V.add(enc, inputs=['throttle'], outputs=['enc/speed'], threaded=True)\n elif cfg.ENCODER_TYPE == \"arduino\":\n from donkeycar.parts.encoder import ArduinoEncoder\n enc = ArduinoEncoder(mm_per_tick=cfg.MM_PER_TICK, debug=cfg.ODOM_DEBUG)\n V.add(enc, outputs=['enc/speed'], threaded=True)\n else:\n print(\"No supported encoder found\")\n\n logger.info(\"cfg.CAMERA_TYPE %s\"%cfg.CAMERA_TYPE)\n if camera_type == \"stereo\":\n\n if cfg.CAMERA_TYPE == \"WEBCAM\":\n from donkeycar.parts.camera import Webcam\n\n camA = Webcam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 0)\n camB = Webcam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 1)\n\n elif cfg.CAMERA_TYPE == \"CVCAM\":\n from donkeycar.parts.cv import CvCam\n\n camA = CvCam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 0)\n camB = CvCam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 1)\n else:\n raise(Exception(\"Unsupported camera type: %s\" % cfg.CAMERA_TYPE))\n\n V.add(camA, outputs=['cam/image_array_a'], threaded=True)\n V.add(camB, outputs=['cam/image_array_b'], threaded=True)\n\n from donkeycar.parts.image import StereoPair\n\n V.add(StereoPair(), inputs=['cam/image_array_a', 'cam/image_array_b'],\n outputs=['cam/image_array'])\n elif cfg.CAMERA_TYPE == \"D435\":\n from donkeycar.parts.realsense435i import RealSense435i\n cam = RealSense435i(\n enable_rgb=cfg.REALSENSE_D435_RGB,\n enable_depth=cfg.REALSENSE_D435_DEPTH,\n enable_imu=cfg.REALSENSE_D435_IMU,\n device_id=cfg.REALSENSE_D435_ID)\n V.add(cam, inputs=[],\n outputs=['cam/image_array', 'cam/depth_array',\n 'imu/acl_x', 'imu/acl_y', 'imu/acl_z',\n 'imu/gyr_x', 'imu/gyr_y', 'imu/gyr_z'],\n threaded=True)\n\n else:\n if cfg.DONKEY_GYM:\n from donkeycar.parts.dgym import DonkeyGymEnv\n\n inputs = []\n outputs = ['cam/image_array']\n threaded = True\n if cfg.DONKEY_GYM:\n from donkeycar.parts.dgym import DonkeyGymEnv \n #rbx\n cam = DonkeyGymEnv(cfg.DONKEY_SIM_PATH, host=cfg.SIM_HOST, env_name=cfg.DONKEY_GYM_ENV_NAME, conf=cfg.GYM_CONF, record_location=cfg.SIM_RECORD_LOCATION, record_gyroaccel=cfg.SIM_RECORD_GYROACCEL, record_velocity=cfg.SIM_RECORD_VELOCITY, record_lidar=cfg.SIM_RECORD_LIDAR, delay=cfg.SIM_ARTIFICIAL_LATENCY)\n threaded = True\n inputs = ['angle', 'throttle']\n elif cfg.CAMERA_TYPE == \"PICAM\":\n from donkeycar.parts.camera import PiCamera\n cam = PiCamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, framerate=cfg.CAMERA_FRAMERATE, vflip=cfg.CAMERA_VFLIP, hflip=cfg.CAMERA_HFLIP)\n elif cfg.CAMERA_TYPE == \"WEBCAM\":\n from donkeycar.parts.camera import Webcam\n cam = Webcam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, camera_index=cfg.CAMERA_INDEX)\n elif cfg.CAMERA_TYPE == \"CVCAM\":\n from donkeycar.parts.cv import CvCam\n cam = CvCam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam=cfg.CAMERA_INDEX)\n elif cfg.CAMERA_TYPE == \"CSIC\":\n from donkeycar.parts.camera import CSICamera\n cam = CSICamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, framerate=cfg.CAMERA_FRAMERATE, \n capture_width=cfg.IMAGE_W, capture_height=cfg.IMAGE_H, gstreamer_flip=cfg.CSIC_CAM_GSTREAMER_FLIP_PARM)\n elif cfg.CAMERA_TYPE == \"V4L\":\n from donkeycar.parts.camera import V4LCamera\n cam = V4LCamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, framerate=cfg.CAMERA_FRAMERATE)\n elif cfg.CAMERA_TYPE == \"MOCK\":\n from donkeycar.parts.camera import MockCamera\n cam = MockCamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH)\n elif cfg.CAMERA_TYPE == \"IMAGE_LIST\":\n from donkeycar.parts.camera import ImageListCamera\n cam = ImageListCamera(path_mask=cfg.PATH_MASK)\n elif cfg.CAMERA_TYPE == \"LEOPARD\":\n from donkeycar.parts.leopard_imaging import LICamera\n cam = LICamera(width=cfg.IMAGE_W, height=cfg.IMAGE_H, fps=cfg.CAMERA_FRAMERATE)\n else:\n raise(Exception(\"Unkown camera type: %s\" % cfg.CAMERA_TYPE))\n\n \n # Donkey gym part will output position information if it is configured\n if cfg.DONKEY_GYM:\n if cfg.SIM_RECORD_LOCATION:\n outputs += ['pos/pos_x', 'pos/pos_y', 'pos/pos_z', 'pos/speed', 'pos/cte']\n if cfg.SIM_RECORD_GYROACCEL:\n outputs += ['gyro/gyro_x', 'gyro/gyro_y', 'gyro/gyro_z', 'accel/accel_x', 'accel/accel_y', 'accel/accel_z']\n if cfg.SIM_RECORD_VELOCITY:\n outputs += ['vel/vel_x', 'vel/vel_y', 'vel/vel_z']\n if cfg.SIM_RECORD_LIDAR:\n outputs += ['lidar/dist_array']\n \n V.add(cam, inputs=inputs, outputs=outputs, threaded=threaded)\n\n # add lidar\n if cfg.USE_LIDAR:\n from donkeycar.parts.lidar import RPLidar\n if cfg.LIDAR_TYPE == 'RP':\n print(\"adding RP lidar part\")\n lidar = RPLidar(lower_limit = cfg.LIDAR_LOWER_LIMIT, upper_limit = cfg.LIDAR_UPPER_LIMIT)\n V.add(lidar, inputs=[],outputs=['lidar/dist_array'], threaded=True)\n if cfg.LIDAR_TYPE == 'YD':\n print(\"YD Lidar not yet supported\")\n \n if cfg.SHOW_FPS:\n from donkeycar.parts.fps import FrequencyLogger\n V.add(FrequencyLogger(cfg.FPS_DEBUG_INTERVAL), outputs=[\"fps/current\", \"fps/fps_list\"])\n\n#This web controller will create a web server that is capable\n #of managing steering, throttle, and modes, and more.\n ctr = LocalWebController(port=cfg.WEB_CONTROL_PORT, mode=cfg.WEB_INIT_MODE)\n \n V.add(ctr,\n inputs=['cam/image_array', 'tub/num_records', 'user/mode', 'recording'],\n outputs=['user/angle', 'user/throttle', 'user/mode', 'recording'],\n threaded=True)\n \n if use_joystick or cfg.USE_JOYSTICK_AS_DEFAULT:\n #modify max_throttle closer to 1.0 to have more power\n #modify steering_scale lower than 1.0 to have less responsive steering\n if cfg.CONTROLLER_TYPE == \"pigpio_rc\": # an RC controllers read by GPIO pins. They typically don't have buttons\n from donkeycar.parts.controller import RCReceiver\n ctr = RCReceiver(cfg)\n V.add(\n ctr,\n inputs=['user/mode', 'recording'], \n outputs=['user/angle', 'user/throttle', 'user/mode', 'recording'],\n threaded=False)\n else:\n if cfg.CONTROLLER_TYPE == \"custom\": #custom controller created with `donkey createjs` command\n from my_joystick import MyJoystickController\n ctr = MyJoystickController(\n throttle_dir=cfg.JOYSTICK_THROTTLE_DIR,\n throttle_scale=cfg.JOYSTICK_MAX_THROTTLE,\n steering_scale=cfg.JOYSTICK_STEERING_SCALE,\n auto_record_on_throttle=cfg.AUTO_RECORD_ON_THROTTLE)\n ctr.set_deadzone(cfg.JOYSTICK_DEADZONE) \n elif cfg.CONTROLLER_TYPE == \"MM1\":\n from donkeycar.parts.robohat import RoboHATController \n ctr = RoboHATController(cfg)\n else:\n from donkeycar.parts.controller import get_js_controller\n ctr = get_js_controller(cfg)\n if cfg.USE_NETWORKED_JS:\n from donkeycar.parts.controller import JoyStickSub\n netwkJs = JoyStickSub(cfg.NETWORK_JS_SERVER_IP)\n V.add(netwkJs, threaded=True)\n ctr.js = netwkJs\n V.add(\n ctr, \n inputs=['cam/image_array', 'user/mode', 'recording'], \n outputs=['user/angle', 'user/throttle', 'user/mode', 'recording'],\n threaded=True)\n \n\n #this throttle filter will allow one tap back for esc reverse\n th_filter = ThrottleFilter()\n V.add(th_filter, inputs=['user/throttle'], outputs=['user/throttle'])\n\n #See if we should even run the pilot module.\n #This is only needed because the part run_condition only accepts boolean\n class PilotCondition:\n def run(self, mode):\n if mode == 'user':\n return False\n else:\n return True\n\n V.add(PilotCondition(), inputs=['user/mode'], outputs=['run_pilot'])\n\n class LedConditionLogic:\n def __init__(self, cfg):\n self.cfg = cfg\n\n def run(self, mode, recording, recording_alert, behavior_state, model_file_changed, track_loc):\n #returns a blink rate. 0 for off. -1 for on. positive for rate.\n\n if track_loc is not None:\n led.set_rgb(*self.cfg.LOC_COLORS[track_loc])\n return -1\n\n if model_file_changed:\n led.set_rgb(self.cfg.MODEL_RELOADED_LED_R, self.cfg.MODEL_RELOADED_LED_G, self.cfg.MODEL_RELOADED_LED_B)\n return 0.1\n else:\n led.set_rgb(self.cfg.LED_R, self.cfg.LED_G, self.cfg.LED_B)\n\n if recording_alert:\n led.set_rgb(*recording_alert)\n return self.cfg.REC_COUNT_ALERT_BLINK_RATE\n else:\n led.set_rgb(self.cfg.LED_R, self.cfg.LED_G, self.cfg.LED_B)\n\n if behavior_state is not None and model_type == 'behavior':\n r, g, b = self.cfg.BEHAVIOR_LED_COLORS[behavior_state]\n led.set_rgb(r, g, b)\n return -1 #solid on\n\n if recording:\n return -1 #solid on\n elif mode == 'user':\n return 1\n elif mode == 'local_angle':\n return 0.5\n elif mode == 'local':\n return 0.1\n return 0\n\n if cfg.HAVE_RGB_LED and not cfg.DONKEY_GYM:\n from donkeycar.parts.led_status import RGB_LED\n led = RGB_LED(cfg.LED_PIN_R, cfg.LED_PIN_G, cfg.LED_PIN_B, cfg.LED_INVERT)\n led.set_rgb(cfg.LED_R, cfg.LED_G, cfg.LED_B)\n\n V.add(LedConditionLogic(cfg), inputs=['user/mode', 'recording', \"records/alert\", 'behavior/state', 'modelfile/modified', \"pilot/loc\"],\n outputs=['led/blink_rate'])\n\n V.add(led, inputs=['led/blink_rate'])\n\n def get_record_alert_color(num_records):\n col = (0, 0, 0)\n for count, color in cfg.RECORD_ALERT_COLOR_ARR:\n if num_records >= count:\n col = color\n return col\n\n class RecordTracker:\n def __init__(self):\n self.last_num_rec_print = 0\n self.dur_alert = 0\n self.force_alert = 0\n\n def run(self, num_records):\n if num_records is None:\n return 0\n\n if self.last_num_rec_print != num_records or self.force_alert:\n self.last_num_rec_print = num_records\n\n if num_records % 10 == 0:\n print(\"recorded\", num_records, \"records\")\n\n if num_records % cfg.REC_COUNT_ALERT == 0 or self.force_alert:\n self.dur_alert = num_records // cfg.REC_COUNT_ALERT * cfg.REC_COUNT_ALERT_CYC\n self.force_alert = 0\n\n if self.dur_alert > 0:\n self.dur_alert -= 1\n\n if self.dur_alert != 0:\n return get_record_alert_color(num_records)\n\n return 0\n\n rec_tracker_part = RecordTracker()\n V.add(rec_tracker_part, inputs=[\"tub/num_records\"], outputs=['records/alert'])\n\n if cfg.AUTO_RECORD_ON_THROTTLE:\n def show_record_count_status():\n rec_tracker_part.last_num_rec_print = 0\n rec_tracker_part.force_alert = 1\n if (cfg.CONTROLLER_TYPE != \"pigpio_rc\") and (cfg.CONTROLLER_TYPE != \"MM1\"): # these controllers don't use the joystick class\n if isinstance(ctr, JoystickController):\n ctr.set_button_down_trigger('circle', show_record_count_status) #then we are not using the circle button. hijack that to force a record count indication\n else:\n \n show_record_count_status()\n\n #Sombrero\n if cfg.HAVE_SOMBRERO:\n from donkeycar.parts.sombrero import Sombrero\n s = Sombrero()\n\n #IMU\n if cfg.HAVE_IMU:\n from donkeycar.parts.imu import IMU\n imu = IMU(sensor=cfg.IMU_SENSOR, dlp_setting=cfg.IMU_DLP_CONFIG)\n V.add(imu, outputs=['imu/acl_x', 'imu/acl_y', 'imu/acl_z',\n 'imu/gyr_x', 'imu/gyr_y', 'imu/gyr_z'], threaded=True)\n\n # Use the FPV preview, which will show the cropped image output, or the full frame.\n if cfg.USE_FPV:\n V.add(WebFpv(), inputs=['cam/image_array'], threaded=True)\n\n #Behavioral state\n if cfg.TRAIN_BEHAVIORS:\n bh = BehaviorPart(cfg.BEHAVIOR_LIST)\n V.add(bh, outputs=['behavior/state', 'behavior/label', \"behavior/one_hot_state_array\"])\n try:\n ctr.set_button_down_trigger('L1', bh.increment_state)\n except:\n pass\n\n inputs = ['cam/image_array', \"behavior/one_hot_state_array\"]\n #IMU\n elif cfg.USE_LIDAR:\n inputs = ['cam/image_array', 'lidar/dist_array']\n\n elif cfg.HAVE_ODOM:\n inputs = ['cam/image_array', 'enc/speed']\n\n elif model_type == \"imu\":\n assert cfg.HAVE_IMU, 'Missing imu parameter in config'\n # Run the pilot if the mode is not user.\n inputs = ['cam/image_array',\n 'imu/acl_x', 'imu/acl_y', 'imu/acl_z',\n 'imu/gyr_x', 'imu/gyr_y', 'imu/gyr_z']\n\n else:\n inputs = ['cam/image_array']\n\n def load_model(kl, model_path):\n start = time.time()\n print('loading model', model_path)\n kl.load(model_path)\n print('finished loading in %s sec.' % (str(time.time() - start)) )\n\n def load_weights(kl, weights_path):\n start = time.time()\n try:\n print('loading model weights', weights_path)\n kl.model.load_weights(weights_path)\n print('finished loading in %s sec.' % (str(time.time() - start)) )\n except Exception as e:\n print(e)\n print('ERR>> problems loading weights', weights_path)\n\n def load_model_json(kl, json_fnm):\n start = time.time()\n print('loading model json', json_fnm)\n from tensorflow.python import keras\n try:\n with open(json_fnm, 'r') as handle:\n contents = handle.read()\n kl.model = keras.models.model_from_json(contents)\n print('finished loading json in %s sec.' % (str(time.time() - start)) )\n except Exception as e:\n print(e)\n print(\"ERR>> problems loading model json\", json_fnm)\n\n if model_path:\n # When we have a model, first create an appropriate Keras part\n kl = dk.utils.get_model_by_type(model_type, cfg)\n\n model_reload_cb = None\n\n if '.h5' in model_path or '.trt' in model_path or '.tflite' in \\\n model_path or '.savedmodel' in model_path:\n # load the whole model with weigths, etc\n load_model(kl, model_path)\n\n def reload_model(filename):\n load_model(kl, filename)\n\n model_reload_cb = reload_model\n\n elif '.json' in model_path:\n # when we have a .json extension\n # load the model from there and look for a matching\n # .wts file with just weights\n load_model_json(kl, model_path)\n weights_path = model_path.replace('.json', '.weights')\n load_weights(kl, weights_path)\n\n def reload_weights(filename):\n weights_path = filename.replace('.json', '.weights')\n load_weights(kl, weights_path)\n\n model_reload_cb = reload_weights\n\n else:\n print(\"ERR>> Unknown extension type on model file!!\")\n return\n\n # this part will signal visual LED, if connected\n V.add(FileWatcher(model_path, verbose=True),\n outputs=['modelfile/modified'])\n\n # these parts will reload the model file, but only when ai is running\n # so we don't interrupt user driving\n V.add(FileWatcher(model_path), outputs=['modelfile/dirty'],\n run_condition=\"ai_running\")\n V.add(DelayedTrigger(100), inputs=['modelfile/dirty'],\n outputs=['modelfile/reload'], run_condition=\"ai_running\")\n V.add(TriggeredCallback(model_path, model_reload_cb),\n inputs=[\"modelfile/reload\"], run_condition=\"ai_running\")\n\n outputs = ['pilot/angle', 'pilot/throttle']\n\n if cfg.TRAIN_LOCALIZER:\n outputs.append(\"pilot/loc\")\n # Add image transformations like crop or trapezoidal mask\n if hasattr(cfg, 'TRANSFORMATIONS') and cfg.TRANSFORMATIONS:\n from donkeycar.pipeline.augmentations import ImageAugmentation\n V.add(ImageAugmentation(cfg, 'TRANSFORMATIONS'),\n inputs=['cam/image_array'], outputs=['cam/image_array_trans'])\n inputs = ['cam/image_array_trans'] + inputs[1:]\n\n V.add(kl, inputs=inputs, outputs=outputs, run_condition='run_pilot')\n\n if cfg.STOP_SIGN_DETECTOR:\n from donkeycar.parts.object_detector.stop_sign_detector \\\n import StopSignDetector\n V.add(StopSignDetector(cfg.STOP_SIGN_MIN_SCORE,\n cfg.STOP_SIGN_SHOW_BOUNDING_BOX,\n cfg.STOP_SIGN_MAX_REVERSE_COUNT,\n cfg.STOP_SIGN_REVERSE_THROTTLE),\n inputs=['cam/image_array', 'pilot/throttle'],\n outputs=['pilot/throttle', 'cam/image_array'])\n V.add(ThrottleFilter(), \n inputs=['pilot/throttle'],\n outputs=['pilot/throttle'])\n\n # Choose what inputs should change the car.\n class DriveMode:\n def run(self, mode,\n user_angle, user_throttle,\n pilot_angle, pilot_throttle):\n if mode == 'user':\n return user_angle, user_throttle\n\n elif mode == 'local_angle':\n return pilot_angle if pilot_angle else 0.0, user_throttle\n\n else:\n return pilot_angle if pilot_angle else 0.0, \\\n pilot_throttle * cfg.AI_THROTTLE_MULT \\\n if pilot_throttle else 0.0\n\n V.add(DriveMode(),\n inputs=['user/mode', 'user/angle', 'user/throttle',\n 'pilot/angle', 'pilot/throttle'],\n outputs=['angle', 'throttle'])\n\n\n #to give the car a boost when starting ai mode in a race.\n aiLauncher = AiLaunch(cfg.AI_LAUNCH_DURATION, cfg.AI_LAUNCH_THROTTLE, cfg.AI_LAUNCH_KEEP_ENABLED)\n\n V.add(aiLauncher,\n inputs=['user/mode', 'throttle'],\n outputs=['throttle'])\n\n if (cfg.CONTROLLER_TYPE != \"pigpio_rc\") and (cfg.CONTROLLER_TYPE != \"MM1\"):\n if isinstance(ctr, JoystickController):\n ctr.set_button_down_trigger(cfg.AI_LAUNCH_ENABLE_BUTTON, aiLauncher.enable_ai_launch)\n\n class AiRunCondition:\n '''\n A bool part to let us know when ai is running.\n '''\n def run(self, mode):\n if mode == \"user\":\n return False\n return True\n\n V.add(AiRunCondition(), inputs=['user/mode'], outputs=['ai_running'])\n\n # Ai Recording\n class AiRecordingCondition:\n '''\n return True when ai mode, otherwize respect user mode recording flag\n '''\n def run(self, mode, recording):\n if mode == 'user':\n return recording\n return True\n\n if cfg.RECORD_DURING_AI:\n V.add(AiRecordingCondition(), inputs=['user/mode', 'recording'], outputs=['recording'])\n\n # Drive train setup\n if cfg.DONKEY_GYM or cfg.DRIVE_TRAIN_TYPE == \"MOCK\":\n pass\n elif cfg.DRIVE_TRAIN_TYPE == \"PWM_STEERING_THROTTLE\":\n #\n # drivetrain for RC car with servo and ESC.\n # using a PwmPin for steering (servo)\n # and as second PwmPin for throttle (ESC)\n #\n from donkeycar.parts.actuator import PWMSteering, PWMThrottle, PulseController\n steering_controller = PulseController(\n pwm_pin=pins.pwm_pin_by_id(cfg.PWM_STEERING_PIN),\n pwm_scale=cfg.PWM_STEERING_SCALE, \n pwm_inverted=cfg.PWM_STEERING_INVERTED)\n steering = PWMSteering(controller=steering_controller,\n left_pulse=cfg.STEERING_LEFT_PWM, \n right_pulse=cfg.STEERING_RIGHT_PWM)\n \n throttle_controller = PulseController(\n pwm_pin=pins.pwm_pin_by_id(cfg.PWM_THROTTLE_PIN), \n pwm_scale=cfg.PWM_THROTTLE_SCALE, \n pwm_inverted=cfg.PWM_THROTTLE_INVERTED)\n throttle = PWMThrottle(controller=throttle_controller,\n max_pulse=cfg.THROTTLE_FORWARD_PWM,\n zero_pulse=cfg.THROTTLE_STOPPED_PWM, \n min_pulse=cfg.THROTTLE_REVERSE_PWM)\n V.add(steering, inputs=['angle'], threaded=True)\n V.add(throttle, inputs=['throttle'], threaded=True)\n\n elif cfg.DRIVE_TRAIN_TYPE == \"I2C_SERVO\":\n #\n # Thi driver is DEPRECATED in favor of 'DRIVE_TRAIN_TYPE == \"PWM_STEERING_THROTTLE\"'\n # This driver will be removed in a future release\n #\n from donkeycar.parts.actuator import PCA9685, PWMSteering, PWMThrottle\n\n steering_controller = PCA9685(cfg.STEERING_CHANNEL, cfg.PCA9685_I2C_ADDR, busnum=cfg.PCA9685_I2C_BUSNUM)\n steering = PWMSteering(controller=steering_controller,\n left_pulse=cfg.STEERING_LEFT_PWM,\n right_pulse=cfg.STEERING_RIGHT_PWM)\n\n throttle_controller = PCA9685(cfg.THROTTLE_CHANNEL, cfg.PCA9685_I2C_ADDR, busnum=cfg.PCA9685_I2C_BUSNUM)\n throttle = PWMThrottle(controller=throttle_controller,\n max_pulse=cfg.THROTTLE_FORWARD_PWM,\n zero_pulse=cfg.THROTTLE_STOPPED_PWM,\n min_pulse=cfg.THROTTLE_REVERSE_PWM)\n\n V.add(steering, inputs=['angle'], threaded=True)\n V.add(throttle, inputs=['throttle'], threaded=True)\n\n elif cfg.DRIVE_TRAIN_TYPE == \"DC_STEER_THROTTLE\":\n steering = actuator.L298N_HBridge_2pin(\n pins.pwm_pin_by_id(cfg.HBRIDGE_PIN_LEFT), \n pins.pwm_pin_by_id(cfg.HBRIDGE_PIN_RIGHT))\n throttle = Mini_HBridge_DC_Motor_PWM(\n pins.pwm_pin_by_id(cfg.HBRIDGE_PIN_FWD), \n pins.pwm_pin_by_id(cfg.HBRIDGE_PIN_BWD))\n\n V.add(steering, inputs=['angle'])\n V.add(throttle, inputs=['throttle'])\n\n elif cfg.DRIVE_TRAIN_TYPE == \"DC_TWO_WHEEL\":\n left_motor = actuator.L298N_HBridge_2pin(\n pins.pwm_pin_by_id(cfg.HBRIDGE_PIN_LEFT_FWD), \n pins.pwm_pin_by_id(cfg.HBRIDGE_PIN_LEFT_BWD))\n right_motor = actuator.L298N_HBridge_2pin(\n pins.pwm_pin_by_id(cfg.HBRIDGE_PIN_RIGHT_FWD), \n pins.pwm_pin_by_id(cfg.HBRIDGE_PIN_RIGHT_BWD))\n\n two_wheel_control = actuator.TwoWheelSteeringThrottle()\n\n V.add(two_wheel_control,\n inputs=['throttle', 'angle'],\n outputs=['left_motor_speed', 'right_motor_speed'])\n\n V.add(left_motor, inputs=['left_motor_speed'])\n V.add(right_motor, inputs=['right_motor_speed'])\n\n elif cfg.DRIVE_TRAIN_TYPE == \"DC_TWO_WHEEL_L298N\":\n left_motor = actuator.L298N_HBridge_3pin(\n pins.output_pin_by_id(cfg.HBRIDGE_L298N_PIN_LEFT_FWD), \n pins.output_pin_by_id(cfg.HBRIDGE_L298N_PIN_LEFT_BWD), \n pins.pwm_pin_by_id(cfg.HBRIDGE_L298N_PIN_LEFT_EN))\n right_motor = actuator.L298N_HBridge_3pin(\n pins.output_pin_by_id(cfg.HBRIDGE_L298N_PIN_RIGHT_FWD), \n pins.output_pin_by_id(cfg.HBRIDGE_L298N_PIN_RIGHT_BWD), \n pins.pwm_pin_by_id(cfg.HBRIDGE_L298N_PIN_RIGHT_EN))\n\n two_wheel_control = actuator.TwoWheelSteeringThrottle()\n\n V.add(two_wheel_control,\n inputs=['throttle', 'angle'],\n outputs=['left_motor_speed', 'right_motor_speed'])\n\n V.add(left_motor, inputs=['left_motor_speed'])\n V.add(right_motor, inputs=['right_motor_speed'])\n\n elif cfg.DRIVE_TRAIN_TYPE == \"SERVO_HBRIDGE_2PIN\":\n #\n # Servo for steering and HBridge motor driver in 2pin mode for motor\n #\n from donkeycar.parts.actuator import PWMSteering, PWMThrottle, PulseController\n steering_controller = PulseController(\n pwm_pin=pins.pwm_pin_by_id(cfg.PWM_STEERING_PIN),\n pwm_scale=cfg.PWM_STEERING_SCALE, \n pwm_inverted=cfg.PWM_STEERING_INVERTED)\n steering = PWMSteering(controller=steering_controller,\n left_pulse=cfg.STEERING_LEFT_PWM, \n right_pulse=cfg.STEERING_RIGHT_PWM)\n\n motor = actuator.L298N_HBridge_2pin(\n pins.pwm_pin_by_id(cfg.HBRIDGE_2PIN_DUTY_FWD), \n pins.pwm_pin_by_id(cfg.HBRIDGE_2PIN_DUTY_BWD))\n\n V.add(steering, inputs=['angle'], threaded=True)\n V.add(motor, inputs=[\"throttle\"])\n \n elif cfg.DRIVE_TRAIN_TYPE == \"SERVO_HBRIDGE_3PIN\":\n #\n # Servo for steering and HBridge motor driver in 3pin mode for motor\n #\n from donkeycar.parts.actuator import PWMSteering, PWMThrottle, PulseController\n steering_controller = PulseController(\n pwm_pin=pins.pwm_pin_by_id(cfg.PWM_STEERING_PIN),\n pwm_scale=cfg.PWM_STEERING_SCALE, \n pwm_inverted=cfg.PWM_STEERING_INVERTED)\n steering = PWMSteering(controller=steering_controller,\n left_pulse=cfg.STEERING_LEFT_PWM, \n right_pulse=cfg.STEERING_RIGHT_PWM)\n\n motor = actuator.L298N_HBridge_3pin(\n pins.output_pin_by_id(cfg.HBRIDGE_3PIN_FWD), \n pins.output_pin_by_id(cfg.HBRIDGE_3PIN_BWD), \n pins.pwm_pin_by_id(cfg.HBRIDGE_3PIN_DUTY))\n\n V.add(steering, inputs=['angle'], threaded=True)\n V.add(motor, inputs=[\"throttle\"])\n \n elif cfg.DRIVE_TRAIN_TYPE == \"SERVO_HBRIDGE_PWM\":\n #\n # Thi driver is DEPRECATED in favor of 'DRIVE_TRAIN_TYPE == \"SERVO_HBRIDGE_2PIN\"'\n # This driver will be removed in a future release\n #\n from donkeycar.parts.actuator import ServoBlaster, PWMSteering\n steering_controller = ServoBlaster(cfg.STEERING_CHANNEL) #really pin\n # PWM pulse values should be in the range of 100 to 200\n assert(cfg.STEERING_LEFT_PWM <= 200)\n assert(cfg.STEERING_RIGHT_PWM <= 200)\n steering = PWMSteering(controller=steering_controller,\n left_pulse=cfg.STEERING_LEFT_PWM,\n right_pulse=cfg.STEERING_RIGHT_PWM)\n\n from donkeycar.parts.actuator import Mini_HBridge_DC_Motor_PWM\n motor = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_FWD, cfg.HBRIDGE_PIN_BWD)\n\n V.add(steering, inputs=['angle'], threaded=True)\n V.add(motor, inputs=[\"throttle\"])\n \n elif cfg.DRIVE_TRAIN_TYPE == \"MM1\":\n from donkeycar.parts.robohat import RoboHATDriver\n V.add(RoboHATDriver(cfg), inputs=['angle', 'throttle'])\n \n elif cfg.DRIVE_TRAIN_TYPE == \"PIGPIO_PWM\":\n #\n # Thi driver is DEPRECATED in favor of 'DRIVE_TRAIN_TYPE == \"PWM_STEERING_THROTTLE\"'\n # This driver will be removed in a future release\n #\n from donkeycar.parts.actuator import PWMSteering, PWMThrottle, PiGPIO_PWM\n steering_controller = PiGPIO_PWM(cfg.STEERING_PWM_PIN, freq=cfg.STEERING_PWM_FREQ, inverted=cfg.STEERING_PWM_INVERTED)\n steering = PWMSteering(controller=steering_controller,\n left_pulse=cfg.STEERING_LEFT_PWM, \n right_pulse=cfg.STEERING_RIGHT_PWM)\n \n throttle_controller = PiGPIO_PWM(cfg.THROTTLE_PWM_PIN, freq=cfg.THROTTLE_PWM_FREQ, inverted=cfg.THROTTLE_PWM_INVERTED)\n throttle = PWMThrottle(controller=throttle_controller,\n max_pulse=cfg.THROTTLE_FORWARD_PWM,\n zero_pulse=cfg.THROTTLE_STOPPED_PWM, \n min_pulse=cfg.THROTTLE_REVERSE_PWM)\n V.add(steering, inputs=['angle'], threaded=True)\n V.add(throttle, inputs=['throttle'], threaded=True)\n\n # OLED setup\n if cfg.USE_SSD1306_128_32:\n from donkeycar.parts.oled import OLEDPart\n auto_record_on_throttle = cfg.USE_JOYSTICK_AS_DEFAULT and cfg.AUTO_RECORD_ON_THROTTLE\n oled_part = OLEDPart(cfg.SSD1306_128_32_I2C_ROTATION, cfg.SSD1306_RESOLUTION, auto_record_on_throttle)\n V.add(oled_part, inputs=['recording', 'tub/num_records', 'user/mode'], outputs=[], threaded=True)\n\n # add tub to save data\n\n if cfg.USE_LIDAR:\n inputs = ['cam/image_array', 'lidar/dist_array', 'user/angle', 'user/throttle', 'user/mode']\n types = ['image_array', 'nparray','float', 'float', 'str']\n else:\n inputs=['cam/image_array','user/angle', 'user/throttle', 'user/mode']\n types=['image_array','float', 'float','str']\n\n if cfg.HAVE_ODOM:\n inputs += ['enc/speed']\n types += ['float']\n\n if cfg.TRAIN_BEHAVIORS:\n inputs += ['behavior/state', 'behavior/label', \"behavior/one_hot_state_array\"]\n types += ['int', 'str', 'vector']\n\n if cfg.CAMERA_TYPE == \"D435\" and cfg.REALSENSE_D435_DEPTH:\n inputs += ['cam/depth_array']\n types += ['gray16_array']\n\n if cfg.HAVE_IMU or (cfg.CAMERA_TYPE == \"D435\" and cfg.REALSENSE_D435_IMU):\n inputs += ['imu/acl_x', 'imu/acl_y', 'imu/acl_z',\n 'imu/gyr_x', 'imu/gyr_y', 'imu/gyr_z']\n\n types +=['float', 'float', 'float',\n 'float', 'float', 'float']\n\n # rbx\n if cfg.DONKEY_GYM:\n if cfg.SIM_RECORD_LOCATION: \n inputs += ['pos/pos_x', 'pos/pos_y', 'pos/pos_z', 'pos/speed', 'pos/cte']\n types += ['float', 'float', 'float', 'float', 'float']\n if cfg.SIM_RECORD_GYROACCEL: \n inputs += ['gyro/gyro_x', 'gyro/gyro_y', 'gyro/gyro_z', 'accel/accel_x', 'accel/accel_y', 'accel/accel_z']\n types += ['float', 'float', 'float', 'float', 'float', 'float']\n if cfg.SIM_RECORD_VELOCITY: \n inputs += ['vel/vel_x', 'vel/vel_y', 'vel/vel_z']\n types += ['float', 'float', 'float']\n if cfg.SIM_RECORD_LIDAR:\n inputs += ['lidar/dist_array']\n types += ['nparray']\n\n if cfg.RECORD_DURING_AI:\n inputs += ['pilot/angle', 'pilot/throttle']\n types += ['float', 'float']\n\n if cfg.HAVE_PERFMON:\n from donkeycar.parts.perfmon import PerfMonitor\n mon = PerfMonitor(cfg)\n perfmon_outputs = ['perf/cpu', 'perf/mem', 'perf/freq']\n inputs += perfmon_outputs\n types += ['float', 'float', 'float']\n V.add(mon, inputs=[], outputs=perfmon_outputs, threaded=True)\n\n # do we want to store new records into own dir or append to existing\n tub_path = TubHandler(path=cfg.DATA_PATH).create_tub_path() if \\\n cfg.AUTO_CREATE_NEW_TUB else cfg.DATA_PATH\n tub_writer = TubWriter(tub_path, inputs=inputs, types=types, metadata=meta)\n V.add(tub_writer, inputs=inputs, outputs=[\"tub/num_records\"], run_condition='recording')\n\n # Telemetry (we add the same metrics added to the TubHandler\n if cfg.HAVE_MQTT_TELEMETRY:\n telem_inputs, _ = tel.add_step_inputs(inputs, types)\n V.add(tel, inputs=telem_inputs, outputs=[\"tub/queue_size\"], threaded=True)\n\n if cfg.PUB_CAMERA_IMAGES:\n from donkeycar.parts.network import TCPServeValue\n from donkeycar.parts.image import ImgArrToJpg\n pub = TCPServeValue(\"camera\")\n V.add(ImgArrToJpg(), inputs=['cam/image_array'], outputs=['jpg/bin'])\n V.add(pub, inputs=['jpg/bin'])\n\n if type(ctr) is LocalWebController:\n if cfg.DONKEY_GYM:\n print(\"You can now go to http://localhost:%d to drive your car.\" % cfg.WEB_CONTROL_PORT)\n else:\n print(\"You can now go to <your hostname.local>:%d to drive your car.\" % cfg.WEB_CONTROL_PORT) \n elif (cfg.CONTROLLER_TYPE != \"pigpio_rc\") and (cfg.CONTROLLER_TYPE != \"MM1\"):\n if isinstance(ctr, JoystickController):\n print(\"You can now move your joystick to drive your car.\")\n ctr.set_tub(tub_writer.tub)\n ctr.print_controls()\n\n # run the vehicle\n V.start(rate_hz=cfg.DRIVE_LOOP_HZ, max_loop_count=cfg.MAX_LOOPS)\n\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n cfg = dk.load_config(myconfig=args['--myconfig'])\n\n if args['drive']:\n model_type = args['--type']\n camera_type = args['--camera']\n drive(cfg, model_path=args['--model'], use_joystick=args['--js'],\n model_type=model_type, camera_type=camera_type,\n meta=args['--meta'])\n elif args['train']:\n print('Use python train.py instead.\\n')\n" ]
[ [ "tensorflow.python.keras.models.model_from_json" ] ]
Taemin0707/uncertainty_for_robot
[ "381ee3e399a804a4b94d3c09b40ff45c996347f7" ]
[ "uncertainty_of_deeplearning/src/gui_number_recognizer_cnn.py" ]
[ "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThis program creates a Number-Recognizer.\n\nAuthor: Taemin Choi\nEmail: [email protected]\nLast edited: November 2018\n\"\"\"\n\nimport os\nimport sys\nimport time\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import *\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom PIL import Image\nfrom PIL import ImageQt\nfrom PIL import ImageDraw\nimport numpy as np\nimport tensorflow as tf\n\nclass NumberRecognizer(object):\n \"\"\"\n\n \"\"\"\n def __init__(self):\n # print(sys.version)\n # for reproducibility\n tf.set_random_seed(777)\n\n def predict_with_dropout(self, image):\n # 예측용 이미지 데이터 처리\n self.test_input = []\n test_image = image\n self.test_input.append(np.array(test_image))\n self.test_input = np.reshape(self.test_input, (-1, 784))\n print(\"테스트 이미지 = \", self.test_input.shape)\n\n tf.reset_default_graph()\n\n # input place holders\n X = tf.placeholder(tf.float32, [None, 784])\n X_img = tf.reshape(X, [-1, 28, 28, 1]) # img 28x28x1 (black/white)\n\n # dropout (keep_prob) rate 0.7 on training, but should be 1 for testing\n keep_prob = tf.placeholder(tf.float32)\n\n # dropout (keep_prob) rate 0.7 on training, but should be 1 for testing\n keep_prob = tf.placeholder(tf.float32)\n\n # L1 ImgIn shape=(?, 28, 28, 1)\n W1 = tf.Variable(tf.random_normal([3, 3, 1, 32], stddev=0.01))\n # Conv -> (?, 28, 28, 32)\n # Pool -> (?, 14, 14, 32)\n L1 = tf.nn.conv2d(X_img, W1, strides=[1, 1, 1, 1], padding='SAME')\n L1 = tf.nn.relu(L1)\n L1 = tf.nn.max_pool(L1, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n L1 = tf.nn.dropout(L1, keep_prob=keep_prob)\n '''\n Tensor(\"Conv2D:0\", shape=(?, 28, 28, 32), dtype=float32)\n Tensor(\"Relu:0\", shape=(?, 28, 28, 32), dtype=float32)\n Tensor(\"MaxPool:0\", shape=(?, 14, 14, 32), dtype=float32)\n Tensor(\"dropout/mul:0\", shape=(?, 14, 14, 32), dtype=float32)\n '''\n\n # L2 ImgIn shape=(?, 14, 14, 32)\n W2 = tf.Variable(tf.random_normal([3, 3, 32, 64], stddev=0.01))\n # Conv ->(?, 14, 14, 64)\n # Pool ->(?, 7, 7, 64)\n L2 = tf.nn.conv2d(L1, W2, strides=[1, 1, 1, 1], padding='SAME')\n L2 = tf.nn.relu(L2)\n L2 = tf.nn.max_pool(L2, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n L2 = tf.nn.dropout(L2, keep_prob=keep_prob)\n '''\n Tensor(\"Conv2D_1:0\", shape=(?, 14, 14, 64), dtype=float32)\n Tensor(\"Relu_1:0\", shape=(?, 14, 14, 64), dtype=float32)\n Tensor(\"MaxPool_1:0\", shape=(?, 7, 7, 64), dtype=float32)\n Tensor(\"dropout_1/mul:0\", shape=(?, 7, 7, 64), dtype=float32)\n '''\n\n # L3 ImgIn shape=(?, 7, 7, 64)\n W3 = tf.Variable(tf.random_normal([3, 3, 64, 128], stddev=0.01))\n # Conv ->(?, 7, 7, 128)\n # Pool ->(?, 4, 4, 128)\n # Reshape ->(?, 4 * 4 * 128) # Flatten them for FC\n L3 = tf.nn.conv2d(L2, W3, strides=[1, 1, 1, 1], padding='SAME')\n L3 = tf.nn.relu(L3)\n L3 = tf.nn.max_pool(L3, ksize=[1, 2, 2, 1], strides=[\n 1, 2, 2, 1], padding='SAME')\n L3 = tf.nn.dropout(L3, keep_prob=keep_prob)\n L3_flat = tf.reshape(L3, [-1, 128 * 4 * 4])\n '''\n Tensor(\"Conv2D_2:0\", shape=(?, 7, 7, 128), dtype=float32)\n Tensor(\"Relu_2:0\", shape=(?, 7, 7, 128), dtype=float32)\n Tensor(\"MaxPool_2:0\", shape=(?, 4, 4, 128), dtype=float32)\n Tensor(\"dropout_2/mul:0\", shape=(?, 4, 4, 128), dtype=float32)\n Tensor(\"Reshape_1:0\", shape=(?, 2048), dtype=float32)\n '''\n\n # L4 FC 4x4x128 inputs -> 625 outputs\n W4 = tf.get_variable(\"W4\", shape=[128 * 4 * 4, 625],\n initializer=tf.contrib.layers.xavier_initializer())\n b4 = tf.Variable(tf.random_normal([625]))\n L4 = tf.nn.relu(tf.matmul(L3_flat, W4) + b4)\n L4 = tf.nn.dropout(L4, keep_prob=keep_prob)\n '''\n Tensor(\"Relu_3:0\", shape=(?, 625), dtype=float32)\n Tensor(\"dropout_3/mul:0\", shape=(?, 625), dtype=float32)\n '''\n\n # L5 Final FC 625 inputs -> 10 outputs\n W5 = tf.get_variable(\"W5\", shape=[625, 10],\n initializer=tf.contrib.layers.xavier_initializer())\n b5 = tf.Variable(tf.random_normal([10]))\n logits = tf.nn.softmax(tf.matmul(L4, W5) + b5)\n\n with tf.Session() as sess:\n\n save_path = './models/recognizer_number_cnn_model'\n new_saver = tf.train.Saver()\n new_saver.restore(sess, save_path)\n\n number_list = []\n number_zero = []\n number_one = []\n number_two = []\n number_three = []\n number_four = []\n number_five = []\n number_six = []\n number_seven = []\n number_eight = []\n number_nine = []\n\n iter = 500\n\n predict_result = sess.run(logits, feed_dict={X: self.test_input.reshape(1, 784), keep_prob: 0.7})\n number = np.where(predict_result[0] == np.max(predict_result[0]))\n\n print(\"-------------------------------------------------------\")\n print(\"number = \", number[0][0])\n\n # for i in range(iter):\n # result = sess.run(hypothesis, feed_dict={X: self.test_input.reshape(1, 784), keep_prob: 0.7})\n # for j in range(10):\n # number_list[j].append(result[0][j])\n\n for i in range(iter):\n result = sess.run(logits, feed_dict={X: self.test_input.reshape(1, 784), keep_prob: 0.7})\n # print(result.shape)\n number_zero.append(result[0][0])\n number_one.append(result[0][1])\n number_two.append(result[0][2])\n number_three.append(result[0][3])\n number_four.append(result[0][4])\n number_five.append(result[0][5])\n number_six.append(result[0][6])\n number_seven.append(result[0][7])\n number_eight.append(result[0][8])\n number_nine.append(result[0][9])\n\n variance_zero = np.var(number_zero)\n variance_one = np.var(number_one)\n variance_two = np.var(number_two)\n variance_three = np.var(number_three)\n variance_four = np.var(number_four)\n variance_five = np.var(number_five)\n variance_six = np.var(number_six)\n variance_seven = np.var(number_seven)\n variance_eight = np.var(number_eight)\n variance_nine = np.var(number_nine)\n\n mean_zero = np.mean(number_zero)\n mean_one = np.mean(number_one)\n mean_two = np.mean(number_two)\n mean_three = np.mean(number_three)\n mean_four = np.mean(number_four)\n mean_five = np.mean(number_five)\n mean_six = np.mean(number_six)\n mean_seven = np.mean(number_seven)\n mean_eight = np.mean(number_eight)\n mean_nine = np.mean(number_nine)\n\n variance = [variance_zero, variance_one, variance_two, variance_three, variance_four,\\\n variance_five, variance_six, variance_seven, variance_eight, variance_nine]\n\n mean = [mean_zero, mean_one, mean_two, mean_three, mean_four, \\\n mean_five, mean_six, mean_seven, mean_eight, mean_nine]\n\n print(\"mean = \", mean)\n print(\"variance = \", variance)\n # index = np.where(variance == np.min(variance))\n # print(\"result = \", index)\n return mean, variance\n\nclass MainWindow(QMainWindow):\n\n def __init__(self, parent=None):\n super(MainWindow, self).__init__(parent)\n self.setWindowTitle(\"Number-Recognizer\")\n self.setGeometry(10, 10, 1280, 960)\n\n self.init_window()\n self.form_widget = FormWidget(self)\n self.setCentralWidget(self.form_widget)\n\n def init_window(self):\n # 메뉴바\n menubar = self.menuBar()\n fileMenu = menubar.addMenu('File')\n importMenu = menubar.addMenu('Import')\n\n # 서브 메뉴들\n newAct = QAction('New', self)\n newAct.triggered.connect(self.btn1_clicked)\n fileMenu.addAction(newAct)\n\n impAct = QAction('Import image', self)\n impAct.triggered.connect(self.import_btn_clicked)\n fileMenu.addAction(impAct)\n\n saveAct = QAction('Save result', self)\n saveAct.triggered.connect(self.btn1_clicked)\n fileMenu.addAction(saveAct)\n\n closeAct = QAction('Close', self)\n closeAct.triggered.connect(self.btn1_clicked)\n fileMenu.addAction(closeAct)\n\n def import_btn_clicked(self):\n fname = QFileDialog.getOpenFileName()\n\n def btn1_clicked(self):\n QMessageBox.about(self, \"message\", \"clicked\")\n\n def closeEvent(self, event):\n reply = QMessageBox.question(self, 'Message',\n \"Are you sure to quit?\", QMessageBox.Yes |\n QMessageBox.No, QMessageBox.No)\n\n if reply == QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n\nclass FormWidget(QWidget):\n\n def __init__(self, parent):\n super(FormWidget, self).__init__(parent)\n self.main_image_path = \"/home/taemin/images/kist.jpg\"\n self.main_image = Image.open(self.main_image_path)\n self.init_widget()\n self.number_recognizer = NumberRecognizer()\n self.rectangle_size = 28\n # sweep 정보 저장을 위한 빈 리스트\n self.mean_data_list = []\n self.variance_data_list = []\n\n def init_widget(self):\n # 이미지 라벨\n self.main_image_label = QLabel(self)\n pixmap = QPixmap(self.main_image_path)\n self.main_image_label.setPixmap(pixmap)\n self.main_image_label.resize(pixmap.width(), pixmap.height())\n\n # 박스크기 정하는 슬라이드 위젯\n self.slide = QSlider(Qt.Horizontal)\n self.slide.setMinimum(10)\n self.slide.setMaximum(50)\n self.slide.setValue(28)\n self.slide.setTickPosition(QSlider.TicksBelow)\n self.slide.setTickInterval(5)\n self.slide.setFocusPolicy(Qt.NoFocus)\n self.slide.valueChanged.connect(self.change_slide_value)\n\n # 박스크기를 보여주는 위젯\n self.text_label = QLabel(\"Box Size = \")\n self.box_size_label = QLabel(\"28\", self)\n\n # 버튼\n self.rotate_left = QPushButton(\"Rotate Left\")\n self.new_image = QPushButton(\"New Image\")\n self.rotate_right = QPushButton(\"Rotate Right\")\n\n self.draw = QPushButton(\"Draw_Rectangle\")\n self.move_up = QPushButton(\"Move Up\")\n self.crop = QPushButton(\"Crop_image\")\n\n self.move_left = QPushButton(\"Move Left\")\n self.calculate = QPushButton(\"Calculate\")\n self.move_right = QPushButton(\"Move Right\")\n\n self.init = QPushButton(\"Init_Rectangle\")\n self.move_down = QPushButton(\"Move Down\")\n self.sweep = QPushButton(\"Sweep\")\n self.save = QPushButton(\"Save\")\n\n self.nope1 = QPushButton(\"\")\n self.nope2 = QPushButton(\"\")\n self.nope3 = QPushButton(\"\")\n self.nope4 = QPushButton(\"\")\n\n # 버튼 이벤트 처리\n # 이미지 회전\n self.rotate_left.clicked.connect(self.rotate_left_button_clicked)\n self.rotate_right.clicked.connect(self.rotate_right_button_clicked)\n # 이미지 불러오기\n self.new_image.clicked.connect(self.new_image_button_clicked)\n # 사각형 안 이미지 계산하기\n self.calculate.clicked.connect(self.calculate_button_clicked)\n # 사각형 움직이기\n self.move_up.clicked.connect(self.move_up_button_clicked)\n self.move_down.clicked.connect(self.move_down_button_clicked)\n self.move_left.clicked.connect(self.move_left_button_clicked)\n self.move_right.clicked.connect(self.move_right_button_clicked)\n # 사각형 이미지 처리\n self.draw.clicked.connect(self.draw_button_clicked)\n self.crop.clicked.connect(self.crop_button_clicked)\n self.init.clicked.connect(self.init_button_clicked)\n self.sweep.clicked.connect(self.sweep_button_clicked)\n self.save.clicked.connect(self.save_button_clicked)\n\n # 그래프\n self.fig = plt.Figure()\n self.canvas = FigureCanvas(self.fig)\n\n # 결과창\n self.text = QTextBrowser(self)\n self.text.append(\"안녕하세요\")\n self.text.append(\"여기에 결과를 보여 주겠습니다.\")\n\n # 레이아웃 설정\n self.left_1_button_layout = QHBoxLayout()\n self.left_1_button_layout.addWidget(self.rotate_left)\n self.left_1_button_layout.addWidget(self.new_image)\n self.left_1_button_layout.addWidget(self.rotate_right)\n\n self.left_2_button_layout = QHBoxLayout()\n self.left_2_button_layout.addWidget(self.nope1)\n self.left_2_button_layout.addWidget(self.move_up)\n self.left_2_button_layout.addWidget(self.nope2)\n\n self.left_3_button_layout = QHBoxLayout()\n self.left_3_button_layout.addWidget(self.move_left)\n self.left_3_button_layout.addWidget(self.calculate)\n self.left_3_button_layout.addWidget(self.move_right)\n\n self.left_4_button_layout = QHBoxLayout()\n self.left_4_button_layout.addWidget(self.nope3)\n self.left_4_button_layout.addWidget(self.move_down)\n self.left_4_button_layout.addWidget(self.nope4)\n\n self.left_5_button_layout = QHBoxLayout()\n self.left_5_button_layout.addWidget(self.draw)\n self.left_5_button_layout.addWidget(self.crop)\n self.left_5_button_layout.addWidget(self.init)\n self.left_5_button_layout.addWidget(self.sweep)\n self.left_5_button_layout.addWidget(self.save)\n\n self.slide_layout = QHBoxLayout()\n self.slide_layout.addWidget(self.slide)\n self.slide_layout.addWidget(self.text_label)\n self.slide_layout.addWidget(self.box_size_label)\n\n self.left_layout = QVBoxLayout()\n self.left_layout.addWidget(self.main_image_label)\n self.left_layout.addLayout(self.slide_layout)\n self.left_layout.addLayout(self.left_1_button_layout)\n self.left_layout.addLayout(self.left_2_button_layout)\n self.left_layout.addLayout(self.left_3_button_layout)\n self.left_layout.addLayout(self.left_4_button_layout)\n self.left_layout.addLayout(self.left_5_button_layout)\n\n\n self.right_layout = QVBoxLayout()\n self.right_layout.addWidget(self.text)\n self.right_layout.addWidget(self.canvas)\n\n self.main_layout = QHBoxLayout()\n self.main_layout.addLayout(self.left_layout)\n self.main_layout.addLayout(self.right_layout)\n\n self.setLayout(self.main_layout)\n\n def new_image_button_clicked(self):\n fname = QFileDialog.getOpenFileName()\n image_path = fname[0]\n if image_path == None:\n print(\"Error loading image\")\n self.main_image = Image.open(image_path)\n pixmap = QPixmap(image_path)\n self.main_image_path = image_path\n self.main_image_label.setPixmap(pixmap)\n self.main_image_label.resize(pixmap.width(), pixmap.height())\n self.draw_rectangle()\n\n def rotate_left_button_clicked(self):\n self.main_image = self.main_image.rotate(15)\n new_image = ImageQt.ImageQt(self.main_image)\n new_image = QImage(new_image)\n pixmap = QPixmap.fromImage(new_image)\n self.main_image_label.setPixmap(pixmap)\n self.main_image_label.resize(pixmap.width(), pixmap.height())\n print(\"회전 완료\")\n\n def rotate_right_button_clicked(self):\n self.main_image = self.main_image.rotate(-15)\n new_image = ImageQt.ImageQt(self.main_image)\n new_image = QImage(new_image)\n pixmap = QPixmap.fromImage(new_image)\n self.main_image_label.setPixmap(pixmap)\n self.main_image_label.resize(pixmap.width(), pixmap.height())\n print(\"회전 완료\")\n\n def draw_button_clicked(self):\n self.main_image = Image.open(self.main_image_path)\n main_image = self.main_image\n size = self.rectangle_size / 2\n width, height = main_image.size\n self.vertex_of_rect = [(width / 2) - size, (height / 2) - size, (width / 2) + size, (height / 2) + size]\n image_draw = ImageDraw.Draw(main_image)\n image_draw.rectangle(((self.vertex_of_rect[0], self.vertex_of_rect[1]), \\\n (self.vertex_of_rect[2], self.vertex_of_rect[3])), outline='green')\n new_image = ImageQt.ImageQt(main_image)\n new_image = QImage(new_image)\n pixmap = QPixmap.fromImage(new_image)\n self.main_image_label.setPixmap(pixmap)\n self.main_image_label.resize(pixmap.width(), pixmap.height())\n\n def crop_button_clicked(self):\n crop_area = (int(self.vertex_of_rect[0]), int(self.vertex_of_rect[1]), int(self.vertex_of_rect[2]), int(self.vertex_of_rect[3]))\n self.cropped_image = self.main_image.crop(crop_area)\n self.cropped_image = self.cropped_image.convert('L')\n self.cropped_image.show()\n\n def move_up_button_clicked(self):\n self.main_image = Image.open(self.main_image_path)\n self.vertex_of_rect[1] = self.vertex_of_rect[1] - 1\n self.vertex_of_rect[3] = self.vertex_of_rect[3] - 1\n image_draw = ImageDraw.Draw(self.main_image)\n image_draw.rectangle(((self.vertex_of_rect[0], self.vertex_of_rect[1]), \\\n (self.vertex_of_rect[2], self.vertex_of_rect[3])), outline='yellow')\n new_image = ImageQt.ImageQt(self.main_image)\n new_image = QImage(new_image)\n pixmap = QPixmap.fromImage(new_image)\n self.main_image_label.setPixmap(pixmap)\n self.main_image_label.resize(pixmap.width(), pixmap.height())\n\n def move_down_button_clicked(self):\n self.main_image = Image.open(self.main_image_path)\n self.vertex_of_rect[1] = self.vertex_of_rect[1] + 1\n self.vertex_of_rect[3] = self.vertex_of_rect[3] + 1\n image_draw = ImageDraw.Draw(self.main_image)\n image_draw.rectangle(((self.vertex_of_rect[0], self.vertex_of_rect[1]), \\\n (self.vertex_of_rect[2], self.vertex_of_rect[3])), outline='yellow')\n new_image = ImageQt.ImageQt(self.main_image)\n new_image = QImage(new_image)\n pixmap = QPixmap.fromImage(new_image)\n self.main_image_label.setPixmap(pixmap)\n self.main_image_label.resize(pixmap.width(), pixmap.height())\n\n def move_left_button_clicked(self):\n self.main_image = Image.open(self.main_image_path)\n self.vertex_of_rect[0] = self.vertex_of_rect[0] - 1\n self.vertex_of_rect[2] = self.vertex_of_rect[2] - 1\n image_draw = ImageDraw.Draw(self.main_image)\n image_draw.rectangle(((self.vertex_of_rect[0], self.vertex_of_rect[1]), \\\n (self.vertex_of_rect[2], self.vertex_of_rect[3])), outline='yellow')\n new_image = ImageQt.ImageQt(self.main_image)\n new_image = QImage(new_image)\n pixmap = QPixmap.fromImage(new_image)\n self.main_image_label.setPixmap(pixmap)\n self.main_image_label.resize(pixmap.width(), pixmap.height())\n\n def move_right_button_clicked(self):\n self.main_image = Image.open(self.main_image_path)\n self.vertex_of_rect[0] = self.vertex_of_rect[0] + 1\n self.vertex_of_rect[2] = self.vertex_of_rect[2] + 1\n image_draw = ImageDraw.Draw(self.main_image)\n image_draw.rectangle(((self.vertex_of_rect[0], self.vertex_of_rect[1]), \\\n (self.vertex_of_rect[2], self.vertex_of_rect[3])), outline='yellow')\n new_image = ImageQt.ImageQt(self.main_image)\n new_image = QImage(new_image)\n pixmap = QPixmap.fromImage(new_image)\n self.main_image_label.setPixmap(pixmap)\n self.main_image_label.resize(pixmap.width(), pixmap.height())\n \n def change_slide_value(self, value):\n self.rectangle_size = value\n self.box_size_label.setText(\"{}\".format(self.rectangle_size))\n self.draw_button_clicked()\n print(self.rectangle_size)\n\n def init_button_clicked(self):\n self.main_image = Image.open(self.main_image_path)\n main_image = self.main_image\n size = self.rectangle_size\n width, height = main_image.size\n self.vertex_of_rect = [0, 0, size, size]\n image_draw = ImageDraw.Draw(main_image)\n image_draw.rectangle(((self.vertex_of_rect[0], self.vertex_of_rect[1]), \\\n (self.vertex_of_rect[2], self.vertex_of_rect[3])), outline='green')\n new_image = ImageQt.ImageQt(main_image)\n new_image = QImage(new_image)\n pixmap = QPixmap.fromImage(new_image)\n self.main_image_label.setPixmap(pixmap)\n self.main_image_label.resize(pixmap.width(), pixmap.height())\n\n def sweep_button_clicked(self):\n self.main_image = Image.open(self.main_image_path)\n self.start_point = self.vertex_of_rect[0]\n image_draw = ImageDraw.Draw(self.main_image)\n image_draw.rectangle(((self.vertex_of_rect[0], self.vertex_of_rect[1]), \\\n (self.vertex_of_rect[2], self.vertex_of_rect[3])), outline='yellow')\n new_image = ImageQt.ImageQt(self.main_image)\n new_image = QImage(new_image)\n pixmap = QPixmap.fromImage(new_image)\n self.main_image_label.setPixmap(pixmap)\n self.main_image_label.resize(pixmap.width(), pixmap.height())\n crop_area = (int(self.vertex_of_rect[0]), int(self.vertex_of_rect[1]), int(self.vertex_of_rect[2]), int(self.vertex_of_rect[3]))\n self.cropped_image = self.main_image.crop(crop_area)\n self.cropped_image = self.cropped_image.convert('L')\n file_name = './sweep_images/{}.jpg'.format(self.vertex_of_rect[0])\n self.cropped_image.save(file_name)\n \n (mean, variance) = self.number_recognizer.predict_with_dropout(self.cropped_image)\n self.mean_data_list.append(mean)\n self.variance_data_list.append(variance)\n\n width, height = self.main_image.size\n if self.vertex_of_rect[2] + 1 <= width:\n self.vertex_of_rect[0] = self.vertex_of_rect[0] + 1\n self.vertex_of_rect[2] = self.vertex_of_rect[2] + 1\n else:\n self.save_button_clicked()\n\n def save_button_clicked(self):\n # 그래프 관련\n print(\"whowowow\")\n mean_zero = []\n mean_one = []\n mean_two = []\n mean_three = [] \n mean_four = []\n mean_five = []\n mean_six = []\n mean_seven = [] \n mean_eight = []\n mean_nine = []\n variance_zero = []\n variance_one = []\n variance_two = []\n variance_three = []\n variance_four = []\n variance_five = []\n variance_six = []\n variance_seven = []\n variance_eight = []\n variance_nine = []\n \n data_length = len(self.mean_data_list)\n\n if data_length == 1:\n self.calculate_button_clicked()\n else:\n for i in range(data_length):\n mean_zero.append(self.mean_data_list[i][0])\n mean_one.append(self.mean_data_list[i][1])\n mean_two.append(self.mean_data_list[i][2])\n mean_three.append(self.mean_data_list[i][3])\n mean_four.append(self.mean_data_list[i][4])\n mean_five.append(self.mean_data_list[i][5])\n mean_six.append(self.mean_data_list[i][6])\n mean_seven.append(self.mean_data_list[i][7])\n mean_eight.append(self.mean_data_list[i][8])\n mean_nine.append(self.mean_data_list[i][9])\n\n # 그래프를 위한 분산 축소\n reduction_ratio = 5\n variance_zero.append(self.mean_data_list[i][0] / reduction_ratio)\n variance_one.append(self.mean_data_list[i][1] / reduction_ratio)\n variance_two.append(self.mean_data_list[i][2] / reduction_ratio)\n variance_three.append(self.mean_data_list[i][3] / reduction_ratio)\n variance_four.append(self.mean_data_list[i][4] / reduction_ratio)\n variance_five.append(self.mean_data_list[i][5] / reduction_ratio)\n variance_six.append(self.mean_data_list[i][6] / reduction_ratio)\n variance_seven.append(self.mean_data_list[i][7] / reduction_ratio)\n variance_eight.append(self.mean_data_list[i][8] / reduction_ratio)\n variance_nine.append(self.mean_data_list[i][9] / reduction_ratio)\n\n x_range = range(data_length)\n\n ax = self.fig.add_subplot(1, 1, 1)\n\n # 막대 그래프\n error_bar_zero = ax.errorbar(x_range, mean_zero, yerr=(variance_zero), fmt='o', ecolor='orangered', color='orangered', label='Zero')\n error_bar_one = ax.errorbar(x_range, mean_one, yerr=(variance_one), fmt='o', ecolor='orangered', color='darkorange', label='One')\n error_bar_two = ax.errorbar(x_range, mean_two, yerr=(variance_two), fmt='o', ecolor='orangered', color='gold', label='Two')\n error_bar_three = ax.errorbar(x_range, mean_three, yerr=(variance_three), fmt='o', ecolor='orangered', color='yellowgreen', label='Three')\n error_bar_four = ax.errorbar(x_range, mean_four, yerr=(variance_four), fmt='o', ecolor='orangered', color='seagreen', label='Four')\n error_bar_five = ax.errorbar(x_range, mean_five, yerr=(variance_five), fmt='o', ecolor='orangered', color='lightseagreen', label='Five')\n error_bar_six = ax.errorbar(x_range, mean_six, yerr=(variance_six), fmt='o', ecolor='orangered', color='steelblue', label='Six')\n error_bar_seven = ax.errorbar(x_range, mean_seven, yerr=(variance_seven), fmt='o', ecolor='orangered', color='darkblue', label='Seven')\n error_bar_eight = ax.errorbar(x_range, mean_eight, yerr=(variance_eight), fmt='o', ecolor='orangered', color='darkviolet', label='Eight')\n error_bar_nine = ax.errorbar(x_range, mean_nine, yerr=(variance_nine), fmt='o', ecolor='orangered', color='deeppink', label='Nine')\n\n ax.set_xlabel('Number')\n ax.set_ylabel('Softmax result')\n ax.set_title('Uncertainty')\n ax.set_xticks(x_range)\n ax.set_xticklabels(x_range)\n ax.set_ylim([0, 1])\n ax.legend()\n self.canvas.draw()\n ax.clear()\n\n sweep_area = (0, 0, int(self.vertex_of_rect[2]), int(self.vertex_of_rect[3]))\n main_image = Image.open(self.main_image_path)\n self.sweeped_image = main_image.crop(sweep_area)\n # self.sweeped_image = self.sweeped_image.convert('L')\n file_name = './sweep_images_full/.jpg'\n self.cropped_image.save(file_name)\n self.sweeped_image.show()\n\n def calculate_button_clicked(self):\n # 시간 측정\n start_time = time.time()\n (mean, variance) = self.number_recognizer.predict_with_dropout(self.cropped_image)\n sorted_mean = np.sort(mean)\n # print(sorted_mean)\n first_number = np.where(mean == sorted_mean[9])\n first_number = first_number[0][0]\n mean_first_number = mean[first_number]\n var_first_number = variance[first_number]\n second_number = np.where(mean == sorted_mean[8])\n second_number = second_number[0][0]\n mean_second_number = mean[second_number]\n var_second_number = variance[second_number]\n third_number = np.where(mean == sorted_mean[7])\n third_number = third_number[0][0]\n mean_third_number = mean[third_number]\n var_third_number = variance[third_number]\n\n # 시간 측정 종료\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n # 텍스트 브라우저\n self.text.clear()\n self.text.append(\"인식 결과는 다음과 같습니다.\")\n self.text.append(\"인식된 숫자는 {} 입니다.\".format(first_number))\n self.text.append(\"후보 3개의 정보는 다음과 같습니다.\")\n self.text.append(\"-------------------------------------\")\n self.text.append(\"1st = {}\".format(first_number))\n self.text.append(\"Mean = {0:.4f}\".format(mean_first_number))\n self.text.append(\"Variance = {0:.4f}\".format(var_first_number))\n self.text.append(\"-------------------------------------\")\n self.text.append(\"2nd = {}\".format(second_number))\n self.text.append(\"Mean = {0:.4f}\".format(mean_second_number))\n self.text.append(\"Variance = {0:.4f}\".format(var_second_number))\n self.text.append(\"-------------------------------------\")\n self.text.append(\"3rd = {}\".format(third_number))\n self.text.append(\"Mean = {0:.4f}\".format(mean_third_number))\n self.text.append(\"Variance = {0:.4f}\".format(var_third_number))\n self.text.append(\"-------------------------------------\")\n self.text.append(\"계산 소요 시간은 {0:.4f}초 입니다.\" .format(time.time() - start_time))\n\n # 그래프 관련\n n_groups = 3\n means = (mean_first_number, mean_second_number, mean_third_number)\n variances = (var_first_number, var_second_number, var_third_number)\n\n ax = self.fig.add_subplot(1, 1, 1)\n index = np.arange(n_groups)\n\n # 막대 사이의 거리\n bar_width = 0.3\n\n # 막대 그래프\n rect1 = ax.bar(0, mean_first_number, bar_width, yerr=var_first_number, capsize=3, ecolor='r', label='First')\n rect2 = ax.bar(1, mean_second_number, bar_width, yerr=var_second_number, capsize=3, ecolor='r', label='Second')\n rect3 = ax.bar(2, mean_third_number, bar_width, yerr=var_third_number, capsize=3, ecolor='r', label='Third')\n ax.set_xlabel('Number')\n ax.set_ylabel('Softmax result')\n ax.set_title('Uncertainty')\n ax.set_xticks(index)\n x_labels = [first_number, second_number, third_number]\n ax.set_xticklabels(x_labels)\n ax.legend()\n self.canvas.draw()\n ax.clear()\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n example = MainWindow()\n example.show()\n sys.exit(app.exec_())\n" ]
[ [ "matplotlib.pyplot.Figure", "tensorflow.nn.max_pool", "numpy.max", "numpy.mean", "numpy.var", "numpy.where", "tensorflow.nn.conv2d", "numpy.reshape", "numpy.arange", "tensorflow.reset_default_graph", "tensorflow.contrib.layers.xavier_initializer", "tensorflow.Session", "tensorflow.train.Saver", "tensorflow.nn.dropout", "tensorflow.matmul", "tensorflow.placeholder", "tensorflow.set_random_seed", "numpy.array", "tensorflow.nn.relu", "tensorflow.reshape", "numpy.sort", "matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg", "tensorflow.random_normal" ] ]
AUAMO/atomic_data_codes
[ "5f12b59152bef209f95c60596c23b4c40786de72" ]
[ "gcr/DP_data_analysis.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 15 10:06:27 2016\n\n@author: ALEXIS\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\nspect_dir = 'C:/Users/ivan/OneDrive/Research/ar_OES/DATA/BC1E'\nos.chdir(spect_dir)\n\n# %%\ndef retrieve_file_dir_data(spect_dir):\n from astropy.io import fits\n from scipy.optimize import curve_fit\n from scipy import stats\n print('filelist: ')\n filelist = list()\n spectlist = list()\n tempdenslist = list()\n temp_dens_av = list()\n yy_temps = list()\n yy_dens = list()\n \n for filename in os.listdir(spect_dir):\n if 'BC1G' in filename:\n continue\n# if 'CM100' in filename:\n# continue\n# if 'CM075' in filename:\n# continue\n# if 'CM050' in filename:\n# continue\n \n\n print(filename)\n hdulist = fits.open(filename)\n\n def spect_get():\n hdu_size = np.size(hdulist)\n scan_lambda = hdulist[hdu_size-2].data.T\n wavelengths = np.array(scan_lambda[0]).T\n scan_spect = hdulist[hdu_size-1].data.T\n\n spect = np.array(scan_spect[0])\n spec_av = np.mean(spect[:, 2000:2047])\n spect = spect - spec_av\n for i in range(1,10):\n tmp_data = spect\n spect = np.array(scan_spect[i])\n spec_av = np.mean(spect[:, 2000:2047])\n spect = spect - spec_av\n spect_array = np.vstack((tmp_data, spect))\n spect = spect_array\n\n spect_mean = spect.mean(axis=0)\n\n return (wavelengths, spect_array, spect_mean)\n\n def temp_dens_get(indx):\n hdu_size = np.size(hdulist)\n scan_size = hdu_size - 2\n scan_dat = {}\n for i in range(1,scan_size):\n scan_dat[\"scan{0}\".format(i)] = hdulist[i].data\n\n DP_START = scan_dat['scan5'][indx][0]\n DP_STOP = np.abs(DP_START)\n DP_STEP = scan_dat['scan5'][indx][1]\n DP_RAW = scan_dat['scan5'][indx][2]\n V_TRACE = np.arange(DP_START, DP_STOP + DP_STEP, DP_STEP)\n isat_x = V_TRACE[0:20] ; isat_y = DP_RAW[0:20]\n isat_slope, isat_intercept, isat_rval, isat_pval, std_err = \\\n stats.linregress(isat_x, isat_y)\n isat_trace = isat_slope * V_TRACE + isat_intercept\n zero_x = V_TRACE[75:85] ; zero_y = isat_trace[75:85]\n zero_slope, zero_intercept, zero_rval, zero_pval, std_err = \\\n stats.linregress(zero_x, zero_y)\n def tanh_fit(xx, a0, a1, a2, a3, a4):\n return(a0 * (xx - a1) + a2 * np.tanh((xx - a1)/(a3)) + a4)\n ifit_params = curve_fit(tanh_fit, V_TRACE, DP_RAW)\n\n # Area of probe tip with 1 mm diameter and 2.5 mm length\n tipArea = 0.5 * (np.pi * 0.5e-3 ** 2) + (np.pi * 1e-3 * 2.5e-3)\n a0 = float(ifit_params[0][0]) # ion saturation slope\n a1 = float(ifit_params[0][1]) # voltage offset / V_f\n a2 = float(ifit_params[0][2]) # ion saturation current\n a3 = float(ifit_params[0][3]) # slope at zstatsero volts\n a4 = float(ifit_params[0][4]) # current offset\n ifit_trace = a0*(V_TRACE-a1) + a2*np.tanh((V_TRACE-a1)/(a3)) + a4\n zero_x = V_TRACE[75:85] ; zero_y = ifit_trace[75:85]\n zero_slope, zero_intercept, zero_rval, zero_pval, std_err = \\\n stats.linregress(zero_x, zero_y)\n di_dv = a0 + a2 / (a3 * np.cosh(a1/a3)**2)\n t_e = np.abs(a2)/ (2. * di_dv)\n # print(\"t_e = {:6.2e} eV \".format(t_e))\n n_e = (a2 / (1.6e-19 * tipArea)) * (6.6e-26 / \\\n (1.602e-19 * t_e))**0.5\n # print(\"n_e = {:6.2e} m^2 \".format(n_e))\n # print(\"isat = {:6.2e} Amps\".format(a2))\n # print(\"slope at V_0 = {:6.2e} Amps/Volt\".format(di_dv))\n radial_position = indx * 2\n # print(\"radial position = \" , radial_position, \"mm.\")\n temp_dens_data = [[radial_position],[t_e],[n_e],[a2],[di_dv]]\n temp_dens_array = np.array(temp_dens_data)\n\n return temp_dens_array\n\n\n data = temp_dens_get(0)\n for i in range(1,26):\n tmp_data = data\n data = temp_dens_get(i)\n temp_dens_data = np.hstack((tmp_data, data))\n data = temp_dens_data\n wavelengths, spect_array, spect_mean = spect_get()\n tmp_av_data = temp_dens_data[0:39].mean(axis=1)\n temp_dens_av.append(tmp_av_data)\n\n filelist.append(filename)\n spectlist.append(spect_mean)\n tempdenslist.append(temp_dens_data)\n yy_temps.append(temp_dens_data[1])\n yy_dens.append(temp_dens_data[2])\n \n xx_rad = temp_dens_data[0]\n\n \n return (xx_rad, yy_temps, yy_dens, filelist)\n \nxx, yy1, yy2, filelist = retrieve_file_dir_data(spect_dir)\n\n# %%\n\n\n\nfor i in range(24):\n# tag = filelist[i][]\n plt.xlim(0,40)\n plt.ylim(3,8)\n plt.plot(xx, yy1[i])\n\n# %%\n\nfor i in range(24):\n# tag = filelist[i][]\n plt.xlim(0,40)\n plt.ylim(0e16, 3.5e16)\n plt.plot(xx, yy2[i])\n\n\n\n\n\n\n\n# %% Plot the results.\n" ]
[ [ "numpy.hstack", "numpy.abs", "numpy.cosh", "matplotlib.pyplot.ylim", "numpy.arange", "matplotlib.pyplot.plot", "matplotlib.pyplot.xlim", "numpy.size", "numpy.mean", "scipy.stats.linregress", "numpy.tanh", "numpy.array", "scipy.optimize.curve_fit", "numpy.vstack" ] ]
namachan10777/nmf-learn
[ "c0e0d81508632554f3274816331aa72eeb648ade" ]
[ "ICA/mix.py" ]
[ "#!/usr/bin/python\n# 2019 Nakano Masaki\n\nimport sys\nimport soundfile as sf\nimport numpy as np\n\nif __name__ == '__main__':\n n = len(sys.args)\n mix = np.random.rand(n, n) * 2 - 1\n _, samplerate = sf.read(sys.args[1])\n wavs = []\n for f in sys.args:\n wav, rate = sf.read(f)\n assert rate, 'contradictory samplerate'\n wavs.append(wav)\n\n mixed = mix * np.array(wavs)\n\n\ndata1, samplrate1 = sf.read('s1.wav')\ndata2, samplrate2 = sf.read('s2.wav')\n\nmix_matrix = np.array([[0.4, 0.6],[-0.8, 0.7]])\nsounds = np.array([data1, data2])\nprint(sounds)\nmix_sounds = np.dot(mix_matrix, sounds)\n\nsf.write('mix1.wav', mix_sounds[0], samplrate1)\nsf.write('mix2.wav', mix_sounds[1], samplrate2)\n" ]
[ [ "numpy.dot", "numpy.array", "numpy.random.rand" ] ]
facultyai/sherlockml-boltzmannclean
[ "6e2b49bce9a6020b2e70e399ef6bf6740af5e69b" ]
[ "boltzmannclean.py" ]
[ "from __future__ import division, print_function\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.impute import SimpleImputer as Imputer\nfrom sklearn.model_selection import GridSearchCV\n\nCOLNAME_SEPARATOR = \"_boltzmannclean\"\n\n\ndef clean(dataframe, numerical_columns, categorical_columns, tune_rbm):\n \"\"\"Replaces missing values in dataframe with imputed values from an RBM\"\"\"\n\n numerics, scaler = preprocess_numerics(dataframe, numerical_columns)\n\n categoricals, category_dict = preprocess_categoricals(\n dataframe, categorical_columns\n )\n\n preprocessed_array = np.hstack((numerics, categoricals))\n\n if preprocessed_array.size > 0:\n # create and train a Restricted Boltzmann Machine\n rbm = train_rbm(preprocessed_array, tune_hyperparameters=tune_rbm)\n\n imputed_array = rbm.transform(preprocessed_array)\n\n imputed_numerics = postprocess_numerics(\n imputed_array[:, : numerics.shape[1]], dataframe[numerical_columns], scaler\n )\n\n imputed_categoricals = postprocess_categoricals(\n imputed_array[:, numerics.shape[1] :],\n dataframe[categorical_columns],\n category_dict,\n )\n\n imputed_dataframe = imputed_numerics.join(imputed_categoricals)\n\n for colname in imputed_dataframe.columns:\n dataframe[colname] = imputed_dataframe[colname]\n\n return dataframe\n\n\ndef preprocess_categoricals(dataframe, categorical_columns):\n \"\"\"\n Encode categorical dataframe columns for a Restricted Boltzmann Machine.\n\n Parameters\n ----------\n dataframe : pd.DataFrame\n A Pandas DataFrame to be used for training an RBM on.\n categorical_columns : list of str\n A list of the column names to be treated as categorical values.\n\n Returns\n -------\n encoded : np.array\n A numpy array of the categorical columns encoded for RBM training.\n category_dict: dict\n A dictionary mapping categorical column names to a list of categories.\n\n \"\"\"\n\n categoricals = pd.DataFrame(dataframe[categorical_columns])\n\n if not categoricals.empty:\n # label encoding\n category_dict = {}\n for colname in categoricals.columns:\n category_dict[colname] = (\n categoricals[colname].astype(\"category\").cat.categories\n )\n categoricals[colname] = categoricals[colname].astype(\"category\").cat.codes\n\n categoricals[categoricals == -1] = np.nan\n\n # one-hot encoding\n encoded = pd.get_dummies(\n categoricals.astype(\"object\"), prefix_sep=COLNAME_SEPARATOR\n )\n\n col_iterator = encoded.items()\n\n # reinstate our nulls\n for colname in categoricals.columns:\n nulls = categoricals.index[categoricals[colname].isnull()]\n for _ in range(len(category_dict[colname])):\n encoded_colname, __ = next(col_iterator)\n encoded.loc[nulls, encoded_colname] = np.nan\n\n # extract the numpy array\n encoded = encoded.values\n else:\n encoded = np.empty((dataframe.shape[0], 0))\n category_dict = {}\n\n return encoded, category_dict\n\n\ndef reverse_dummy_encoding(dummy_dataframe, category_dict):\n \"\"\"\n Reconstructs the original from a one-hot encoded dataframe.\n\n \"\"\"\n\n current_col = 0\n col_positions = {}\n\n for colname, values in category_dict.items():\n col_positions[colname] = list(range(current_col, current_col + len(values)))\n current_col += len(values)\n\n dataframe = pd.DataFrame(\n {\n colname: pd.Categorical.from_codes(\n np.argmax(\n dummy_dataframe.iloc[:, col_positions[colname]].values, axis=1\n ),\n category_dict[colname],\n )\n for colname in category_dict.keys()\n },\n dtype=\"object\",\n )\n\n return dataframe\n\n\ndef postprocess_categoricals(imputed_array, original_dataframe, category_dict):\n \"\"\"\n Recreate a categorical dataframe from values imputed by an RBM.\n\n Parameters\n ----------\n imputed_array : np.array\n A numpy array with values in the range [0,1].\n original_dataframe : pd.DataFrame\n The DataFrame with the columns used to create the original numpy array.\n category_dict: dict\n A dictionary mapping categorical column names to a list of categories.\n\n Returns\n -------\n dataframe : pd.DataFrame\n A DataFrame with columns reconstructed from the input array.\n\n \"\"\"\n\n dataframe = pd.DataFrame(imputed_array)\n\n if not dataframe.empty:\n dataframe = reverse_dummy_encoding(dataframe, category_dict)\n\n dataframe.index = original_dataframe.index\n\n for colname in dataframe.columns:\n dataframe[colname] = dataframe[colname].astype(\n original_dataframe[colname].dtype\n )\n\n return dataframe\n\n\ndef preprocess_numerics(dataframe, numerical_columns):\n \"\"\"\n Preprocess numerical dataframe columns for a Restricted Boltzmann Machine.\n\n Parameters\n ----------\n dataframe : pd.DataFrame\n A Pandas DataFrame to be used for training an RBM on.\n numerical_columns : list of str\n A list of the column names to be treated as numerical values.\n\n Returns\n -------\n numerics : np.array\n A numpy array of the numerical columns scaled to [0,1].\n scaler: sklearn.preprocessing.MinMaxScaler\n The scikit-learn scaler used to transform the values.\n\n \"\"\"\n\n # converts to numerical values where possible, replaces with NaN if not\n numerics = pd.DataFrame(dataframe[numerical_columns]._convert(numeric=True))\n # selects only columns with some numerical values\n numerics = numerics.select_dtypes([np.number])\n\n if not numerics.empty:\n to_impute = np.logical_not(np.isfinite(numerics))\n\n # avoids that annoying pandas warning\n numerics.is_copy = False\n # replaces infs with nans\n numerics[to_impute] = np.nan\n\n # replace NaNs with column means to leave min-max scaling unaffected\n array = Imputer().fit_transform(numerics)\n\n # scale values to the range [0,1]\n scaler = MinMaxScaler().fit(array)\n numerics = scaler.transform(array)\n\n # put our NaNs back in to be imputed by the RBM\n numerics[to_impute] = np.nan\n else:\n numerics = np.empty((dataframe.shape[0], 0))\n scaler = None\n\n return numerics, scaler\n\n\ndef postprocess_numerics(imputed_array, original_dataframe, scaler):\n \"\"\"\n Recreate a numerical dataframe from values imputed by an RBM.\n\n Parameters\n ----------\n imputed_array : np.array\n A numpy array with values in the range [0,1].\n original_dataframe : pd.DataFrame\n The DataFrame with the columns used to create the original numpy array.\n scaler: sklearn.preprocessing.MinMaxScaler\n The scikit-learn scaler used to transform the values.\n\n Returns\n -------\n dataframe : pd.DataFrame\n A DataFrame with numerical columns reconstructed from the input array.\n\n \"\"\"\n if scaler:\n array = scaler.inverse_transform(imputed_array)\n else:\n array = np.empty_like(imputed_array)\n\n imputed_dataframe = pd.DataFrame(array, index=original_dataframe.index)\n imputed_dataframe.columns = (\n original_dataframe._convert(numeric=True).select_dtypes([np.number]).columns\n )\n\n for colname in imputed_dataframe.columns:\n imputed_dataframe[colname] = imputed_dataframe[colname].astype(\n original_dataframe[colname].dtype\n )\n\n return imputed_dataframe\n\n\ndef train_rbm(array, tune_hyperparameters):\n \"\"\"\n Creates and trains a Restricted Boltzmann Machine.\n\n Parameters\n ----------\n array : np.array\n A numpy array of np.nan's and floats in the range [0,1].\n tune_hyperparameters : bool\n Tune learn rate and hidden layer size of the RBM, train for longer.\n\n Returns\n -------\n rbm : RestrictedBoltzmannMachine\n A trained RBM which implements the scikit-learn transformer interface\n\n \"\"\"\n\n rbm = RestrictedBoltzmannMachine(\n n_hidden=array.shape[1], batchsize=min(array.shape[0], 10)\n )\n\n if tune_hyperparameters:\n rbm.max_epochs = 50\n param_grid = {\n \"n_hidden\": [rbm.n_hidden // 10, rbm.n_hidden, rbm.n_hidden * 10],\n \"adagrad\": [True, False],\n }\n grid_search = GridSearchCV(rbm, param_grid=param_grid)\n grid_search.fit(array)\n rbm.verbose = True\n\n rbm.fit(array)\n\n return rbm\n\n\nclass RestrictedBoltzmannMachine(BaseEstimator, TransformerMixin):\n \"\"\"\n Restricted Boltzmann Machine trained by Persistent Contrastive Divergence.\n\n Creates and trains a Restricted Boltzmann Machine which can then be used to\n fill in missing values in a numpy array. Trained using Persistent\n Contrastive Divergence (PCD) gradient descent (optionally with adagrad).\n Implements scikit-learn's transformer interface, uses training techniques\n and notation from Geoffrey Hinton.\n\n See \"A Practical Guide to Training Restricted Boltzmann Machines\"\n (https://www.cs.toronto.edu/~hinton/absps/guideTR.pdf) for more info.\n\n Parameters\n ----------\n n_hidden : int, optional\n Size of the hidden layer for the RBM.\n learn_rate : float, optional\n Initial learning rate for gradient descent.\n batchsize : int, optional\n The size of a gradient descent minibatch.\n dropout_fraction : float, optional\n Fraction of hidden units to drop out in the PCD phase of PCD.\n max_epochs : int, optional\n Maximum number of training epochs allowed.\n adagrad : bool, optional\n Whether to use the adagrad algorithm during gradient descent.\n verbose : bool, optional\n Whether to print out epoch numbers during fitting.\n\n \"\"\"\n\n def __init__(\n self,\n n_hidden=100,\n learn_rate=0.01,\n batchsize=10,\n dropout_fraction=0.5,\n max_epochs=1,\n adagrad=True,\n verbose=False,\n ):\n self.n_hidden = n_hidden\n self.learn_rate = learn_rate\n self.batchsize = batchsize\n self.dropout_fraction = dropout_fraction\n self.max_epochs = max_epochs\n self.adagrad = adagrad\n self.verbose = verbose\n\n def score_samples(self, X):\n\n noise_fraction = 0.5\n\n mask = np.random.random(size=X.shape)\n\n noisy_X = X.copy()\n noisy_X[mask < noise_fraction] = np.nan\n\n X_reco = self.transform(noisy_X)\n\n scores = -1 * np.sum(np.square(X_reco - np.nan_to_num(X)), axis=1)\n\n return scores\n\n def score(self, X, y=None):\n score = np.sum(self.score_samples(X))\n return score\n\n def transform(self, X, y=None):\n\n if X.ndim == 1:\n X = X.reshape((1, X.shape[0]))\n\n X_reco = self._reconstruct_until_stable(\n np.nan_to_num(X), self.w_, self.a_, self.b_, fixed_values=np.isfinite(X)\n )\n\n return X_reco\n\n def fit(self, X, y=None):\n\n if self.verbose:\n print(\"Training RBM...\")\n\n if X.ndim == 1:\n X = X.reshape((1, X.shape[0]))\n\n X = X[np.isfinite(X).any(axis=1)]\n\n n_visible = X.shape[1]\n num_examples = X.shape[0]\n n_hidden = self.n_hidden\n batchsize = self.batchsize\n\n w = 0.01 * np.random.randn(n_visible, n_hidden)\n delta_w = np.zeros_like(w)\n\n prior = np.true_divide(np.nan_to_num(X).sum(axis=0), num_examples)\n prior[prior == 1] = 0.9999\n\n a = np.log(1 / (1 - prior))\n a = np.reshape(a, (1, n_visible))\n delta_a = np.zeros_like(a)\n\n b = -4 * np.ones((1, n_hidden))\n delta_b = np.zeros_like(b)\n\n weight_decay = 0.01\n\n if self.adagrad:\n w_adagrad = np.ones_like(w)\n a_adagrad = np.ones_like(a)\n b_adagrad = np.ones_like(b)\n adagrad_eps = 1e-8\n\n n_batches = num_examples // batchsize\n\n pcd_chain = np.random.random_sample((batchsize, n_visible))\n\n for epoch in range(self.max_epochs):\n if self.verbose:\n print(\"\\rEpoch \", epoch + 1, \" of \", self.max_epochs, end=\"\")\n\n np.random.shuffle(X)\n\n for batch in range(n_batches):\n\n # positive phase of contrastive divergence\n\n v0 = X[int(batch * batchsize) : int((batch + 1) * batchsize)]\n\n # deal with nans\n visible_dropout = 1 - np.isfinite(v0).sum(axis=1) / v0.shape[1]\n\n nan_scaling = 1.0 / (1 - visible_dropout)\n nan_scaling = nan_scaling.reshape((v0.shape[0], 1))\n\n v0 = np.nan_to_num(v0)\n\n prob_h0, h0 = self._sample_hidden(v0, w, b)\n\n # negative phase of (persistent) contrastive divergence\n\n pcd_chain = self._reconstruct(\n pcd_chain, w, a, b, dropout_fraction=self.dropout_fraction\n )\n\n prob_h, h = self._sample_hidden(\n pcd_chain, w, b, dropout_fraction=self.dropout_fraction\n )\n\n # gradient for weights\n vh0 = np.dot((v0 * nan_scaling).T, prob_h0)\n vh = np.dot(pcd_chain.T, prob_h)\n\n # gradient for visible biases\n positive_visible_grad = np.sum(v0, axis=0)\n negative_visible_grad = np.sum(pcd_chain, axis=0)\n\n # gradient for hidden biases\n positive_hidden_grad = np.sum(prob_h0, axis=0)\n negative_hidden_grad = np.sum(prob_h, axis=0)\n\n m = 0.5 if epoch < 5 else 0.9\n\n w_grad = vh0 - vh\n a_grad = positive_visible_grad - negative_visible_grad\n b_grad = positive_hidden_grad - negative_hidden_grad\n\n if self.adagrad:\n w_adagrad += np.square(w_grad)\n a_adagrad += np.square(a_grad)\n b_adagrad += np.square(b_grad)\n\n w_learn_rate = self.learn_rate / np.sqrt(adagrad_eps + w_adagrad)\n\n a_learn_rate = self.learn_rate / np.sqrt(adagrad_eps + a_adagrad)\n\n b_learn_rate = self.learn_rate / np.sqrt(adagrad_eps + b_adagrad)\n else:\n w_learn_rate = self.learn_rate\n a_learn_rate = self.learn_rate\n b_learn_rate = self.learn_rate\n\n delta_w = delta_w * m + (w_learn_rate / batchsize) * (w_grad)\n delta_a = delta_a * m + (a_learn_rate / batchsize) * (a_grad)\n delta_b = delta_b * m + (b_learn_rate / batchsize) * (b_grad)\n\n # L1 weight decay\n w += delta_w - weight_decay * np.sign(w) * (self.learn_rate / batchsize)\n a += delta_a\n b += delta_b\n\n self.w_ = w\n self.a_ = a\n self.b_ = b\n if self.verbose:\n print(\"\\n\")\n\n return self\n\n def _sample_hidden(self, v, w, b, dropout_fraction=0.0):\n prob_h = self._logistic(v, w, b)\n h = prob_h > np.random.rand(v.shape[0], self.n_hidden)\n h = np.multiply(\n h,\n np.random.binomial(\n [np.ones((v.shape[0], self.n_hidden))], 1 - dropout_fraction\n )[0]\n * (1.0 / (1 - dropout_fraction)),\n )\n return prob_h, h\n\n def _logistic(self, x, w, b):\n xw = np.dot(x, w)\n return 1 / (1 + np.exp(-xw - b))\n\n def _free_energy(self, v, w, a, b):\n vw = np.dot(v, w)\n return -1 * (np.dot(v, a.T) + np.sum(np.log(1 + np.exp(b + vw))))\n\n def _reconstruct(self, v0, w, a, b, dropout_fraction=0.0):\n _, h = self._sample_hidden(v0, w, b, dropout_fraction)\n v = self._logistic(h, w.T, a)\n return v\n\n def _reconstruct_until_stable(self, v, w, a, b, fixed_values=[], threshold=0.01):\n\n reco_free_energy = self._free_energy(v, w, a, b)\n reco_free_energy_new = reco_free_energy.copy()\n\n batchsize = v.shape[0]\n\n delta_free_energy = np.ones((batchsize, 1))\n converged = np.zeros((batchsize,), dtype=bool)\n\n v_true = v.copy()\n\n if self.verbose:\n print(\"Reconstructing\", batchsize, \"examples...\")\n\n while converged.sum() < batchsize:\n unconverged = np.logical_not(converged)\n\n v[unconverged] = self._reconstruct(v[unconverged], w, a, b)\n\n v[fixed_values] = v_true[fixed_values]\n\n reco_free_energy_new[unconverged] = self._free_energy(\n v[unconverged], w, a, b\n )\n\n delta_free_energy[unconverged] = np.abs(\n reco_free_energy_new[unconverged] - reco_free_energy[unconverged]\n ) / (reco_free_energy[unconverged] + 1e-8)\n\n converged = (delta_free_energy < threshold).flatten()\n\n reco_free_energy = reco_free_energy_new\n\n return v\n" ]
[ [ "numpy.dot", "numpy.sqrt", "numpy.random.random_sample", "pandas.DataFrame", "numpy.nan_to_num", "numpy.zeros_like", "numpy.random.randn", "numpy.exp", "sklearn.preprocessing.MinMaxScaler", "numpy.square", "numpy.hstack", "numpy.ones_like", "numpy.reshape", "numpy.empty_like", "sklearn.impute.SimpleImputer", "numpy.argmax", "numpy.zeros", "numpy.logical_not", "numpy.log", "numpy.random.rand", "numpy.sum", "sklearn.model_selection.GridSearchCV", "numpy.random.random", "numpy.abs", "numpy.isfinite", "numpy.random.shuffle", "numpy.ones", "numpy.sign", "numpy.empty" ] ]
lafleur1/rgnModified
[ "56ffbcefa48d314326f98a5d90e3050aa0d33157" ]
[ "viewEnergyDistributions.py" ]
[ "#view the distriution of fa scores, # h-bonds, and percent SS for true and false HLH structures\n\nimport pandas as pd\nimport sys,os,json\nimport tempfile\nimport numpy as np\nimport argparse\nfrom pyrosetta import *\nfrom pyrosetta.rosetta.protocols.minimization_packing import MinMover\nimport time\nfrom pyrosetta.toolbox import cleanATOM\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\npyrosetta.init()\n\ndef getSSString(pose):\n #returns string of SS positions\n DSSP = pyrosetta.rosetta.protocols.moves.DsspMover()\n DSSP.apply(pose) # populates the pose's Pose.secstruct, get sec struct for sequence\n return pose.secstruct()\n\ndef getHBondInfo(pose):\n #parses get_hbonds output,]\n seqLen = len(pose.sequence())\n hbondset = pose.get_hbonds()\n allhbonds = hbondset.hbonds()\n numberBonds = len(allhbonds)\n donors = []\n acceptors = []\n donorPairs = [] #(resi,atm)\n acceptorPairs=[] #resi, atm\n for hbond in allhbonds:\n donors.append(hbond.don_res())\n #print (\"DONOR\")\n #print (hbond.don_res())\n #print (hbond.don_hatm())\n #print (pose.residue(hbond.don_res()))\n #print(pose.residue(hbond.don_res()).atom(hbond.don_hatm()))\n #print(pose.residue(hbond.don_res()).atom_name(hbond.don_hatm()))\n donorPairs.append(hbond.don_res(), pose.residue(hbond.don_res()).atom_name(hbond.don_hatm()))\n print (\"ACCEPTOR\")\n print (hbond.acc_res())\n print (hbond.acc_atm())\n print(pose.residue(hbond.acc_res()))\n print(pose.residue(hbond.acc_res()).atom(hbond.acc_atm()))\n print(pose.residue(hbond.acc_res()).atom_name(hbond.acc_atm()))\n acceptorPairs.append(hbond.acc_res(), pose.residue(hbond.acc_res()).atom_name(hbond.acc_atm()))\n #print (hbond.don_res(), hbond.acc_res())\n #create donor and acceptor string reps\n donorSet = list(set(donors)).sort()\n acceptorSet = list(set(acceptors)).sort()\n donorString = \"\" #D if donor, A if acceptor, X if neither\n acceptorStrign = \"\"\n for i in range(1, seqLen + 1): #residues are 1 indexed in pyrosetta\n if i in donors:\n donorString = donorString + \"D\"\n else:\n donorString = donorString + \"X\"\n if i in acceptors:\n acceptorStrign = acceptorStrign + \"A\"\n else:\n acceptorStrign = acceptorStrign + \"X\"\n return donorString, acceptorStrign, numberBonds\n\ndef getHBondResiduesAndAtomsV1(pose):\n #parses get_hbonds material into a usage form\n #does locations as (residue, atom)\n seqLen = len(pose.sequence())\n hbondset = pose.get_hbonds()\n allhbonds = hbondset.hbonds()\n donorPairs = [] #(resi,atm)\n acceptorPairs=[] #resi, atm\n for hbond in allhbonds:\n cleanedUpDonorAtom = pose.residue(hbond.don_res()).atom_name(hbond.don_hatm()).replace(\" \",\"\")\n donorstr = str(hbond.don_res())+\":\"+cleanedUpDonorAtom\n donorPairs.append(donorstr)\n cleanedupAccAtom = pose.residue(hbond.acc_res()).atom_name(hbond.acc_atm()).replace(\" \",\"\")\n accStr = str(hbond.acc_res()) + \":\" + cleanedupAccAtom\n acceptorPairs.append(accStr)\n return donorPairs, acceptorPairs\n\ndef getHBondResiduesAndAtomsV2(pose):\n #parses get_hbonds material into a usage form\n #does locations as (chain, residue, atom)\n seqLen = len(pose.sequence())\n hbondset = pose.get_hbonds()\n allhbonds = hbondset.hbonds()\n donorPairs = [] #(resi,atm)\n acceptorPairs=[] #resi, atm\n for hbond in allhbonds:\n donorlocation = pose.pdb_info().pose2pdb(hbond.don_res()).split(\" \") #1st is residue, second is chain ID in pdb\n cleanedUpDonorAtom = pose.residue(hbond.don_res()).atom_name(hbond.don_hatm()).replace(\" \",\"\")\n donorstr = donorlocation[1] + \":\" + donorlocation[0] +\":\"+cleanedUpDonorAtom\n donorPairs.append(donorstr)\n acclocation = pose.pdb_info().pose2pdb(hbond.acc_res()).split(\" \")\n cleanedupAccAtom = pose.residue(hbond.acc_res()).atom_name(hbond.acc_atm()).replace(\" \",\"\")\n accStr = acclocation[1] + \":\" + acclocation[0] + \":\" + cleanedupAccAtom\n acceptorPairs.append(accStr)\n return donorPairs, acceptorPairs\n\n\ndef processOne(name, scorefxn):\n cleanATOM(name)\n cleanPDBName = name[:-4] + \".clean.pdb\"\n start = pose_from_pdb(cleanPDBName)\n #ss\n ss = getSSString(start)\n fractionH = ss.count(\"H\") / len(ss)\n fractionL = ss.count(\"L\") / len(ss)\n #hbonds\n donors, acceptors, numberBonds = getHBondInfo(start)\n # fa score\n score = scorefxn(start)\n print (\"ON \", name)\n print (\"Secondary structure: \")\n print (ss)\n print (\"fraction H: \", fractionH, \" fraction L \", fractionL, \" number H bonds: \", numberBonds, \" score: \", score)\n return ss, fractionH, fractionL, numberBonds, score\n\n\ndef processAllFolders():\n truePosDir = \"./testSetChains/\"\n myPosDir = \"./positiveHLHTestSet/\"\n myNegDir = \"./negativeHLHTestSet/\"\n scorefxn = get_fa_scorefxn()\n asDict = {'structure': [], 'dataset': [], 'score': [], 'fractionH': [], 'fractionL': [], 'numberHBonds': []}\n for file in os.listdir(myNegDir):\n ss, fractionH, fractionL, numberBonds, score = processOne(myNegDir + file, scorefxn)\n asDict['score'].append(score)\n asDict['fractionH'].append(fractionH)\n asDict['fractionL'].append(fractionL)\n asDict['numberHBonds'].append(numberBonds)\n # asDict['s'].append(ss)\n asDict['dataset'].append(\"negativeTrRosettaPredicted\")\n asDict['structure'].append(file)\n for file in os.listdir(myPosDir):\n ss, fractionH, fractionL, numberBonds, score = processOne(myPosDir + file, scorefxn)\n asDict['score'].append(score)\n asDict['fractionH'].append(fractionH)\n asDict['fractionL'].append(fractionL)\n asDict['numberHBonds'].append(numberBonds)\n # asDict['s'].append(ss)\n asDict['dataset'].append(\"positiveTrRosettaPredicted\")\n asDict['structure'].append(file)\n for file in os.listdir(truePosDir):\n ss, fractionH, fractionL, numberBonds, score = processOne(truePosDir + file, scorefxn)\n asDict['score'].append(score)\n asDict['fractionH'].append(fractionH)\n asDict['fractionL'].append(fractionL)\n asDict['numberHBonds'].append(numberBonds)\n # asDict['s'].append(ss)\n asDict['dataset'].append(\"positiveOriginalSet\")\n asDict['structure'].append(file)\n # graph interesting stuff\n asDF = pd.DataFrame(asDict) # change to dataframe for sns plotting\n # save csv\n asDF.to_csv(\"relevantData.csv\")\n sns.violinplot(x=\"dataset\", y=\"score\", data=asDF)\n plt.show()\n sns.violinplot(x=\"dataset\", y=\"numberHBonds\", data=asDF)\n plt.show()\n ax = sns.scatterplot(x=\"fractionH\", y=\"fractionL\", hue=\"dataset\", data=asDF)\n plt.show()\n\nif __name__ == '__main__':\n #true positive structures:\n #look at multichain hbonds\n name = \"./180312_massive_set_train_pdbs/redesigned_closed_7_7_7_9middlesbobby_1_9_S_237903.pdb_middle1.pdb-7_7_7_9middlesbobby_1_9_S_254850_0001.pdb_middle1.pdb-bobby_1_9_S_246831_padded_0001.pdb\"\n cleanATOM(name)\n cleanPDBName = name[:-4] + \".clean.pdb\"\n start = pose_from_pdb(cleanPDBName)\n x,y = getHBondResiduesAndAtomsV2(start)\n print (x)\n print (y)\n print (start.get_hbonds())\n" ]
[ [ "matplotlib.pyplot.show", "pandas.DataFrame" ] ]
Demon-JieHao/Modeling-Structure-for-Transformer-Network
[ "329831964731ccb7361b847e0ff7c2d809ab7231" ]
[ "thumt/layers/attention.py" ]
[ "# coding=utf-8\n# Copyright 2018 The THUMT Authors\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport tensorflow as tf\n\nfrom thumt.layers.nn import linear\n\n\ndef add_timing_signal(x, min_timescale=1.0, max_timescale=1.0e4, name=None):\n \"\"\"\n This function adds a bunch of sinusoids of different frequencies to a\n Tensor. See paper: `Attention is all you need'\n\n :param x: A tensor with shape [batch, length, channels]\n :param min_timescale: A floating point number\n :param max_timescale: A floating point number\n :param name: An optional string\n\n :returns: a Tensor the same shape as x.\n \"\"\"\n\n with tf.name_scope(name, default_name=\"add_timing_signal\", values=[x]):\n length = tf.shape(x)[1]\n channels = tf.shape(x)[2]\n position = tf.to_float(tf.range(length))\n num_timescales = channels // 2\n\n log_timescale_increment = (\n math.log(float(max_timescale) / float(min_timescale)) /\n (tf.to_float(num_timescales) - 1)\n )\n inv_timescales = min_timescale * tf.exp(\n tf.to_float(tf.range(num_timescales)) * -log_timescale_increment\n )\n\n scaled_time = (tf.expand_dims(position, 1) *\n tf.expand_dims(inv_timescales, 0))\n signal = tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=1)\n signal = tf.pad(signal, [[0, 0], [0, tf.mod(channels, 2)]])\n signal = tf.reshape(signal, [1, length, channels])\n\n return x + signal\n\n\ndef split_heads(inputs, num_heads, name=None):\n \"\"\" Split heads\n :param inputs: A tensor with shape [batch, ..., channels]\n :param num_heads: An integer\n :param name: An optional string\n :returns: A tensor with shape [batch, heads, ..., channels / heads]\n \"\"\"\n\n with tf.name_scope(name, default_name=\"split_heads\", values=[inputs]):\n x = inputs\n n = num_heads\n old_shape = x.get_shape().dims\n ndims = x.shape.ndims\n\n last = old_shape[-1]\n new_shape = old_shape[:-1] + [n] + [last // n if last else None]\n ret = tf.reshape(x, tf.concat([tf.shape(x)[:-1], [n, -1]], 0))\n ret.set_shape(new_shape)\n perm = [0, ndims - 1] + [i for i in range(1, ndims - 1)] + [ndims]\n return tf.transpose(ret, perm)\n\n\ndef combine_heads(inputs, name=None):\n \"\"\" Combine heads\n :param inputs: A tensor with shape [batch, heads, length, channels]\n :param name: An optional string\n :returns: A tensor with shape [batch, length, heads * channels]\n \"\"\"\n\n with tf.name_scope(name, default_name=\"combine_heads\", values=[inputs]):\n x = inputs\n x = tf.transpose(x, [0, 2, 1, 3])\n old_shape = x.get_shape().dims\n a, b = old_shape[-2:]\n new_shape = old_shape[:-2] + [a * b if a and b else None]\n x = tf.reshape(x, tf.concat([tf.shape(x)[:-2], [-1]], 0))\n x.set_shape(new_shape)\n\n return x\n\n\ndef attention_bias(inputs, mode, inf=-1e9, name=None):\n \"\"\" A bias tensor used in attention mechanism\n :param inputs: A tensor\n :param mode: one of \"causal\", \"masking\", \"proximal\" or \"distance\"\n :param inf: A floating value\n :param name: optional string\n :returns: A 4D tensor with shape [batch, heads, queries, memories]\n \"\"\"\n\n with tf.name_scope(name, default_name=\"attention_bias\", values=[inputs]):\n if mode == \"causal\":\n length = inputs\n lower_triangle = tf.matrix_band_part(\n tf.ones([length, length]), -1, 0\n )\n ret = inf * (1.0 - lower_triangle)\n return tf.reshape(ret, [1, 1, length, length])\n elif mode == \"masking\":\n mask = inputs\n ret = (1.0 - mask) * inf\n return tf.expand_dims(tf.expand_dims(ret, 1), 1)\n elif mode == \"proximal\":\n length = inputs\n r = tf.to_float(tf.range(length))\n diff = tf.expand_dims(r, 0) - tf.expand_dims(r, 1)\n m = tf.expand_dims(tf.expand_dims(-tf.log(1 + tf.abs(diff)), 0), 0)\n return m\n elif mode == \"distance\":\n length, distance = inputs\n distance = tf.where(distance > length, 0, distance)\n distance = tf.cast(distance, tf.int64)\n lower_triangle = tf.matrix_band_part(\n tf.ones([length, length]), -1, 0\n )\n mask_triangle = 1.0 - tf.matrix_band_part(\n tf.ones([length, length]), distance - 1, 0\n )\n ret = inf * (1.0 - lower_triangle + mask_triangle)\n return tf.reshape(ret, [1, 1, length, length])\n else:\n raise ValueError(\"Unknown mode %s\" % mode)\n\n\ndef attention(query, memories, bias, hidden_size, cache=None, reuse=None,\n dtype=None, scope=None):\n \"\"\" Standard attention layer\n\n :param query: A tensor with shape [batch, key_size]\n :param memories: A tensor with shape [batch, memory_size, key_size]\n :param bias: A tensor with shape [batch, memory_size]\n :param hidden_size: An integer\n :param cache: A dictionary of precomputed value\n :param reuse: A boolean value, whether to reuse the scope\n :param dtype: An optional instance of tf.DType\n :param scope: An optional string, the scope of this layer\n :return: A tensor with shape [batch, value_size] and\n a Tensor with shape [batch, memory_size]\n \"\"\"\n\n with tf.variable_scope(scope or \"attention\", reuse=reuse,\n values=[query, memories, bias], dtype=dtype):\n mem_shape = tf.shape(memories)\n key_size = memories.get_shape().as_list()[-1]\n\n if cache is None:\n k = tf.reshape(memories, [-1, key_size])\n k = linear(k, hidden_size, False, False, scope=\"k_transform\")\n\n if query is None:\n return {\"key\": k}\n else:\n k = cache[\"key\"]\n\n q = linear(query, hidden_size, False, False, scope=\"q_transform\")\n k = tf.reshape(k, [mem_shape[0], mem_shape[1], hidden_size])\n\n hidden = tf.tanh(q[:, None, :] + k)\n hidden = tf.reshape(hidden, [-1, hidden_size])\n\n # Shape: [batch, mem_size, 1]\n logits = linear(hidden, 1, False, False, scope=\"logits\")\n logits = tf.reshape(logits, [-1, mem_shape[1]])\n\n if bias is not None:\n logits = logits + bias\n\n alpha = tf.nn.softmax(logits)\n\n outputs = {\n \"value\": tf.reduce_sum(alpha[:, :, None] * memories, axis=1),\n \"weight\": alpha\n }\n\n return outputs\n\n\ndef additive_attention(queries, keys, values, bias, hidden_size, concat=False,\n keep_prob=None, dtype=None, scope=None):\n \"\"\" Additive attention mechanism. This layer is implemented using a\n one layer feed forward neural network\n\n :param queries: A tensor with shape [batch, heads, length_q, depth_k]\n :param keys: A tensor with shape [batch, heads, length_kv, depth_k]\n :param values: A tensor with shape [batch, heads, length_kv, depth_v]\n :param bias: A tensor\n :param hidden_size: An integer\n :param concat: A boolean value. If ``concat'' is set to True, then\n the computation of attention mechanism is following $tanh(W[q, k])$.\n When ``concat'' is set to False, the computation is following\n $tanh(Wq + Vk)$\n :param keep_prob: a scalar in [0, 1]\n :param dtype: An optional instance of tf.DType\n :param scope: An optional string, the scope of this layer\n\n :returns: A dict with the following keys:\n weights: A tensor with shape [batch, length_q]\n outputs: A tensor with shape [batch, length_q, depth_v]\n \"\"\"\n\n with tf.variable_scope(scope, default_name=\"additive_attention\",\n values=[queries, keys, values, bias], dtype=dtype):\n length_q = tf.shape(queries)[2]\n length_kv = tf.shape(keys)[2]\n q = tf.tile(tf.expand_dims(queries, 3), [1, 1, 1, length_kv, 1])\n k = tf.tile(tf.expand_dims(keys, 2), [1, 1, length_q, 1, 1])\n\n if concat:\n combined = tf.tanh(linear(tf.concat([q, k], axis=-1), hidden_size,\n True, True, name=\"qk_transform\"))\n else:\n q = linear(queries, hidden_size, True, True, name=\"q_transform\")\n k = linear(keys, hidden_size, True, True, name=\"key_transform\")\n combined = tf.tanh(q + k)\n\n # shape: [batch, heads, length_q, length_kv]\n logits = tf.squeeze(linear(combined, 1, True, True, name=\"logits\"),\n axis=-1)\n\n if bias is not None:\n logits += bias\n\n weights = tf.nn.softmax(logits, name=\"attention_weights\")\n\n if keep_prob or keep_prob < 1.0:\n weights = tf.nn.dropout(weights, keep_prob)\n\n outputs = tf.matmul(weights, values)\n\n return {\"weights\": weights, \"outputs\": outputs}\n\n\ndef multiplicative_attention(queries, keys, values, bias, keep_prob=None,\n name=None):\n \"\"\" Multiplicative attention mechanism. This layer is implemented using\n dot-product operation.\n\n :param queries: A tensor with shape [batch, heads, length_q, depth_k]\n :param keys: A tensor with shape [batch, heads, length_kv, depth_k]\n :param values: A tensor with shape [batch, heads, length_kv, depth_v]\n :param bias: A tensor\n :param keep_prob: a scalar in (0, 1]\n :param name: the name of this operation\n\n :returns: A dict with the following keys:\n weights: A tensor with shape [batch, heads, length_q, length_kv]\n outputs: A tensor with shape [batch, heads, length_q, depth_v]\n \"\"\"\n\n with tf.name_scope(name, default_name=\"multiplicative_attention\",\n values=[queries, keys, values, bias]):\n # shape: [batch, heads, length_q, length_kv]\n logits = tf.matmul(queries, keys, transpose_b=True)\n\n if bias is not None:\n logits += bias\n\n weights = tf.nn.softmax(logits, name=\"attention_weights\")\n\n if keep_prob is not None and keep_prob < 1.0:\n weights = tf.nn.dropout(weights, keep_prob)\n\n outputs = tf.matmul(weights, values)\n\n return {\"weights\": weights, \"outputs\": outputs}\n\n\ndef multihead_attention(queries, memories, bias, num_heads, key_size,\n value_size, output_size, keep_prob=None, output=True,\n state=None, dtype=None, scope=None):\n \"\"\" Multi-head scaled-dot-product attention with input/output\n transformations.\n\n :param queries: A tensor with shape [batch, length_q, depth_q]\n :param memories: A tensor with shape [batch, length_m, depth_m]\n :param bias: A tensor (see attention_bias)\n :param num_heads: An integer dividing key_size and value_size\n :param key_size: An integer\n :param value_size: An integer\n :param output_size: An integer\n :param keep_prob: A floating point number in (0, 1]\n :param output: Whether to use output transformation\n :param state: An optional dictionary used for incremental decoding\n :param dtype: An optional instance of tf.DType\n :param scope: An optional string\n\n :returns: A dict with the following keys:\n weights: A tensor with shape [batch, heads, length_q, length_kv]\n outputs: A tensor with shape [batch, length_q, depth_v]\n \"\"\"\n\n if key_size % num_heads != 0:\n raise ValueError(\"Key size (%d) must be divisible by the number of \"\n \"attention heads (%d).\" % (key_size, num_heads))\n\n if value_size % num_heads != 0:\n raise ValueError(\"Value size (%d) must be divisible by the number of \"\n \"attention heads (%d).\" % (value_size, num_heads))\n\n with tf.variable_scope(scope, default_name=\"multihead_attention\",\n values=[queries, memories], dtype=dtype):\n next_state = {}\n\n if memories is None:\n # self attention\n size = key_size * 2 + value_size\n combined = linear(queries, size, True, True, scope=\"qkv_transform\")\n q, k, v = tf.split(combined, [key_size, key_size, value_size],\n axis=-1)\n\n if state is not None:\n k = tf.concat([state[\"key\"], k], axis=1)\n v = tf.concat([state[\"value\"], v], axis=1)\n next_state[\"key\"] = k\n next_state[\"value\"] = v\n else:\n q = linear(queries, key_size, True, True, scope=\"q_transform\")\n combined = linear(memories, key_size + value_size, True,\n scope=\"kv_transform\")\n k, v = tf.split(combined, [key_size, value_size], axis=-1)\n\n # split heads\n q = split_heads(q, num_heads)\n k = split_heads(k, num_heads)\n v = split_heads(v, num_heads)\n\n # scale query\n key_depth_per_head = key_size // num_heads\n q *= key_depth_per_head ** -0.5\n\n # attention\n results = multiplicative_attention(q, k, v, bias, keep_prob)\n\n # combine heads\n weights = results[\"weights\"]\n x = combine_heads(results[\"outputs\"])\n\n if output:\n outputs = linear(x, output_size, True, True,\n scope=\"output_transform\")\n else:\n outputs = x\n\n outputs = {\"weights\": weights, \"outputs\": outputs}\n\n if state is not None:\n outputs[\"state\"] = next_state\n\n return outputs\n" ]
[ [ "tensorflow.concat", "tensorflow.reduce_sum", "tensorflow.cast", "tensorflow.tanh", "tensorflow.where", "tensorflow.name_scope", "tensorflow.to_float", "tensorflow.nn.dropout", "tensorflow.matmul", "tensorflow.shape", "tensorflow.split", "tensorflow.nn.softmax", "tensorflow.transpose", "tensorflow.sin", "tensorflow.range", "tensorflow.cos", "tensorflow.reshape", "tensorflow.expand_dims", "tensorflow.ones", "tensorflow.mod", "tensorflow.variable_scope", "tensorflow.abs" ] ]
violapterin/channel-estimation-via-dantzig-selector-code
[ "4f533725e451269fc35379a756f67f29322a10f1" ]
[ "src/test.py" ]
[ "#! /usr/bin/env python3\n\nimport numpy as np\nimport scipy as sp\nimport cvxpy as cp\nimport random\n\nimport constants as cst\nimport classes as cls\nimport functions as fct\n\naa = np.array ([[3,1,5], [2,4,6], [7,7,-7]])\nbb = np.array ([[9,7,-8], [-1,0,3]])\nx = fct.vectorize (aa)\ny = fct.vectorize (bb)\nz = np.concatenate ((x,y), axis=0)\ncc = np.concatenate ((aa,bb), axis=0)\nprint (z)\nprint (cc)\n\n'''\na = np.array ([1,3,4])\nb = np.array ([6,-2,-7])\nc = np.concatenate ((a,b))\nprint (a)\nprint (b)\nprint (c)\n'''\n\n\n'''\na = np.array ([1,3,4,2,-7]).T\nss = fct.get_largest_index (a, 2)\nprint (\"a = \", a)\nprint (\"ss = \", ss)\n#a.T [ss] = np.array ([9,9]).T\nb = np.array ([9,8]).T\nfct.assign_subvec (a, ss, b)\nprint (\"a = \", a)\nquit ()\n'''\n\n'''\nnp.set_printoptions (precision=2)\n\nnn = 5\ns = 2\nmm = 3\ng_ss = np.random.normal (0, 1, (s, 1))\nss = np.random.choice (range (nn), s)\ng = np.zeros ((nn, 1))\nfct.embed_subvec (g, ss, g_ss)\npp = np.random.normal (0, 1, (mm, nn))\nz = np.random.normal (0, 1/4, (mm, 1))\ny = pp @ g + z\nf_h = np.linalg.pinv (pp) @ y\nss_h = fct.get_supp (f_h, s)\ng_h = np.zeros ((nn, 1))\ng_h = fct.mask_vec (g_h, f_h)\n\n\nprint (f_h)\nprint (g_h)\n'''\n\nquit ()\n\n\ndef test_beta ():\n nn_yy = 8\n nn_hh = 16\n nn_y = nn_yy ** 2\n nn_h = nn_hh ** 2\n ll = 4\n num_rep = 6\n crd_true = int (np.sqrt (nn_y))\n crd_rep_true = 2 * nn_y # rep.\n crd_rep_0 = 2 * nn_h\n crd_rep_est_2 = crd_rep_true\n c_decay = 2 ^ (-6)\n #crd_est_1 = (crd_est_0 * crd_est_2) ** (1/2)\n crd_rep_est_1 = int ((crd_rep_0 + crd_rep_est_2) / 2)\n s_g = 0.2\n scale = list (range (nn_h))\n\n os.system (\"rm -r ../tmp\")\n os.system (\"mkdir ../tmp\")\n\n for i_exp in range (num_rep):\n print (\"experiment:\", i_exp)\n pp = (np.random.normal (0, 1, (nn_y, nn_h))\n + 1J * np.random.normal (0, 1, (nn_y, nn_h)))\n pp /= np.sqrt (nn_y/np.sqrt(2))\n\n kk = np.zeros ((nn_hh, nn_hh), dtype = complex)\n for n_1 in range (nn_hh):\n for n_2 in range (nn_hh):\n kk [n_1] [n_2] = ((1 / np.sqrt (nn_hh))\n * np.exp (2 * np.pi * 1J * n_1 * n_2 / nn_hh))\n\n hh = np.zeros ((nn_hh, nn_hh), dtype = complex)\n for l in range (ll):\n alpha = np.random.normal (0, nn_hh / ll) + 1J * np.random.normal (0, nn_hh / ll)\n phi = 2 * np.pi * np.sin (np.random.uniform (0, 2 * np.pi))\n theta = 2 * np.pi * np.sin (np.random.uniform (0, 2 * np.pi))\n hh += (alpha / nn_hh) * np.outer (\n np.array ([np.exp (1J * i * phi) for i in range (nn_hh)]),\n np.array ([np.exp (1J * i * theta) for i in range (nn_hh)]))\n hh = kk @ hh @ kk.conj().T\n h = fct.vectorize (hh)\n\n z = np.random.normal (0, s_g, (nn_y)) + 1J * np.random.normal (0, s_g, (nn_y))\n y = pp @ h + z\n y_rep = fct.find_rep_vec (y)\n pp_rep = fct.find_rep_mat (pp)\n\n # LS\n h_rep_hat_0th = np.linalg.pinv (pp_rep) @ y_rep\n h_hat_llss = fct.inv_find_rep_vec (h_rep_hat_0th)\n\n # DS\n h_rep = cp.Variable (2 * nn_h)\n h_rep_abs = cp.Variable (2 * nn_h)\n k = pp_rep.T @ y_rep\n qq = pp_rep.T @ pp_rep\n c = np.ones ((2 * nn_h))\n g_g = np.sqrt (2 * np.log (2 * nn_h)) * s_g\n\n prob = cp.Problem (\n cp.Minimize (c.T @ h_rep_abs),\n [h_rep - h_rep_abs <= 0,\n - h_rep - h_rep_abs <= 0,\n qq @ h_rep - g_g * c <= k,\n - qq @ h_rep - g_g * c <= - k])\n\n prob.solve (solver = cp.ECOS)\n h_rep_hat_1 = h_rep.value\n h_hat_ddss = fct.inv_find_rep_vec (h_rep_hat_1)\n\n # Plot\n h_abs = np.abs (h)\n h_hat_abs_llss = np.abs (h_hat_llss)\n h_hat_abs_ddss = np.abs (h_hat_ddss)\n h_abs_sort, h_hat_abs_llss_sort, h_hat_abs_ddss_sort = map (\n list, zip (*sorted (zip (h_abs, h_hat_abs_llss, h_hat_abs_ddss),\n reverse = True)))\n sc = np.array (range (len(h_abs_sort)))\n\n plt.plot(sc, h_abs_sort, \n marker = 'o', # circle\n markersize = 5, linestyle = \"None\")\n plt.plot(sc, h_hat_abs_llss_sort,\n marker = 'v', # triangle down\n markersize = 3, linestyle = \"None\")\n plt.plot(sc, h_hat_abs_ddss_sort,\n marker = 's', # square\n markersize = 4, linestyle = \"None\")\n nam_fil = \"../tmp/\" + str(i_exp).zfill(4) + \".png\"\n print (\" \", nam_fil)\n plt.savefig (nam_fil)\n plt.close ()\n\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # \n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # \n\ndef test_alpha ():\n nn_yy = 4\n nn_hh = 16\n nn_y = nn_yy ** 2\n nn_h = nn_hh ** 2\n ll = 4\n crd_est_2 = 2 * nn_yy\n crd_est_1 = int ((crd_est_2 * 2 * nn_h) ** (1/2))\n s_g = 0.2\n\n err_rel_llss = 0\n err_rel_ddss = 0\n err_rel_ddss_ddss = 0\n err_rel_ddss_ddss_llss = 0\n num_rep = 8\n\n for _ in range (num_rep):\n print (\"experiment\", _)\n\n pp = (np.random.normal (0, 1, (nn_y, nn_h))\n + 1J * np.random.normal (0, 1, (nn_y, nn_h)))\n pp /= np.sqrt (nn_y/np.sqrt(2))\n\n kk = np.zeros ((nn_hh, nn_hh), dtype = complex)\n for n_1 in range (nn_hh):\n for n_2 in range (nn_hh):\n kk [n_1] [n_2] = ((1 / np.sqrt (nn_hh))\n * np.exp (2 * np.pi * 1J * n_1 * n_2 / nn_hh))\n\n hh = np.zeros ((nn_hh, nn_hh), dtype = complex)\n for _ in range (ll):\n alpha = np.random.normal (0, nn_hh / ll) + 1J * np.random.normal (0, nn_hh / ll)\n phi = 2 * np.pi * np.sin (np.random.uniform (0, 2 * np.pi))\n theta = 2 * np.pi * np.sin (np.random.uniform (0, 2 * np.pi))\n hh += (alpha / nn_hh) * np.outer (\n np.array ([np.exp (1J * i * phi) for i in range (nn_hh)]),\n np.array ([np.exp (1J * i * theta) for i in range (nn_hh)]))\n hh = kk @ hh @ kk.conj().T\n h = fct.vectorize (hh)\n\n z = np.random.normal (0, s_g, (nn_y)) + 1J * np.random.normal (0, s_g, (nn_y))\n y = pp @ h + z\n y_rep = fct.find_rep_vec (y)\n pp_rep = fct.find_rep_mat (pp)\n norm_hh = np.linalg.norm (hh, ord='fro')\n\n # LS\n h_rep_hat_0 = np.linalg.pinv (pp_rep) @ y_rep\n h_hat_llss = fct.inv_find_rep_vec (h_rep_hat_0)\n hh_hat_llss = fct.inv_vectorize (h_hat_llss, nn_hh, nn_hh)\n err_rel_llss += np.linalg.norm (hh - hh_hat_llss, ord='fro') / norm_hh\n\n # DS\n h_rep = cp.Variable (2 * nn_h)\n h_rep_abs = cp.Variable (2 * nn_h)\n k = pp_rep.T @ y_rep\n qq = pp_rep.T @ pp_rep\n c = np.ones ((2 * nn_h))\n g_g = np.sqrt (2 * np.log (2 * nn_h)) * s_g\n\n prob = cp.Problem (\n cp.Minimize (c.T @ h_rep_abs),\n [h_rep - h_rep_abs <= 0,\n - h_rep - h_rep_abs <= 0,\n qq @ h_rep - g_g * c <= k,\n - qq @ h_rep - g_g * c <= - k])\n\n prob.solve (solver = cp.ECOS)\n h_rep_hat_1 = h_rep.value\n h_hat_ddss = fct.inv_find_rep_vec (h_rep_hat_1)\n hh_hat_ddss = fct.inv_vectorize (h_hat_ddss, nn_hh, nn_hh)\n err_rel_ddss += np.linalg.norm (hh - hh_hat_ddss, ord='fro') / norm_hh\n\n # DS, DS\n ss_est_1 = np.sort (np.argsort (np.abs (h_rep_hat_1)) [-crd_rep_est_1:])\n pp_rep_1 = pp_rep [:, ss_est_1]\n\n h_rep = cp.Variable (crd_rep_est_1)\n h_rep_abs = cp.Variable (crd_rep_est_1)\n k = pp_rep_1.T @ y_rep\n qq = pp_rep_1.T @ pp_rep_1\n c = np.ones ((crd_rep_est_1))\n g_g = np.sqrt (2 * np.log (crd_rep_est_1)) * s_g\n\n prob = cp.Problem (\n cp.Minimize (c.T @ h_rep_abs),\n [h_rep - h_rep_abs <= 0,\n - h_rep - h_rep_abs <= 0,\n qq @ h_rep - g_g * c <= k,\n - qq @ h_rep - g_g * c <= - k])\n\n prob.solve (solver = cp.ECOS)\n h_rep_hat_ss_2 = h_rep.value\n h_rep_hat_2 = np.zeros ((2 * nn_h))\n for i in range (crd_est_1):\n h_rep_hat_2 [ss_est_1 [i]] = h_rep_hat_ss_2 [i]\n h_hat_ddss_ddss = fct.inv_find_rep_vec (h_rep_hat_2)\n hh_hat_ddss_ddss = fct.inv_vectorize (h_hat_ddss_ddss, nn_hh, nn_hh)\n err_rel_ddss_ddss += np.linalg.norm (hh - hh_hat_ddss_ddss, ord='fro') / norm_hh\n\n # DS, DS, LS\n ss_est_2 = np.sort (np.argsort (np.abs (h_rep_hat_2)) [-crd_est_2:])\n pp_rep_2 = pp_rep [:, ss_est_2]\n\n h_rep_hat_ss_3 = np.linalg.pinv (pp_rep_2) @ y_rep\n h_rep_hat_3 = np.zeros ((2 * nn_h))\n for i in range (crd_est_2):\n h_rep_hat_3 [ss_est_2 [i]] = h_rep_hat_ss_3 [i]\n h_hat_ddss_ddss_llss = fct.inv_find_rep_vec (h_rep_hat_3)\n hh_hat_ddss_ddss_llss = fct.inv_vectorize (h_hat_ddss_ddss_llss, nn_hh, nn_hh)\n err_rel_ddss_ddss_llss += np.linalg.norm (hh - hh_hat_ddss_ddss_llss, ord='fro') / norm_hh\n\n\n err_rel_llss /= num_rep\n err_rel_ddss /= num_rep\n err_rel_ddss_ddss /= num_rep\n err_rel_ddss_ddss_llss /= num_rep\n print (\"LS: \", err_rel_llss)\n print (\"DS: \", err_rel_ddss)\n print (\"DS, DS: \", err_rel_ddss_ddss)\n print (\"DS, DS, LS: \", err_rel_ddss_ddss_llss)\n\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\nquit ()\n\n" ]
[ [ "numpy.log", "numpy.sqrt", "numpy.abs", "numpy.linalg.norm", "numpy.ones", "numpy.concatenate", "numpy.linalg.pinv", "numpy.random.normal", "numpy.exp", "numpy.random.uniform", "numpy.array", "numpy.zeros" ] ]
jdasam/scDCC
[ "8ebaed766db5ad56021983ebc13e9a60b6c7b453" ]
[ "scDCC_latent.py" ]
[ "from time import time\nimport math, os\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.nn import Parameter\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, TensorDataset\n\nfrom scDCC import scDCC\nimport numpy as np\nimport collections\nfrom sklearn import metrics\nimport h5py\nimport scanpy.api as sc\nfrom preprocess import read_dataset, normalize\nfrom utils import cluster_acc, generate_random_pair\n\n\n\nif __name__ == \"__main__\":\n\n # setting the hyper parameters\n import argparse\n parser = argparse.ArgumentParser(description='train',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--n_clusters', default=8, type=int)\n parser.add_argument('--label_cells', default=0.1, type=float)\n parser.add_argument('--label_cells_files', default='label_selected_cells_1.txt')\n parser.add_argument('--n_pairwise', default=0, type=int)\n parser.add_argument('--n_pairwise_error', default=0, type=float)\n parser.add_argument('--batch_size', default=256, type=int)\n parser.add_argument('--data_file', default='data/10X_PBMC_select_2100.h5')\n parser.add_argument('--maxiter', default=2000, type=int)\n parser.add_argument('--pretrain_epochs', default=300, type=int)\n parser.add_argument('--gamma', default=1., type=float,\n help='coefficient of clustering loss')\n parser.add_argument('--update_interval', default=1, type=int)\n parser.add_argument('--tol', default=0.001, type=float)\n parser.add_argument('--ae_weights', default=None)\n parser.add_argument('--save_dir', default='results/scDCC_p0_1/')\n parser.add_argument('--ae_weight_file', default='AE_weights_p0_1.pth.tar')\n parser.add_argument('--constraints_file', default='p0_1')\n parser.add_argument('--pretrain_latent_file', default='AE_latent.csv')\n parser.add_argument('--final_latent_file', default='FINAL_latent.csv')\n\n\n args = parser.parse_args()\n\n data_mat = h5py.File(args.data_file)\n x = np.array(data_mat['X'])\n y = np.array(data_mat['Y'])\n data_mat.close()\n\n # preprocessing scRNA-seq read counts matrix\n adata = sc.AnnData(x)\n adata.obs['Group'] = y\n\n adata = read_dataset(adata,\n transpose=False,\n test_split=False,\n copy=True)\n\n adata = normalize(adata,\n size_factors=True,\n normalize_input=True,\n logtrans_input=True)\n\n input_size = adata.n_vars\n\n print(args)\n\n print(adata.X.shape)\n print(y.shape)\n\n if not os.path.exists(args.label_cells_files):\n indx = np.arange(len(y))\n np.random.shuffle(indx)\n label_cell_indx = indx[0:int(np.ceil(args.label_cells*len(y)))]\n else:\n label_cell_indx = np.loadtxt(args.label_cells_files, dtype=np.int)\n\n x_sd = adata.X.std(0)\n x_sd_median = np.median(x_sd)\n print(\"median of gene sd: %.5f\" % x_sd_median)\n\n if args.n_pairwise > 0:\n ml_ind1, ml_ind2, cl_ind1, cl_ind2, error_num = generate_random_pair(y, label_cell_indx, args.n_pairwise, args.n_pairwise_error)\n\n print(\"Must link paris: %d\" % ml_ind1.shape[0])\n print(\"Cannot link paris: %d\" % cl_ind1.shape[0])\n print(\"Number of error pairs: %d\" % error_num)\n\n np.savetxt('ml_ind1_'+args.constraints_file+'.csv', ml_ind1, delimiter=\",\")\n np.savetxt('ml_ind2_'+args.constraints_file+'.csv', ml_ind2, delimiter=\",\")\n np.savetxt('cl_ind1_'+args.constraints_file+'.csv', cl_ind1, delimiter=\",\")\n np.savetxt('cl_ind2_'+args.constraints_file+'.csv', cl_ind2, delimiter=\",\")\n else:\n ml_ind1, ml_ind2, cl_ind1, cl_ind2 = np.array([]), np.array([]), np.array([]), np.array([])\n\n sd = 2.5\n\n model = scDCC(input_dim=adata.n_vars, z_dim=32, n_clusters=args.n_clusters, \n encodeLayer=[256, 64], decodeLayer=[64, 256], sigma=sd, gamma=args.gamma).cuda()\n \n print(str(model))\n\n t0 = time()\n if args.ae_weights is None:\n model.pretrain_autoencoder(x=adata.X, raw_counts=adata.raw.X, size_factor=adata.obs.size_factors, \n batch_size=args.batch_size, epochs=args.pretrain_epochs, ae_weights=args.ae_weight_file)\n else:\n if os.path.isfile(args.ae_weights):\n print(\"==> loading checkpoint '{}'\".format(args.ae_weights))\n checkpoint = torch.load(args.ae_weights)\n model.load_state_dict(checkpoint['ae_state_dict'])\n else:\n print(\"==> no checkpoint found at '{}'\".format(args.ae_weights))\n raise ValueError\n \n print('Pretraining time: %d seconds.' % int(time() - t0))\n\n pretrain_latent = model.encodeBatch(torch.tensor(adata.X).cuda()).cpu().numpy()\n np.savetxt(args.pretrain_latent_file, pretrain_latent, delimiter=\",\")\n\n if not os.path.exists(args.save_dir):\n os.makedirs(args.save_dir)\n\n y_pred, _, _, _, _ = model.fit(X=adata.X, X_raw=adata.raw.X, sf=adata.obs.size_factors, y=y, batch_size=args.batch_size, num_epochs=args.maxiter, \n ml_ind1=ml_ind1, ml_ind2=ml_ind2, cl_ind1=cl_ind1, cl_ind2=cl_ind2,\n update_interval=args.update_interval, tol=args.tol, save_dir=args.save_dir)\n print('Total time: %d seconds.' % int(time() - t0))\n\n eval_cell_y_pred = np.delete(y_pred, label_cell_indx)\n eval_cell_y = np.delete(y, label_cell_indx)\n acc = np.round(cluster_acc(eval_cell_y, eval_cell_y_pred), 5)\n nmi = np.round(metrics.normalized_mutual_info_score(eval_cell_y, eval_cell_y_pred), 5)\n ari = np.round(metrics.adjusted_rand_score(eval_cell_y, eval_cell_y_pred), 5)\n print('Evaluating cells: ACC= %.4f, NMI= %.4f, ARI= %.4f' % (acc, nmi, ari))\n\n if not os.path.exists(args.label_cells_files):\n np.savetxt(args.label_cells_files, label_cell_indx, fmt=\"%i\")\n\n final_latent = model.encodeBatch(torch.tensor(adata.X).cuda()).cpu().numpy()\n np.savetxt(args.final_latent_file, final_latent, delimiter=\",\")" ]
[ [ "torch.load", "numpy.median", "numpy.random.shuffle", "sklearn.metrics.normalized_mutual_info_score", "torch.tensor", "numpy.delete", "numpy.savetxt", "sklearn.metrics.adjusted_rand_score", "numpy.array", "numpy.loadtxt" ] ]
neloial/tac
[ "b4d92629c293a15016fed0ce80a7dfde4bf68b19" ]
[ "scripts TP4/script_tp4_neloial.py" ]
[ "\"\"\"Analyse frequency distribution of words\"\"\"\n\nimport nltk\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\nfrom nltk.corpus import stopwords\nfrom collections import defaultdict\nfrom textblob import Blobber\nfrom textblob_fr import PatternTagger, PatternAnalyzer\n\nsw = stopwords.words(\"french\")\nsw += [\"les\", \"plus\", \"cette\", \"fait\", \"faire\", \"être\", \"deux\", \"comme\", \"dont\", \"tout\", \n \"ils\", \"bien\", \"sans\", \"peut\", \"tous\", \"après\", \"ainsi\", \"donc\", \"cet\", \"sous\",\n \"celle\", \"entre\", \"encore\", \"toutes\", \"pendant\", \"moins\", \"dire\", \"cela\", \"non\",\n \"faut\", \"trois\", \"aussi\", \"dit\", \"avoir\", \"doit\", \"contre\", \"depuis\", \"autres\",\n \"van\", \"het\", \"autre\", \"jusqu\"]\nsw = set(sw)\ntb = Blobber(pos_tagger=PatternTagger(), analyzer=PatternAnalyzer())\n# limit = 10**8\n\ndata_path = \"/Volumes/Extreme SSD/Temp/TPTraitAuto/data/txt2/\"\nfiles = os.listdir(data_path)\ncovered_years = set()\ndic = defaultdict(int)\n\n\nfor f in sorted(files):\n if \"_\" in f:\n elems = f.split(\"_\")\n city = elems[0]\n year = elems[1]\n tome = elems[3]\n part = elems[5]\n covered_years.add(year)\n decade = year[:3] + \"0s\"\n dic[decade] += 1\n else:\n print(f\"Anomalous file: {f}\")\n with open(data_path + f, encoding='latin-1') as fil:\n text = fil.read()\n words = nltk.Text(nltk.word_tokenize(text))\n match = words.concordance('prix', width = 300, lines = 100)\n #print(f\"{f} contains these mentions of price:\")\n #print(match)\n output_file = 'sent_prix' + city + '_' + year + '_' + tome + '_' + part\n output_path = os.path.join('/Volumes/Extreme SSD/Temp/TPTraitAuto/data/sentiment_raw/',str(output_file))\n original_stdout = sys.stdout\n with open(output_path, 'w') as fil2:\n sys.stdout = fil2\n print(match)\n sys.stdout = original_stdout\n input_text = match\n blob = tb(input_text)\n pola, subj = blob.sentiment\n perc = f\"{100*abs(pola):.0f}\"\n if pola > 0:\n sent = f\"{perc}% positive\"\n elif pola < 0:\n sent = f\"{perc}% negative\"\n else:\n sent = \"neutral\"\n if subj > 0:\n fact = f\"{100*subj:.0f}% subjective\"\n else:\n fact = \"perfectly objective\"\n print(f\"This text is {sent} and {fact}.\")\n\n# make graph of frequency of the word prix per year \n\n with open(data_path + f, encoding='latin-1') as fil:\n text = fil.read()\n words = nltk.wordpunct_tokenize(text)\n print(f\"{len(words)} words found\")\n kept = [w.lower() for w in words if w in ('prix', 'travaux', 'construction')]\n voc = set(kept)\n print(f\"{len(kept)} words kept ({len(voc)} different word forms)\")\n fig = plt.figure(figsize = (10,4))\n plt.gcf().subplots_adjust(bottom=0.15) # to avoid x-ticks cut-off\n fdist = nltk.FreqDist(kept)\n print(fdist.most_common(50))\n fdist.plot(3, cumulative=False)\n #fdist.plot(50, cumulative=True)\n print(fdist.hapaxes())\n p = 'plot_' + city + '_' + year + '_' + tome + '_' + part\n output_path = os.path.join('/Volumes/Extreme SSD/Temp/TPTraitAuto/data/plots/',str(p)+'.png')\n fig.savefig(output_path, bbox_inches = \"tight\")" ]
[ [ "matplotlib.pyplot.gcf", "matplotlib.pyplot.figure" ] ]
takua624/brainiak
[ "4774975bef95a445a1b62a5809627a6f023297d9" ]
[ "examples/utils/fmrisim_example.py" ]
[ "# Copyright 2016 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"fMRI Simulator example script\n\nExample script to generate a run of a participant's data. This generates\ndata representing a pair of conditions that are then combined\n\n Authors: Cameron Ellis (Princeton) 2016\n\"\"\"\nimport logging\nimport numpy as np\nfrom brainiak.utils import fmrisim as sim\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D # noqa: F401\nimport nibabel\n\nlogger = logging.getLogger(__name__)\n\n# Inputs for generate_signal\ndimensions = np.array([64, 64, 36]) # What is the size of the brain\nfeature_size = [9, 4, 9, 9]\nfeature_type = ['loop', 'cube', 'cavity', 'sphere']\ncoordinates_A = np.array(\n [[32, 32, 18], [26, 32, 18], [32, 26, 18], [32, 32, 12]])\ncoordinates_B = np.array(\n [[32, 32, 18], [38, 32, 18], [32, 38, 18], [32, 32, 24]])\nsignal_magnitude = [1, 0.5, 0.25, -1] # In percent signal change\n\n# Inputs for generate_stimfunction\nonsets_A = [10, 30, 50, 70, 90]\nonsets_B = [0, 20, 40, 60, 80]\nevent_durations = [6]\ntr_duration = 2\ntemporal_res = 1000.0 # How many elements per second are there\nduration = 100\n\n# Specify a name to save this generated volume.\nsavename = 'examples/utils/example.nii'\n\n# Generate a volume representing the location and quality of the signal\nvolume_signal_A = sim.generate_signal(dimensions=dimensions,\n feature_coordinates=coordinates_A,\n feature_type=feature_type,\n feature_size=feature_size,\n signal_magnitude=signal_magnitude,\n )\n\nvolume_signal_B = sim.generate_signal(dimensions=dimensions,\n feature_coordinates=coordinates_B,\n feature_type=feature_type,\n feature_size=feature_size,\n signal_magnitude=signal_magnitude,\n )\n\n# Visualize the signal that was generated for condition A\nfig = plt.figure()\nsim.plot_brain(fig,\n volume_signal_A)\nplt.show()\n\n# Create the time course for the signal to be generated\nstimfunction_A = sim.generate_stimfunction(onsets=onsets_A,\n event_durations=event_durations,\n total_time=duration,\n temporal_resolution=temporal_res,\n )\n\nstimfunction_B = sim.generate_stimfunction(onsets=onsets_B,\n event_durations=event_durations,\n total_time=duration,\n temporal_resolution=temporal_res,\n )\n\n# Convolve the HRF with the stimulus sequence\nsignal_function_A = sim.convolve_hrf(stimfunction=stimfunction_A,\n tr_duration=tr_duration,\n temporal_resolution=temporal_res,\n )\n\nsignal_function_B = sim.convolve_hrf(stimfunction=stimfunction_B,\n tr_duration=tr_duration,\n temporal_resolution=temporal_res,\n )\n\n# Multiply the HRF timecourse with the signal\nsignal_A = sim.apply_signal(signal_function=signal_function_A,\n volume_signal=volume_signal_A,\n )\n\nsignal_B = sim.apply_signal(signal_function=signal_function_B,\n volume_signal=volume_signal_B,\n )\n\n# Combine the signals from the two conditions\nsignal = signal_A + signal_B\n\n# Combine the stim functions\nstimfunction = list(np.add(stimfunction_A, stimfunction_B))\nstimfunction_tr = stimfunction[::int(tr_duration * temporal_res)]\n\n# Generate the mask of the signal\nmask, template = sim.mask_brain(signal, mask_threshold=0.2)\n\n# Mask the signal to the shape of a brain (attenuates signal according to grey\n# matter likelihood)\nsignal *= mask.reshape(dimensions[0], dimensions[1], dimensions[2], 1)\n\n# Generate original noise dict for comparison later\norig_noise_dict = sim._noise_dict_update({})\n\n# Create the noise volumes (using the default parameters\nnoise = sim.generate_noise(dimensions=dimensions,\n stimfunction_tr=stimfunction_tr,\n tr_duration=tr_duration,\n mask=mask,\n template=template,\n noise_dict=orig_noise_dict,\n )\n\n# Standardize the signal activity to make it percent signal change\nmean_act = (mask * orig_noise_dict['max_activity']).sum() / (mask > 0).sum()\nsignal = signal * mean_act / 100\n\n# Combine the signal and the noise\nbrain = signal + noise\n\n# Display the brain\nfig = plt.figure()\nfor tr_counter in list(range(0, brain.shape[3])):\n\n # Get the axis to be plotted\n ax = sim.plot_brain(fig,\n brain[:, :, :, tr_counter],\n mask=mask,\n percentile=99.9)\n\n # Wait for an input\n logging.info(tr_counter)\n plt.pause(0.5)\n\n# Save the volume\naffine_matrix = np.diag([-1, 1, 1, 1]) # LR gets flipped\nbrain_nifti = nibabel.Nifti1Image(brain, affine_matrix) # Create a nifti brain\nnibabel.save(brain_nifti, savename)\n\n# Load in the test dataset and generate a random volume based on it\n\n# Pull out the data and associated data\nvolume = nibabel.load(savename).get_data()\ndimensions = volume.shape[0:3]\ntotal_time = volume.shape[3] * tr_duration\nstimfunction = sim.generate_stimfunction(onsets=[],\n event_durations=[0],\n total_time=total_time,\n )\nstimfunction_tr = stimfunction[::int(tr_duration * temporal_res)]\n\n# Calculate the mask\nmask, template = sim.mask_brain(volume=volume,\n mask_self=True,\n )\n\n# Calculate the noise parameters\nnoise_dict = sim.calc_noise(volume=volume,\n mask=mask,\n )\n\n# Create the noise volumes (using the default parameters\nnoise = sim.generate_noise(dimensions=dimensions,\n tr_duration=tr_duration,\n stimfunction_tr=stimfunction_tr,\n template=template,\n mask=mask,\n noise_dict=noise_dict,\n )\n\n# Create a nifti brain\nbrain_noise = nibabel.Nifti1Image(noise, affine_matrix)\nnibabel.save(brain_noise, 'examples/utils/example2.nii') # Save\n" ]
[ [ "numpy.diag", "numpy.add", "numpy.array", "matplotlib.pyplot.pause", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
fritzt/gcgridobj
[ "727778b26cbf1a35ecf741665469f08084d4be44" ]
[ "gcgridobj/atmos_isa_mini.py" ]
[ "import numpy as np\nfrom . import physconstants\n\n# Persistent (module) variables\nz_int = None\np_int = None\n\ndef altitude_to_many(z_m):\n '''Lightweight version of atmosisa from the Aerospace Toolbox'''\n\n # Sort from lowest to highest altitude\n sort_idx = np.argsort(z_m)\n #z_sorted = z_m[sort_idx]\n \n # COESA data\n height_vec = np.array([-0.1,0,11,20,32,47,51,71,84.8520,1e6]) # km\n lapse_vec = np.array([0.0,-6.5,0.0,1.0,2.8,0.0,-2.8,-2.0,0.0]) # K/km\n T_reference = 288.15\n height_delta = np.diff(height_vec)\n\n # Change in temperature between each level\n T_delta = height_delta*lapse_vec\n T_vec = np.cumsum(np.concatenate([[T_reference],T_delta]))\n\n # Gas composition\n gas_MW = [28.0134,31.9988,39.948,44.00995,20.183,4.0026,83.80,131.30,16.04303,2.01594]\n\n gas_frac = [0.78084,0.209476,0.00934,0.000314,0.00001818,0.00000524,0.00000114,0.000000087,0.000002,0.0000005]\n\n # Normalize, to be 100% safe\n gas_frac = gas_frac/np.sum(gas_frac)\n \n n_vals = z_m.size\n p_pa = np.zeros(n_vals)\n\n # Temperature at target altitudes\n T_K = np.interp(z_m/1000.0,height_vec,T_vec)\n\n R_star = physconstants.R_gas # J/K/mol\n g0 = physconstants.g0 # m/s2\n\n iLo = 0\n iHi = 1\n zLo = height_vec[0] * 1000.0\n zHi = height_vec[1] * 1000.0\n MgR = sum(gas_frac*gas_MW)*1e-3*g0/R_star\n TLo = T_vec[iLo]\n alphaTemp = 0\n # Exponential offset\n P_base = 101325 * np.exp(-MgR*zLo/TLo)\n for iPoint in range(T_K.size):\n i_sort = sort_idx[iPoint]\n zCurr = z_m[i_sort]\n while zCurr > zHi:\n if np.abs(alphaTemp) > 0:\n PNew = P_base * np.power(T_vec[iHi]/T_vec[iLo],MgR/-alphaTemp)\n else:\n PNew = P_base * np.exp(MgR*(zLo-zHi)/TLo)\n \n #fprintf('%5.2f km, %5.2f K, %9.2f -> %9.2f hPa, %8.5f K/m,\\n',HVec(iLo),TVec(iLo),PBase./100,PNew./100,alphaTemp);\n P_base = PNew\n iLo = iHi\n iHi += 1\n zLo = zHi\n zHi = height_vec[iHi] * 1000\n TLo = T_vec[iLo]\n alphaTemp = lapse_vec[iLo] / 1000\n \n if np.abs(alphaTemp) > 0:\n p_pa[i_sort] = P_base * np.power(T_K[i_sort]/TLo,MgR/-alphaTemp)\n else:\n p_pa[i_sort] = P_base * np.exp(MgR*(zLo-zCurr)/TLo)\n\n # Also calculate air density in kg/m3\n rho_kgm3 = (28.97e-3) * p_pa[sort_idx] / (8.314 * T_K[sort_idx])\n #dynVisc = (np.power(T_K,1.5) * 1.458e-6)/(T_K + 110.4)\n #kinVisc = dynVisc/rho_kgm3\n\n return p_pa, T_K, rho_kgm3\n\ndef altitude_to_pressure(z_m):\n p_pa, T_K, rho_kgm3 = altitude_to_many(z_m)\n return p_pa\n\ndef pressure_to_altitude(p_pa):\n '''ATMOSPALT Lightweight version of atmospalt from the MATLAB Aerospace Toolbox\n Returns the COESA estimate of altitude (in m) for a pressure (in Pa)'''\n # Use the module-level variables\n global z_int, p_int\n\n # Generate interpolation vecor\n if z_int is None or p_int is None:\n z_int = np.arange(82e3,-1e3,-1.0)\n p_int = altitude_to_pressure(z_int)\n\n z_m = np.interp(np.array(p_pa),p_int,z_int,np.inf,z_int[-1])\n return z_m\n" ]
[ [ "numpy.abs", "numpy.power", "numpy.arange", "numpy.concatenate", "numpy.diff", "numpy.interp", "numpy.exp", "numpy.argsort", "numpy.array", "numpy.zeros", "numpy.sum" ] ]
timgates42/jax
[ "ac62a5a6bdd3395046470516e7873f20ab62bd55" ]
[ "tests/api_test.py" ]
[ "# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport collections\nfrom contextlib import contextmanager\nimport copy\nfrom functools import partial\nimport re\nimport unittest\nimport types\nimport warnings\nimport weakref\nimport functools\nimport itertools as it\n\nfrom absl import logging\nfrom absl.testing import absltest, parameterized\nimport numpy as np\n\nimport concurrent.futures\n\nimport jax\nimport jax.numpy as jnp\nfrom jax import float0, jit, grad, device_put, jacfwd, jacrev, hessian\nfrom jax import api, core, lax, lax_reference, lazy\nfrom jax.core import Primitive\nfrom jax.interpreters import ad\nfrom jax.interpreters import xla\nfrom jax.interpreters.sharded_jit import PartitionSpec as P\nfrom jax.lib import xla_bridge as xb\nfrom jax import test_util as jtu\nfrom jax import tree_util\nfrom jax import linear_util as lu\nfrom jax.lib import version\n\nfrom jax.config import config\nconfig.parse_flags_with_absl()\nFLAGS = config.FLAGS\n\n\nclass CPPJitTest(jtu.JaxTestCase):\n \"\"\"Shared tests between the Python and the C++ jax,jit implementations.\n\n Because the Python implementation supports more features, we need to have the\n Python tests that extend the C++ tests (and not the other way around).\n \"\"\"\n\n @property\n def jit(self):\n # Right now, the CPP tests also test the Python code-path when jaxlib is\n # too old.\n # TODO(jblespiau,phawkins): Remove this when jaxlib has been released.\n # This is in the future, because we are making a breaking change to\n # Tensorflow.\n if version <= (0, 1, 55):\n raise unittest.SkipTest(\"Disabled because it depends on some future \"\n \"release of jax_jit.cc within jaxlib.\")\n else:\n return jax.api._cpp_jit\n\n def test_jit_of_noncallable(self):\n self.assertRaisesRegex(TypeError, \"Expected a callable value.*\",\n lambda: self.jit(3))\n\n def test_jit_of_generator(self):\n\n def gen(x):\n yield x\n\n self.assertRaisesRegex(TypeError,\n \"Expected a function, got a generator function.*\",\n lambda: self.jit(gen))\n\n @parameterized.parameters([\n # Integer support\n (1, 2, 3, 4, 5),\n # Numpy array support\n (\n np.asarray(1, np.int32),\n np.asarray(2, np.int32),\n np.asarray(3, np.int32),\n np.asarray(4, np.int32),\n np.asarray(5, np.int32),\n ),\n ])\n def test_jit_static_args(self, one, two, three, four, five):\n side = []\n # For the CPP jit, we need to clear the cache to prevent cache hits between\n # parameterized tests.\n if hasattr(self.jit, \"cache_clear\"):\n self.jit.cache_clear()\n\n def f(x, y, z, flag=False, flag2=False):\n del flag2 # unused\n assert flag\n side.append(None)\n return 100 * x + 10 * y + z\n\n f1 = self.jit(f, static_argnums=(3, 4))\n assert f1(one, two, three, True, False) == 123\n assert len(side) == 1\n assert f1(one, two, three, True, False) == 123\n assert len(side) == 1 # Obvious cache hit.\n assert f1(two, one, three, True, False) == 213\n assert len(side) == 1 # Should cache hit because same signature.\n assert f1(two, one, three, True, True) == 213\n assert len(side) == 2\n\n side[:] = []\n f2 = self.jit(f, static_argnums=(0, 2, 3, 4))\n assert f2(1, 2, 3, True, False) == 123\n assert len(side) == 1\n assert f2(1, 3, 3, True, False) == 133\n assert len(side) == 1\n assert f2(2, 2, 3, True, False) == 223\n assert len(side) == 2\n assert f2(2, 4, 3, True, False) == 243\n assert len(side) == 2\n assert f2(2, 4, 3, True, True) == 243\n assert len(side) == 3\n assert f2(2, 5, 3, True, True) == 253\n assert len(side) == 3\n\n def test_static_args_equality(self):\n if version < (0, 1, 57):\n raise unittest.SkipTest(\"this test requires a newest jaxlib\")\n\n class A():\n\n def __hash__(self):\n return 1\n\n def __eq__(self, other):\n return isinstance(other, A)\n\n side = []\n def f(x, static_arg):\n del static_arg\n side.append(None)\n return x * 100\n\n f1 = self.jit(f, static_argnums=(1,))\n\n self.assertEqual(f1(1, A()), 100)\n self.assertLen(side, 1)\n self.assertEqual(f1(1, A()), 100)\n self.assertLen(side, 1)\n if self.jit == jax.api._cpp_jit:\n self.assertEqual(f1._cpp_jitted_f._cache_size(), 1)\n\n @parameterized.parameters([\n (1, 2, 3),\n (\n np.asarray(1, np.int32),\n np.asarray(2, np.int32),\n np.asarray(3, np.int32),\n ),\n ])\n def test_jit_kwargs(self, one, two, three):\n side = []\n # For the CPP jit, we need to clear the cache to prevent cache hits between\n # parameterized tests.\n if hasattr(self.jit, \"cache_clear\"):\n self.jit.cache_clear()\n\n def f(x, y, z):\n print(x, y, z)\n side.append(None)\n return 100 * x + 10 * y + z\n\n f = self.jit(f)\n assert f(one, two, three) == 123\n assert len(side) == 1\n assert f(one, two, three) == 123\n assert len(side) == 1\n\n assert f(one, two, z=three) == 123\n assert len(side) == 2 # actually recompiles from kwarg\n assert f(one, two, z=three) == 123\n assert len(side) == 2 # but should still cache\n\n f(one, two, z=np.zeros(3)) # doesn't crash\n if FLAGS.jax_enable_x64:\n # In the above call, three is of a new type (int64), thus it should\n # trigger a new compilation.\n assert len(side) == 3\n\n def test_jit_device(self):\n device = xb.devices()[-1]\n x = self.jit(lambda x: x, device=device)(3.)\n self.assertIsInstance(x, xla.DeviceArray)\n self.assertEqual(x.device_buffer.device(), device)\n\n def test_complex_support(self):\n self.assertEqual(self.jit(lambda x: x + 1)(1 + 1j), 2 + 1j)\n\n def test_jit_with_many_args_works(self):\n\n @self.jit\n def f(args_list):\n return sum(args_list)\n\n self.assertEqual(f(list(range(500))), sum(range(500)))\n\n # Jit and Donate arguments\n assertDeleted = lambda self, x: self._assertDeleted(x, True)\n assertNotDeleted = lambda self, x: self._assertDeleted(x, False)\n\n def _assertDeleted(self, x, deleted):\n if hasattr(x, \"device_buffer\"):\n self.assertEqual(x.device_buffer.is_deleted(), deleted)\n else:\n for buffer in x.device_buffers:\n self.assertEqual(buffer.is_deleted(), deleted)\n\n def test_jit_donate_argnums_warning_raised(self):\n x = jnp.array([1.0, 2.0], jnp.float32)\n y = jnp.array([1, 2], jnp.int32)\n f = self.jit(lambda x, y: x.sum() + y.sum(), donate_argnums=(0, 1))\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n f(x, y)\n\n self.assertLen(w, 1)\n self.assertTrue(issubclass(w[-1].category, UserWarning))\n self.assertIn(\n \"Some donated buffers were not usable: f32[2]{0}, s32[2]{0}\",\n str(w[-1].message))\n\n @jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\n def test_jit_donate_argnums_invalidates_input(self):\n # We can't just use `lambda x: x` because JAX simplifies this away to an\n # empty XLA computation.\n move = self.jit(lambda x: x + x - x, donate_argnums=0)\n x = jnp.ones([])\n y = move(x)\n self.assertDeleted(x)\n self.assertEqual(y, 1.)\n\n @jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\n def test_jit_donate_argnums_static_argnums(self):\n jit_fun = self.jit(\n lambda a, b, c, d: ((a + b + c), (a + b + d)),\n static_argnums=(0, 1),\n donate_argnums=(2, 3))\n\n c = jax.device_put(jnp.array([1., 1.]))\n d = jax.device_put(jnp.array([1., 1., 1.]))\n e, f = jit_fun(1, 2, c, d)\n np.testing.assert_allclose(e, jnp.array([4., 4.]))\n np.testing.assert_allclose(f, jnp.array([4., 4., 4.]))\n self.assertDeleted(c)\n self.assertDeleted(d)\n\n @jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\n def test_jnp_array_copy(self):\n # https://github.com/google/jax/issues/3412\n\n @partial(self.jit, donate_argnums=(0,))\n def _test(array):\n return array.at[0].set(77)\n\n x = jnp.asarray([0, 1])\n x_copy = jnp.array(x, copy=True)\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n _test(x) # donation\n\n # Gives: RuntimeError: Invalid argument: CopyToHostAsync() called on invalid buffer.\n print(x_copy) # doesn't crash\n\n def test_jit_global_cache(self):\n def f(x):\n assert python_should_be_executing\n return x\n\n python_should_be_executing = True\n self.jit(f)(2)\n python_should_be_executing = False\n self.jit(f)(3)\n\n def test_jit_shallow_copy(self):\n def f(x):\n return copy.copy(x)\n self.jit(f)(1)\n\n def test_jit_deep_copy(self):\n def f(x):\n return copy.deepcopy(x)\n self.jit(f)(1)\n\n def test_disable_jit(self):\n effects = []\n\n @self.jit\n def f(x):\n effects.append(1)\n return x\n\n with api.disable_jit():\n f(2)\n f(2)\n assert len(effects) == 2\n\n f(2)\n f(2)\n assert len(effects) == 3\n\n def test_static_argnum_errors_on_keyword_arguments(self):\n if version < (0, 1, 58):\n raise unittest.SkipTest(\"Disabled because it depends on some future \"\n \"release of jax_jit.cc within jaxlib.\")\n f = self.jit(lambda x: x, static_argnums=0)\n msg = (\"jitted function has static_argnums=(0,), donate_argnums=() but was \"\n \"called with only 0 positional arguments.\")\n with self.assertRaisesRegex(ValueError, re.escape(msg)):\n f(x=4)\n\n def test_static_argnum_on_method(self):\n\n class A:\n\n @functools.partial(self.jit, static_argnums=(0,))\n def my_func_jit(self, x):\n return x+2\n\n A().my_func_jit(3)\n\n def test_static_argnum_on_static_method_is_not_supported(self):\n with self.assertRaisesRegex(TypeError, \"Expected a callable value\"):\n\n class A:\n\n @functools.partial(self.jit, static_argnums=(0,))\n @classmethod\n def my_classmethod_jit(cls, x):\n return x+2\n\n def test_classmethod_is_not_supported(self):\n with self.assertRaisesRegex(TypeError, \"Expected a callable value\"):\n\n class A:\n\n @functools.partial(self.jit)\n @staticmethod\n def my_staticmethod_jit(x):\n return x + 2\n\n def test_concurrent_jit(self):\n @self.jit\n def f(x):\n return x + x - 3.\n\n xs = [np.random.randn(i) for i in range(10)]\n with concurrent.futures.ThreadPoolExecutor() as executor:\n futures = [executor.submit(partial(f, x)) for x in xs]\n ys = [f.result() for f in futures]\n for x, y in zip(xs, ys):\n self.assertAllClose(x * 2 - 3., y)\n\n def test_trivial_computations(self):\n x = jnp.array([1, 2, 3])\n y = self.jit(lambda x: x)(x)\n self.assertIs(x, y)\n\n z1, z2 = self.jit(lambda x: (x, x))(x)\n self.assertIs(z1, z2)\n\n x1, x2 = jnp.array([1, 2]), jnp.array([2, 3])\n z1, z2, z3 = self.jit(lambda x, y: (y, 1, x))(x1, x2)\n self.assertIs(z1, x2)\n self.assertIs(z3, x1)\n self.assertEqual(z2, 1)\n\n def test_jit_bad_input(self):\n def f(x):\n return x\n\n self.assertRaisesRegex(\n TypeError, \".* 'foo' of type <.*'str'> is not a valid JAX type\",\n lambda: self.jit(f)(\"foo\"))\n\n def test_jit_on_all_devices(self):\n # Verifies we can run the same computation on every device present, even\n # if they are, for example, different models of GPU.\n data = np.random.rand(1000).astype(np.float32)\n f = self.jit(jnp.negative)\n for device in jax.local_devices():\n x = device_put(data, device=device)\n np.testing.assert_array_equal(-data, f(x))\n\n def test_jit_nested_donate_ignored(self):\n jit_fun = self.jit(lambda x: self.jit(lambda y: y**2, donate_argnums=0)(x))\n a = jax.device_put(jnp.array(1))\n\n # NOTE(mattjj): stopped raising error here and instead just ignored\n # with self.assertRaisesRegex(ValueError, \"nested.*not supported\"):\n # jit_fun(a)\n\n jit_fun(a) # doesn't crash\n\n def test_jit_reference_dropping(self):\n x = jnp.ones(10)\n f = (lambda x: lambda: x)(x) # reference to x in f's closure\n g = self.jit(f)\n x = weakref.ref(x) # no more strong ref to x in this scope\n assert x() is not None # x is still around\n f() # f runs\n g() # g runs\n g() # g runs a second time\n del f # delete the raw callable\n assert x() is not None # x is still around\n g() # g still runs\n del g # no more references to x\n assert x() is None # x is gone\n\n def test_jit_raises_on_first_invocation_on_non_hashable_static_argnum(self):\n if self.jit != jax.api._python_jit:\n raise unittest.SkipTest(\"this test only applies to _python_jit\")\n f = lambda x, y: x + 3\n jitted_f = self.jit(f, static_argnums=(1,))\n\n msg = (\"Non-hashable static arguments are not supported, as this can lead \"\n \"to unexpected cache-misses. Static argument (index 1) of type \"\n \"<class 'numpy.ndarray'> for function <lambda> is non-hashable.\")\n with self.assertRaisesRegex(ValueError, re.escape(msg)):\n jitted_f(1, np.asarray(1))\n\n def test_cpp_jit_raises_on_non_hashable_static_argnum(self):\n if version < (0, 1, 57):\n raise unittest.SkipTest(\"Disabled because it depends on some future \"\n \"release of jax_jit.cc within jaxlib.\")\n\n if self.jit != jax.api._cpp_jit:\n raise unittest.SkipTest(\"this test only applies to _cpp_jit\")\n\n f = lambda x, y: x + 3\n jitted_f = jax.api._cpp_jit(f, static_argnums=[1])\n\n jitted_f(1, 1)\n\n msg = (\"Non-hashable static arguments are not supported. An error occured \"\n \"while trying to hash an object of type <class 'numpy.ndarray'>, 1. \"\n \"The error was:\\nTypeError: unhashable type: 'numpy.ndarray'\")\n\n with self.assertRaisesRegex(ValueError, re.escape(msg)):\n jitted_f(1, np.asarray(1))\n\n class HashableWithoutEq:\n\n def __hash__(self):\n return 1\n\n def __eq__(self, other):\n raise NotImplementedError(\n \"A Python error is as is, without stack trace\")\n\n with self.assertRaisesRegex(\n ValueError,\n re.escape(\"static arguments should be comparable using __eq__\")):\n jitted_f(1, HashableWithoutEq())\n\n def test_cpp_jitted_function_returns_PyBuffer(self):\n if version < (0, 1, 58):\n raise unittest.SkipTest(\"Disabled because it depends on some future \"\n \"release of jax_jit.cc within jaxlib.\")\n if self.jit != jax.api._cpp_jit:\n raise unittest.SkipTest(\"this test only applies to _cpp_jit\")\n\n jitted_f = self.jit(lambda a: a + 1)\n jitted_f(1)\n self.assertIsInstance(jitted_f(2), xla._CppDeviceArray)\n\n @jtu.skip_on_devices(\"cpu\")\n def test_explicit_backend(self):\n f = lambda x: x + 1\n jitted_f = jit(f, backend=jtu.device_under_test())\n jitted_f_cpu = jit(f, backend=\"cpu\")\n\n result = jitted_f(1.)\n result_cpu = jitted_f_cpu(1.)\n self.assertEqual(result.device_buffer.platform(), jtu.device_under_test())\n self.assertEqual(result_cpu.device_buffer.platform(), \"cpu\")\n\n @jtu.skip_on_devices(\"cpu\")\n def test_mismatched_nested_backends(self):\n @partial(jit, backend=jtu.device_under_test())\n def f(x):\n return jit(lambda x: x + 1, backend=\"cpu\")(x)\n\n with self.assertRaisesRegex(\n ValueError,\n f\"Outer-jit backend specification {jtu.device_under_test()} must match \"\n f\"explicit inner-jit backend specification cpu.\"):\n f(1.)\n\n\nclass PythonJitTest(CPPJitTest):\n\n @property\n def jit(self):\n return jax.api._python_jit\n\n\nclass APITest(jtu.JaxTestCase):\n\n def test_grad_bad_input(self):\n def f(x):\n return x\n\n self.assertRaisesRegex(\n TypeError, \".* 'foo' of type <.*'str'> is not a valid JAX type\",\n lambda: grad(f)(\"foo\"))\n\n def test_grad_argnums(self):\n def f(x, y, z, flag=False):\n assert flag\n return 1.0 * x + 2.0 * y + 3.0 * z\n\n assert grad(f)(1.0, 1.0, 1.0, flag=True) == 1.0\n assert grad(f, argnums=1)(1.0, 1.0, 1.0, flag=True) == 2.0\n assert grad(f, argnums=(2, 0))(1.0, 1.0, 1.0, flag=True) == (3.0, 1.0)\n\n def test_value_and_grad_argnums(self):\n def f(x, y, z, flag=False):\n assert flag\n return 1.0 * x + 2.0 * y + 3.0 * z\n\n y = f(1.0, 1.0, 1.0, flag=True)\n assert api.value_and_grad(f)(1.0, 1.0, 1.0, flag=True) == (y, 1.0)\n assert api.value_and_grad(f, argnums=1)(1.0, 1.0, 1.0, flag=True) == (y, 2.0)\n assert api.value_and_grad(f, argnums=(2, 0))(1.0, 1.0, 1.0, flag=True) == (y, (3.0, 1.0))\n\n def test_grad_of_jit(self):\n side = []\n\n @jit\n def f(x):\n side.append(None)\n return x * x\n\n assert grad(f)(1.0) == 2.0\n assert len(side) == 1\n assert grad(f)(2.0) == 4.0\n assert len(side) == 1\n\n def test_jit_of_grad(self):\n side = []\n\n @jit\n def f(x):\n side.append(None)\n return x * x\n\n g = jit(grad(f))\n assert g(1.0) == 2.0\n assert len(side) == 1\n assert g(2.0) == 4.0\n assert len(side) == 1\n\n def test_bad_input(self):\n def f(x):\n return x\n\n self.assertRaisesRegex(\n TypeError, \".* 'foo' of type <.*'str'> is not a valid JAX type\",\n lambda: grad(f)(\"foo\"))\n\n self.assertRaisesRegex(\n TypeError, \".* 'foo' of type <.*'str'> is not a valid JAX type\",\n lambda: jit(f)(\"foo\"))\n\n def test_grad_tuple_output(self):\n jtu.check_raises(lambda: grad(lambda x: (x,x))(1.0), TypeError,\n \"Gradient only defined for scalar-output functions. \")\n\n def test_grad_unit_output(self):\n jtu.check_raises(lambda: grad(lambda x: ())(np.zeros(3)), TypeError,\n \"Gradient only defined for scalar-output functions. \")\n\n def test_grad_nonscalar_output(self):\n jtu.check_raises(lambda: grad(lambda x: x)(np.zeros(3)), TypeError,\n \"Gradient only defined for scalar-output functions. \")\n\n def test_unwrapped_numpy(self):\n def f(x):\n return np.exp(x)\n\n with self.assertRaisesRegex(Exception, \"The numpy.ndarray conversion .*\"):\n grad(f)(np.zeros(3))\n\n def test_binop_mismatch(self):\n def f(x, y):\n return x + y\n\n jtu.check_raises(\n lambda: f(jnp.zeros(3), jnp.zeros(4)),\n TypeError,\n \"add got incompatible shapes for broadcasting: (3,), (4,).\")\n\n jtu.check_raises(\n lambda: grad(f)(np.zeros(3), np.zeros(4)),\n TypeError,\n \"add got incompatible shapes for broadcasting: (3,), (4,).\")\n\n def test_dot_mismatch(self):\n def f(x, y):\n return jnp.dot(x, y)\n\n self.assertRaisesRegex(\n TypeError, \"Incompatible shapes for dot: got \\\\(3L?,\\\\) and \\\\(4L?,\\\\).\",\n lambda: grad(f)(np.zeros(3), np.zeros(4)))\n\n def test_abstract_error_message(self):\n for castfun in [float, complex, int]:\n def f(x):\n return castfun(x)\n\n self.assertRaisesRegex(\n TypeError,\n f\"[Tt]ry using `x.astype\\\\({castfun.__name__}\\\\)`\",\n lambda: jit(f)(1.0))\n\n def test_switch_value_jit(self):\n def f(x):\n y = x > 0\n if y:\n return x\n else:\n return -x\n\n assert grad(f)(1.0) == 1.0\n assert grad(f)(-1.0) == -1.0\n with self.assertRaisesRegex(core.ConcretizationTypeError,\n \"Abstract tracer value\"):\n jit(f)(1)\n\n def test_range_err(self):\n def f(x, n):\n for i in range(n):\n x = x + i\n return x\n\n assert jit(f, static_argnums=(1,))(0, 5) == 10\n self.assertRaisesRegex(\n TypeError,\n \"('(?:JaxprTracer|DynamicJaxprTracer)' object cannot be interpreted as an integer\"\n \"|Abstract value passed to .*)\",\n lambda: jit(f)(0, 5))\n\n def test_casts(self):\n for castfun in [hex, oct, int]:\n f = lambda x: castfun(x)\n self.assertRaisesRegex(\n TypeError,\n \"('(?:JaxprTracer|DynamicJaxprTracer)' object cannot be interpreted as an integer\"\n \"|Abstract tracer value encountered where concrete value is expected.*)\", lambda: jit(f)(0))\n\n def test_unimplemented_interpreter_rules(self):\n foo_p = Primitive('foo')\n def foo(x):\n return foo_p.bind(x)\n\n jtu.check_raises(lambda: foo(1.0), NotImplementedError,\n \"Evaluation rule for 'foo' not implemented\")\n\n jtu.check_raises(lambda: jit(foo)(1.0), NotImplementedError,\n \"Abstract evaluation for 'foo' not implemented\")\n\n jtu.check_raises(lambda: grad(foo)(1.0), NotImplementedError,\n \"Differentiation rule for 'foo' not implemented\")\n\n foo_p.def_abstract_eval(lambda x: x)\n\n jtu.check_raises(lambda: jit(foo)(1.0), NotImplementedError,\n \"XLA translation rule for primitive 'foo' not found\")\n\n foo_p.def_impl(lambda x: x)\n ad.defjvp(foo_p, lambda g, x: foo(g))\n\n jtu.check_raises(lambda: grad(foo)(1.0), NotImplementedError,\n \"Transpose rule (for reverse-mode differentiation) for 'foo' not implemented\")\n\n def test_device_put_and_get(self):\n x = np.arange(12.).reshape((3, 4)).astype(\"float32\")\n dx = api.device_put(x)\n self.assertIsInstance(dx, xla.DeviceArray)\n x2 = api.device_get(dx)\n self.assertIsInstance(x2, np.ndarray)\n assert np.all(x == x2)\n\n y = [x, (2 * x, 3 * x)]\n dy = api.device_put(y)\n y2 = api.device_get(dy)\n self.assertIsInstance(y2, list)\n self.assertIsInstance(y2[0], np.ndarray)\n assert np.all(y2[0] == x)\n self.assertIsInstance(y2[1], tuple)\n self.assertIsInstance(y2[1][0], np.ndarray)\n assert np.all(y2[1][0] == 2 * x)\n self.assertIsInstance(y2[1][1], np.ndarray)\n assert np.all(y2[1][1] == 3 * x)\n\n def test_device_get_scalar(self):\n x = np.arange(12.).reshape((3, 4)).astype(\"float32\")\n x = api.device_put(x)\n self.assertIsInstance(x, xla.DeviceArray)\n y = [x, 2]\n y2 = api.device_get(y)\n self.assertIsInstance(y2, list)\n self.assertIsInstance(y2[0], np.ndarray)\n assert np.all(y2[0] == x)\n self.assertIsInstance(y2[1], int)\n self.assertEqual(y2[1], 2)\n\n @parameterized.parameters([(3,)], [(2, 0)])\n def test_device_put_across_devices(self, shape):\n if len(api.local_devices()) < 2:\n raise unittest.SkipTest(\"this test requires multiple devices\")\n d1, d2 = api.local_devices()[:2]\n data = np.random.randn(*shape).astype(np.float32)\n x = api.device_put(data, device=d1)\n self.assertEqual(x.device_buffer.device(), d1)\n y = api.device_put(x, device=d2)\n self.assertEqual(y.device_buffer.device(), d2)\n np.testing.assert_array_equal(data, np.array(y))\n # Make sure these don't crash\n api.device_put(x)\n api.device_put(y)\n\n @jtu.skip_on_devices(\"cpu\")\n def test_device_put_across_platforms(self):\n default_device = jax.devices()[0]\n cpu_device = jax.devices(\"cpu\")[0]\n\n np_arr = np.array([1,2,3])\n scalar = 1\n device_arr = jnp.array([1,2,3])\n assert device_arr.device_buffer.device() is default_device\n\n for val in [np_arr, device_arr, scalar]:\n x = api.device_put(val, device=cpu_device)\n self.assertEqual(x.device_buffer.device(), cpu_device)\n\n @jtu.skip_on_devices(\"tpu\")\n def test_jacobian(self):\n R = np.random.RandomState(0).randn\n A = R(4, 3)\n x = R(3)\n\n f = lambda x: jnp.dot(A, x)\n assert np.allclose(jacfwd(f)(x), A)\n assert np.allclose(jacrev(f)(x), A)\n\n f = lambda x: jnp.tanh(jnp.dot(A, x))\n assert np.allclose(jacfwd(f)(x), jacrev(f)(x))\n\n @jtu.skip_on_devices(\"tpu\")\n def test_hessian(self):\n R = np.random.RandomState(0).randn\n A = R(4, 4)\n x = R(4)\n\n f = lambda x: jnp.dot(x, jnp.dot(A, x))\n assert np.allclose(hessian(f)(x), A + A.T)\n\n def test_std_basis(self):\n basis = api._std_basis(jnp.zeros(3))\n assert getattr(basis, \"shape\", None) == (3, 3)\n assert np.allclose(basis, np.eye(3))\n\n basis = api._std_basis(jnp.zeros((3, 3)))\n assert getattr(basis, \"shape\", None) == (9, 3, 3)\n assert np.allclose(basis, np.eye(9).reshape(9, 3, 3))\n\n basis = api._std_basis([0., (jnp.zeros(3), jnp.zeros((3, 4)))])\n assert isinstance(basis, list) and len(basis) == 2\n assert getattr(basis[0], \"shape\", None) == (16,)\n assert isinstance(basis[1], tuple) and len(basis[1]) == 2\n assert getattr(basis[1][0], \"shape\", None) == (16, 3)\n assert getattr(basis[1][1], \"shape\", None) == (16, 3, 4)\n\n @jtu.skip_on_devices(\"tpu\")\n def test_jacobian_on_pytrees(self):\n for jacfun in [jacfwd, jacrev]:\n ans = jacfun(lambda x, y: (x, y))(0., 1.)\n expected = (1., 0.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = jacfun(lambda x, y: (x, y), 1)(0., 1.)\n expected = (0., 1.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = jacfun(lambda x, y: (x, y), (0, 1))(0., 1.)\n expected = ((1., 0.),\n (0., 1.),)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = jacfun(lambda x: x[:2])((1., 2., 3.))\n expected = ((1., 0., 0.),\n (0., 1., 0.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n R = np.random.RandomState(0).randn\n x = R(2)\n y = R(3)\n ans = jacfun(lambda x, y: {'x': x, 'xy': jnp.outer(x, y)})(x, y)\n expected = {'x': np.eye(2),\n 'xy': np.kron(np.eye(2), y[:, None]).reshape(2, 3, 2)}\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @jtu.skip_on_devices(\"tpu\")\n def test_hessian_on_pytrees(self):\n ans = hessian(lambda x: jnp.array(x)**2)((1., 2.))\n expected = ((np.array([2., 0.]), np.array([0., 0.])),\n (np.array([0., 0.]), np.array([0., 2.])))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @jtu.skip_on_devices(\"tpu\")\n def test_issue1372(self):\n def quad(x):\n return jnp.dot(x, x)\n\n def f(x, u):\n return quad(x) + quad(u)\n\n x, u = jnp.ones(5), jnp.ones(2)\n\n rev = jacrev\n fwd = jacfwd\n\n # Diagonal entries\n self.assertEqual(rev(rev(f, 0), 0)(x, u).shape, (5, 5))\n self.assertEqual(rev(fwd(f, 0), 0)(x, u).shape, (5, 5))\n self.assertEqual(fwd(rev(f, 0), 0)(x, u).shape, (5, 5))\n self.assertEqual(fwd(fwd(f, 0), 0)(x, u).shape, (5, 5))\n self.assertEqual(rev(rev(f, 1), 1)(x, u).shape, (2, 2))\n self.assertEqual(rev(fwd(f, 1), 1)(x, u).shape, (2, 2))\n self.assertEqual(fwd(rev(f, 1), 1)(x, u).shape, (2, 2))\n self.assertEqual(fwd(fwd(f, 1), 1)(x, u).shape, (2, 2))\n\n # Off-diagonal entries by reverse-mode on the outside\n self.assertEqual(rev(rev(f, 1), 0)(x, u).shape, (2, 5))\n self.assertEqual(rev(fwd(f, 1), 0)(x, u).shape, (2, 5))\n self.assertEqual(rev(rev(f, 0), 1)(x, u).shape, (5, 2))\n self.assertEqual(rev(fwd(f, 0), 1)(x, u).shape, (5, 2))\n\n # Off-diagonal entries by forward-mode on the outside\n self.assertEqual(fwd(rev(f, 1), 0)(x, u).shape, (2, 5))\n self.assertEqual(fwd(fwd(f, 1), 0)(x, u).shape, (2, 5))\n self.assertEqual(fwd(rev(f, 0), 1)(x, u).shape, (5, 2))\n self.assertEqual(fwd(fwd(f, 0), 1)(x, u).shape, (5, 2))\n\n\n def test_large_device_constant(self):\n ans = jit(lambda x: 2 * x)(jnp.ones(int(2e6))) # doesn't crash\n self.assertAllClose(ans, np.ones(int(2e6)) * 2., check_dtypes=False)\n\n def test_grad_and_aux_basic(self):\n g, aux = grad(lambda x: (x**3, [x**2]), has_aux=True)(3.)\n self.assertAllClose(g, grad(lambda x: x**3)(3.))\n self.assertAllClose(aux, [9.], check_dtypes=False)\n\n def test_grad_and_aux_nested(self):\n def f(x):\n g, aux = grad(lambda x: (x**3, [x**3]), has_aux=True)(x)\n return aux[0]\n\n f2 = lambda x: x**3\n\n self.assertEqual(grad(f)(4.), grad(f2)(4.))\n self.assertEqual(jit(grad(f))(4.), grad(f2)(4.))\n self.assertEqual(jit(grad(jit(f)))(4.), grad(f2)(4.))\n\n def f(x):\n g, aux = grad(lambda x: (x**3, [x**3]), has_aux=True)(x)\n return aux[0] * jnp.sin(x)\n\n f2 = lambda x: x**3 * jnp.sin(x)\n\n self.assertEqual(grad(f)(4.), grad(f2)(4.))\n self.assertEqual(jit(grad(f))(4.), grad(f2)(4.))\n self.assertEqual(jit(grad(jit(f)))(4.), grad(f2)(4.))\n\n def test_grad_and_aux_constant(self):\n g, aux = grad(lambda x: (x**3, [4.]), has_aux=True)(4.)\n self.assertEqual(g, grad(lambda x: x**3)(4.))\n self.assertEqual(aux, [4.])\n\n g, aux = grad(lambda x: (x**3, [x**2, 4.]), has_aux=True)(4.)\n self.assertEqual(g, grad(lambda x: x**3)(4.))\n self.assertEqual(aux, [4.**2, 4.])\n\n def test_grad_and_aux_no_tracers(self):\n # see https://github.com/google/jax/issues/1950\n def f(x):\n aux = dict(identity=x, p1=x+1)\n return x ** 2, aux\n\n _, aux = jax.grad(f, has_aux=True)(3.)\n self.assertIsInstance(aux, dict)\n for val in aux.values():\n self.assertNotIsInstance(val, core.Tracer)\n\n def test_jvp_mismatched_arguments(self):\n self.assertRaisesRegex(\n TypeError,\n (\"primal and tangent arguments to jax.jvp must have the same tree \"\n \"structure\"),\n lambda: api.jvp(lambda x, y: x * y, (np.float32(2),), ()))\n # If primals and tangents must both be tuples or both lists\n self.assertRaisesRegex(\n TypeError,\n (\"primal and tangent arguments to jax.jvp must have the same tree \"\n \"structure\"),\n lambda: api.jvp(lambda x, y: x * y, (np.float32(2),), [np.float32(2)]))\n self.assertRaisesRegex(\n TypeError,\n \"primal and tangent arguments to jax.jvp do not match.\",\n lambda: api.jvp(lambda x: -x, (np.float16(2),), (np.float32(4),)))\n\n def test_jvp_non_tuple_arguments(self):\n def f(x, y): return x + y\n self.assertRaisesRegex(\n TypeError,\n \"primal and tangent arguments to jax.jvp must be tuples or lists; found float and tuple.\",\n lambda: api.jvp(f, 0., (1.,)))\n self.assertRaisesRegex(\n TypeError,\n \"primal and tangent arguments to jax.jvp must be tuples or lists; found tuple and ndarray.\",\n lambda: api.jvp(f, (0.,), np.array([1., 2.])))\n\n def test_vjp_mismatched_arguments(self):\n _, pullback = api.vjp(lambda x, y: x * y, np.float32(3), np.float32(4))\n self.assertRaisesRegex(\n TypeError,\n \"Tree structure of cotangent input.*does not match\",\n lambda: pullback((np.float32(7), np.float32(100))))\n self.assertRaisesRegex(\n TypeError,\n \"Type of cotangent input to vjp pullback.*is not the expected tangent type\",\n lambda: pullback((np.float16(42))))\n\n def test_jvp_jit_cached(self):\n \"\"\"Bug in caching in presence of JVP and JIT.\"\"\"\n\n def func(x):\n def inner(y):\n return y * x\n\n # Must have two calls to the inner jit (the second one hits the cache)\n res1 = api.jit(inner)(4.)\n res2 = api.jit(inner)(5.)\n return res1 + res2\n\n self.assertAllClose((45., 9.), api.jvp(func, (5.,), (1.,)))\n\n def test_linear_transpose_abstract(self):\n x = types.SimpleNamespace(shape=(3,), dtype=np.float32)\n y = jnp.arange(3, dtype=np.float32)\n transpose_fun = api.linear_transpose(lambda x: 2 * x, x)\n z, = transpose_fun(y)\n self.assertArraysEqual(2 * y, z, check_dtypes=True)\n\n def test_linear_transpose_error(self):\n with self.assertRaisesRegex(\n TypeError, \"linear_transpose only supports float and complex inputs\"):\n api.linear_transpose(lambda x: x, 1)\n\n transpose_fun = api.linear_transpose(lambda x: [x, x], 1.0)\n with self.assertRaisesRegex(TypeError, \"cotangent tree does not match\"):\n transpose_fun(1.0)\n\n transpose_fun = api.linear_transpose(lambda x: jnp.stack([x, x]), 1.0)\n with self.assertRaisesRegex(TypeError, \"cotangent type does not match\"):\n transpose_fun(1.0)\n\n transpose_fun = api.linear_transpose(lambda x: 1j * x, 1.0)\n with self.assertRaisesRegex(TypeError, \"cotangent type does not match\"):\n transpose_fun(1.0)\n\n transpose_fun = api.linear_transpose(lambda x: x, 1.0)\n with self.assertRaisesRegex(TypeError, \"cotangent type does not match\"):\n transpose_fun(1j)\n\n def test_linear_transpose_complex(self):\n f = lambda x: (1 + 2j) * x\n transpose = api.linear_transpose(f, 1j)\n actual, = transpose(3 + 4j)\n expected = -5 + 10j\n self.assertEqual(actual, expected)\n\n def test_complex_grad_raises_error(self):\n self.assertRaises(TypeError, lambda: grad(lambda x: jnp.sin(x))(1 + 2j))\n\n def test_holomorphic_grad(self):\n out = grad(lambda x: jnp.sin(x), holomorphic=True)(1 + 2j)\n expected = 2.0327230070196656 - 3.0518977991518j\n self.assertAllClose(out, expected, check_dtypes=False)\n\n def test_nonholomorphic_grad(self):\n zs = 0.5j * np.arange(5) + np.arange(5)\n\n def f(z):\n return jnp.sum(jnp.cos(jnp.abs(z)))\n\n ans = grad(f)(zs)\n expected = np.array([ 0. +0.j,\n -0.80430663+0.40215331j,\n -0.70368982+0.35184491j,\n 0.1886467 -0.09432335j,\n 0.86873727-0.43436864j])\n self.assertAllClose(ans, expected, check_dtypes=False,\n atol=jtu.default_gradient_tolerance,\n rtol=jtu.default_gradient_tolerance)\n\n def test_complex_output_jacrev_raises_error(self):\n self.assertRaises(TypeError, lambda: jacrev(lambda x: jnp.sin(x))(1 + 2j))\n\n def test_nonholomorphic_jacrev(self):\n # code based on https://github.com/google/jax/issues/603\n zs = 0.5j * np.arange(5) + np.arange(5)\n\n def f(z):\n return jnp.cos(jnp.linalg.norm(2 * z))\n\n ans = jacrev(f)(zs)\n expected = grad(f)(zs)\n self.assertAllClose(ans, expected)\n\n def test_complex_input_jacfwd_raises_error(self):\n self.assertRaises(TypeError, lambda: jacfwd(lambda x: jnp.sin(x))(1 + 2j))\n\n def test_legacy_devicearray_repr(self):\n dx = device_put(3.)\n str(dx.item()) # doesn't crash\n\n def test_devicearray_repr(self):\n x = device_put(jnp.zeros(3))\n self.assertIsInstance(x, xla.DeviceArray)\n repr(x) # doesn't crash\n\n x = device_put(jnp.ones(3) + 1j * jnp.ones(3))\n self.assertIsInstance(x, xla.DeviceArray)\n repr(x) # doesn't crash\n\n def test_devicearray_delete(self):\n x = device_put(1.)\n x.delete()\n self.assertRaisesRegex(RuntimeError, \"DeviceArray has been deleted.\",\n lambda: repr(x))\n\n def test_devicearray_block_until_ready(self):\n x = device_put(1.)\n y = x.block_until_ready()\n # Tests mostly that block_until_ready() does not produce an error.\n self.assertTrue(y is x)\n\n def test_devicearray_weakref_friendly(self):\n x = device_put(1.)\n y = weakref.ref(x)\n self.assertEqual(y(), 1.)\n del x\n self.assertIsNone(y())\n\n def test_namedtuple_transparency(self):\n # See https://github.com/google/jax/issues/446\n Point = collections.namedtuple(\"Point\", [\"x\", \"y\"])\n\n def f(pt):\n return jnp.sqrt(pt.x ** 2 + pt.y ** 2)\n\n pt = Point(1., 2.)\n\n f(pt) # doesn't crash\n g = api.grad(f)(pt)\n self.assertIsInstance(g, Point)\n\n f_jit = api.jit(f)\n self.assertAllClose(f(pt), f_jit(pt), check_dtypes=False)\n\n def test_namedtuple_subclass_transparency(self):\n # See https://github.com/google/jax/issues/806\n Point = collections.namedtuple(\"Point\", [\"x\", \"y\"])\n\n class ZeroPoint(Point):\n def is_zero(self):\n return (self.x == 0) and (self.y == 0)\n\n pt = ZeroPoint(0., 0.)\n\n def f(pt):\n return 0. if pt.is_zero() else jnp.sqrt(pt.x ** 2 + pt.y ** 2)\n\n f(pt) # doesn't crash\n _ = api.grad(f)(pt)\n self.assertIsInstance(pt, ZeroPoint)\n\n @parameterized.parameters(1, 2, 3)\n def test_shape_dtype_struct(self, i):\n s = api.ShapeDtypeStruct(shape=(i, 2, 3), dtype=jnp.float32)\n self.assertEqual(s.shape, (i, 2, 3))\n self.assertEqual(s.dtype, jnp.float32)\n self.assertEqual(s.ndim, 3)\n self.assertEqual(s.size, i * 2 * 3)\n self.assertLen(s, i)\n for f in (str, repr):\n self.assertEqual(\n f(s), \"ShapeDtypeStruct(shape=({}, 2, 3), dtype=float32)\".format(i))\n\n def test_shape_dtype_struct_scalar(self):\n s = api.ShapeDtypeStruct(shape=(), dtype=jnp.float32)\n self.assertEmpty(s.shape)\n self.assertEqual(s.size, 1)\n self.assertEqual(s.ndim, 0)\n with self.assertRaisesRegex(TypeError, \"len[(][)] of unsized object\"):\n _ = len(s)\n\n def test_eval_shape(self):\n def fun(x, y):\n return jnp.tanh(jnp.dot(x, y) + 3.)\n\n x = jnp.ones((2, 3))\n y = jnp.ones((3, 4))\n out_shape = api.eval_shape(fun, x, y)\n\n self.assertEqual(out_shape.shape, (2, 4))\n\n def test_eval_shape_constants(self):\n def fun():\n x = jnp.ones((2, 3))\n y = jnp.ones((3, 4))\n return jnp.tanh(jnp.dot(x, y) + 3.)\n\n out_shape = api.eval_shape(fun)\n\n self.assertEqual(out_shape.shape, (2, 4))\n\n def test_eval_shape_tuple_unpacking(self):\n def fun(x, y):\n a, b = x\n return a + b + y\n\n x = (jnp.ones(2), jnp.ones(2))\n y = 3.\n out_shape = api.eval_shape(fun, x, y)\n\n self.assertEqual(out_shape.shape, (2,))\n\n def test_eval_shape_tuple_itemgetting(self):\n def fun(x, y):\n return x[0] + x[1] + y\n\n x = (jnp.ones(2), jnp.ones(2))\n y = 3.\n out_shape = api.eval_shape(fun, x, y)\n\n self.assertEqual(out_shape.shape, (2,))\n\n def test_eval_shape_output_dict(self):\n def fun(x, y):\n return {'hi': x[0] + x[1] + y}\n\n x = (jnp.ones(2), jnp.ones(2))\n y = 3.\n out_shape = api.eval_shape(fun, x, y)\n out_shape = tree_util.tree_map(np.shape, out_shape)\n\n self.assertEqual(out_shape, {'hi': (2,)})\n\n def test_eval_shape_shape_error(self):\n def fun(x, y):\n return jnp.tanh(jnp.dot(x, y) + 3.)\n\n x = jnp.ones((3, 3))\n y = jnp.ones((4, 4))\n\n self.assertRaises(TypeError, lambda: api.eval_shape(fun, x, y))\n\n def test_eval_shape_duck_typing(self):\n def fun(A, b, x):\n return jnp.dot(A, x) + b\n\n class MyArgArray(object):\n def __init__(self, shape, dtype):\n self.shape = shape\n self.dtype = dtype\n\n A = MyArgArray((3, 4), jnp.float32)\n b = MyArgArray((5,), jnp.float32)\n x = MyArgArray((4, 5), jnp.float32)\n out_shape = api.eval_shape(fun, A, b, x)\n\n self.assertEqual(out_shape.shape, (3, 5))\n\n def test_issue_871(self):\n T = jnp.array([[1., 2.], [3., 4.], [5., 6.]])\n x = jnp.array([1, 2, 3])\n msg = (\"linearized function called on tangent values inconsistent with \"\n \"the original primal values\")\n\n y, f_jvp = api.linearize(jnp.sum, x)\n with self.assertRaisesRegex(ValueError, msg):\n f_jvp(T)\n\n y, f_jvp = api.linearize(api.jit(jnp.sum), x)\n with self.assertRaisesRegex(ValueError, msg):\n f_jvp(T)\n\n def test_partial_eval_lower(self):\n # this is a simplified model of a bug that arose when we first used @jit in\n # a jvp rule. it's in this file because we want to use make_jaxpr.\n\n # NOTE(mattjj): I no longer understand what this was meant to test. My guess\n # is it was related to staging out the broadcast into a jaxpr to be\n # transposed, but after #1749 that's no longer a problem. After changing\n # make_jaxpr (and jit) to stage out sub-calls fully, this test started to\n # fail; I left it in as skipped because deleting tests feels wrong.\n raise unittest.SkipTest(\"obsolete test\")\n\n @api.jit\n def f(a, b, c):\n a = lax.broadcast(a, (2,))\n return lax.select(a, b, c)\n\n a = np.ones((3, 3), dtype=np.bool_)\n b = np.ones((2, 3, 3))\n c = np.ones((2, 3, 3))\n\n jaxpr = api.make_jaxpr(lambda b, c: f(a, b, c))(b, c)\n subjaxpr = next(eqn.params[\"call_jaxpr\"] for eqn in jaxpr.jaxpr.eqns\n if \"call_jaxpr\" in eqn.params)\n self.assertEqual(len(subjaxpr.eqns), 1)\n\n def test_grad_of_int_errors(self):\n # Errors without allow_int=True\n dfn = grad(lambda x: x ** 2)\n self.assertRaisesRegex(\n TypeError,\n (r\"grad requires real- or complex-valued inputs \\(input dtype that is a \"\n r\"sub-dtype of np.floating or np.complexfloating\\), but got int.*.\"),\n lambda: dfn(3))\n\n def test_jvp_of_int_identity(self):\n primals = (1,)\n tangents = (np.zeros(shape=(), dtype=float0),)\n\n _, out = api.jvp(lambda x: x, primals, tangents)\n self.assertEqual(out, np.zeros(shape=(), dtype=float0))\n\n def test_jvp_of_int_add(self):\n primals = (2,)\n tangents = (np.zeros(shape=(), dtype=float0),)\n\n _, out_tangent = api.jvp(lambda x: x+1, primals, tangents)\n self.assertEqual(out_tangent, np.zeros(shape=(), dtype=float0))\n\n def test_jit_jvp_of_int(self):\n primals = (2,)\n tangents = (np.zeros(shape=(), dtype=float0),)\n\n _, out_tangent = api.jvp(jax.jit(lambda x: x+1), primals, tangents)\n self.assertEqual(out_tangent, np.zeros(shape=(), dtype=float0))\n\n def test_vjp_of_int_index(self):\n primal, fn_vjp = api.vjp(lambda x, i: x[i], np.ones(2)*2, 1)\n tangent_x, tangent_i = fn_vjp(1.)\n self.assertEqual(primal, 2.)\n self.assertAllClose(tangent_x, jnp.array([0., 1.]))\n self.assertEqual(tangent_i, np.zeros(shape=(), dtype=float0))\n\n def test_vjp_of_int_shapes(self):\n out, fn_vjp = api.vjp(lambda x: lax.reshape(x, (2, 2)), np.ones((4, 1),\n dtype=int))\n tangent, = fn_vjp(out)\n self.assertArraysEqual(tangent, np.zeros(shape=(4, 1), dtype=float0))\n\n def test_jit_vjp_of_int(self):\n primal, fn_vjp = api.vjp(lambda x, y: x+y, 2, 1)\n tangent_x, tangent_i = jax.jit(fn_vjp)(1)\n self.assertEqual(primal, 3)\n self.assertEqual(tangent_x, np.zeros(shape=(), dtype=float0))\n self.assertEqual(tangent_i, np.zeros(shape=(), dtype=float0))\n\n def test_vjp_of_int_fulllike(self):\n # Regression test for tangent and cotangent mismatch in convert_element_type\n # transpose rule wrt a ConstVar\n f = lax.full_like\n out, vjp = api.vjp(f, np.zeros((2, 2)), 1)\n self.assertAllClose(out, jnp.ones((2, 2)))\n tangent_x, tangent_y = vjp(out)\n self.assertAllClose(tangent_x, jnp.zeros((2, 2)))\n self.assertEqual(tangent_y, np.zeros(shape=(), dtype=float0))\n\n def test_grad_of_int(self):\n # Need real-valued output, but testing integer input.\n out = api.grad(lambda x: x+0., allow_int=True)(1)\n self.assertEqual(out, np.zeros(shape=(), dtype=float0))\n\n def test_grad_of_bool(self):\n def cond(pred):\n return lax.cond(pred, lambda _: 1., lambda _: 2., 1.)\n value, grd = api.value_and_grad(cond, allow_int=True)(True)\n self.assertEqual(value, 1.)\n self.assertEqual(grd, np.zeros(shape=(), dtype=float0))\n\n def test_grad_of_int_index(self):\n grad_x, grad_i = api.grad(lambda x, i: x[i], argnums=(0, 1),\n allow_int=True)(np.ones(2), 1)\n self.assertAllClose(grad_x, jnp.array([0., 1.]))\n self.assertEqual(grad_i, np.zeros(shape=(), dtype=float0))\n\n def test_jit_grad_of_int(self):\n grad_f = api.grad(lambda x, i: x[i], argnums=(0, 1), allow_int=True)\n grad_x, grad_i = jax.jit(grad_f)(np.ones(2), 1)\n self.assertAllClose(grad_x, jnp.array([0., 1.]))\n self.assertEqual(grad_i, np.zeros(shape=(), dtype=float0))\n\n def test_float0_reshape(self):\n # dtype-agnostic operations are supported\n float0_array = jax.grad(lambda x: jnp.sum(x+0.),\n allow_int=True)(np.ones((2, 4), dtype=int))\n\n self.assertArraysEqual(float0_array.reshape((4, 2)),\n np.zeros((4, 2), dtype=float0))\n self.assertArraysEqual(float0_array.transpose(),\n np.zeros((4, 2), dtype=float0))\n\n def test_float0_error(self):\n # float0 is incompatible with other dtypes\n float0_array = jax.grad(lambda x: x+0., allow_int=True)(1)\n error_text = \"float0s do not support any operations by design\"\n\n with self.assertRaisesRegex(TypeError, error_text):\n # dispatch via DeviceArray\n _ = float0_array + jnp.zeros(())\n\n with self.assertRaisesRegex(TypeError, error_text):\n # dispatch via lax\n _ = lax.add(float0_array, jnp.zeros(()))\n\n def test_grad_complex_result_errors(self):\n dfn = grad(lambda x: x ** 2 + 1j)\n self.assertRaisesRegex(\n TypeError,\n (r\"grad requires real-valued outputs \\(output dtype that is a \"\n r\"sub-dtype of np.floating\\), but got complex.*\"),\n lambda: dfn(3.))\n\n def test_holomorphic_grad_of_float_errors(self):\n dfn = grad(lambda x: x ** 2, holomorphic=True)\n self.assertRaisesRegex(\n TypeError,\n (r\"grad with holomorphic=True requires inputs with complex dtype, \"\n r\"but got float.*\"),\n lambda: dfn(3.))\n\n def test_holomorphic_jacrev_of_float_errors(self):\n dfn = jacrev(lambda x: x ** 2, holomorphic=True)\n self.assertRaisesRegex(\n TypeError,\n (r\"jacrev with holomorphic=True requires inputs with complex dtype, \"\n r\"but got float.*\"),\n lambda: dfn(3.))\n\n def test_holomorphic_jacfwd_of_float_errors(self):\n dfn = jacfwd(lambda x: x ** 2, holomorphic=True)\n self.assertRaisesRegex(\n TypeError,\n (r\"jacfwd with holomorphic=True requires inputs with complex dtype, \"\n r\"but got float.*\"),\n lambda: dfn(3.))\n\n def test_jacfwd_of_complex_errors(self):\n dfn = jacfwd(lambda x: x ** 2)\n self.assertRaisesRegex(\n TypeError,\n (r\"jacfwd requires real-valued inputs \\(input dtype that is a \"\n r\"sub-dtype of np.floating\\), but got complex.*\"),\n lambda: dfn(3. + 1j))\n\n def test_xla_computation(self):\n # these tests basically check the examples in the xla_computation docstring\n\n def e(x):\n return jnp.sin(jnp.cos(x))\n c = api.xla_computation(e)(2.)\n self.assertIn('cosine', c.as_hlo_text())\n self.assertIn('sine', c.as_hlo_text())\n\n def f(x):\n return x - lax.psum(x, 'i')\n axis_env = [('i', 4)]\n c = api.xla_computation(f, axis_env=axis_env)(2)\n self.assertIn('all-reduce', c.as_hlo_text())\n self.assertIn('replica_groups={{0,1,2,3}}', c.as_hlo_text())\n\n def g(x):\n rowsum = lax.psum(x, 'i')\n colsum = lax.psum(x, 'j')\n allsum = lax.psum(x, ('i', 'j'))\n return rowsum, colsum, allsum\n axis_env = [('i', 4), ('j', 2)]\n c = api.xla_computation(g, axis_env=axis_env)(5.)\n self.assertIn('all-reduce', c.as_hlo_text())\n self.assertIn('replica_groups={{0,2,4,6},{1,3,5,7}}', c.as_hlo_text())\n self.assertIn('replica_groups={{0,1},{2,3},{4,5},{6,7}}', c.as_hlo_text())\n self.assertIn('replica_groups={{0,1,2,3,4,5,6,7}}', c.as_hlo_text())\n\n def h(x):\n rowsum = lax.psum(x, 'i', axis_index_groups=[[0, 1], [2, 3]])\n colsum = lax.psum(x, 'j')\n return rowsum, colsum\n axis_env = [('i', 4), ('j', 2)]\n c = api.xla_computation(h, axis_env=axis_env)(5.)\n self.assertIn('all-reduce', c.as_hlo_text())\n self.assertIn('replica_groups={{0,2},{4,6},{1,3},{5,7}}', c.as_hlo_text())\n self.assertIn('replica_groups={{0,1},{2,3},{4,5},{6,7}}', c.as_hlo_text())\n\n def test_xla_computation_args(self):\n def foo(x, y, z):\n return x + y + z\n\n c = api.xla_computation(foo)(1., 2., 3.)\n self.assertEqual(len(c.program_shape().parameter_shapes()), 3)\n\n c = api.xla_computation(foo, tuple_args=True)(1., 2., 3.)\n param_shapes = c.program_shape().parameter_shapes()\n self.assertEqual(len(param_shapes), 1)\n self.assertEqual(param_shapes[0].xla_element_type(),\n xb.xla_client.PrimitiveType.TUPLE)\n\n def test_xla_computation_duck_typing(self):\n def foo(x, y, z):\n return x + y + z\n\n x = jax.ShapeDtypeStruct((), np.float32)\n y = jax.ShapeDtypeStruct((), np.float32)\n z = jax.ShapeDtypeStruct((), np.float32)\n\n c = api.xla_computation(foo)(x, y, z)\n self.assertEqual(len(c.program_shape().parameter_shapes()), 3)\n\n c = api.xla_computation(foo, tuple_args=True)(1., 2., 3.)\n param_shapes = c.program_shape().parameter_shapes()\n self.assertEqual(len(param_shapes), 1)\n self.assertEqual(param_shapes[0].xla_element_type(),\n xb.xla_client.PrimitiveType.TUPLE)\n\n def test_staging_out_multi_replica(self):\n def f(x):\n return api.pmap(jnp.mean)(x)\n xla_comp = api.xla_computation(f)\n xla_comp(jnp.arange(8)).as_hlo_text() # doesn't crash\n\n def test_xla_computation_instantiate_constant_outputs(self):\n def f():\n return jnp.zeros((3, 4))\n\n if config.omnistaging_enabled:\n xla_comp = api.xla_computation(f)()\n else:\n xla_comp = api.xla_computation(f, instantiate_const_outputs=True)()\n out_shape, = xla_comp.program_shape().result_shape().tuple_shapes()\n self.assertEqual(out_shape.dimensions(), (3, 4))\n\n def test_xla_computation_static_argnums(self):\n def f(x, y):\n return x + y\n\n xla_comp = api.xla_computation(f, static_argnums=(1,))(2, 3)\n hlo_text = xla_comp.as_hlo_text()\n self.assertIn(\"constant(3)\", hlo_text)\n # The static arguments should be removed from the function being compiled,\n # thus the function should have only a single argument.\n self.assertIn(\"parameter.1\", hlo_text)\n self.assertNotIn(\"parameter.2\", hlo_text)\n\n def test_xla_computation_return_shape(self):\n _, shape_tree = api.xla_computation(lambda x: (x + 1, jnp.zeros(2, jnp.float32)),\n return_shape=True)(np.int32(1))\n expected = (api.ShapeDtypeStruct(shape=(), dtype=jnp.int32),\n api.ShapeDtypeStruct(shape=(2,), dtype=jnp.float32))\n self.assertEqual(shape_tree, expected)\n\n def test_xla_computation_partitioned(self):\n def f(x, y):\n return jnp.dot(x, y) + 1\n\n x = jax.ShapeDtypeStruct((8, 8), np.float32)\n y = jax.ShapeDtypeStruct((8, 16), np.float32)\n xla_comp = api.xla_computation(f, in_parts=(P(2, 2), None),\n out_parts=P(4, 1))(x, y)\n hlo_text = xla_comp.as_hlo_text()\n self.assertIn('sharding={devices=[2,2]0,1,2,3}', hlo_text)\n self.assertIn('sharding={replicated}', hlo_text)\n self.assertIn('sharding={{devices=[4,1]0,1,2,3}}', hlo_text)\n\n def test_xla_computation_replicated_and_partitioned(self):\n def f(x, y):\n return jnp.dot(x, y), lax.psum(x, 'i')\n\n x = jax.ShapeDtypeStruct((8, 8), np.float32)\n y = jax.ShapeDtypeStruct((8, 16), np.float32)\n axis_env = [('i', 4)]\n xla_comp = api.xla_computation(f, axis_env=axis_env,\n in_parts=(P(2, 2), None),\n out_parts=(P(4, 1), None))(x, y)\n hlo_text = xla_comp.as_hlo_text()\n self.assertIn('all-reduce', hlo_text)\n self.assertIn('replica_groups={{0,1,2,3}}', hlo_text)\n self.assertIn('sharding={devices=[2,2]0,1,2,3}', hlo_text)\n self.assertIn('sharding={replicated}', hlo_text)\n self.assertIn('sharding={{devices=[4,1]0,1,2,3}, {replicated}}', hlo_text)\n\n def test_xla_computation_psum_constant(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test requires omnistaging\")\n f = lambda: jax.lax.psum(1, \"i\")\n api.xla_computation(f, axis_env=[(\"i\", 2)])() # doesn't crash\n\n @jtu.skip_on_devices(\"cpu\", \"gpu\")\n def test_xla_computation_donate_argnums(self):\n api.xla_computation(lambda x: None, donate_argnums=(0,))(3) # doesn't crash\n\n def test_concurrent_device_get_and_put(self):\n def f(x):\n for _ in range(100):\n y = jax.device_put(x)\n x = jax.device_get(y)\n return x\n\n xs = [np.random.randn(i) for i in range(10)]\n with concurrent.futures.ThreadPoolExecutor() as executor:\n futures = [executor.submit(partial(f, x)) for x in xs]\n ys = [f.result() for f in futures]\n for x, y in zip(xs, ys):\n self.assertAllClose(x, y)\n\n def test_dtype_warning(self):\n # cf. issue #1230\n if FLAGS.jax_enable_x64:\n raise unittest.SkipTest(\"test only applies when x64 is disabled\")\n\n def check_warning(warn, nowarn):\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n\n nowarn() # get rid of extra startup warning\n\n prev_len = len(w)\n nowarn()\n assert len(w) == prev_len\n\n warn()\n assert len(w) > 0\n msg = str(w[-1].message)\n expected_prefix = \"Explicitly requested dtype \"\n self.assertEqual(expected_prefix, msg[:len(expected_prefix)])\n\n prev_len = len(w)\n nowarn()\n assert len(w) == prev_len\n\n check_warning(lambda: jnp.array([1, 2, 3], dtype=\"float64\"),\n lambda: jnp.array([1, 2, 3], dtype=\"float32\"))\n check_warning(lambda: jnp.array([1, 2, 3], dtype=\"float64\"),\n lambda: jnp.array([1, 2, 3], dtype=float))\n check_warning(lambda: jnp.ones(3, dtype=np.float64),\n lambda: jnp.ones(3))\n check_warning(lambda: jnp.ones(3, dtype=np.float64),\n lambda: jnp.ones(3, dtype=float))\n check_warning(lambda: jnp.ones_like(3, dtype=np.int64),\n lambda: jnp.ones_like(3, dtype=np.int32))\n check_warning(lambda: jnp.zeros(3, dtype=\"int64\"),\n lambda: jnp.zeros(3, dtype=\"int32\"))\n check_warning(lambda: jnp.zeros_like(3, dtype=\"float64\"),\n lambda: jnp.zeros_like(3, dtype=\"float32\"))\n check_warning(lambda: jnp.full((2, 3), 1, dtype=\"int64\"),\n lambda: jnp.full((2, 3), 1))\n check_warning(lambda: jnp.ones(3).astype(\"float64\"),\n lambda: jnp.ones(3).astype(\"float32\"))\n check_warning(lambda: jnp.eye(3, dtype=np.float64),\n lambda: jnp.eye(3))\n check_warning(lambda: jnp.arange(3, dtype=np.float64),\n lambda: jnp.arange(3, dtype=np.float32))\n check_warning(lambda: jnp.linspace(0, 3, dtype=np.float64),\n lambda: jnp.linspace(0, 3, dtype=np.float32))\n check_warning(lambda: jnp.tri(2, dtype=\"float64\"),\n lambda: jnp.tri(2, dtype=\"float32\"))\n check_warning(lambda: jnp.arange(1).astype(\"float64\"),\n lambda: jnp.arange(1).astype(float))\n check_warning(lambda: jnp.arange(1.0).astype(\"int64\"),\n lambda: jnp.arange(1.0).astype(int))\n\n def test_vmap_preserves_docstr(self):\n def superfun(a):\n \"\"\"Does things with stuff.\"\"\"\n pass\n\n self.assertRegex(api.vmap(superfun).__doc__, \"\\n\".join([\n \"Vectorized version of superfun.*\",\n \"\",\n \"Original documentation:\",\n \"\",\n superfun.__doc__,\n ]))\n\n def test_vmap_in_axes_list(self):\n # https://github.com/google/jax/issues/2367\n dictionary = {'a': 5., 'b': jnp.ones(2)}\n x = jnp.zeros(3)\n y = jnp.arange(3.)\n\n\n def f(dct, x, y):\n return dct['a'] + dct['b'] + x + y\n\n out1 = api.vmap(f, (None, 0, 0))(dictionary, x, y)\n out2 = api.vmap(f, [None, 0, 0])(dictionary, x, y)\n self.assertAllClose(out1, out2)\n\n def test_vmap_in_axes_tree_prefix_error(self):\n # https://github.com/google/jax/issues/795\n self.assertRaisesRegex(\n ValueError,\n \"vmap in_axes specification must be a tree prefix of the corresponding \"\n r\"value, got specification \\(0, 0\\) for value tree \"\n r\"PyTreeDef\\(tuple, \\[\\*\\]\\).\",\n lambda: api.vmap(lambda x: x, in_axes=(0, 0))(jnp.ones(3))\n )\n\n def test_vmap_in_axes_leaf_types(self):\n with self.assertRaisesRegex(\n TypeError, r\"vmap in_axes must be an int, None, or .*\"):\n api.vmap(lambda x: x, in_axes=(jnp.array([1., 2.]),))(jnp.array([1., 2.]))\n\n def test_vmap_out_axes_leaf_types(self):\n with self.assertRaisesRegex(\n TypeError, r\"vmap out_axes must be an int, None, or .*\"):\n api.vmap(lambda x: x, out_axes=(jnp.array([1., 2.]),))(jnp.array([1., 2.]))\n\n def test_vmap_unbatched_object_passthrough_issue_183(self):\n # https://github.com/google/jax/issues/183\n fun = lambda f, x: f(x)\n vfun = api.vmap(fun, (None, 0))\n ans = vfun(lambda x: x + 1, jnp.arange(3))\n self.assertAllClose(ans, np.arange(1, 4), check_dtypes=False)\n\n def test_vmap_mismatched_axis_sizes_error_message_issue_705(self):\n # https://github.com/google/jax/issues/705\n def h(a, b):\n return jnp.sum(a) + jnp.sum(b)\n\n X = np.random.randn(10, 4)\n U = np.random.randn(10, 2)\n\n with self.assertRaisesRegex(\n ValueError,\n \"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n r\"arg 0 has shape \\(10, 4\\) and axis 0 is to be mapped\" \"\\n\"\n r\"arg 1 has shape \\(10, 2\\) and axis 1 is to be mapped\" \"\\n\"\n \"so\\n\"\n \"arg 0 has an axis to be mapped of size 10\\n\"\n \"arg 1 has an axis to be mapped of size 2\"):\n api.vmap(h, in_axes=(0, 1))(X, U)\n\n with self.assertRaisesRegex(\n ValueError,\n \"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n r\"arg 0 has shape \\(10, 4\\) and axis 0 is to be mapped\" \"\\n\"\n r\"arg 1 has shape \\(10, 2\\) and axis 1 is to be mapped\" \"\\n\"\n r\"arg 2 has shape \\(10, 4\\) and axis 0 is to be mapped\" \"\\n\"\n \"so\\n\"\n \"args 0, 2 have axes to be mapped of size 10\\n\"\n \"arg 1 has an axis to be mapped of size 2\"):\n api.vmap(lambda x, y, z: None, in_axes=(0, 1, 0))(X, U, X)\n\n with self.assertRaisesRegex(\n ValueError,\n \"vmap got inconsistent sizes for array axes to be mapped:\\n\"\n \"the tree of axis sizes is:\\n\"\n r\"\\(10, \\[2, 2\\]\\)\"):\n api.vmap(h, in_axes=(0, 1))(X, [U, U])\n\n with self.assertRaisesRegex(\n ValueError, \"vmap got arg 0 of rank 0 but axis to be mapped 0\"):\n # The mapped inputs cannot be scalars\n api.vmap(lambda x: x)(1.)\n\n with self.assertRaisesRegex(\n ValueError, \"vmap must have at least one non-None value in in_axes\"):\n # If the output is mapped, there must be a non-None in_axes\n api.vmap(lambda x: x, in_axes=None)(jnp.array([1., 2.]))\n\n with self.assertRaisesRegex(\n ValueError, \"vmap got arg 0 of rank 1 but axis to be mapped 1\"):\n api.vmap(lambda x: x, in_axes=1)(jnp.array([1., 2.]))\n\n # Error is: TypeError: only integer scalar arrays can be converted to a scalar index\n with self.assertRaisesRegex(\n ValueError,\n \"vmap out_axes specification must be a tree prefix of the \"\n \"corresponding value.*\"):\n api.vmap(lambda x: x, in_axes=0, out_axes=(2, 3))(jnp.array([1., 2.]))\n\n with self.assertRaisesRegex(\n ValueError, \"vmap has mapped output but out_axes is None\"):\n # If the output is mapped, then there must be some out_axes specified\n api.vmap(lambda x: x, out_axes=None)(jnp.array([1., 2.]))\n\n def test_vmap_structured_in_axes(self):\n\n A, B, C, D = 2, 3, 4, 5\n K = 6 # batch size\n x = np.ones((K, A, B)) # batch axis in different locations\n y = np.ones((B, K, C))\n z = np.ones((C, D, K))\n\n def foo(tree_arg):\n x, (y, z) = tree_arg\n return jnp.dot(x, jnp.dot(y, z))\n\n tree = (x, (y, z))\n vfoo = api.vmap(foo, in_axes=((0, (1, 2)),))\n self.assertEqual(vfoo(tree).shape, (6, 2, 5))\n\n Point = collections.namedtuple(\"Point\", [\"x\", \"y\"])\n tree = (x, Point(y, z))\n vfoo = api.vmap(foo, in_axes=((0, Point(1, 2)),))\n self.assertEqual(vfoo(tree).shape, (6, 2, 5))\n\n def foo(tree_arg):\n x, dct = tree_arg\n y, z = dct['a'], dct['b']\n return jnp.dot(x, jnp.dot(y, z))\n\n tree = (x, {'a': y, 'b': z})\n vfoo = api.vmap(foo, in_axes=((0, {'a': 1, 'b': 2}),))\n self.assertEqual(vfoo(tree).shape, (6, 2, 5))\n\n tree = (x, collections.OrderedDict([('a', y), ('b', z)]))\n vfoo = api.vmap(\n foo, in_axes=((0, collections.OrderedDict([('a', 1), ('b', 2)])),))\n self.assertEqual(vfoo(tree).shape, (6, 2, 5))\n\n def test_pmap_global_cache(self):\n def f(x, y):\n return x, y\n\n x = np.ones((1, 1, 1))\n\n # All defaults\n with jtu.assert_num_jit_and_pmap_compilations(1):\n for _ in range(2):\n api.pmap(f)(x, x)\n\n # With axis name\n with jtu.assert_num_jit_and_pmap_compilations(1):\n for _ in range(2):\n api.pmap(f, 'i')(x, x)\n\n # With in_axes and out_axes\n if config.omnistaging_enabled:\n for x_in, y_in, x_out, y_out in it.product(*((0, 1, 2) for _ in range(4))):\n with jtu.assert_num_jit_and_pmap_compilations(1):\n for _ in range(2):\n api.pmap(f, 'i', in_axes=(x_in, y_in), out_axes=(x_out, y_out))(x, x)\n\n # Forward-mode AD on the outside\n with jtu.assert_num_jit_and_pmap_compilations(1):\n for _ in range(2):\n api.jvp(api.pmap(f), (x, x), (x, x))\n\n # Reverse-mode AD on the outside. One compilation for forward, one for backward.\n with jtu.assert_num_jit_and_pmap_compilations(2):\n for _ in range(2):\n api.vjp(api.pmap(f), x, x)[1]((x, x))\n\n def test_device_array_repr(self):\n rep = jnp.ones(()) + 1.\n self.assertStartsWith(repr(rep), \"DeviceArray\")\n\n def test_device_array_hash(self):\n rep = jnp.ones(()) + 1.\n self.assertIsInstance(rep, jax.interpreters.xla._DeviceArray)\n msg = \"JAX DeviceArray, like numpy.ndarray, is not hashable.\"\n with self.assertRaisesRegex(TypeError, msg):\n hash(rep)\n with self.assertRaisesRegex(TypeError, msg):\n hash(rep.device_buffer)\n\n def test_grad_without_enough_args_error_message(self):\n # https://github.com/google/jax/issues/1696\n def f(x, y): return x + y\n df = api.grad(f, argnums=0)\n self.assertRaisesRegex(\n TypeError,\n \"differentiating with respect to argnums=0 requires at least 1 \"\n \"positional arguments to be passed by the caller, but got only 0 \"\n \"positional arguments.\",\n lambda: partial(df, x=0.)(y=1.))\n\n def test_grad_of_jit_compilation_caching(self):\n if not hasattr(self, \"assertLogs\"):\n raise unittest.SkipTest(\"test requires assertLogs (python 3)\")\n\n lax.add(1, 2) # make sure some initial warnings are already printed\n\n sin = api.jit(jnp.sin)\n\n prev_level = logging.get_verbosity()\n try:\n logging.set_verbosity('DEBUG')\n with self.assertLogs(level=logging.DEBUG) as l:\n ans1 = api.grad(sin)(2.)\n ans2 = api.grad(sin)(3.)\n finally:\n logging.set_verbosity(prev_level)\n self.assertLen(l.output, 2)\n\n self.assertAllClose(ans1, np.cos(2.), check_dtypes=False)\n self.assertAllClose(ans2, np.cos(3.), check_dtypes=False)\n\n def test_trivial_computations(self):\n x = jnp.array([1, 2, 3])\n y = api.jit(lambda x: x)(x)\n self.assertIs(x, y)\n\n z1, z2 = api.jit(lambda x: (x, x))(x)\n self.assertIs(z1, z2)\n\n x1, x2 = jnp.array([1, 2]), jnp.array([2, 3])\n z1, z2, z3 = api.jit(lambda x, y: (y, 1, x))(x1, x2)\n self.assertIs(z1, x2)\n self.assertIs(z3, x1)\n self.assertEqual(z2, 1)\n\n def test_nested_jit_hoisting(self):\n @api.jit\n def f(x, y):\n z = 2 * x\n return y + z, 3\n\n @api.jit\n def g(x):\n return f(2, x)\n\n jaxpr_subcomp = xla.jaxpr_subcomp\n\n jaxprs = []\n def jaxpr_subcomp_and_collect(c, jaxpr, *args, **kwargs):\n jaxprs.append(jaxpr)\n return jaxpr_subcomp(c, jaxpr, *args, **kwargs)\n\n try:\n xla.jaxpr_subcomp = jaxpr_subcomp_and_collect\n ans = g(3)\n finally:\n xla.jaxpr_subcomp = jaxpr_subcomp\n\n self.assertEqual(ans, (7, 3))\n self.assertLen(jaxprs, 2)\n outer_jaxpr, inner_jaxpr = jaxprs\n\n self.assertLen(outer_jaxpr.eqns, 1)\n self.assertEqual(outer_jaxpr.eqns[0].primitive.name, 'xla_call')\n subjaxpr_1 = outer_jaxpr.eqns[0].params[\"call_jaxpr\"]\n self.assertEqual(str(subjaxpr_1), str(inner_jaxpr))\n self.assertLen(inner_jaxpr.eqns, 2)\n self.assertEqual(inner_jaxpr.eqns[0].primitive.name, 'mul')\n self.assertEqual(inner_jaxpr.eqns[1].primitive.name, 'add')\n\n def test_primitive_compilation_cache(self):\n with jtu.count_primitive_compiles() as count:\n lax.add(1, 2)\n lax.add(2, 3)\n self.assertEqual(count[0], 1)\n\n def test_arange_jit(self):\n # see https://github.com/google/jax/issues/553\n def fun(x):\n r = jnp.arange(x.shape[0])[x]\n return r\n\n jit(fun)(jnp.array([0, 1, 2], dtype=jnp.int32)) # doesn't crash\n\n def helper_save_tracer(self, x):\n self._saved_tracer = x\n return x\n\n def test_escaped_tracers_different_top_level_traces(self):\n api.jit(self.helper_save_tracer)(0.)\n with self.assertRaisesRegex(\n core.UnexpectedTracerError, \"Encountered an unexpected tracer\"):\n api.jit(lambda x: self._saved_tracer)(0.)\n\n def test_escaped_tracers_cant_lift_sublevels(self):\n api.jit(self.helper_save_tracer)(0.)\n with self.assertRaisesRegex(\n core.UnexpectedTracerError,\n re.compile(\n \"Encountered an unexpected tracer\",\n re.DOTALL)):\n api.jit(lambda x: x)(self._saved_tracer)\n\n def test_escaped_tracers_tracer_from_higher_level(self):\n api.grad(self.helper_save_tracer)(0.)\n with self.assertRaisesRegex(\n core.UnexpectedTracerError,\n re.compile(\n \"Encountered an unexpected tracer.*Tracer from a higher level\",\n re.DOTALL)):\n api.grad(lambda x: x)(self._saved_tracer)\n\n def test_escaped_tracers_incompatible_sublevel(self):\n def func1(x):\n api.jit(self.helper_save_tracer)(0.)\n # Use the tracer\n return x + self._saved_tracer\n with self.assertRaisesRegex(\n core.UnexpectedTracerError,\n re.compile(\"Encountered an unexpected tracer\",\n re.DOTALL)):\n api.jit(func1)(2.)\n\n def test_escaped_tracers_cant_lift(self):\n def func1(x):\n api.grad(self.helper_save_tracer)(0.)\n return x + self._saved_tracer\n with self.assertRaisesRegex(\n core.UnexpectedTracerError,\n re.compile(\"Encountered an unexpected tracer.*Can't lift\",\n re.DOTALL)):\n api.grad(func1)(2.)\n\n def test_escaped_tracers_not_among_input_tracers(self):\n def func1(x):\n api.grad(self.helper_save_tracer)(x)\n # Use the tracer\n return x + self._saved_tracer\n\n with self.assertRaisesRegex(\n core.UnexpectedTracerError,\n re.compile(\n \"Encountered an unexpected tracer.*Tracer not among input tracers\",\n re.DOTALL)):\n api.jit(func1)(2.)\n\n def test_escaped_tracer_omnistaging(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test is omnistaging-specific\")\n\n count = 1\n\n @jit\n def f():\n nonlocal count\n count = jnp.add(count, 1)\n f() # leaked a tracer! but currently undetected\n\n def f(x, c):\n jnp.add(count, 1)\n return None, None\n\n @jit\n def g():\n lax.scan(f, None, None, length=2)\n\n with self.assertRaisesRegex(core.UnexpectedTracerError,\n \"tracer created on line\"):\n g()\n\n def test_escaped_tracer_omnistaging_top_trace(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test is omnistaging-specific\")\n\n count = 1\n\n def f(_, __):\n nonlocal count\n count = jnp.add(count, 1)\n return None, None\n\n lax.scan(f, None, None, length=2) # leaked a tracer! (of level 1!)\n\n with self.assertRaisesRegex(core.UnexpectedTracerError,\n \"tracer created on line\"):\n # The following call will try and raise the ones array to the count tracer\n # level, which is no longer live.\n jax.jit(jnp.add)(jnp.ones(()), count)\n\n def test_pmap_static_kwarg_error_message(self):\n # https://github.com/google/jax/issues/3007\n def f(a, b):\n return a + b\n\n g = jax.pmap(f, static_broadcasted_argnums=(1,))\n\n msg = (r\"pmapped function has static_broadcasted_argnums=\\(1,\\) but was \"\n r\"called with only 1 positional argument. All static broadcasted \"\n r\"arguments must be passed positionally.\")\n with self.assertRaisesRegex(ValueError, msg):\n g(jnp.ones((1, 1)), b=1)\n\n def test_vmap_unmapped_last(self):\n @partial(jax.vmap, out_axes=-1)\n def f(x):\n return np.zeros((2,))\n f(np.zeros((5,)))\n\n # TODO(jakevdp): re-enable this if possible.\n @unittest.skipIf(True, \"broken by convert_element_type change.\")\n def test_xla_constant_dedup(self):\n y = np.array([7, 14], dtype=np.float32)\n def f(x):\n return x + y + y\n\n x = np.array([1, 2], dtype=np.float32)\n hlo_lines = jax.xla_computation(f)(x).as_hlo_text().split('\\n')\n hlo_lines = set([s.strip() for s in hlo_lines])\n self.assertIn('constant.1 = f32[2]{0} constant({7, 14})', hlo_lines)\n self.assertNotIn('constant.2 = f32[2]{0} constant({7, 14})', hlo_lines)\n\n def test_omnistaging_flag(self):\n if FLAGS.jax_omnistaging:\n jaxpr = api.make_jaxpr(lambda: jnp.add(1, 1))()\n self.assertLen(jaxpr.jaxpr.eqns, 1)\n else:\n # omnistaging can be enabled programmatically without setting the flag,\n # but that shouldn't happen in tests\n jaxpr = api.make_jaxpr(lambda: jnp.add(1, 1))()\n self.assertLen(jaxpr.jaxpr.eqns, 0)\n\n def test_eval_context(self):\n @jit\n def f():\n with core.eval_context():\n assert jnp.add(1, 1) == 2\n\n f() # doesn't crash\n\n def test_concrete_error_because_arg(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test is omnistaging-specific\")\n\n @jax.jit\n def f(x, y):\n if x > y:\n return x\n else:\n return y\n\n msg = r\"at flattened positions \\[0, 1\\]\"\n with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n f(1, 2)\n\n def test_concrete_error_because_const(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test is omnistaging-specific\")\n\n @jax.jit\n def f():\n assert jnp.add(1, 1) > 0\n\n msg = \"on these lines\"\n with self.assertRaisesRegex(core.ConcretizationTypeError, msg):\n f()\n\n # TODO(jakevdp): re-enable this if possible.\n @unittest.skipIf(True, \"broken by convert_element_type change.\")\n def test_xla_computation_zeros_doesnt_device_put(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test is omnistaging-specific\")\n\n count = 0\n def device_put_and_count(*args, **kwargs):\n nonlocal count\n count += 1\n return orig_device_put(*args, **kwargs)\n orig_device_put, xla.device_put = xla.device_put, device_put_and_count\n try:\n api.xla_computation(lambda: jnp.zeros(3))()\n finally:\n xla.device_put = orig_device_put\n self.assertEqual(count, 0)\n\n def test_join_concrete_arrays_with_omnistaging(self):\n # https://github.com/google/jax/issues/4622\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test is omnistaging-specific\")\n\n x = jnp.array([1., 2., 3.])\n y = jnp.array([1., 2., 4.])\n\n @jit\n def f():\n core.lattice_join(core.ConcreteArray(x), core.ConcreteArray(y))\n\n f() # doesn't crash\n\n def test_linearize_aval_error(self):\n # https://github.com/google/jax/issues/4622\n f = lambda x: x\n\n # these should not error\n _, f_jvp = api.linearize(f, 1.)\n f_jvp(1.)\n _, f_jvp = api.linearize(f, np.ones(2, np.int32))\n f_jvp(np.zeros(2, float0))\n\n # these should error\n _, f_jvp = api.linearize(f, 1.)\n with self.assertRaisesRegex(ValueError, \"tangent values inconsistent\"):\n f_jvp(1)\n _, f_jvp = api.linearize(f, np.ones(2, np.int32))\n with self.assertRaisesRegex(ValueError, \"tangent values inconsistent\"):\n f_jvp(np.ones(2, np.int32))\n\n\nclass RematTest(jtu.JaxTestCase):\n\n def test_remat_basic(self):\n @api.remat\n def g(x):\n return lax.sin(lax.sin(x)), 3.\n\n def f(x):\n x, _ = g(x)\n return x\n\n ans = f(2.)\n expected = np.sin(np.sin(2.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans, f_lin = api.linearize(f, 2.)\n expected = np.sin(np.sin(2.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = f_lin(3.)\n expected = np.cos(np.sin(2.)) * np.cos(2.) * 3.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n sin_calls = []\n cos_calls = []\n sin_impl = lax.sin_p.impl\n cos_impl = lax.cos_p.impl\n try:\n lax.sin_p.def_impl(lambda x: sin_calls.append(1) or sin_impl(x))\n lax.cos_p.def_impl(lambda x: cos_calls.append(1) or cos_impl(x))\n f_lin(3.)\n finally:\n lax.sin_p.def_impl(sin_impl)\n lax.cos_p.def_impl(cos_impl)\n self.assertEqual(len(sin_calls), 1)\n self.assertEqual(len(cos_calls), 2)\n\n def test_remat_freevars(self):\n def f1(x):\n y = 2 * jnp.sin(x)\n z = jnp.cos(x) * jnp.sin(y)\n return z\n\n def f2(x):\n y = 2 * jnp.sin(x)\n z = api.remat(lambda x: jnp.cos(x) * jnp.sin(y))(x)\n return z\n\n ans, f_lin = api.linearize(f2, 2.)\n expected, f_lin_expected = api.linearize(f1, 2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = f_lin(3.)\n expected = f_lin_expected(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_grad_python_control_flow(self):\n @partial(api.remat, concrete=True)\n def g(x):\n if x > 0:\n return lax.sin(x), 3.\n else:\n return lax.cos(x), 4.\n\n def f(x):\n x, _ = g(x)\n return x\n\n ans = f(2.)\n expected = np.sin(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(f)(2.)\n expected = np.cos(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_jit(self):\n @api.remat\n def g(x):\n return lax.sin(lax.sin(x))\n\n def f_(x):\n return g(x)\n f = api.jit(f_)\n\n ans = f(2.)\n expected = np.sin(np.sin(2.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(f)(2.)\n expected = np.cos(np.sin(2.)) * np.cos(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.grad(f_))(2.)\n expected = np.cos(np.sin(2.)) * np.cos(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_vmap(self):\n @api.remat\n def g(x):\n return lax.sin(lax.sin(x))\n\n x = np.arange(3.)\n\n ans = api.vmap(g)(x)\n expected = np.sin(np.sin(x))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jacfwd(g)(x)\n expected = np.diag(np.cos(np.sin(x)) * np.cos(x))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jacrev(g)(x)\n expected = np.diag(np.cos(np.sin(x)) * np.cos(x))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_higher_order_autodiff(self):\n def f(x):\n return lax.cos(lax.sin(x))\n g = api.remat(f)\n\n ans = api.grad(api.grad(g))(3.)\n expected = api.grad(api.grad(f))(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_scan(self):\n to_scan = lambda c, x: (jnp.sin(c), None)\n\n def f_noremat(x):\n y, _ = lax.scan(to_scan, x, np.arange(3.))\n return y\n\n def f_yesremat(x):\n y, _ = lax.scan(api.remat(to_scan), x, np.arange(3.))\n return y\n\n ans = f_yesremat(4.)\n expected = f_noremat(4.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(f_yesremat)(4.)\n expected = api.grad(f_noremat)(4.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n jaxpr = api.make_jaxpr(api.linearize(f_yesremat, 4.)[1])(1.)\n scan_eqn, = jaxpr.jaxpr.eqns\n self.assertIn(' cos ', str(scan_eqn.params['jaxpr']))\n\n jaxpr = api.make_jaxpr(api.vjp(f_yesremat, 4.)[1])(1.)\n scan_eqn, = jaxpr.jaxpr.eqns\n self.assertIn(' cos ', str(scan_eqn.params['jaxpr']))\n\n def test_remat_no_redundant_flops(self):\n # see https://github.com/google/jax/pull/1749#issuecomment-558267584\n\n @api.jit\n def g(x):\n return f(2., x)\n\n @api.remat\n def f(x, y):\n return jnp.sin(x) * y\n\n # We swap out sin_p's impl rule to count how many times it's invoked\n called = []\n sin_impl = lax.sin_p.impl\n try:\n lax.sin_p.def_impl(lambda x: called.append(1) or sin_impl(x))\n api.grad(g)(3.)\n finally:\n lax.sin_p.def_impl(sin_impl)\n num_calls = len(called)\n self.assertLessEqual(num_calls, 1)\n\n def test_remat_binomial_checkpointing(self):\n def binom_checkpoint(funs):\n if len(funs) == 1:\n return funs[0]\n else:\n f1 = binom_checkpoint(funs[:len(funs)//2])\n f2 = binom_checkpoint(funs[len(funs)//2:])\n return api.remat(lambda x: f1(f2(x)))\n\n f1 = binom_checkpoint([jnp.sin, jnp.sin, jnp.sin, jnp.sin])\n f2 = lambda x: jnp.sin(jnp.sin(jnp.sin(jnp.sin(x))))\n x = 4.\n self.assertAllClose(f1(x), f2(x), check_dtypes=False)\n self.assertAllClose(api.grad(f1)(x), api.grad(f2)(x), check_dtypes=False)\n\n def test_remat_symbolic_zeros(self):\n # code from https://github.com/google/jax/issues/1907\n\n key = jax.random.PRNGKey(0)\n key, split = jax.random.split(key)\n n = 5\n\n def func(D0):\n def shift(R, dR, **unused_kwargs):\n return R + dR\n\n def apply_fn(R):\n return D0 * R\n\n Rinit = jax.random.uniform(split, (n,3), minval=0.0, maxval=5.0,\n dtype=jnp.float32)\n\n def move(R,i):\n F = apply_fn(R)\n return shift(R, 0.001 * F), jnp.array([0.])\n\n move = api.remat(move)\n R, temp = lax.scan(move, Rinit, jnp.arange(2))\n return R[0, 0]\n\n api.grad(func)(5.0) # doesn't crash\n\n def test_remat_jit2(self):\n @api.jit\n def f(x):\n y = 2 * x\n\n @api.remat\n def g():\n return y\n\n return g()\n\n self.assertAllClose(f(3), 6, check_dtypes=False)\n\n def test_remat_nontrivial_env(self):\n # simplified from https://github.com/google/jax/issues/2030\n\n @api.remat\n def foo(state, dt=0.5, c=1):\n u, u_t = state\n u_tt = c**2 * u\n u_t = u_t + u_tt * dt\n return (u, u_t)\n\n @partial(api.jit, static_argnums=(1,))\n def _multi_step(state, count, dt, c):\n f = lambda s, _: (foo(s, dt, c), _)\n return lax.scan(f, state, None, count)\n\n def multi_step(state, count, dt=1/jnp.sqrt(2), c=1):\n return _multi_step(state, count, dt, c)\n\n def loss(u0, target, steps, dt=1/jnp.sqrt(2), c=1):\n init = (u0, jnp.zeros_like(u0))\n (uf, _), _ = multi_step(init, steps, dt, c)\n return ((uf - target) ** 2).mean()\n\n target = jnp.zeros((128, 128))\n u0 = jnp.ones_like(target)\n loss(u0, target, 10) # doesn't crash\n\n def test_remat_jit3(self):\n # https://github.com/google/jax/issues/2180\n def f(w, x):\n a = jnp.dot(x, w)\n b = jnp.einsum(\"btd,bTd->btT\", a, a)\n c = jnp.einsum(\"btT,btd->btd\", b, a)\n return jnp.sum(c)\n\n w = jnp.ones([1, 1])\n x = jnp.ones([1, 1, 1])\n f = api.remat(f)\n api.grad(f)(w, x) # doesn't crash\n\n @api.jit\n def mul(a, b):\n return a * b\n\n def f(w, x):\n a = mul(w, x)\n b = mul(a, a)\n return b\n\n w = 1.\n x = 1.\n f = api.remat(f)\n api.grad(f)(w, x) # doesn't crash\n\n def test_remat_scan2(self):\n # https://github.com/google/jax/issues/1963\n\n def scan_bug(x0):\n f = lambda x, _: (x + 1, None)\n def scanned_f(x, _):\n return lax.scan(f, x, xs=None, length=1)[0], None\n x, _ = jax.remat(scanned_f)(x0, None)\n return x\n\n jax.grad(scan_bug)(1.0) # doesn't crash\n\n def test_remat_jit_static_argnum(self):\n # https://github.com/google/jax/issues/2833\n if config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works without omnistaging\") # see next test\n\n def f(a_bool, y):\n if a_bool:\n return y + 1\n else:\n return y\n\n api.jit(api.remat(f, concrete=True), static_argnums=0)(True, 1) # no crash\n\n\n def test_remat_jit_static_argnum_omnistaging(self):\n # https://github.com/google/jax/issues/2833\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\") # see previous test\n\n def named_call(f):\n def named_f(*args):\n f_ = lu.wrap_init(lambda: (f(*args),))\n out, = core.call_p.bind(f_)\n return out\n return named_f\n\n def f(a_bool, y):\n if a_bool:\n return y + 1\n else:\n return y\n\n api.jit(named_call(f), static_argnums=0)(True, 1) # no crash\n\n def test_remat_eval_counter(self):\n # https://github.com/google/jax/issues/2737\n add_one_p = Primitive('add_one')\n add_one = add_one_p.bind\n\n num_evals = 0\n\n @contextmanager\n def assertEvals(n):\n start = num_evals\n yield\n assert num_evals - start == n\n\n def add_one_impl(x):\n nonlocal num_evals\n num_evals += 1\n return x + 1\n add_one_p.def_impl(add_one_impl)\n\n def add_one_jvp(pin, tin):\n pout = add_one(pin[0])\n return pout, pout * tin[0]\n ad.primitive_jvps[add_one_p] = add_one_jvp\n\n add_one_p.def_abstract_eval(lambda x: x)\n\n v = np.zeros((1,))\n\n f = jax.remat(add_one)\n g = jax.remat(lambda x: add_one(f(x)))\n\n # 2 calls needed to evaluate g\n with assertEvals(2):\n _, vjp = jax.vjp(g, v)\n # 2 calls made while transposing g, 1 call made while transposing f\n with assertEvals(3):\n vjp(v)\n\n @jax.util.curry\n def call(f, *args):\n return jax.core.call(\n jax.linear_util.wrap_init(lambda *args: [f(*args)]),\n *args, name='foo')[0]\n\n f = call(add_one)\n g = jax.remat(lambda x: add_one(f(x)))\n\n # 2 calls needed to evaluate g\n with assertEvals(2):\n _, vjp = jax.vjp(g, v)\n # 2 calls made while transposing g, no reevaluation for transposition of f\n with assertEvals(2):\n vjp(v)\n\n def test_escaped_tracer_remat(self):\n # b/169779185\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n def f():\n seq = [jnp.zeros([])]\n def g():\n seq[0] += 1 # this is line 7 btw\n return seq[0]\n\n api.remat(g)()\n api.remat(g)()\n\n with self.assertRaisesRegex(core.UnexpectedTracerError, \"global state\"):\n api.jit(f)()\n\n\nclass JaxprTest(jtu.JaxTestCase):\n\n def test_scalar_literals(self):\n jaxpr = api.make_jaxpr(lambda x: x + 2)(42)\n self.assertLen(jaxpr.jaxpr.constvars, 0)\n\n def test_const(self):\n def fun(x):\n return (x, 1., np.zeros(1))\n\n if config.omnistaging_enabled:\n expected = \"\"\"\n { lambda a ; b.\n let\n in (b, 1.0, a) }\n \"\"\"\n else:\n expected = \"\"\"\n { lambda b ; a.\n let\n in (a, 1.0, b) }\n \"\"\"\n\n jaxpr = api.make_jaxpr(fun)(0.)\n self.assertMultiLineStrippedEqual(expected, str(jaxpr))\n\n def test_cond(self):\n def f(x):\n return lax.cond(x >= 0.,\n x + 1.,\n lambda xt: xt + x,\n x + 2.,\n lambda xf: xf - x)\n if config.omnistaging_enabled:\n expected = \"\"\"\n { lambda ; a.\n let b = ge a 0.0\n c = add a 1.0\n d = add a 2.0\n e = convert_element_type[ new_dtype=int32 ] b\n f = cond[ branches=( { lambda ; e_ a b c.\n let d = sub c a\n in (d,) }\n { lambda ; a f_ b c.\n let d = add b a\n in (d,) } )\n linear=(False, False, False, False) ] e a a c d\n in (f,) }\n \"\"\"\n else:\n expected = \"\"\"\n { lambda ; a.\n let b = ge a 0.0\n c = convert_element_type[ new_dtype=int32 ] b\n d = add a 1.0\n e = add a 2.0\n f = cond[ branches=( { lambda ; e_ c a b.\n let d = sub b c\n in (d,) }\n { lambda ; c f_ a b.\n let d = add a c\n in (d,) } )\n linear=(False, False, False, False) ] c a a d e\n in (f,) }\n \"\"\"\n jaxpr = api.make_jaxpr(f)(3.)\n self.assertMultiLineStrippedEqual(expected, str(jaxpr))\n\n def test_make_jaxpr_static_argnums(self):\n def f(x, y):\n return x + y\n\n jaxpr = api.make_jaxpr(f, static_argnums=(1,))(2, 3)\n self.assertIn('3', str(jaxpr))\n\n def test_make_jaxpr_return_shape(self):\n _, shape_tree = api.make_jaxpr(lambda x: (x + 1, jnp.zeros(2, jnp.float32)),\n return_shape=True)(np.int32(1))\n expected = (api.ShapeDtypeStruct(shape=(), dtype=jnp.int32),\n api.ShapeDtypeStruct(shape=(2,), dtype=jnp.float32))\n self.assertEqual(shape_tree, expected)\n\n\nclass LazyTest(jtu.JaxTestCase):\n\n @contextmanager\n def count_compiles(self):\n\n make_computation_builder = xb.make_computation_builder\n count = [0]\n\n def make_computation_builder_and_count(*args, **kwargs):\n count[0] += 1\n return make_computation_builder(*args, **kwargs)\n\n xb.make_computation_builder = make_computation_builder_and_count\n try:\n yield count\n finally:\n xb.make_computation_builder = make_computation_builder\n\n @jtu.skip_on_devices(\"tpu\")\n def test_lazy_jit_closed_over_values(self):\n if not core.skip_checks:\n raise unittest.SkipTest(\"oom test skipped when core.skip_checks is False\")\n\n y = jnp.arange(int(1e12)) # will likely oom if materialized\n ans = jit(lambda x: (x + y)[1])(1)\n self.assertEqual(ans, 2)\n\n def test_jit_forces_arguments(self):\n\n @api.jit\n def f(x):\n assert python_should_be_executing\n return jnp.sum(x)\n\n x = jnp.zeros(10, dtype=jnp.int32)\n assert not lazy.is_trivial(x._lazy_expr)\n\n python_should_be_executing = True\n _ = f(x)\n\n python_should_be_executing = False # should not recompile\n x = np.zeros(10, dtype=np.int32)\n _ = f(x)\n\n @parameterized.parameters(jtu.cases_from_list(range(10000)))\n def test_random_lazy_program(self, seed):\n\n def random_array(rng):\n kind = rng.choice(['arr', 'iota', 'eye', 'tri'])\n if kind == 'arr':\n dtype = [np.float32, np.int32][rng.choice(2)]\n dim = rng.randint(4)\n shape = rng.randint(4, size=dim)\n np_x = np.asarray(rng.randn(*shape), dtype=dtype)\n jax_x = jnp.array(np_x, dtype=dtype)\n elif kind == 'iota':\n dtype = [np.float32, np.int32][rng.choice(2)]\n size = rng.randint(5)\n np_x = np.arange(size, dtype=dtype)\n jax_x = lax.iota(dtype, size)\n elif kind == 'eye':\n dtype = [np.float32, np.int32][rng.choice(2)]\n N = rng.randint(2, 5)\n M = None if rng.rand() < 0.5 else rng.randint(2, 5)\n k = rng.choice([-1, 0, 1])\n np_x = np.eye(N, M, k, dtype=dtype)\n jax_x = jnp.eye(N, M, k, dtype=dtype)\n elif kind == 'tri':\n dtype = [np.float32, np.int32][rng.choice(2)]\n N = rng.randint(2, 5)\n M = None if rng.rand() < 0.5 else rng.randint(2, 5)\n k = rng.choice([-1, 0, 1])\n np_x = np.tri(N, M, k, dtype=dtype)\n jax_x = jnp.tri(N, M, k, dtype=dtype)\n else:\n assert False\n assert type(np_x) is np.ndarray and xla.type_is_device_array(jax_x)\n return np_x, jax_x\n\n def random_op(rng, shape):\n kind = rng.choice(['transpose', 'broadcast', 'reshape'])\n if kind == 'transpose':\n perm = tuple(rng.permutation(len(shape)))\n return Op(partial(np.transpose, axes=perm),\n partial(lax.transpose, permutation=perm))\n elif kind == 'broadcast':\n n = rng.randint(1, 3)\n new_sizes = rng.randint(1, 4, size=n)\n new_ndim = n + len(shape)\n bcast_dims = tuple(sorted(rng.permutation(new_ndim)[:len(shape)]))\n shape_iter = iter(shape)\n new_sizes = iter(rng.randint(1, 4, size=n))\n new_shape = [next(shape_iter) if i in bcast_dims else next(new_sizes)\n for i in range(new_ndim)]\n return Op(partial(lax_reference.broadcast_in_dim, shape=new_shape,\n broadcast_dimensions=bcast_dims),\n partial(lax.broadcast_in_dim, shape=new_shape,\n broadcast_dimensions=bcast_dims))\n elif kind == 'reshape':\n new_shape = list(shape)\n for _ in range(rng.randint(1, 3)):\n loc = len(new_shape) and rng.randint(len(new_shape))\n new_shape.insert(loc, 1)\n new_shape = tuple(new_shape)\n return Op(partial(np.reshape, newshape=new_shape),\n partial(lax.reshape, new_sizes=new_shape))\n else:\n assert False\n Op = collections.namedtuple('Op', ['np_fn', 'jax_fn'])\n\n rng = np.random.RandomState(seed)\n np_x, jax_x = _, orig_x = random_array(rng)\n ops = []\n with jtu.count_primitive_compiles() as count:\n for _ in range(rng.randint(5)):\n op = random_op(rng, np.shape(np_x))\n np_x = op.np_fn(np_x)\n jax_x = op.jax_fn(jax_x)\n ops.append(op)\n self.assertEqual(count[0], 0)\n\n kind = rng.choice(['closure', 'npy_value', 'force', 'add'])\n if kind == 'closure':\n result = api.jit(lambda x: x + jax_x)(0)\n self.assertAllClose(np_x, result, check_dtypes=False)\n elif kind == 'npy_value':\n self.assertAllClose(np_x, jax_x, check_dtypes=False)\n elif kind == 'force':\n result = xla._force(jax_x)\n self.assertAllClose(np_x, result, check_dtypes=False)\n elif kind == 'add':\n result = jax_x + np.zeros(jax_x.shape, dtype=jax_x.dtype)\n self.assertAllClose(np_x, result, check_dtypes=False)\n else:\n assert False\n\n @jit\n def apply_ops(x):\n for op in ops:\n x = op.jax_fn(x)\n return x\n\n jit_result = apply_ops(orig_x)\n self.assertAllClose(jit_result, np_x, check_dtypes=False)\n\n @jit\n def apply_ops_closure():\n x = orig_x\n for op in ops:\n x = op.jax_fn(x)\n return x\n\n jit_result = apply_ops_closure()\n self.assertAllClose(jit_result, np_x, check_dtypes=False)\n\n def test_constant_forcing_computations_cached(self):\n # from https://github.com/google/jax/issues/1909\n xla._lazy_force_computation.cache_clear() # clear force compile cache\n big_lazy_x = np.ones((api.device_count(), 100))\n f = api.pmap(lambda x: 2 * x)\n _ = f(big_lazy_x)\n\n with self.count_compiles() as count:\n _ = f(big_lazy_x)\n self.assertEqual(count[0], 0)\n\n def test_zeros_ones_compilation(self):\n w = jnp.ones(3) + jnp.ones(3) # ensure + has a cache entry\n w.block_until_ready()\n\n xla._lazy_force_computation.cache_clear() # clear force compile cache\n\n with self.count_compiles() as count:\n x = jnp.ones(3) + jnp.zeros(3)\n y = jnp.ones(3) + jnp.ones(3)\n\n self.assertEqual(1, count[0])\n self.assertAllClose(x, np.ones(3), check_dtypes=False)\n self.assertAllClose(y, np.ones(3) + np.ones(3), check_dtypes=False)\n\nclass CustomJVPTest(jtu.JaxTestCase):\n\n def test_basic(self):\n @api.custom_jvp\n def f(x):\n return jnp.sin(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * jnp.cos(x) * g\n f.defjvp(f_jvp)\n\n x = 3.\n self.assertAllClose(f(x), jnp.sin(x))\n self.assertAllClose(api.jvp(f, (x,), (1.,)),\n (jnp.sin(x), 2 * jnp.cos(x)))\n self.assertAllClose(api.grad(f)(x), 2 * jnp.cos(x))\n\n def test_invariance(self):\n @api.custom_jvp\n def f(x):\n return jnp.cos(2 * x) / 2.\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return (f(x), 3 * g)\n f.defjvp(f_jvp)\n def f2(x):\n y, _ = api.jvp(f, (x,), (x,))\n return y\n def f3(x):\n y, _ = api.jvp(f2, (x,), (x,))\n return y\n x = 1.\n self.assertAllClose(api.jvp(f, (x,), (x,)),\n api.jvp(f2, (x,), (x,)),\n check_dtypes=False)\n self.assertAllClose(api.jvp(f, (x,), (x,)),\n api.jvp(f3, (x,), (x,)),\n check_dtypes=False)\n\n def test_python_control_flow(self):\n @api.custom_jvp\n def f(x):\n if x > 0:\n return jnp.sin(x)\n else:\n return jnp.cos(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n if x > 0:\n return f(x), 2 * g\n else:\n return f(x), 3 * g\n f.defjvp(f_jvp)\n x = 2.\n self.assertAllClose(f(x), jnp.sin(x))\n self.assertAllClose(f(-x), jnp.cos(-x))\n self.assertAllClose(api.jvp(f, (x,), (1.,)),\n (jnp.sin(x), 2.),\n check_dtypes=False)\n self.assertAllClose(api.jvp(f, (-x,), (1.,)),\n (jnp.cos(-x), 3.),\n check_dtypes=False)\n self.assertAllClose(api.grad(f)(x), 2., check_dtypes=False)\n self.assertAllClose(api.grad(f)(-x), 3., check_dtypes=False)\n\n def test_vmap(self):\n @api.custom_jvp\n def f(x):\n assert jnp.ndim(x) == 0\n return jnp.sin(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n assert jnp.ndim(x) == jnp.ndim(g) == 0\n return f(x), 2 * jnp.cos(x) * g\n f.defjvp(f_jvp)\n\n x = jnp.arange(3.)\n xx = jnp.arange(6.).reshape(2, 3)\n\n # vmap of f\n self.assertAllClose(api.vmap(f)(x), jnp.sin(x))\n self.assertAllClose(api.vmap(api.vmap(f))(xx), jnp.sin(xx))\n\n # vmap of jvp of f\n self.assertAllClose(api.vmap(lambda x: api.jvp(f, (x,), (x,)))(x),\n (jnp.sin(x), 2 * jnp.cos(x) * x))\n self.assertAllClose(api.vmap(api.vmap(lambda x: api.jvp(f, (x,), (x,))))(xx),\n (jnp.sin(xx), 2 * jnp.cos(xx) * xx))\n\n # jvp of vmap of f\n self.assertAllClose(api.jvp(api.vmap(f), (x,), (x,)),\n (jnp.sin(x), 2 * jnp.cos(x) * x))\n self.assertAllClose(api.jvp(api.vmap(api.vmap(f)), (xx,), (xx,)),\n (jnp.sin(xx), 2 * jnp.cos(xx) * xx))\n\n # vmap of jvp of vmap of f\n self.assertAllClose(api.vmap(lambda x: api.jvp(api.vmap(f), (x,), (x,)))(xx),\n (jnp.sin(xx), 2 * jnp.cos(xx) * xx))\n\n def test_jit(self):\n @api.custom_jvp\n def f(x):\n return jnp.sin(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * jnp.cos(x) * g\n f.defjvp(f_jvp)\n\n x = 3.\n\n # jit\n self.assertAllClose(api.jit(f)(x), jnp.sin(x))\n self.assertAllClose(api.jit(api.jit(f))(x), jnp.sin(x))\n\n # jit of jvp\n self.assertAllClose(api.jit(lambda x: api.jvp(f, (x,), (x,)))(x),\n (jnp.sin(x), 2 * jnp.cos(x) * x),\n check_dtypes=False)\n\n # jvp of jit\n self.assertAllClose(api.jvp(api.jit(f), (x,), (x,)),\n (jnp.sin(x), 2 * jnp.cos(x) * x),\n check_dtypes=False)\n\n def test_pytrees(self):\n @api.custom_jvp\n def f(x):\n return {'b': jnp.sin(x['a'])}\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), {'b': 2 * jnp.cos(x['a']) * g['a']}\n f.defjvp(f_jvp)\n x = {'a': 3.}\n self.assertAllClose(f(x)['b'], jnp.sin(x['a']))\n self.assertAllClose(api.jvp(f, (x,), (x,)),\n ({'b': jnp.sin(x['a'])},\n {'b': 2 * jnp.cos(x['a']) * x['a']}),\n check_dtypes=False)\n\n def test_kwargs(self):\n # from https://github.com/google/jax/issues/1938\n @api.custom_jvp\n def my_fun(x, y, c=1.):\n return c * (x + y)\n def my_jvp(primals, tangents):\n x, y, c = primals\n t_x, t_y, t_c = tangents\n return my_fun(x, y, c), t_c\n my_fun.defjvp(my_jvp)\n f = lambda x, y: jnp.square(my_fun(x, y, c=2.)).sum()\n f(10., 5.) # doesn't crash\n api.jvp(f, (10., 5.), (1., 1.)) # doesn't crash\n\n def test_initial_style(self):\n @api.custom_jvp\n def f(x):\n return 3 * x\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * g\n f.defjvp(f_jvp)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.grad(foo)(3.)\n expected = 2.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.jit(foo))(3.)\n expected = 2.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.grad(foo))(3.)\n expected = 2.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.grad(foo))(3.)\n expected = 0.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.grad(api.jit(foo)))(3.)\n expected = 0.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.jit(api.grad(foo)))(3.)\n expected = 0.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.grad(api.grad(foo)))(3.)\n expected = 0.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_initial_style_vmap(self):\n @api.custom_jvp\n def f(x):\n assert jnp.ndim(x) == 0\n return 3 * x\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * g\n f.defjvp(f_jvp)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.vmap(foo)(jnp.ones(3))\n expected = 3. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.vmap(api.jit(foo))(jnp.ones(3))\n expected = 3. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.vmap(foo))(jnp.ones(3))\n expected = 3. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.vmap(foo)(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.vmap(api.jit(foo))(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.jit(api.vmap(foo))(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.jit(lambda x: api.vmap(foo)(x).sum()))(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.grad(lambda x: api.vmap(foo)(x).sum()))(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_closed_over_tracers_error_message(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n def f(x):\n @api.custom_jvp\n def g(y):\n return x + y\n def g_jvp(primals, tangents):\n return g(x), 2 * primals[0]\n g.defjvp(g_jvp)\n return g(1.)\n\n self.assertRaises(ad.CustomJVPException, lambda: api.jvp(f, (3.,), (1.,)))\n self.assertRaises(ad.CustomJVPException, lambda: api.grad(f)(3.))\n\n def test_nondiff_arg(self):\n @partial(api.custom_jvp, nondiff_argnums=(0,))\n def app(f, x):\n return f(x)\n def app_jvp(f, primals, tangents):\n (x,), (t,) = primals, tangents\n return app(f, x), 3 * t\n app.defjvp(app_jvp)\n\n ans = app(lambda x: 2 * x, 1)\n expected = 2\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jvp(lambda x: app(lambda y: 2 * y, x), (1.,), (1.,))\n expected = (2., 3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_nondiff_arg_jit_tracer(self):\n @partial(api.custom_jvp, nondiff_argnums=(0,))\n def f(x, y):\n return x * y\n def f_jvp(x, primals, tangents):\n (y,), (t_y,) = primals, tangents\n return f(x, y), 5 * t_y\n f.defjvp(f_jvp)\n\n @jit\n def g(x, y):\n return f(x, y)\n\n ans = api.jvp(lambda y: g(2., y), (3.,), (1.,))\n expected = (6., 5.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_nondiff_arg_hiding_jvp_tracer(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n def f(x):\n @partial(api.custom_jvp, nondiff_argnums=(0,))\n def g(h, x):\n return h(x)\n @g.defjvp\n def g_jvp(h, primals, tangents):\n x, = primals\n t, = tangents\n return g(h, x), 2. * t\n h = lambda y: x + y # capture x\n return g(h, x)\n\n with self.assertRaisesRegex(ad.CustomJVPException, \"Detected differentiation\"):\n api.jvp(f, (2.,), (1.,))\n\n def test_vmap_axes(self):\n raise unittest.SkipTest(\"TODO\") # TODO(mattjj): write test\n\n def test_pmap(self):\n raise unittest.SkipTest(\"TODO\") # TODO(mattjj): write test\n\n def test_missing_jvp_rule_error_message(self):\n @api.custom_jvp\n def foo(x):\n return x ** 2\n\n self.assertRaisesRegex(\n AttributeError,\n r\"No JVP defined for custom_jvp function foo using defjvp.\",\n lambda: foo(2))\n self.assertRaisesRegex(\n AttributeError,\n r\"No JVP defined for custom_jvp function foo using defjvp.\",\n lambda: api.jvp(foo, (2.,), (1.,)))\n self.assertRaisesRegex(\n AttributeError,\n r\"No JVP defined for custom_jvp function foo using defjvp.\",\n lambda: api.grad(foo)(2.))\n\n def test_jvp_rule_inconsistent_pytree_structures_error_message(self):\n @api.custom_jvp\n def f(x):\n return (x**2,)\n\n @f.defjvp\n def foo_jvp(primals, tangents):\n x, = primals\n t, = tangents\n return f(x), [2 * x * t, x]\n\n f(2.) # doesn't crash\n self.assertRaisesRegex(\n TypeError,\n re.escape(\n \"Custom JVP rule must produce primal and tangent outputs \"\n \"with equal container (pytree) structures, but got \"\n \"{} and {} respectively.\".format(\n tree_util.tree_structure((1,)),\n tree_util.tree_structure([1, 2]))\n ),\n lambda: api.jvp(f, (2.,), (1.,)))\n\n def test_primal_tangent_aval_disagreement_error_message(self):\n @api.custom_jvp\n def f(x):\n return x ** 2\n\n @f.defjvp\n def foo_jvp(primals, tangents):\n x, = primals\n t, = tangents\n return f(x), jnp.reshape(t, (1,))\n\n f(2.) # doesn't crash\n self.assertRaisesRegex(\n TypeError,\n re.escape(\n \"Custom JVP rule must produce primal and tangent outputs \"\n \"with equal shapes and dtypes, but got float32[] and float32[1] \"\n \"respectively.\"),\n lambda: api.jvp(f, (jnp.float32(2.),), (jnp.float32(1.),)))\n\n def test_jvp_rule_doesnt_return_pair_error_message(self):\n # https://github.com/google/jax/issues/2516\n\n @api.custom_jvp\n def f(x):\n return x ** 2\n\n @f.defjvp\n def foo_jvp(primals, tangents):\n x, = primals\n t, = tangents\n return t\n\n f(2.) # doesn't crash\n self.assertRaisesRegex(\n TypeError,\n re.escape(\n \"Custom JVP rule must produce a pair (list or tuple of length two) \"\n \"representing primal and tangent outputs, got 1.0\"),\n lambda: api.jvp(f, (2.,), (1.,)))\n\n def test_multiple_rule_invocations(self):\n @jax.custom_jvp\n def expit(x):\n return 1 / (1 + lax.exp(-x))\n\n @expit.defjvp\n def _expit_jvp(primals, tangents):\n (x,), (t,) = primals, tangents\n ans = expit(x)\n t_out = t * ans * (1 - ans)\n return ans, t_out\n\n def scanned_fun(c, _):\n return [expit(c[0])] + [c[i-1] + c[i] for i in range(1, len(c))], None\n\n def foo(x):\n c, _ = lax.scan(scanned_fun, [x, 0., 0., 0., 0.], None, length=10)\n return c[-1]\n\n # just make sure these don't crash\n foo(3.)\n grad(foo)(3.)\n grad(lambda x: jax.vmap(foo)(x).sum())(jnp.arange(3.))\n\n def test_hard_stuff(self):\n arr = jnp.ones((5, 2, 2))\n api.jit(jax.vmap(jnp.linalg.det))(arr) # doesn't crash\n\n def test_hard_stuff2(self):\n @jax.custom_jvp\n def f(x):\n return lax.tie_in(x, np.zeros(x.shape, x.dtype))\n\n @f.defjvp\n def f_jvp(primals, tangents):\n x, = primals\n t, = tangents\n return f(x), t\n\n # don't crash\n jax.jit(jax.vmap(f))(jnp.arange(3.))\n jax.jit(jax.vmap(jax.grad(f)))(jnp.arange(3.))\n jax.jit(jax.grad(lambda x: jax.vmap(f)(x).sum()))(jnp.arange(3.))\n jax.grad(lambda x: jax.vmap(f)(x).sum())(jnp.arange(3.))\n jax.jvp(jax.vmap(f), (jnp.arange(3.),), (jnp.ones(3),))\n\n def test_hard_stuff3(self):\n @jax.custom_jvp\n def relu(x):\n return jnp.maximum(x, 0)\n\n @relu.defjvp\n def _relu_jvp(primals, tangents):\n x, = primals\n t, = tangents\n return relu(x), lax.select(x > 0, t, lax.full_like(t, 0))\n\n def scanned_fun(c, _):\n return [relu(c[0])] + [c[i-1] + c[i] for i in range(1, len(c))], None\n\n def f(x):\n c, _ = lax.scan(scanned_fun, [x, 0., 0., 0., 0.], None, length=10)\n return c[-1]\n\n # don't crash\n jax.jit(jax.vmap(f))(jnp.arange(3.))\n jax.jit(jax.vmap(jax.grad(f)))(jnp.arange(3.))\n jax.jit(jax.grad(lambda x: jax.vmap(f)(x).sum()))(jnp.arange(3.))\n jax.grad(lambda x: jax.vmap(f)(x).sum())(jnp.arange(3.))\n jax.jvp(jax.jit(jax.vmap(f)), (jnp.arange(3.),), (jnp.ones(3),))\n\n def test_eval_shape(self):\n @jax.custom_jvp\n def expit(x):\n return 1 / (1 + lax.exp(-x))\n\n @expit.defjvp\n def _expit_jvp(primals, tangents):\n (x,), (t,) = primals, tangents\n ans = expit(x)\n t_out = t * ans * (1 - ans)\n return ans, t_out\n\n # don't crash\n api.eval_shape(expit, jnp.ones((2, 3)))\n api.eval_shape(api.grad(lambda x: expit(x).sum()), jnp.ones((2, 3)))\n\n def test_jaxpr_zeros(self):\n # from https://github.com/google/jax/issues/2657\n @api.custom_jvp\n def f(A, b):\n return A @ b\n\n def f_jvp(primals, tangents):\n A, b = primals\n dA, db = tangents\n z = f(A, b)\n dz = A @ db + dA @ b\n return z, dz\n\n f.defjvp(f_jvp)\n\n def experiment(theta):\n def step(q, _):\n z = f(jnp.eye(3), jnp.ones(3) * theta)\n q += z[0]\n return q, q\n\n q = 0.\n q, _ = lax.scan(step, q, None, 4)\n return q\n\n grad(experiment)(1.) # doesn't crash\n\n def test_linear_in_scan(self):\n @api.custom_jvp\n def f(x):\n return -x\n\n @f.defjvp\n def f_jvp(primals, tangents):\n x, = primals\n x_dot, = tangents\n return f(x), f(x_dot)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.grad(foo)(3.)\n expected = -1.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_custom_jvps_first_rule_is_none(self):\n # https://github.com/google/jax/issues/3389\n @api.custom_jvp\n def f(x, y):\n return x ** 2 * y\n\n f.defjvps(None, lambda x_dot, primal_out, x, y: 2 * x * y * x_dot)\n ans = grad(f, 1)(2., 3.) # doesn't crash\n expected = 12.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_concurrent_initial_style(self):\n # https://github.com/google/jax/issues/3843\n def unroll(param, sequence):\n def scan_f(prev_state, inputs):\n return prev_state, jax.nn.sigmoid(param * inputs)\n return jnp.sum(jax.lax.scan(scan_f, None, sequence)[1])\n\n def run():\n return jax.grad(unroll)(jnp.array(1.0), jnp.array([1.0]))\n\n expected = run()\n\n # we just don't want this to crash\n n_workers = 2\n with concurrent.futures.ThreadPoolExecutor(max_workers=n_workers) as e:\n futures = []\n for _ in range(n_workers):\n futures.append(e.submit(run))\n results = [f.result() for f in futures]\n for ans in results:\n self.assertAllClose(ans, expected)\n\n def test_nondiff_argnums_vmap_tracer(self):\n # https://github.com/google/jax/issues/3964\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n @partial(jax.custom_jvp, nondiff_argnums=(0, 2))\n def sample(shape, param, seed):\n return jax.random.uniform(key=seed, shape=shape, minval=param)\n\n @sample.defjvp\n def sample_jvp(shape, seed, primals, tangents):\n param, = primals\n dparam, = tangents\n dparam = jnp.broadcast_to(dparam, shape)\n samples = sample(shape, param, seed)\n return samples, samples * dparam # dummy jvp for proof of concept\n\n # check these don't crash\n jax.vmap(lambda seed: sample((2,3), 1., seed))(\n jax.random.split(jax.random.PRNGKey(1), 10))\n jax.jvp(lambda x: sample((2, 3), x, jax.random.PRNGKey(1)),\n (1.,), (1.,))\n\n def test_fun_with_nested_calls_2(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n def call(f, *args):\n f = api.custom_jvp(f)\n f.defjvp(lambda primals, tangents: (f(*primals), sum(tangents)))\n return f(*args)\n\n def fun_with_nested_calls_2(x):\n def bar(y):\n def baz(w):\n q = call(lambda x: y, x)\n q = q + call(lambda: y)\n q = q + call(lambda y: w + y, y)\n q = call(lambda w: call(jnp.sin, x) * y, 1.0) + q\n return q\n return api.jit(baz)(x)\n return call(bar, x)\n\n # test these don't crash\n self.assertAllClose(api.jit(fun_with_nested_calls_2)(3.),\n fun_with_nested_calls_2(3.))\n api.vmap(fun_with_nested_calls_2)(jnp.arange(3.))\n\n def test_closure_with_vmap(self):\n if not config.omnistaging_enabled:\n raise unittest.SkipTest(\"test only works with omnistaging\")\n\n # https://github.com/google/jax/issues/3822\n alpha = np.float32(2.)\n\n def sample(seed):\n @api.custom_jvp\n def f(alpha):\n return jax.random.gamma(seed, alpha, shape=[])\n\n @f.defjvp\n def f_jvp(primal, tangent):\n alpha = primal\n dalpha = tangent\n sample = f(alpha)\n partial_alpha = lax.random_gamma_grad(alpha, sample)\n return sample, partial_alpha * dalpha\n return f(alpha)\n\n api.vmap(sample)(jax.random.split(jax.random.PRNGKey(1), 3)) # don't crash\n\n def test_float0(self):\n @api.custom_jvp\n def f(x, y):\n return x, y\n def f_jvp(primals, _):\n # we need a defined (non-float0) tangent to trigger the rule\n return primals, (2., 1)\n f.defjvp(f_jvp)\n\n primals = (2., 3)\n tangents = (np.ones(()), np.zeros((), float0),)\n expected_tangents = (2., np.zeros((), float0))\n self.assertArraysEqual(api.jvp(f, primals, tangents),\n (primals, expected_tangents))\n\n def test_float0_initial_style(self):\n @api.custom_jvp\n def f(x, y):\n return x, y\n def f_jvp(primals, _):\n x, y = primals\n return (x, y), (2., 1)\n f.defjvp(f_jvp)\n\n def foo(x, y):\n out, _ = lax.scan(lambda c, _: (f(*c), None), (x, y), None, length=1)\n return out\n\n primals = (2., 3)\n tangents = (np.ones(()), np.zeros((), float0),)\n expected_tangents = (2., np.zeros((), float0))\n self.assertArraysEqual(api.jvp(foo, primals, tangents),\n (primals, expected_tangents))\n\n def test_remat(self):\n @api.custom_jvp\n def f(x):\n return jnp.sin(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * jnp.cos(x) * g\n f.defjvp(f_jvp)\n\n @api.remat\n def g(x):\n return f(f(x))\n\n ans = g(2.)\n expected = np.sin(np.sin(2.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(g)(2.)\n expected = 4. * api.grad(lambda x: jnp.sin(jnp.sin(x)))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_higher_order(self):\n @api.custom_jvp\n def f(x):\n return jnp.sin(x)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * jnp.cos(x) * g\n f.defjvp(f_jvp)\n\n def g(x):\n return f(f(x))\n\n ans = api.grad(api.grad(api.remat(g)))(2.)\n expected = api.grad(api.grad(g))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.remat(api.grad(g)))(2.)\n expected = api.grad(api.grad(g))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.grad(api.grad(api.remat(g))))(2.)\n expected = api.grad(api.grad(api.grad(g)))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_initial_style_vmap_2(self):\n # This is like test_initial_style_vmap except the primal function closes\n # over an array constant.\n y = jnp.array([1., 2., 3.])\n\n @api.custom_jvp\n def f(x):\n assert jnp.ndim(x) == 0\n return 3 * x * jnp.sum(y)\n def f_jvp(primals, tangents):\n x, = primals\n g, = tangents\n return f(x), 2 * g\n f.defjvp(f_jvp)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.grad(lambda x: api.vmap(foo)(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.vmap(api.jit(foo))(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.jit(api.vmap(foo))(x).sum())(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.jit(lambda x: api.vmap(foo)(x).sum()))(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.jit(api.grad(lambda x: api.vmap(foo)(x).sum()))(jnp.ones(3))\n expected = 2. * jnp.ones(3)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n\nclass CustomVJPTest(jtu.JaxTestCase):\n\n def test_basic(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n x = 3.\n self.assertAllClose(f(x), jnp.sin(x))\n self.assertAllClose(api.grad(f)(x), 2 * jnp.cos(x))\n self.assertAllClose(api.value_and_grad(f)(x),\n (jnp.sin(x), 2 * jnp.cos(x)))\n\n def test_invariance(self):\n @api.custom_vjp\n def f(x):\n return jnp.cos(2 * x) / 2.\n def f_fwd(x):\n return (f(x), x)\n def f_rev(x, g):\n return (g * 3,)\n f.defvjp(f_fwd, f_rev)\n def f2(x):\n y, _ = api.value_and_grad(f)(x)\n return y\n def f3(x):\n y, _ = api.value_and_grad(f2)(x)\n return y\n x = 1.\n self.assertAllClose(f(x), f2(x), check_dtypes=False)\n self.assertAllClose(f(x), f3(x), check_dtypes=False)\n self.assertAllClose(api.grad(f)(x), api.grad(f2)(x),\n check_dtypes=False)\n self.assertAllClose(api.grad(f)(x), api.grad(f3)(x),\n check_dtypes=False)\n\n def test_python_control_flow(self):\n @api.custom_vjp\n def f(x):\n if x > 0:\n return jnp.sin(x)\n else:\n return jnp.cos(x)\n def f_fwd(x):\n if x > 0:\n return f(x), x\n else:\n return f(x), x\n def f_rev(x, g):\n if x > 0:\n return (2 * g,)\n else:\n return (3 * g,)\n f.defvjp(f_fwd, f_rev)\n x = 2.\n self.assertAllClose(f(x), jnp.sin(x))\n self.assertAllClose(f(-x), jnp.cos(-x))\n self.assertAllClose(api.value_and_grad(f)(x), (jnp.sin(x), 2.),\n check_dtypes=False)\n self.assertAllClose(api.value_and_grad(f)(-x), (jnp.cos(-x), 3.),\n check_dtypes=False)\n\n def test_vmap(self):\n @api.custom_vjp\n def f(x):\n assert jnp.ndim(x) == 0\n return jnp.sin(x)\n def f_fwd(x):\n assert jnp.ndim(x) == 0\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n x = jnp.arange(3.)\n xx = jnp.arange(6.).reshape(2, 3)\n\n # vmap of f\n self.assertAllClose(api.vmap(f)(x), jnp.sin(x))\n self.assertAllClose(api.vmap(api.vmap(f))(xx), jnp.sin(xx))\n\n # vmap of grad of f\n self.assertAllClose(api.vmap(api.grad(f))(x), 2 * jnp.cos(x))\n self.assertAllClose(api.vmap(api.value_and_grad(f))(x),\n (jnp.sin(x), 2 * jnp.cos(x)))\n self.assertAllClose(api.vmap(api.vmap(api.grad(f)))(xx), 2 * jnp.cos(xx))\n self.assertAllClose(api.vmap(api.vmap(api.value_and_grad(f)))(xx),\n (jnp.sin(xx), 2 * jnp.cos(xx)))\n\n # grad of vmap of f\n self.assertAllClose(api.grad(lambda x: api.vmap(f)(x).sum())(x),\n 2 * jnp.cos(x))\n self.assertAllClose(api.grad(lambda x: api.vmap(api.vmap(f))(x).sum())(xx),\n 2 * jnp.cos(xx))\n\n # vmap of grad of vmap of f\n self.assertAllClose(api.vmap(api.grad(lambda x: api.vmap(f)(x).sum()))(xx),\n 2 * jnp.cos(xx))\n\n def test_jit(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n x = 3.\n\n # jit\n self.assertAllClose(api.jit(f)(x), jnp.sin(x))\n self.assertAllClose(api.jit(api.jit(f))(x), jnp.sin(x))\n\n # jit of grad\n self.assertAllClose(api.jit(api.grad(f))(x), 2 * jnp.cos(x),\n check_dtypes=False)\n\n # grad of jit\n self.assertAllClose(api.grad(api.jit(f))(x), 2 * jnp.cos(x),\n check_dtypes=False)\n\n def test_pytrees(self):\n @api.custom_vjp\n def f(x):\n return {'b': jnp.sin(x['a'])}\n def f_fwd(x):\n return f(x), {'r': jnp.cos(x['a'])}\n def f_bwd(res, g):\n cos_x = res['r']\n return ({'a': 2 * cos_x * g['b']},)\n f.defvjp(f_fwd, f_bwd)\n x = {'a': 3.}\n self.assertAllClose(f(x)['b'], jnp.sin(x['a']))\n self.assertAllClose(api.grad(lambda x: f(x)['b'])(x),\n {'a': 2 * jnp.cos(x['a'])})\n\n def test_jvp_error(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n self.assertRaisesRegex(\n TypeError,\n r\"can't apply forward-mode autodiff \\(jvp\\) to a custom_vjp function.\",\n lambda: api.jvp(f, (3.,), (1.,)))\n self.assertRaisesRegex(\n TypeError,\n r\"can't apply forward-mode autodiff \\(jvp\\) to a custom_vjp function.\",\n lambda: api.jvp(api.vmap(f), (jnp.arange(3.),), (jnp.ones(3),)))\n\n def test_kwargs(self):\n # from https://github.com/google/jax/issues/1938\n @api.custom_vjp\n def my_fun(x, y, c=1.):\n return c * (x + y)\n my_fun.defvjp(lambda x, y, c=1.: (my_fun(c, y, c), None),\n lambda _, g: (g, g, g))\n f = lambda x, y: jnp.square(my_fun(x, y, c=2.)).sum()\n f(10., 5.) # doesn't crash\n api.grad(f)(10., 5.) # doesn't crash\n\n def test_initial_style(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.grad(foo)(3.)\n expected = 2. * jnp.cos(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.grad(foo))(3.)\n expected = -2. * jnp.sin(3.)\n self.assertAllClose(ans, expected)\n\n def test_initial_style_vmap(self):\n @api.custom_vjp\n def f(x):\n assert jnp.ndim(x) == 0\n return 3 * x\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.vmap(foo)(jnp.arange(3.))\n expected = 3. * jnp.arange(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.vmap(foo)(x).sum())(jnp.arange(3.))\n expected = 2. * jnp.cos(jnp.arange(3.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_nondiff_arg(self):\n @partial(api.custom_vjp, nondiff_argnums=(0,))\n def app(f, x):\n return f(x)\n def app_fwd(f, x):\n return app(f, x), jnp.cos(x)\n def app_rev(f, cos_x, g):\n return (cos_x * g,)\n app.defvjp(app_fwd, app_rev)\n\n ans = app(lambda x: 2 * x, 1)\n expected = 2\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.value_and_grad(lambda x: app(lambda y: 2 * y, x))(1.)\n expected = (2., jnp.cos(1.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_nondiff_arg_tracer(self):\n # This test is now skipped because we decided not to support this behavior\n # anymore (namely, nondiff args can't be tracers), but\n # test_closed_over_tracer is a replacement test for analogous behavior that\n # we do support\n raise unittest.SkipTest(\"removed support for tracers in nondiff args\")\n\n @partial(api.custom_vjp, nondiff_argnums=(0,))\n def f(x, y):\n return x * y\n def f_fwd(x, y):\n return f(x, y), jnp.cos(y)\n def f_rev(x, cos_y, g):\n return (cos_y * g,)\n f.defvjp(f_fwd, f_rev)\n\n @jit\n def g(x, y):\n return f(x, y)\n\n ans = g(2, 3.)\n expected = 6.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(g, 1)(2., 3.)\n expected = jnp.cos(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_closed_over_tracer(self):\n # This test is similar to test_nondiff_arg_tracer except it uses lexical\n # closure rather than the nondiff_argnums mechanism. We decided to disallow\n # tracers in nondiff_argnums to greatly simplify bookkeeping while still\n # supporting the cases for which it is necessary.\n def outer(x):\n @api.custom_vjp\n def f(y):\n return x * y\n def f_fwd(y):\n return f(y), jnp.cos(y)\n def f_rev(cos_y, g):\n return (cos_y * g,)\n f.defvjp(f_fwd, f_rev)\n return f\n\n @jit\n def g(x, y):\n return outer(x)(y)\n\n ans = g(2, 3.)\n expected = 6.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(g, 1)(2., 3.)\n expected = jnp.cos(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_nondiff_arg_tracer_error(self):\n # This is similar to the old (now skipped) test_nondiff_arg_tracer, except\n # we're testing for the error message that that usage pattern now raises.\n\n @partial(api.custom_vjp, nondiff_argnums=(0,))\n def f(x, y):\n return x * y\n def f_fwd(x, y):\n return f(x, y), jnp.cos(y)\n def f_rev(x, cos_y, g):\n return (cos_y * g,)\n f.defvjp(f_fwd, f_rev)\n\n @jit\n def g(x, y):\n return f(x, y)\n\n with self.assertRaisesRegex(core.UnexpectedTracerError, \"custom_vjp\"):\n _ = g(2, 3.)\n with self.assertRaisesRegex(core.UnexpectedTracerError, \"custom_vjp\"):\n _ = api.grad(g, 1)(2., 3.)\n\n def test_vmap_axes(self):\n raise unittest.SkipTest(\"TODO\") # TODO(mattjj): write test\n\n def test_pmap(self):\n raise unittest.SkipTest(\"TODO\") # TODO(mattjj): write test\n\n def test_missing_vjp_rule_error(self):\n @api.custom_vjp\n def foo(x):\n return x ** 2\n\n self.assertRaisesRegex(\n AttributeError,\n r\"No VJP defined for custom_vjp function foo using defvjp.\",\n lambda: foo(2))\n self.assertRaisesRegex(\n AttributeError,\n r\"No VJP defined for custom_vjp function foo using defvjp.\",\n lambda: api.grad(foo)(2.))\n\n def test_vjp_rule_inconsistent_pytree_structures_error(self):\n @api.custom_vjp\n def f(x):\n return x\n\n def foo_fwd(x):\n return x, None\n\n def foo_bwd(_, g):\n return (g, g)\n\n f.defvjp(foo_fwd, foo_bwd)\n\n f(2) # doesn't crash\n self.assertRaisesRegex(\n TypeError,\n re.escape(\n \"Custom VJP rule must produce an output with the same container \"\n \"(pytree) structure as the args tuple of the primal function, \"\n \"and in particular must produce a tuple of length equal to the \"\n \"number of arguments to the primal function, but got VJP output \"\n \"structure {} for primal input structure {}.\".format(\n tree_util.tree_structure((1, 1)),\n tree_util.tree_structure((1,)))\n ),\n lambda: api.grad(f)(2.))\n\n def test_issue2511(self):\n arr = jnp.ones((5, 2, 2))\n foo = lambda x: api.vmap(jnp.linalg.det, (0,))(x)\n api.jit(foo)(arr) # doesn't crash\n\n def test_lowering_out_of_traces(self):\n # https://github.com/google/jax/issues/2578\n\n class F(collections.namedtuple(\"F\", [\"a\"])):\n def __call__(self, x):\n return jax.nn.relu(self.a) * x\n\n @jax.jit\n def g(f, x):\n return f(x)\n\n jax.grad(g, argnums=(1,))(F(2.0), 0.) # doesn't crash\n\n def test_nondiff_argnums_stop_gradient(self):\n # This test is now skipped because we decided not to support this behavior\n # anymore (namely, nondiff args can't be tracers), but test_clip_gradient is\n # a replacement showing behavior we do support.\n raise unittest.SkipTest(\"removed support for tracers in nondiff args\")\n\n # https://github.com/google/jax/issues/2784\n @partial(api.custom_vjp, nondiff_argnums=(0, 1))\n def _clip_gradient(lo, hi, x):\n return x # identity function\n\n def clip_gradient_fwd(lo, hi, x):\n # return x, None\n return x, (hi, )\n\n def clip_gradient_bwd(lo, hi, _, g):\n return (jnp.clip(g, lo, hi),)\n\n _clip_gradient.defvjp(clip_gradient_fwd, clip_gradient_bwd)\n\n def clip_gradient(x):\n lo = -1\n hi = x + 1 # causes things to break\n return _clip_gradient(lo, hi, x)\n\n jax.grad(clip_gradient)(1.) # doesn't crash\n\n def test_clip_gradient(self):\n # https://github.com/google/jax/issues/2784\n @api.custom_vjp\n def _clip_gradient(lo, hi, x):\n return x # identity function when not differentiating\n\n def clip_gradient_fwd(lo, hi, x):\n return x, (lo, hi,)\n\n def clip_gradient_bwd(res, g):\n lo, hi = res\n return (None, None, jnp.clip(g, lo, hi),)\n\n _clip_gradient.defvjp(clip_gradient_fwd, clip_gradient_bwd)\n\n def clip_gradient(x):\n lo = -0.1\n hi = x + 0.1\n return _clip_gradient(lo, hi, x)\n\n g = jax.grad(clip_gradient)(0.1) # doesn't crash\n self.assertAllClose(g, jnp.array(0.2))\n\n def test_nestable_vjp(self):\n # Verify that https://github.com/google/jax/issues/3667 is resolved.\n def f(x):\n return x ** 2\n\n @api.custom_vjp\n def g(x):\n return f(x)\n\n def g_fwd(x):\n y, f_vjp = api.vjp(f, x)\n return y, f_vjp\n\n def g_bwd(f_vjp, y_bar):\n return f_vjp(y_bar)\n\n g.defvjp(g_fwd, g_bwd)\n\n # Check that VJP can be nested in simple situations. For this to pass,\n # vjp has to return a PyTree.\n _, g_vjp = api.vjp(g, 1.0)\n y, = g_vjp(1.0)\n self.assertAllClose(y, jnp.array(2.0))\n\n # Check that VJP can be nested in complex situations. For this to pass,\n # vjp can't treat the closed-over tracer x as a static argument.\n @jit\n def z(x):\n _, g_vjp = api.vjp(g, x)\n return g_vjp\n y, = z(1.0)(3.0)\n self.assertAllClose(y, jnp.array(6.0))\n\n def test_initial_style_vmap_2(self):\n # https://github.com/google/jax/issues/4173\n x = jnp.ones((10, 3))\n\n # Create the custom function\n @api.custom_vjp\n def custom_fun(x):\n return x.sum()\n\n def forward(x):\n return x.sum(), (jnp.ones_like(x),)\n\n def backward(res, g):\n return g * res[0],\n\n custom_fun.defvjp(forward, backward)\n\n def train_fun(x):\n\n def summed_fun(x):\n return api.vmap(custom_fun)(x).sum()\n\n return api.grad(summed_fun)(x)\n\n def scan_body(carry, inputs):\n x = carry\n return carry, train_fun(x)\n\n scan_range = jnp.arange(4)\n lax.scan(scan_body, x, scan_range) # don't crash\n\n def test_initial_style_vmap_3(self):\n # This is like test_initial_style_vmap except the primal function closes\n # over an array constant.\n y = jnp.array([1., 2., 3.])\n\n @api.custom_vjp\n def f(x):\n assert jnp.ndim(x) == 0\n return 3 * x * jnp.sum(y)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n def foo(x):\n out, _ = lax.scan(lambda c, _: (f(c), None), x, None, length=1)\n return out\n\n ans = api.vmap(foo)(jnp.arange(3.))\n expected = 3. * jnp.arange(3.) * 6\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(lambda x: api.vmap(foo)(x).sum())(jnp.arange(3.))\n expected = 2. * jnp.cos(jnp.arange(3.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_bwd_closes_over_tracer(self):\n def f(y):\n @jax.custom_vjp\n def f(x):\n return 2. * jnp.sin(x)\n\n def fwd(x):\n return f(x), ()\n\n def bwd(_, g):\n return (2. * jnp.cos(y) * g,) # capture!\n\n f.defvjp(fwd, bwd)\n\n return jax.grad(f)(1.)\n\n ans = jax.jit(f)(2.)\n self.assertAllClose(ans, 2. * jnp.cos(2.))\n\n ans = jax.vmap(f)(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.jit(jax.vmap(f))(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.vmap(jax.jit(f))(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.grad(f)(4.)\n self.assertAllClose(ans, -2. * jnp.sin(4.))\n\n def test_fwd_closes_over_tracer(self):\n def f(y):\n @jax.custom_vjp\n def f(x):\n return 2. * jnp.sin(x)\n\n def fwd(x):\n return f(x), y\n\n def bwd(y, g):\n return (2. * jnp.cos(y) * g,) # capture!\n\n f.defvjp(fwd, bwd)\n\n return jax.grad(f)(1.)\n\n ans = jax.jit(f)(2.)\n self.assertAllClose(ans, 2. * jnp.cos(2.))\n\n ans = jax.vmap(f)(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.jit(jax.vmap(f))(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.vmap(jax.jit(f))(jnp.arange(3.))\n self.assertAllClose(ans, 2. * jnp.cos(jnp.arange(3.)))\n\n ans = jax.grad(f)(4.)\n self.assertAllClose(ans, -2. * jnp.sin(4.))\n\n def test_float0(self):\n @api.custom_vjp\n def f(x, _):\n return x\n def f_fwd(x, _):\n # we need a defined (non-float0) tangent to trigger the rule\n return x, (2., 1)\n def f_rev(*_):\n return (2., 1)\n f.defvjp(f_fwd, f_rev)\n\n x = 2.\n y = 3\n self.assertEqual(api.grad(f, allow_int=True, argnums=(0, 1))(x, y),\n (2., np.zeros(shape=(), dtype=float0)))\n\n def test_float0_initial_style(self):\n @api.custom_vjp\n def f(x):\n return x\n def f_fwd(x):\n return x, (2., x)\n def f_rev(*_):\n return ((2., 1),)\n f.defvjp(f_fwd, f_rev)\n\n def foo(x, y):\n out, _ = lax.scan(lambda c, _: (f(c), None), (x, y), None, length=1)\n return out[0]\n\n x = 2.\n y = 3\n self.assertEqual(api.grad(foo, allow_int=True, argnums=(0, 1))(x, y),\n (2., np.zeros(shape=(), dtype=float0)))\n\n def test_remat(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n @api.remat\n def g(x):\n return f(f(x))\n\n ans = g(2.)\n expected = np.sin(np.sin(2.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(g)(2.)\n expected = 4. * api.grad(lambda x: jnp.sin(jnp.sin(x)))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_remat_higher_order(self):\n @api.custom_vjp\n def f(x):\n return jnp.sin(x)\n def f_fwd(x):\n return f(x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (2 * cos_x * g,)\n f.defvjp(f_fwd, f_rev)\n\n def g(x):\n return f(f(x))\n\n ans = api.grad(api.grad(api.remat(g)))(2.)\n expected = api.grad(api.grad(g))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.remat(api.grad(g)))(2.)\n expected = api.grad(api.grad(g))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = api.grad(api.grad(api.grad(api.remat(g))))(2.)\n expected = api.grad(api.grad(api.grad(g)))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_bwd_nones(self):\n @api.custom_vjp\n def f(x, y):\n return x * jnp.sin(y)\n def f_fwd(x, y):\n return f(x, y), jnp.cos(y)\n def f_rev(cos, g):\n return (None, 2 * cos * g)\n f.defvjp(f_fwd, f_rev)\n\n ans = api.grad(lambda x: f(x, x))(3.)\n expected = 2 * jnp.cos(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_bwd_nones_vmap(self):\n @api.custom_vjp\n def f(x, y):\n return x * jnp.sin(y)\n def f_fwd(x, y):\n return f(x, y), jnp.cos(y)\n def f_rev(cos, g):\n return (None, 2 * cos * g)\n f.defvjp(f_fwd, f_rev)\n\n ans = api.grad(lambda x: api.vmap(f)(x, x).sum())(jnp.arange(3.))\n expected = 2 * jnp.cos(jnp.arange(3.))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_bwd_nones_pytree(self):\n @api.custom_vjp\n def f(xs, y):\n x1, x2 = xs\n return x1 * x2 * jnp.sin(y)\n def f_fwd(xs, y):\n return f(xs, y), jnp.cos(y)\n def f_rev(cos, g):\n return (None, 2 * cos * g)\n f.defvjp(f_fwd, f_rev)\n\n ans = api.grad(lambda x: f((x, x), x))(3.)\n expected = 2 * jnp.cos(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_custom_vjp_closure_4521(self):\n # https://github.com/google/jax/issues/4521\n @api.custom_vjp\n def g(x, y):\n return None\n def g_fwd(x, y):\n return None, y\n def g_bwd(residuals, z_bar):\n assert False\n\n g.defvjp(g_fwd, g_bwd)\n\n def f(xs, y):\n v_g = api.vmap(g, in_axes=(0, None), out_axes=None)\n v_g(xs, y)\n\n def scan_body(xs, _):\n y = jnp.zeros(1)\n _, vjp_f = api.vjp(f, xs, y)\n vjp_f(None)\n return xs, None\n\n lax.scan(scan_body, jnp.ones(5), None, 100) # doesn't crash\n\n def test_float0_bwd_none(self):\n @api.custom_vjp\n def f(i, x):\n return jnp.sin(x)\n def f_fwd(i, x):\n return f(i, x), jnp.cos(x)\n def f_rev(cos_x, g):\n return (None, 2 * cos_x * g)\n f.defvjp(f_fwd, f_rev)\n\n ans = api.grad(f, 1)(jnp.array([1, 2]), 3.) # doesn't crash\n expected = 2 * jnp.cos(3.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_custom_gradient(self):\n @api.custom_gradient\n def f(x):\n return x ** 2, lambda g: (g * x,)\n\n self.assertAllClose(f(3.), 9., check_dtypes=False)\n self.assertAllClose(api.grad(f)(3.), 3., check_dtypes=False)\n self.assertAllClose(api.grad(api.grad(f))(3.), 1., check_dtypes=False)\n\n def test_custom_gradient_2(self):\n @api.custom_gradient\n def f(x, y):\n return x * y, lambda g: (y, x)\n\n self.assertAllClose(f(3., 4.), 12., check_dtypes=False)\n self.assertAllClose(api.grad(f, argnums=(0, 1))(3., 4.), (4., 3.),\n check_dtypes=False)\n\n def test_custom_gradient_3(self):\n @api.custom_gradient\n def f(x):\n vjp = lambda g: (jnp.cos(x) * jnp.array([3., 4., 5.]),)\n return jnp.sum(jnp.sin(x)), vjp\n\n self.assertAllClose(f(jnp.arange(3)), jnp.sum(jnp.sin(jnp.arange(3.))),\n check_dtypes=False)\n self.assertAllClose(\n api.grad(f)(jnp.arange(3.)),\n api.grad(lambda x: jnp.sum(jnp.sin(x)))(jnp.arange(3.)) * jnp.array([3., 4., 5.]),\n check_dtypes=False)\n\n\nclass InvertibleADTest(jtu.JaxTestCase):\n\n def test_invertible_basic(self):\n def f(x):\n return (jnp.exp(x) * 4) * x\n\n finv = jax.invertible(f)\n\n x = jnp.ones((5,))\n\n if config.omnistaging_enabled:\n expected = \"\"\"\n { lambda ; a b.\n let c = exp a\n d = mul c 4.0\n e = mul d a\n f = mul b a\n g = div e a\n h = mul b g\n i = div g 4.0\n j = mul f 4.0\n _ = log i\n k = mul j i\n l = add_any h k\n in (l,) }\n \"\"\"\n else:\n expected = \"\"\"\n { lambda ; a b.\n let c = exp a\n d = mul c 4.0\n e = mul d a\n f = div e a\n g = mul b f\n h = mul b a\n i = mul h 4.0\n j = div f 4.0\n k = mul i j\n l = add_any g k\n in (l,) }\n \"\"\"\n\n jaxpr = jax.make_jaxpr(lambda p, ct: jax.vjp(finv, p)[1](ct))(x, x)\n self.assertMultiLineStrippedEqual(expected, str(jaxpr))\n\n self.assertAllClose(jax.value_and_grad(lambda x: np.sum(f(x)))(x),\n jax.value_and_grad(lambda x: np.sum(finv(x)))(x),\n check_dtypes=True)\n\n def test_invertible_blocks(self):\n # NB: This is the reversible ResNet block\n def mk_reversible_block(f, g):\n @jax.custom_ivjp\n def rev_block(x1, x2):\n y1 = f(x2) + x1\n y2 = g(y1) + x2\n return y1, y2\n\n @rev_block.defivjp\n def rev_block_ivjp(xs, ys, dys):\n (y1, y2) = ys\n (dy1, dy2) = dys\n\n dgo, dx2 = dy2, dy2\n go, gvjp = jax.vjp(g, y1)\n dy1 += gvjp(dgo)[0]\n del gvjp\n x2 = y2 - go\n\n dfo, dx1 = dy1, dy1\n fo, fvjp = jax.vjp(f, x2)\n dx2 += fvjp(dfo)[0]\n del fvjp\n x1 = y1 - fo\n\n return (x1, x2), (dx1, dx2)\n\n return rev_block\n\n rev_block = mk_reversible_block(jnp.sin, jnp.cos)\n\n def g(x1, x2):\n for i in range(2):\n x1, x2 = rev_block(x1, x2)\n return x1, x2\n\n def reduce(f, x1, x2):\n y1, y2 = f(x1, x2)\n return np.sum(y1) + np.sum(y2)\n\n x = np.ones((1,))\n # FIXME: This breaks when argnums is left as default (i.e. 0), because JVP prunes\n # zero tangents from call primitives.\n self.assertAllClose(jax.value_and_grad(partial(reduce, jax.invertible(g)), argnums=(0, 1))(x, x + 2),\n jax.value_and_grad(partial(reduce, g), argnums=(0, 1))(x, x + 2),\n check_dtypes=True)\n\n def test_invertible_partial_diff(self):\n # Check that we don't have to differentiate with respect to inputs\n # of the invertible function.\n def f(x, y):\n return (jnp.exp(x) * 4) * x, y + 4\n\n finv = jax.invertible(f)\n o = np.ones((5,))\n self.assertAllClose(jax.value_and_grad(lambda x: np.sum(f(x, o)[0]))(o),\n jax.value_and_grad(lambda x: np.sum(finv(x, o)[0]))(o),\n check_dtypes=True)\n\n def test_invertible_pytree(self):\n def f(x, y):\n return jnp.exp(x[0]) * x[1] + y\n\n finv = jax.invertible(f)\n o = np.ones((5,))\n self.assertAllClose(jax.value_and_grad(lambda x: np.sum(f((x, x), x)[0]))(o),\n jax.value_and_grad(lambda x: np.sum(finv((x, x), x)[0]))(o),\n check_dtypes=True)\n\n\nclass DeprecatedCustomTransformsTest(jtu.JaxTestCase):\n\n def test_defvjp_all(self):\n foo_p = Primitive('foo')\n def foo(x): return 2. * foo_p.bind(x)\n\n ad.defvjp_all(foo_p, lambda x: (x**2, lambda g: (4 * g * jnp.sin(x),)))\n val_ans, grad_ans = api.value_and_grad(foo)(3.)\n self.assertAllClose(val_ans, 2 * 3.**2, check_dtypes=False)\n self.assertAllClose(grad_ans, 4 * 2 * np.sin(3.), check_dtypes=False)\n\n def test_defvjp_all_const(self):\n foo_p = Primitive('foo')\n def foo(x): return foo_p.bind(x)\n\n ad.defvjp_all(foo_p, lambda x: (x**2, lambda g: (12.,)))\n val_ans, grad_ans = api.value_and_grad(foo)(3.)\n self.assertAllClose(val_ans, 9., check_dtypes=False)\n self.assertAllClose(grad_ans, 12.)\n\n def test_defvjp_all_higher_order_revmode(self):\n foo_p = Primitive('foo')\n def foo(x): return 2. * foo_p.bind(x)\n\n ad.defvjp_all(foo_p, lambda x: (x**2, lambda g: (g * x ** 2,)))\n ans = api.grad(api.grad(foo))(3.)\n self.assertAllClose(ans, 2 * 2 * 3., check_dtypes=False)\n\n def test_defvjp_all_multiple_arguments(self):\n # also tests passing in symbolic zero tangents b/c we differentiate wrt only\n # the first argument in one case\n\n foo_p = Primitive('foo')\n def foo(x, y): return foo_p.bind(x, y)\n\n def vjpfun(x, y):\n out = x**2 + y**3\n vjp = lambda g: (g + x + y, g * x * 9.)\n return out, vjp\n\n ad.defvjp_all(foo_p, vjpfun)\n val_ans, grad_ans = api.value_and_grad(foo)(3., 4.)\n self.assertAllClose(val_ans, 3.**2 + 4.**3, check_dtypes=False)\n self.assertAllClose(grad_ans, 1. + 3. + 4., check_dtypes=False)\n\n ans = api.grad(foo, (0, 1))(3., 4.)\n self.assertAllClose(ans, (1. + 3. + 4., 1. * 3. * 9.), check_dtypes=False)\n\n def test_defvjp_all_custom_transforms(self):\n @api.custom_transforms\n def foo(x):\n return jnp.sin(x)\n\n api.defvjp_all(foo, lambda x: (jnp.sin(x), lambda g: (g * x,)))\n val_ans, grad_ans = api.value_and_grad(foo)(3.)\n self.assertAllClose(val_ans, np.sin(3.), check_dtypes=False)\n self.assertAllClose(grad_ans, 3., check_dtypes=False)\n\n # TODO(mattjj): add defvjp_all test with pytree arguments\n\n def test_defvjp(self):\n @api.custom_transforms\n def foo(x, y):\n return jnp.sin(x * y)\n\n api.defvjp(foo, None, lambda g, _, x, y: g * x * y)\n val_ans, grad_ans = api.value_and_grad(foo)(3., 4.)\n self.assertAllClose(val_ans, np.sin(3. * 4.), check_dtypes=False)\n self.assertAllClose(grad_ans, 0., check_dtypes=False)\n\n ans_0, ans_1 = api.grad(foo, (0, 1))(3., 4.)\n self.assertAllClose(ans_0, 0., check_dtypes=False)\n self.assertAllClose(ans_1, 3. * 4., check_dtypes=False)\n\n def test_defvjp_higher_order(self):\n @api.custom_transforms\n def foo(x):\n return jnp.sin(2. * x)\n\n api.defvjp(foo, lambda g, _, x: g * jnp.cos(x))\n ans = api.grad(api.grad(foo))(2.)\n expected = api.grad(api.grad(jnp.sin))(2.)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_defvjp_use_ans(self):\n @api.custom_transforms\n def foo(x, y):\n return jnp.sin(x * y)\n\n api.defvjp(foo, None, lambda g, ans, x, y: g * x * y + jnp.cos(ans))\n val_ans, grad_ans = api.value_and_grad(foo, 1)(3., 4.)\n self.assertAllClose(val_ans, np.sin(3. * 4.), check_dtypes=False)\n self.assertAllClose(grad_ans, 3. * 4. + np.cos(np.sin(3. * 4)),\n check_dtypes=False)\n\n def test_custom_transforms_eval_with_pytrees(self):\n @api.custom_transforms\n def f(x):\n a, b = x[0], x[1]\n return {'hi': 2 * a, 'bye': 2 * b}\n\n ans = f((1, 2))\n self.assertEqual(ans, {'hi': 2 * 1, 'bye': 2 * 2})\n\n def test_custom_transforms_jit_with_pytrees(self):\n @api.custom_transforms\n def f(x):\n a, b = x[0], x[1]\n return {'hi': 2 * a, 'bye': 2 * b}\n\n ans = jit(f)((1, 2))\n self.assertEqual(ans, {'hi': 2 * 1, 'bye': 2 * 2})\n\n def test_custom_transforms_jit_with_pytrees_consts(self):\n # The purpose of this test is to exercise the custom_transforms default\n # translation rule in how it deals with constants that are too large to be\n # treated as literals (at the time of writing).\n z = np.arange(10.)\n\n @api.custom_transforms\n def f(x):\n a, b = x[0], x[1]\n return {'hi': 2 * a, 'bye': z * b}\n\n ans = jit(f)((1, 2))\n self.assertAllClose(ans, {'hi': 2 * 1, 'bye': z * 2}, check_dtypes=False)\n\n def test_custom_transforms_jvp_with_pytrees(self):\n @api.custom_transforms\n def f(x):\n a, b = x[0], x[1]\n return {'hi': 2 * a, 'bye': 2 * b}\n\n ans, out_tangent = api.jvp(f, ((1., 2.),), ((3., 4.),))\n self.assertEqual(ans, {'hi': 2 * 1, 'bye': 2 * 2})\n self.assertEqual(out_tangent, {'hi': 2 * 3, 'bye': 2 * 4})\n\n def test_custom_transforms_vmap_with_pytrees(self):\n raise unittest.SkipTest(\"Test deprecated custom_transforms\")\n @api.custom_transforms\n def f(x):\n a, b = x[0], x[1]\n return {'hi': 2 * a, 'bye': 2 * b}\n\n ans = api.vmap(f)((np.arange(3), np.ones((3, 2))))\n expected = {'hi': 2 * np.arange(3), 'bye': 2 * np.ones((3, 2))}\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_custom_transforms_jvp_with_closure(self):\n def f(x):\n @api.custom_transforms\n def g(y):\n return x * y\n return g(x)\n\n ans = api.grad(f)(1.)\n expected = 2.\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def test_custom_vjp_zeros(self):\n @api.custom_transforms\n def f(x, y):\n return 2 * x, 3 * y\n\n def f_vjp(x, y):\n return (2 * x, 3 * y), lambda ts: (4 * ts[0], 5 * ts[1])\n\n api.defvjp_all(f, f_vjp, )\n api.grad(lambda x, y: f(x, y)[0])(1., 2.) # doesn't crash\n\n def test_custom_transforms_vjp_nones(self):\n core.skip_checks = True # Fails with checks\n # issue raised by jsnoek@ and jumper@\n @jax.custom_transforms\n def solve(a, b):\n return jnp.dot(jnp.linalg.inv(a), b)\n # print(solve(a, b))\n\n def solve_vjp(a, b):\n x = solve(a, b)\n def vjp(x_tangent):\n dx = jnp.dot(solve(a, x_tangent), x.T)\n out = (dx, b * 0.)\n return out\n return x, vjp\n jax.defvjp_all(solve, solve_vjp)\n gf = grad(lambda a,b: jnp.sum(solve(a, b)))\n\n n = 3\n a_in = jnp.linspace(0, 1, n)[:, None]\n a = jnp.dot(a_in, a_in.T) + jnp.eye(n) * 0.1\n real_x = np.random.RandomState(0).randn(n)\n b = jnp.dot(a + jnp.eye(a.shape[0]), real_x)\n print(gf(a, b)) # doesn't crash\n\n\nclass BufferDonationTest(jtu.JaxTestCase):\n\n @jtu.skip_on_devices(\"cpu\") # In/out aliasing not supported on CPU.\n def test_pmap_donate_argnums_invalidates_input(self):\n move = api.pmap(lambda x: x + x - x, donate_argnums=0)\n n = jax.local_device_count()\n x = api.pmap(lambda x: x)(jnp.ones([n]))\n y = move(x)\n self.assertDeleted(x)\n np.testing.assert_allclose(y, [1.] * n)\n\n def test_pmap_nested_donate_ignored(self):\n pmap_fun = jit(lambda x: api.pmap(lambda y: y ** 2, donate_argnums=0)(x))\n a = api.pmap(lambda x: x)(jnp.array([1]))\n\n # NOTE(mattjj): stopped raising error here and instead just ignored\n # with self.assertRaisesRegex(ValueError, \"nested.*not supported\"):\n # pmap_fun(a)\n\n pmap_fun(a) # doesn't crash\n\n assertDeleted = lambda self, x: self._assertDeleted(x, True)\n assertNotDeleted = lambda self, x: self._assertDeleted(x, False)\n\n def _assertDeleted(self, x, deleted):\n if hasattr(x, \"device_buffer\"):\n self.assertEqual(x.device_buffer.is_deleted(), deleted)\n else:\n for buffer in x.device_buffers:\n self.assertEqual(buffer.is_deleted(), deleted)\n\n\nclass NamedCallTest(jtu.JaxTestCase):\n\n def test_default_name(self):\n\n @api.named_call\n def my_test_function(x):\n return x**2\n\n @jax.jit\n def f(x):\n return my_test_function(x)\n\n c = jax.xla_computation(f)(2)\n self.assertIn(\"my_test_function\", c.as_hlo_text())\n\n def test_non_jaxtype_arg(self):\n # For the test to fail without the invalid JaxType filter we need to pass\n # in a valid JaxType that forces the invalid Jaxtype to be raised to an\n # abstract value.\n def f(not_a_jaxtype, a_jaxtype):\n # then Jax needs to try and evaluate the abstractified non-JaxType\n if not_a_jaxtype:\n return a_jaxtype\n return 0\n\n f = api.named_call(f, name=\"test\")\n out = jax.jit(f, static_argnums=(0,))(\"not a Jaxtype\", 1)\n self.assertEqual(out, 1)\n\n @parameterized.parameters(jax.jit, jax.grad, jax.vmap, jax.remat)\n def test_jax_transforms(self, transform):\n f = jnp.sum\n x = jnp.array([1.])\n\n unnamed_out = transform(f)(x)\n named_out = transform(api.named_call(f, name=\"test\"))(x)\n\n self.assertEqual(unnamed_out, named_out)\n\n def test_static_argnums(self):\n f = api.named_call(lambda x, y: y if x else None, name=\"test\")\n f = jax.jit(f, static_argnums=(0,))\n out = f(True, 5)\n self.assertEqual(out, 5)\n\n def test_partial_eval(self):\n f = api.named_call(lambda x, y: y if x else None, name=\"test\")\n f = jax.jit(functools.partial(f, True))\n out = f(5)\n self.assertEqual(out, 5)\n\n\nif __name__ == '__main__':\n absltest.main(testLoader=jtu.JaxTestLoader())\n" ]
[ [ "numpy.asarray", "numpy.all", "numpy.random.randn", "numpy.tri", "numpy.exp", "numpy.arange", "numpy.eye", "numpy.float16", "numpy.sin", "numpy.float32", "numpy.zeros", "numpy.random.rand", "numpy.testing.assert_allclose", "numpy.array", "numpy.random.RandomState", "numpy.sum", "numpy.int32", "numpy.cos", "numpy.ones", "numpy.shape" ] ]
tomography/scanscripts
[ "f7486fe1285da4684f3709661f112ccc15c2e4b8" ]
[ "tests/test_scanlib.py" ]
[ "\"\"\"Unit test for the extra tooling in scanlib.\"\"\"\n\nimport logging\nlogging.basicConfig(level=logging.WARNING)\nimport warnings\nimport unittest\n\nimport numpy as np\n\nfrom scanlib.tools import energy_range, energy_range_from_points\nfrom scanlib.scan_variables import parse_list_variable\n\nlog = logging.getLogger(__name__)\n\n\nclass ToolsTestCase(unittest.TestCase):\n \n def test_energy_range_from_points(self):\n points = (8300, 8500, 8700)\n steps = (100, 50, )\n expected = np.array((8300, 8400, 8500, 8550, 8600, 8650, 8700))\n output = energy_range_from_points(energy_points=points,\n energy_steps=steps)\n np.testing.assert_array_equal(output, expected)\n # Check with mismatched arrays\n points = (8.3, 8.5, 8.7)\n steps = (0.1, 0.3, 0.1)\n with self.assertRaises(ValueError):\n energy_range_from_points(energy_points=points,\n energy_steps=steps)\n\n\nclass ScanVariableTestCase(unittest.TestCase):\n\n def test_parse_list_variable(self):\n # Test with a single value\n output = parse_list_variable('0.03')\n self.assertEqual(output, (0.03, ))\n # Test with multiple values\n output = parse_list_variable('0.03, 0.05')\n self.assertEqual(output, (0.03, 0.05))\n # Test with a non-string value\n output = parse_list_variable(0.03)\n self.assertEqual(output, (0.03, ))\n # Test with a non-string \n output = parse_list_variable([0.03, 0.05])\n self.assertEqual(output, (0.03, 0.05))\n" ]
[ [ "numpy.testing.assert_array_equal", "numpy.array" ] ]
openclimatefix/nowcasting_utils
[ "7a45e9d24ce29693d96fd9c75a34ca1d205b64bc" ]
[ "nowcasting_utils/models/losses/FocalLoss.py" ]
[ "\"\"\" Focal Loss - https://arxiv.org/abs/1708.02002 \"\"\"\nfrom typing import List, Optional, Union\n\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn as nn\nfrom torch.autograd import Variable\n\n\nclass FocalLoss(nn.Module):\n \"\"\"Focal Loss\"\"\"\n\n def __init__(\n self,\n gamma: Union[int, float, List] = 0,\n alpha: Optional[Union[int, float, List]] = None,\n size_average: bool = True,\n ):\n \"\"\"\n Focal loss is described in https://arxiv.org/abs/1708.02002\n\n Copied from: https://github.com/clcarwin/focal_loss_pytorch/blob/master/focalloss.py\n\n Courtesy of carwin, MIT License\n\n Args:\n alpha: (tensor, float, or list of floats) The scalar factor for this criterion\n gamma: (float,double) gamma > 0 reduces the relative loss for well-classified\n examples (p>0.5) putting more focus on hard misclassified example\n size_average: (bool, optional) By default, the losses are averaged over\n each loss element in the batch.\n \"\"\"\n super(FocalLoss, self).__init__()\n self.gamma = gamma\n self.alpha = alpha\n if isinstance(alpha, (float, int)):\n self.alpha = torch.Tensor([alpha, 1 - alpha])\n if isinstance(alpha, list):\n self.alpha = torch.Tensor(alpha)\n self.size_average = size_average\n\n def forward(self, x: torch.Tensor, target: torch.Tensor):\n \"\"\"\n Forward model\n\n Args:\n x: prediction\n target: truth\n\n Returns: loss value\n\n \"\"\"\n if x.dim() > 2:\n x = x.view(x.size(0), x.size(1), -1) # N,C,H,W => N,C,H*W\n x = x.transpose(1, 2) # N,C,H*W => N,H*W,C\n x = x.contiguous().view(-1, x.size(2)) # N,H*W,C => N*H*W,C\n target = target.view(-1, 1)\n\n logpt = F.log_softmax(x)\n logpt = logpt.gather(1, target)\n logpt = logpt.view(-1)\n pt = Variable(logpt.data.exp())\n\n if self.alpha is not None:\n if self.alpha.type() != x.data.type():\n self.alpha = self.alpha.data.type_as(x)\n at = self.alpha.gather(0, target.data.view(-1))\n logpt = logpt * Variable(at)\n\n loss = -1 * (1 - pt) ** self.gamma * logpt\n if self.size_average:\n return loss.mean()\n else:\n return loss.sum()\n" ]
[ [ "torch.Tensor", "torch.nn.functional.log_softmax", "torch.autograd.Variable" ] ]
cambel/ur3
[ "e6866e951dbae1257e56b34f739abc1a839c3685" ]
[ "ur_control/src/ur_control/utils.py" ]
[ "# ROS utilities used by the CRI group\n#! /usr/bin/env python\nimport os\nimport sys\nimport copy\nimport time\nimport numpy as np\nimport rospy\nimport rospkg\nimport sys\nimport inspect\nfrom ur_control import transformations, spalg\nfrom sensor_msgs.msg import JointState\nfrom pyquaternion import Quaternion\n\ndef load_urdf_string(package, filename):\n rospack = rospkg.RosPack()\n package_dir = rospack.get_path(package)\n urdf_file = package_dir + '/urdf/' + filename + '.urdf'\n urdf = None\n with open(urdf_file) as f:\n urdf = f.read()\n return urdf\n\nclass PDRotation:\n def __init__(self, kp, kd=None):\n self.kp = np.array(kp)\n self.kd = np.array(kd)\n self.reset()\n\n def reset(self):\n self.last_time = rospy.get_rostime()\n self.last_error = Quaternion()\n\n def set_gains(self, kp=None, kd=None):\n if kp is not None:\n self.kp = np.array(kp)\n if kd is not None:\n self.kd = np.array(kd)\n\n def update(self, quaternion_error, dt=None):\n now = rospy.get_rostime()\n if dt is None:\n dt = now - self.last_time\n\n k_prime = 2 * quaternion_error.scalar*np.identity(3)-spalg.skew(quaternion_error.vector)\n p_term = np.dot(self.kp, k_prime)\n\n # delta_error = quaternion_error - self.last_error\n w = transformations.angular_velocity_from_quaternions(quaternion_error, self.last_error, dt)\n d_term = self.kd * w\n\n output = p_term + d_term\n # Save last values\n self.last_error = quaternion_error\n self.last_time = now\n return output\n\nclass PID:\n def __init__(self, Kp, Ki=None, Kd=None, dynamic_pid=False, max_gain_multiplier=200.0):\n # Proportional gain\n self.Kp = np.array(Kp)\n self.Ki = np.zeros_like(Kp)\n self.Kd = np.zeros_like(Kp)\n # Integral gain\n if Ki is not None:\n self.Ki = np.array(Ki)\n # Derivative gain\n if Kd is not None:\n self.Kd = np.array(Kd)\n self.set_windup(np.ones_like(self.Kp))\n # Reset\n self.reset()\n self.dynamic_pid = dynamic_pid\n self.max_gain_multiplier = max_gain_multiplier\n\n def reset(self):\n self.last_time = rospy.get_rostime()\n self.last_error = np.zeros_like(self.Kp)\n self.integral = np.zeros_like(self.Kp)\n\n def set_gains(self, Kp=None, Ki=None, Kd=None):\n if Kp is not None:\n self.Kp = np.array(Kp)\n if Ki is not None:\n self.Ki = np.array(Ki)\n if Kd is not None:\n self.Kd = np.array(Kd)\n\n def set_windup(self, windup):\n self.i_min = -np.array(windup)\n self.i_max = np.array(windup)\n\n def update(self, error, dt=None):\n # CAUTION: naive scaling of the Kp parameter based on the error\n # The main idea, the smaller the error the higher the gain\n if self.dynamic_pid:\n kp = np.abs([self.Kp[i]/error[i] if error[i] != 0.0 else self.Kp[i] for i in range(6)])\n kp = np.clip(kp, self.Kp, self.Kp*self.max_gain_multiplier)\n kd = np.abs([self.Kd[i]*error[i] if error[i] != 0.0 else self.Kd[i] for i in range(6)])\n kd = np.clip(kd, self.Kd/self.max_gain_multiplier, self.Kd)\n ki = self.Ki\n else:\n kp = self.Kp\n kd = self.Kd\n ki = self.Ki\n\n now = rospy.get_rostime()\n if dt is None:\n dt = now - self.last_time\n delta_error = error - self.last_error\n # Compute terms\n self.integral += error * dt\n p_term = kp * error\n i_term = ki * self.integral\n i_term = np.maximum(self.i_min, np.minimum(i_term, self.i_max))\n \n # First delta error is huge since it was initialized at zero first, avoid considering\n if not np.allclose(self.last_error, np.zeros_like(self.last_error)):\n d_term = kd * delta_error / dt\n else:\n d_term = kd * np.zeros_like(delta_error) / dt\n\n output = p_term + i_term + d_term\n # Save last values\n self.last_error = np.array(error)\n self.last_time = now\n return output\n\n\nclass TextColors:\n \"\"\"\n The C{TextColors} class is used as alternative to the C{rospy} logger. It's useful to\n print messages when C{roscore} is not running.\n \"\"\"\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n log_level = rospy.INFO\n\n def disable(self):\n \"\"\"\n Resets the coloring.\n \"\"\"\n self.HEADER = ''\n self.OKBLUE = ''\n self.OKGREEN = ''\n self.WARNING = ''\n self.FAIL = ''\n self.ENDC = ''\n\n def blue(self, msg):\n \"\"\"\n Prints a B{blue} color message\n @type msg: string\n @param msg: the message to be printed.\n \"\"\"\n print((self.OKBLUE + msg + self.ENDC))\n\n def debug(self, msg):\n \"\"\"\n Prints a B{green} color message\n @type msg: string\n @param msg: the message to be printed.\n \"\"\"\n print((self.OKGREEN + msg + self.ENDC))\n\n def error(self, msg):\n \"\"\"\n Prints a B{red} color message\n @type msg: string\n @param msg: the message to be printed.\n \"\"\"\n print((self.FAIL + msg + self.ENDC))\n\n def ok(self, msg):\n \"\"\"\n Prints a B{green} color message\n @type msg: string\n @param msg: the message to be printed.\n \"\"\"\n print((self.OKGREEN + msg + self.ENDC))\n\n def warning(self, msg):\n \"\"\"\n Prints a B{yellow} color message\n @type msg: string\n @param msg: the message to be printed.\n \"\"\"\n print((self.WARNING + msg + self.ENDC))\n\n def logdebug(self, msg):\n \"\"\"\n Prints message with the word 'Debug' in green at the begging.\n Alternative to C{rospy.logdebug}.\n @type msg: string\n @param msg: the message to be printed.\n \"\"\"\n if self.log_level <= rospy.DEBUG:\n print((self.OKGREEN + 'Debug ' + self.ENDC + str(msg)))\n\n def loginfo(self, msg):\n \"\"\"\n Prints message with the word 'INFO' begging.\n Alternative to C{rospy.loginfo}.\n @type msg: string\n @param msg: the message to be printed.\n \"\"\"\n if self.log_level <= rospy.INFO:\n print(('INFO ' + str(msg)))\n\n def logwarn(self, msg):\n \"\"\"\n Prints message with the word 'Warning' in yellow at the begging.\n Alternative to C{rospy.logwarn}.\n @type msg: string\n @param msg: the message to be printed.\n \"\"\"\n if self.log_level <= rospy.WARN:\n print((self.WARNING + 'Warning ' + self.ENDC + str(msg)))\n\n def logerr(self, msg):\n \"\"\"\n Prints message with the word 'Error' in red at the begging.\n Alternative to C{rospy.logerr}.\n @type msg: string\n @param msg: the message to be printed.\n \"\"\"\n if self.log_level <= rospy.ERROR:\n print((self.FAIL + 'Error ' + self.ENDC + str(msg)))\n\n def logfatal(self, msg):\n \"\"\"\n Prints message with the word 'Fatal' in red at the begging.\n Alternative to C{rospy.logfatal}.\n @type msg: string\n @param msg: the message to be printed.\n \"\"\"\n if self.log_level <= rospy.FATAL:\n print((self.FAIL + 'Fatal ' + self.ENDC + str(msg)))\n\n def set_log_level(self, level):\n \"\"\"\n Sets the log level. Possible values are:\n - DEBUG: 1\n - INFO: 2\n - WARN: 4\n - ERROR: 8\n - FATAL: 16\n @type level: int\n @param level: the new log level\n \"\"\"\n self.log_level = level\n\n\n## Helper Functions ##\ndef assert_shape(variable, name, shape):\n \"\"\"\n Asserts the shape of an np.array\n @type variable: Object\n @param variable: variable to be asserted\n @type name: string\n @param name: variable name\n @type shape: tuple\n @param ttype: expected shape of the np.array\n \"\"\"\n assert variable.shape == shape, '%s must have a shape %r: %r' % (name, shape, variable.shape)\n\n\ndef assert_type(variable, name, ttype):\n \"\"\"\n Asserts the type of a variable with a given name\n @type variable: Object\n @param variable: variable to be asserted\n @type name: string\n @param name: variable name\n @type ttype: Type\n @param ttype: expected variable type\n \"\"\"\n assert type(variable) is ttype, '%s must be of type %r: %r' % (name, ttype, type(variable))\n\n\ndef db_error_msg(name, logger=TextColors()):\n \"\"\"\n Prints out an error message appending the given database name.\n @type name: string\n @param name: database name\n @type logger: Object\n @param logger: Logger instance. When used in ROS, the recommended C{logger=rospy}.\n \"\"\"\n msg = 'Database %s not found. Please generate it. [rosrun denso_openrave generate_databases.py]' % name\n logger.logerr(msg)\n\n\ndef clean_cos(value):\n \"\"\"\n Limits the a value between the range C{[-1, 1]}\n @type value: float\n @param value: The input value\n @rtype: float\n @return: The limited value in the range C{[-1, 1]}\n \"\"\"\n return min(1, max(value, -1))\n\n\ndef has_keys(data, keys):\n \"\"\"\n Checks whether a dictionary has all the given keys.\n @type data: dict\n @param data: Parameter name\n @type keys: list\n @param keys: list containing the expected keys to be found in the dict.\n @rtype: bool\n @return: True if all the keys are found in the dict, false otherwise.\n \"\"\"\n if not isinstance(data, dict):\n return False\n has_all = True\n for key in keys:\n if key not in data:\n has_all = False\n break\n return has_all\n\n\ndef raise_not_implemented():\n \"\"\"\n Raises a NotImplementedError exception\n \"\"\"\n raise NotImplementedError()\n\n\ndef read_key(echo=False):\n \"\"\"\n Reads a key from the keyboard\n @type echo: bool, optional\n @param echo: if set, will show the input key in the console.\n @rtype: str\n @return: The limited value in the range C{[-1, 1]}\n \"\"\"\n if not echo:\n os.system(\"stty -echo\")\n key = sys.stdin.read(1)\n if not echo:\n os.system(\"stty echo\")\n return key.lower()\n\n\ndef read_parameter(name, default):\n \"\"\"\n Get a parameter from the ROS parameter server. If it's not found, a\n warn is printed.\n @type name: string\n @param name: Parameter name\n @type default: Object\n @param default: Default value for the parameter. The type should be\n the same as the one expected for the parameter.\n @rtype: any\n @return: The resulting parameter\n \"\"\"\n if rospy.is_shutdown():\n logger = TextColors()\n logger.logwarn('roscore not found, parameter [%s] using default: %s' % (name, default))\n else:\n if not rospy.has_param(name):\n rospy.logwarn('Parameter [%s] not found, using default: %s' % (name, default))\n return rospy.get_param(name, default)\n return default\n\n\ndef read_parameter_err(name):\n \"\"\"\n Get a parameter from the ROS parameter server. If it's not found, a\n error is printed.\n @type name: string\n @param name: Parameter name\n @rtype: has_param, param\n @return: (has_param) True if succeeded, false otherwise. The\n parameter is None if C{has_param=False}.\n \"\"\"\n if rospy.is_shutdown():\n logger = TextColors()\n logger.logerr('roscore not found')\n has_param = False\n else:\n has_param = True\n if not rospy.has_param(name):\n rospy.logerr(\"Parameter [%s] not found\" % (name))\n has_param = False\n return has_param, rospy.get_param(name, None)\n\n\ndef read_parameter_fatal(name):\n \"\"\"\n Get a parameter from the ROS parameter server. If it's not found, an\n exception will be raised.\n @type name: string\n @param name: Parameter name\n @rtype: any\n @return: The resulting parameter\n \"\"\"\n if rospy.is_shutdown():\n logger = TextColors()\n logger.logfatal('roscore not found')\n raise Exception('Required parameter {0} not found'.format(name))\n else:\n if not rospy.has_param(name):\n rospy.logfatal(\"Parameter [%s] not found\" % (name))\n raise Exception('Required parameter {0} not found'.format(name))\n return rospy.get_param(name, None)\n\n\ndef solve_namespace(namespace=''):\n \"\"\"\n Appends neccessary slashes required for a proper ROS namespace.\n @type namespace: string\n @param namespace: namespace to be fixed.\n @rtype: string\n @return: Proper ROS namespace.\n \"\"\"\n if len(namespace) == 0:\n namespace = rospy.get_namespace()\n elif len(namespace) == 1:\n if namespace != '/':\n namespace = '/' + namespace + '/'\n else:\n if namespace[0] != '/':\n namespace = '/' + namespace\n if namespace[-1] != '/':\n namespace += '/'\n return namespace\n\n\ndef sorted_joint_state_msg(msg, joint_names):\n \"\"\"\n Returns a sorted C{sensor_msgs/JointState} for the given joint names\n @type msg: sensor_msgs/JointState\n @param msg: The input message\n @type joint_names: list\n @param joint_names: The sorted joint names\n @rtype: sensor_msgs/JointState\n @return: The C{JointState} message with the fields in the order given by joint names\n \"\"\"\n valid_names = set(joint_names).intersection(set(msg.name))\n valid_position = len(msg.name) == len(msg.position)\n valid_velocity = len(msg.name) == len(msg.velocity)\n valid_effort = len(msg.name) == len(msg.effort)\n num_joints = len(valid_names)\n retmsg = JointState()\n retmsg.header = copy.deepcopy(msg.header)\n for name in joint_names:\n if name not in valid_names:\n continue\n idx = msg.name.index(name)\n retmsg.name.append(name)\n if valid_position:\n retmsg.position.append(msg.position[idx])\n if valid_velocity:\n retmsg.velocity.append(msg.velocity[idx])\n if valid_effort:\n retmsg.effort.append(msg.effort[idx])\n return retmsg\n\n\ndef unique(data):\n \"\"\"\n Finds the unique elements of an array. B{row-wise} and\n returns the sorted unique elements of an array.\n @type data: np.array\n @param data: Input array.\n @rtype: np.array\n @return: The sorted unique array.\n \"\"\"\n order = np.lexsort(data.T)\n data = data[order]\n diff = np.diff(data, axis=0)\n ui = np.ones(len(data), 'bool')\n ui[1:] = (diff != 0).any(axis=1)\n return data[ui]\n\n\ndef wait_for(predicate, timeout=5.0):\n start_time = time.time()\n while not predicate():\n now = time.time()\n if (now - start_time) > timeout:\n return False\n time.sleep(0.001)\n return True\n" ]
[ [ "numpy.dot", "numpy.ones_like", "numpy.minimum", "numpy.clip", "numpy.lexsort", "numpy.diff", "numpy.zeros_like", "numpy.identity", "numpy.array" ] ]
Zhicheng-Liu/mykrobe
[ "9cfe80d9cb6424f3fbdef2434388a13bf9ee8edb" ]
[ "src/mykrobe/cmds/amr.py" ]
[ "from __future__ import print_function\n\nimport logging\nimport tempfile\n\nlogger = logging.getLogger(__name__)\n\nimport json\n\nimport numpy as np\nimport random\nimport sys\nimport time\nfrom mykrobe.mformat import json_to_csv\nfrom mykrobe.typing import CoverageParser\nfrom mykrobe.typing import Genotyper\nfrom mykrobe.typing.models.base import ProbeCoverage\nfrom mykrobe.typing.models.variant import VariantProbeCoverage\nfrom mykrobe.typing.typer.variant import VariantTyper\nfrom mykrobe.predict import BasePredictor\nfrom mykrobe.predict import MykrobePredictorSusceptibilityResult\nfrom mykrobe.metagenomics import AMRSpeciesPredictor\nfrom mykrobe.species_data import DataDir\nfrom mykrobe.utils import load_json\nfrom mykrobe.utils import fix_amino_acid_X_variants_keys\nfrom mykrobe.version import __version__ as predictor_version\nfrom mykrobe.version import __version__ as atlas_version\n\n\nrandom.seed(42)\n\n\nclass ConfThresholder:\n def __init__(\n self,\n error_rate,\n mean_depth,\n kmer_length,\n incorrect_kmer_to_pc_cov,\n iterations=10000,\n ):\n self.error_rate = error_rate\n self.mean_depth = mean_depth\n self.iterations = iterations\n self.incorrect_kmer_to_pc_cov = incorrect_kmer_to_pc_cov\n self.kmer_length = kmer_length\n\n # For now, store the coverage as well, in case we need to debug.\n # In future, could just store the confidences, as that's all we\n # need to decide on the cutoff\n self.log_conf_and_covg = []\n\n @classmethod\n def _simulate_percent_coverage(cls, kmers_to_sample, kmers_in_allele):\n \"\"\"Simulates sampling kmers, returning the percent coverage.\n This means the % of kmers that are found by the simulation\"\"\"\n found_kmers = set()\n\n for _ in range(kmers_to_sample):\n j = random.randint(1, kmers_in_allele)\n found_kmers.add(j)\n if len(found_kmers) == kmers_in_allele:\n return 100.0\n\n return 100 * len(found_kmers) / kmers_in_allele\n\n @classmethod\n def _get_incorrect_kmer_percent_cov(cls, k_count, incorrect_kmer_to_pc_cov):\n i = k_count\n while i >= 0:\n if i in incorrect_kmer_to_pc_cov:\n return incorrect_kmer_to_pc_cov[i]\n i -= 1\n\n return 0\n\n def _simulate_snps(self):\n correct_covg = np.random.poisson(lam=self.mean_depth, size=self.iterations)\n incorrect_covg = np.random.binomial(\n self.mean_depth, self.error_rate, size=self.iterations\n )\n probe_coverage_list = []\n vtyper = VariantTyper(\n [self.mean_depth], error_rate=self.error_rate, kmer_size=self.kmer_length\n )\n\n for i in range(self.iterations):\n if correct_covg[i] + incorrect_covg[i] == 0:\n continue\n\n min_depth = 1 # not used?\n # Check what allele_length means in depth_to_expected_kmer_coun()! Probably need to change next two lines...\n correct_k_count = (\n self.kmer_length * correct_covg[i]\n ) + 0.01 #  see KmerCountGenotypeModel.depth_to_expected_kmer_count()\n incorrect_k_count = (\n self.kmer_length * incorrect_covg[i]\n ) + 0.01 #  see KmerCountGenotypeModel.depth_to_expected_kmer_count()\n\n correct_percent_coverage = 100\n incorrect_percent_coverage = ConfThresholder._get_incorrect_kmer_percent_cov(\n int(incorrect_k_count), self.incorrect_kmer_to_pc_cov\n )\n correct_probe_coverage = ProbeCoverage(\n correct_percent_coverage,\n self.mean_depth,\n min_depth,\n correct_k_count,\n self.kmer_length,\n )\n incorrect_probe_coverage = ProbeCoverage(\n incorrect_percent_coverage,\n self.mean_depth,\n min_depth,\n incorrect_k_count,\n self.kmer_length,\n )\n vpc = VariantProbeCoverage(\n [correct_probe_coverage], [incorrect_probe_coverage]\n )\n call = vtyper.type(vpc)\n\n cov = np.log10(correct_covg[i] + incorrect_covg[i])\n conf = call[\"info\"][\"conf\"]\n self.log_conf_and_covg.append((conf, cov))\n\n self.log_conf_and_covg.sort(reverse=True)\n\n def get_conf_threshold(self, percent_to_keep=95):\n \"\"\"percent_to_keep determines the confidence cutoff in terms of\n simulatead confience scores. Should be in (0,100]. eg default of 95\n means that we choose a cutoff that would keep 95% of the data\"\"\"\n if len(self.log_conf_and_covg) == 0:\n self._simulate_snps()\n\n conf_cutoff_index = min(\n int(0.01 * percent_to_keep * len(self.log_conf_and_covg)),\n len(self.log_conf_and_covg) - 1,\n )\n return self.log_conf_and_covg[conf_cutoff_index][0]\n\n\ndef ref_data_from_args(args):\n if args.species == \"custom\":\n if args.custom_probe_set_path is None:\n raise ValueError(\n \"Must use --custom_probe_set_path option if the species is 'custom'\"\n )\n ref_data = {\n \"fasta_files\": [args.custom_probe_set_path],\n \"var_to_res_json\": args.custom_variant_to_resistance_json,\n \"hierarchy_json\": None,\n \"lineage_json\": args.custom_lineage_json,\n \"kmer\": args.kmer,\n \"version\": \"custom\",\n \"species_phylo_group\": None,\n }\n else:\n data_dir = DataDir(args.panels_dir)\n species_dir = data_dir.get_species_dir(args.species)\n if args.panel is not None:\n species_dir.set_panel(args.panel)\n ref_data = {\n \"fasta_files\": species_dir.fasta_files(),\n \"var_to_res_json\": species_dir.json_file(\"amr\"),\n \"hierarchy_json\": species_dir.json_file(\"hierarchy\"),\n \"lineage_json\": species_dir.json_file(\"lineage\"),\n \"kmer\": species_dir.kmer(),\n \"version\": species_dir.version(),\n \"species_phylo_group\": species_dir.species_phylo_group(),\n }\n\n if ref_data[\"lineage_json\"] is None:\n ref_data[\"lineage_dict\"] = None\n else:\n ref_data[\"lineage_dict\"] = load_json(ref_data[\"lineage_json\"])\n\n return ref_data\n\n\ndef detect_species_and_get_depths(cov_parser, hierarchy_json, wanted_phylo_group):\n depths = []\n if wanted_phylo_group is None:\n return {}, depths\n\n species_predictor = AMRSpeciesPredictor(\n phylo_group_covgs=cov_parser.covgs.get(\n \"complex\", cov_parser.covgs.get(\"phylo_group\", {})\n ),\n sub_complex_covgs=cov_parser.covgs.get(\"sub-complex\", {}),\n species_covgs=cov_parser.covgs[\"species\"],\n lineage_covgs=cov_parser.covgs.get(\"sub-species\", {}),\n hierarchy_json_file=hierarchy_json,\n )\n phylogenetics = species_predictor.run()\n\n if wanted_phylo_group in species_predictor.out_json[\"phylogenetics\"][\"phylo_group\"]:\n depths = [\n species_predictor.out_json[\"phylogenetics\"][\"phylo_group\"][\n wanted_phylo_group\n ][\"median_depth\"]\n ]\n return phylogenetics, depths\n\n\ndef write_outputs(args, base_json):\n outputs = {}\n\n if args.output_format in [\"csv\", \"json_and_csv\"]:\n outputs[\"csv\"] = json_to_csv(base_json)\n if args.output_format in [\"json\", \"json_and_csv\"]:\n # Verbose json output requires --report_all_calls\n if not args.report_all_calls:\n del base_json[args.sample][\"variant_calls\"]\n del base_json[args.sample][\"sequence_calls\"]\n del base_json[args.sample][\"lineage_calls\"]\n outputs[\"json\"] = json.dumps(base_json, indent=4)\n\n if len(outputs) == 0:\n raise ValueError(\n (\n f\"Output format must be one of: csv,json,json_and_csv. Got \"\n f\"'{args.output_format}'\"\n )\n )\n\n for output_type, output in outputs.items():\n # write to file is specified by user, otherwise send to stdout\n if args.output:\n if args.output_format == \"json_and_csv\":\n outfile = args.output + \".\" + output_type\n else:\n outfile = args.output\n with open(outfile, \"w\") as f:\n f.write(output)\n else:\n print(output)\n\n\ndef fix_X_amino_acid_variants(sample_json):\n if \"susceptibility\" in sample_json:\n for drug_dict in sample_json[\"susceptibility\"].values():\n if \"called_by\" in drug_dict:\n fix_amino_acid_X_variants_keys(drug_dict[\"called_by\"])\n\n if \"variant_calls\" in sample_json:\n fix_amino_acid_X_variants_keys(sample_json[\"variant_calls\"])\n\n\ndef run(parser, args):\n logger.info(f\"Start runnning mykrobe predict. Command line: {' '.join(sys.argv)}\")\n base_json = {args.sample: {}}\n args = parser.parse_args()\n ref_data = ref_data_from_args(args)\n if (\n args.species == \"custom\"\n and ref_data[\"var_to_res_json\"] is None\n and ref_data[\"lineage_json\"] is None\n ):\n logger.info(\n \"Forcing --report_all_calls because species is 'custom' and options --custom_variant_to_resistance_json,--custom_lineage_json were not used\"\n )\n args.report_all_calls = True\n logger.info(\n f\"Running mykrobe predict using species {args.species}, and panel version {ref_data['version']}\"\n )\n\n if args.tmp is None:\n args.tmp = tempfile.mkdtemp() + \"/\"\n\n # Run Cortex\n cp = CoverageParser(\n sample=args.sample,\n panel_file_paths=ref_data[\"fasta_files\"],\n seq=args.seq,\n kmer=ref_data[\"kmer\"],\n force=args.force,\n threads=args.threads,\n verbose=False,\n tmp_dir=args.tmp,\n skeleton_dir=args.skeleton_dir,\n memory=args.memory\n )\n cp.run()\n logger.debug(\"CoverageParser complete\")\n\n if ref_data[\"species_phylo_group\"] is None:\n phylogenetics = {}\n depths = [cp.estimate_depth()]\n else:\n phylogenetics, depths = detect_species_and_get_depths(\n cp, ref_data[\"hierarchy_json\"], ref_data[\"species_phylo_group\"]\n )\n\n # Genotype\n variant_calls_dict = {}\n sequence_calls_dict = {}\n lineage_calls_dict = {}\n lineage_predict_dict = {}\n if args.force and len(depths) == 0:\n depths = [cp.estimate_depth()]\n gt = None\n\n if len(depths) > 0 or args.force:\n gt = Genotyper(\n sample=args.sample,\n expected_depths=depths,\n expected_error_rate=args.expected_error_rate,\n variant_covgs=cp.variant_covgs,\n gene_presence_covgs=cp.covgs[\"presence\"],\n base_json=base_json,\n contamination_depths=[],\n report_all_calls=True,\n ignore_filtered=True,\n filters=args.filters,\n variant_confidence_threshold=args.min_variant_conf,\n sequence_confidence_threshold=args.min_gene_conf,\n model=args.model,\n kmer_size=ref_data[\"kmer\"],\n min_proportion_expected_depth=args.min_proportion_expected_depth,\n ploidy=args.ploidy,\n lineage_variants=ref_data[\"lineage_dict\"],\n )\n gt.run()\n (\n kmer_count_error_rate,\n incorrect_kmer_to_pc_cov,\n ) = gt.estimate_kmer_count_error_rate_and_incorrect_kmer_to_percent_cov()\n logger.debug(\n \"Estimated error rate for kmer count model: \"\n + str(round(100 * kmer_count_error_rate, 2))\n + \"%\"\n )\n if args.guess_sequence_method and kmer_count_error_rate > 0.001:\n logger.warning(\"Guess sequence method is on, and we've guessed ONT\")\n args.ont = True\n\n if args.ont:\n args.expected_error_rate = 0.15\n args.ploidy = \"haploid\"\n args.ignore_minor_calls = True\n logger.warning(\"Setting ploidy to haploid\")\n logger.warning(\"Setting ignore_minor_calls to True\")\n logger.warning(\n \"Setting expected error rate to %s (--ont)\" % args.expected_error_rate\n )\n args.model = \"kmer_count\"\n\n # If the user didn't specify the conf_percent_cutoff, then set it\n # depending on whether or not the --ont flag was used\n if args.conf_percent_cutoff == -1:\n args.conf_percent_cutoff = 90 if args.ont else 100\n\n # conf_percent_cutoff == 100 means that we want to keep all variant calls,\n # in which case there is no need to run the simulations\n if args.conf_percent_cutoff < 100:\n logger.debug(\"Expected depth: \" + str(depths[0]))\n conf_thresholder = ConfThresholder(\n kmer_count_error_rate,\n depths[0],\n ref_data[\"kmer\"],\n incorrect_kmer_to_pc_cov,\n )\n time_start = time.time()\n conf_threshold = conf_thresholder.get_conf_threshold(\n percent_to_keep=args.conf_percent_cutoff\n )\n time_end = time.time()\n time_to_sim = time_end - time_start\n logger.debug(\"Simulation time: \" + str(time_to_sim))\n logger.debug(\n \"Confidence cutoff (using percent cutoff \"\n + str(args.conf_percent_cutoff)\n + \"%): \"\n + str(conf_threshold)\n )\n gt = Genotyper(\n sample=args.sample,\n expected_depths=depths,\n expected_error_rate=kmer_count_error_rate,\n variant_covgs=cp.variant_covgs,\n gene_presence_covgs=cp.covgs[\"presence\"],\n base_json=base_json,\n contamination_depths=[],\n report_all_calls=True,\n ignore_filtered=True,\n filters=args.filters,\n variant_confidence_threshold=conf_threshold,\n sequence_confidence_threshold=args.min_gene_conf,\n model=args.model,\n kmer_size=ref_data[\"kmer\"],\n min_proportion_expected_depth=args.min_proportion_expected_depth,\n ploidy=args.ploidy,\n lineage_variants=ref_data[\"lineage_dict\"],\n )\n gt.run()\n\n variant_calls_dict = gt.variant_calls_dict\n sequence_calls_dict = gt.sequence_calls_dict\n lineage_predict_dict, lineage_calls_dict = gt.predict_lineage()\n else:\n depths = [cp.estimate_depth()]\n\n mykrobe_predictor_susceptibility_result = MykrobePredictorSusceptibilityResult()\n if (\n gt is not None\n and (max(depths) > args.min_depth or args.force)\n and ref_data[\"var_to_res_json\"] is not None\n ):\n predictor = BasePredictor(\n variant_calls=gt.variant_calls,\n called_genes=gt.sequence_calls_dict,\n base_json=base_json[args.sample],\n depth_threshold=args.min_depth,\n ignore_filtered=True,\n ignore_minor_calls=args.ignore_minor_calls,\n variant_to_resistance_json_fp=ref_data[\"var_to_res_json\"],\n )\n mykrobe_predictor_susceptibility_result = predictor.run()\n logger.info(\"Progress: finished making AMR predictions\")\n\n base_json[args.sample] = {\n \"susceptibility\": list(\n mykrobe_predictor_susceptibility_result.to_dict().values()\n )[0],\n \"phylogenetics\": {}\n if phylogenetics == {}\n else list(phylogenetics.to_dict().values())[0],\n \"variant_calls\": variant_calls_dict,\n \"sequence_calls\": sequence_calls_dict,\n \"lineage_calls\": lineage_calls_dict,\n \"kmer\": ref_data[\"kmer\"],\n \"probe_sets\": ref_data[\"fasta_files\"],\n \"files\": args.seq,\n \"version\": {\n \"mykrobe-predictor\": predictor_version,\n \"mykrobe-atlas\": atlas_version,\n },\n \"genotype_model\": args.model,\n }\n if len(lineage_predict_dict) > 0:\n base_json[args.sample][\"phylogenetics\"][\"lineage\"] = lineage_predict_dict\n\n if not args.keep_tmp:\n cp.remove_temporary_files()\n\n logger.info(\"Progress: writing output\")\n fix_X_amino_acid_variants(base_json[args.sample])\n write_outputs(args, base_json)\n logger.info(\"Progress: finished\")\n" ]
[ [ "numpy.random.binomial", "numpy.random.poisson", "numpy.log10" ] ]
Jingyuying/pc_compress
[ "0db6f7df53f6294585d84921b5102dc6ffdeb9fe" ]
[ "src/compression_model_256.py" ]
[ "# coding=utf-8\r\nimport tensorflow.compat.v1 as tf\r\nimport tensorflow_compression as tfc\r\nimport os\r\nimport sys\r\nimport math\r\nimport numpy as np\r\n# tf.enable_eager_execution()\r\nfrom collections import namedtuple\r\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\r\nROOT_DIR = os.path.dirname(BASE_DIR)\r\nimport part_dataset\r\nfrom transform_nets import input_transform_net\r\nimport pc_utils\r\nimport tf_util\r\n\r\nsys.path.append(os.path.join(ROOT_DIR, 'tf_ops/pc_distance'))\r\nimport tf_nn_distance\r\nsys.path.append(os.path.join(ROOT_DIR, 'tf_ops/grouping'))\r\nsys.path.append(os.path.join(ROOT_DIR, 'tf_ops/emd'))\r\nimport tf_auctionmatch\r\nsys.path.append(os.path.join(ROOT_DIR, 'tf_ops/sampling'))\r\nimport tf_sampling\r\n\r\ndef get_cd_loss(pred, pc):\r\n \"\"\" pred: BxNx3,\r\n label: BxN, \"\"\"\r\n dists_forward,_,dists_backward,_ = tf_nn_distance.nn_distance(pred, pc)\r\n loss = (tf.reduce_mean(tf.sqrt(dists_forward)) + tf.reduce_mean(tf.sqrt(dists_backward)))/2\r\n return loss\r\n\r\ndef get_emd_loss(pred, pc, radius):\r\n \"\"\" pred: BxNxC,\r\n label: BxN, \"\"\"\r\n batch_size = pred.get_shape()[0].value\r\n matchl_out, matchr_out = tf_auctionmatch.auction_match(pred, pc)\r\n matched_out = tf_sampling.gather_point(pc, matchl_out)\r\n dist = tf.reshape((pred - matched_out) ** 2, shape=(batch_size, -1))\r\n dist = tf.reduce_mean(dist, axis=1, keep_dims=True)\r\n dist_norm = dist / radius\r\n emd_loss = tf.reduce_mean(dist_norm)\r\n return emd_loss\r\n\r\ndef get_learning_rate(batch):\r\n learning_rate = tf.train.exponential_decay(\r\n 0.0001,\r\n batch , # global_step 当前迭代次数\r\n 10000,\r\n 0.7,\r\n staircase = True) # global_step / decay_steps始终取整数\r\n learning_rate = tf.maximum(learning_rate, 0.00001) # CLIP THE LEARNING RATE!\r\n return learning_rate\r\n\r\ndef get_bn_decay(batch):\r\n bn_momentum = tf.train.exponential_decay(\r\n 0.5,\r\n batch,\r\n 20000,\r\n 0.5,\r\n staircase=True)\r\n bn_decay = tf.minimum(0.99, 1 - bn_momentum)\r\n return bn_decay\r\n\r\ndef input_fn(features, batch_size, preprocess_threads, repeat=True, prefetch_size=1, is_train = True):\r\n with tf.device('/cpu:0'):\r\n # make a dataset from a numpy array\r\n dataset = tf.data.Dataset.from_generator(lambda: iter(features), tf.float32, tf.TensorShape([256, 3]))\r\n # create the iterator\r\n if repeat:\r\n dataset = dataset.shuffle(buffer_size=len(features))\r\n dataset = dataset.repeat()\r\n dataset = dataset.batch(batch_size, drop_remainder=True)\r\n if is_train:\r\n dataset = dataset.map(lambda x: pc_utils.rotate_point_cloud_and_gt(x, None),\r\n num_parallel_calls=preprocess_threads)\r\n dataset = dataset.map(\r\n lambda x: pc_utils.random_scale_point_cloud_and_gt(x, None, scale_low=0.8, scale_high=1.2),\r\n num_parallel_calls=preprocess_threads)\r\n dataset = dataset.map(lambda x: pc_utils.jitter_perturbation_point_cloud(x, sigma=0.005, clip=0.015),\r\n num_parallel_calls=preprocess_threads)\r\n dataset = dataset.map(lambda x: pc_utils.rotate_perturbation_point_cloud(x, angle_sigma=0.03, angle_clip=0.09),\r\n num_parallel_calls=preprocess_threads)\r\n # 流水线,一边生成一边使用\r\n dataset = dataset.prefetch(buffer_size=prefetch_size)\r\n # 使用创建的数据集来构造一个Iterator实例以遍历数据集\r\n return dataset.make_one_shot_iterator().get_next()\r\n # tf2.0\r\n # return dataset\r\n\r\ndef model_fn(features, labels, mode, params):\r\n '''\r\n :param features: batch_features from input_fn\r\n :param labels: batch_labels from input_fn\r\n :param mode: An instance of tf.estimator.ModeKeys\r\n :param params: Additional configuration\r\n :return:\r\n '''\r\n if params.get('decompress') is None:\r\n params['decompress'] = False\r\n params = namedtuple('Struct', params.keys())(*params.values())\r\n del labels\r\n if params.decompress:\r\n assert mode == tf.estimator.ModeKeys.PREDICT, 'Decompression must use prediction mode'\r\n entropy_bottleneck = tfc.EntropyBottleneck(dtype=tf.float32)\r\n y_tilde = entropy_bottleneck.decompress(features, [256], channels=256) # B*N\r\n x_hat = pc_decoder(y_tilde, params.batch_size, is_training=False, bn_decay=False)\r\n predictions = {\r\n 'y_tilde': y_tilde,\r\n 'x_hat': x_hat\r\n }\r\n return tf.estimator.EstimatorSpec(mode, predictions=predictions)\r\n\r\n\r\n training = (mode == tf.estimator.ModeKeys.TRAIN)\r\n # Get training patch from dataset.\r\n # num_points = (params.batch_size * params.num_points)\r\n batch_size = int(features.shape[0])\r\n num_points = int(features.shape[1])\r\n pc = features\r\n bn_decay = get_bn_decay(tf.train.get_global_step())\r\n learning_rate = get_learning_rate(tf.train.get_global_step())\r\n tf.summary.scalar('bn_decay', bn_decay)\r\n tf.summary.scalar('learning_rate', learning_rate)\r\n\r\n # ============= encoder =============\r\n y = pc_encoder(pc, params.knn, is_training=training, bn_decay=bn_decay)\r\n\r\n # ============= bottleneck layer =============\r\n entropy_bottleneck = tfc.EntropyBottleneck()\r\n y_tilde, likelihoods = entropy_bottleneck(y, training=True)\r\n\r\n # ============= decoder =============\r\n x_tilde = pc_decoder(y_tilde, params.batch_size, is_training=training, bn_decay=bn_decay)\r\n\r\n # number of bits divided by number of points\r\n train_bpp = tf.reduce_sum(tf.log(likelihoods)) / (-np.log(2) * int(num_points))\r\n\r\n # 预测模式直接返回结果\r\n if mode == tf.estimator.ModeKeys.PREDICT:\r\n string = entropy_bottleneck.compress(y)\r\n predictions = {\r\n 'string': string,\r\n 'x_tilde': x_tilde,\r\n 'y_tilde': y_tilde\r\n }\r\n return tf.estimator.EstimatorSpec(mode, predictions=predictions) # 生成predict字典\r\n\r\n # 训练和评估\r\n losses = get_emd_loss(x_tilde, pc, 1)\r\n rd_loss = params.lmbda * train_bpp + losses\r\n # tf.summary.scalar('likelihoods',likelihoods)\r\n tf.summary.scalar('loss', losses)\r\n tf.summary.scalar('rd_loss', rd_loss)\r\n tf.summary.scalar('bpp', train_bpp)\r\n\r\n if mode == tf.estimator.ModeKeys.TRAIN:\r\n main_optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\r\n main_step = main_optimizer.minimize(rd_loss, global_step=tf.train.get_global_step())\r\n\r\n aux_optimizer = tf.train.AdamOptimizer(learning_rate=1e-3)\r\n aux_step = aux_optimizer.minimize(entropy_bottleneck.losses[0])\r\n\r\n train_op = tf.group(main_step, aux_step, entropy_bottleneck.updates[0])\r\n\r\n return tf.estimator.EstimatorSpec(mode, loss=rd_loss, train_op=train_op)\r\n\r\n if mode == tf.estimator.ModeKeys.EVAL:\r\n summary_hook = tf.train.SummarySaverHook(\r\n save_steps=5,\r\n output_dir=os.path.join(params.checkpoint_dir, 'eval'),\r\n summary_op=tf.summary.merge_all())\r\n return tf.estimator.EstimatorSpec(mode, loss=rd_loss, evaluation_hooks=[summary_hook])\r\n\r\n\r\n\r\ndef pc_encoder(point_cloud, nasmples, is_training, bn_decay=None):\r\n batch_size = point_cloud.get_shape()[0].value\r\n num_point = point_cloud.get_shape()[1].value\r\n point_dim = point_cloud.get_shape()[2].value\r\n with tf.variable_scope('transform_net1') as sc:\r\n transform = input_transform_net(point_cloud, is_training, bn_decay, K=3)\r\n point_cloud_transformed = tf.matmul(point_cloud, transform)\r\n\r\n point_cloud_transformed = tf.expand_dims(point_cloud_transformed, -1)\r\n nn_dis, idx_batch = tf_util.get_knn(point_cloud, 12)\r\n\r\n # Encoder\r\n net = tf_util.conv2d(point_cloud_transformed, 64, [1, point_dim],\r\n padding='VALID', stride=[1, 1],\r\n bn=True, is_training=is_training,\r\n scope='conv1', bn_decay=bn_decay)\r\n net = tf_util.conv2d(net, 64, [1, 1],\r\n padding='VALID', stride=[1, 1],\r\n bn=True, is_training=is_training,\r\n scope='conv2', bn_decay=bn_decay)\r\n point_feat_1 = tf_util.conv2d(net, 128, [1, 1],\r\n padding='VALID', stride=[1, 1],\r\n bn=True, is_training=is_training,\r\n scope='conv3', bn_decay=bn_decay)\r\n\r\n print('------------ convPN_1 ------------')\r\n point_feat = tf_util.conv2d(point_feat_1, 256, [1, 1],\r\n padding='VALID', stride=[1, 1],\r\n bn=True, is_training=is_training,\r\n scope='conv4', bn_decay=bn_decay)\r\n point_feat = tf_util.conv2d(point_feat, 256, [1, 1],\r\n padding='VALID', stride=[1, 1],\r\n bn=True, is_training=is_training,\r\n scope='conv5', bn_decay=bn_decay)\r\n feature = tf.squeeze(point_feat, squeeze_dims=2)\r\n knn_feat = tf_util.cuda_maxpooling(feature, idx_batch)\r\n knn_feat = tf.expand_dims(knn_feat, axis=2)\r\n point_feat_2 = tf.concat([point_feat, knn_feat], axis=-1) # 32 256 1 256\r\n\r\n print('------------ convPN_2 ------------')\r\n print(point_feat_2)\r\n point_feat = tf_util.conv2d(point_feat_2, 256, [1, 1],\r\n padding='VALID', stride=[1, 1],\r\n bn=True, is_training=is_training,\r\n scope='conv6', bn_decay=bn_decay)\r\n print(point_feat)\r\n point_feat = tf_util.conv2d(point_feat, 256, [1, 1],\r\n padding='VALID', stride=[1, 1],\r\n bn=True, is_training=is_training,\r\n scope='conv7', bn_decay=bn_decay)\r\n feature = tf.squeeze(point_feat, squeeze_dims=2)\r\n knn_feat = tf_util.cuda_maxpooling(feature, idx_batch)\r\n knn_feat = tf.expand_dims(knn_feat, axis=2)\r\n point_feat_3 = tf.concat([point_feat, knn_feat], axis=-1) # 32 256 1 512\r\n mix_feature = tf.concat([point_feat_1, point_feat_2, point_feat_3], axis=-1)\r\n\r\n # ----------- maxpooling--------------\r\n global_feature = tf_util.max_pool2d(mix_feature, [num_point, 1], padding='VALID', scope='maxpool_1')\r\n net = tf.reshape(global_feature, [batch_size, -1])\r\n net = tf_util.fully_connected(net, 512, bn=True, is_training=is_training, scope='fc00', bn_decay=bn_decay)\r\n net = tf_util.fully_connected(net, 512, bn=True, is_training=is_training, scope='fc01', bn_decay=bn_decay)\r\n net = tf_util.fully_connected(net, 256, bn=True, is_training=is_training, scope='fc02', bn_decay=bn_decay)\r\n print(net)\r\n net = tf.reshape(net, [batch_size, -1])\r\n print(net)\r\n return net\r\n\r\ndef pc_decoder(y_tilde, batch_size, is_training, bn_decay):\r\n # UPCONV Decoder\r\n net = tf.reshape(y_tilde, [batch_size, 1, 1, 256])\r\n net = tf_util.fully_connected(net, 256, bn=True, is_training=is_training, scope='fc1', bn_decay=bn_decay)\r\n net = tf_util.fully_connected(net, 512, bn=True, is_training=is_training, scope='fc2', bn_decay=bn_decay)\r\n net = tf_util.fully_connected(net, 256 * 3, activation_fn=None, scope='fc3')\r\n pc_fc = tf.reshape(net, (batch_size, -1, 3))\r\n return pc_fc\r\n\r\n\r\nif __name__=='__main__':\r\n # tf.enable_eager_execution()\r\n # TRAIN_DATASET = part_dataset.PartDataset(\r\n # root='/data/dataset/shapenetcore_partanno_segmentation_benchmark_v0', npoints=2048,\r\n # classification=False, class_choice=None, split='trainval')\r\n print('=============')\r\n # print(input_fn(TRAIN_DATASET,2,8,repeat=True,prefetch_size=6))\r\n\r\n" ]
[ [ "tensorflow.compat.v1.concat", "tensorflow.compat.v1.sqrt", "tensorflow.compat.v1.group", "tensorflow.compat.v1.summary.merge_all", "tensorflow.compat.v1.train.AdamOptimizer", "tensorflow.compat.v1.reshape", "tensorflow.compat.v1.maximum", "tensorflow.compat.v1.variable_scope", "numpy.log", "tensorflow.compat.v1.estimator.EstimatorSpec", "tensorflow.compat.v1.reduce_mean", "tensorflow.compat.v1.train.exponential_decay", "tensorflow.compat.v1.minimum", "tensorflow.compat.v1.summary.scalar", "tensorflow.compat.v1.TensorShape", "tensorflow.compat.v1.log", "tensorflow.compat.v1.device", "tensorflow.compat.v1.expand_dims", "tensorflow.compat.v1.matmul", "tensorflow.compat.v1.train.get_global_step", "tensorflow.compat.v1.squeeze" ] ]
pbizopoulos/signal2image-modules-in-deep-neural-networks-for-eeg-classification
[ "804cb3702d8d054ea7b5ecd299dc22794ddeb241" ]
[ "main.py" ]
[ "import collections\nimport os\nfrom shutil import rmtree\n\nimport numpy as np\nimport onnx\nimport pandas as pd\nimport requests\nimport torch\nfrom matplotlib import pyplot as plt\nfrom onnx_tf.backend import prepare\nfrom PIL import Image\nfrom scipy.signal import spectrogram\nfrom tensorflowjs.converters import tf_saved_model_conversion_v2\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.optim import Adam\nfrom torch.utils.data import DataLoader, Dataset\nfrom torchvision import models\n\ntmpdir = os.getenv('TMPDIR')\nfull = os.getenv('FULL')\n\n\ndef save_tfjs(model, tmpdir, combined_model_name):\n combined_model_name_dir = f'{tmpdir}/tfjs-models/{combined_model_name}'\n os.makedirs(combined_model_name_dir, exist_ok=True)\n example_input = torch.randn(1, 1, 176, requires_grad=False)\n torch.onnx.export(model.cpu(), example_input, f'{combined_model_name_dir}/model.onnx', export_params=True, opset_version=11)\n onnx_model = onnx.load(f'{combined_model_name_dir}/model.onnx')\n tf_model = prepare(onnx_model)\n tf_model.export_graph(f'{combined_model_name_dir}/model')\n tf_saved_model_conversion_v2.convert_tf_saved_model(f'{combined_model_name_dir}/model', combined_model_name_dir, skip_op_check=True)\n rmtree(f'{combined_model_name_dir}/model')\n os.remove(f'{combined_model_name_dir}/model.onnx')\n\n\ndef save_signal(signals_all, signal_index, label_name):\n plt.figure()\n plt.plot(signals_all[signal_index].squeeze(), linewidth=4, color='k')\n plt.axis('off')\n plt.xlim([0, signals_all.shape[-1] - 1])\n plt.ylim([-1000, 1000])\n plt.savefig(f'{tmpdir}/signal-{label_name}.png')\n plt.close()\n\n\ndef save_signal_as_image(signals_all, signal_index, label_name):\n signals_all_min = -1000\n signals_all_max = 1000\n x = signals_all[signal_index] - signals_all_min\n x = signals_all.shape[-1] * x / (signals_all_max - signals_all_min)\n x = x.squeeze(0).floor().long()\n data = torch.zeros(signals_all.shape[-1], signals_all.shape[-1])\n for index in range(signals_all.shape[-1]):\n data[signals_all.shape[-1] - 1 - x[index], index] = 255\n plt.figure()\n plt.imsave(f'{tmpdir}/signal-as-image-{label_name}.png', data, cmap='gray')\n plt.close()\n\n\ndef save_spectrogram(signals_all, signal_index, label_name):\n _, _, Sxx = spectrogram(signals_all[signal_index], fs=signals_all.shape[-1], noverlap=4, nperseg=8, nfft=64, mode='magnitude')\n data = np.array(Image.fromarray(Sxx[0]).resize((signals_all.shape[-1], signals_all.shape[-1]), resample=1))\n plt.figure()\n plt.imsave(f'{tmpdir}/spectrogram-{label_name}.png', data, cmap='gray')\n plt.close()\n\n\ndef save_cnn(signals_all, signal_index, label_name, num_classes):\n model = CNNOneLayer(num_classes, models.alexnet(), 'alexnet-cnn-one-layer')\n model.load_state_dict(torch.load(f'{tmpdir}/alexnet-cnn-one-layer.pt'))\n signal = signals_all[signal_index].unsqueeze(0)\n outputs = []\n\n def hook(_, __, output):\n outputs.append(output)\n\n model.conv.register_forward_hook(hook)\n model(signal)\n data = outputs[0][0, 0].cpu().detach().numpy()\n data = np.array(Image.fromarray(data).resize((signals_all.shape[-1], signals_all.shape[-1]), resample=1))\n plt.figure()\n plt.imsave(f'{tmpdir}/cnn-{label_name}.png', data, cmap='gray')\n plt.close()\n\n\ndef replace_last_layer(base_model, combined_model_name, num_classes):\n if combined_model_name.startswith(('alexnet', 'vgg')):\n base_model.classifier[-1] = nn.Linear(base_model.classifier[-1].in_features, num_classes)\n elif combined_model_name.startswith('resnet'):\n base_model.fc = nn.Linear(base_model.fc.in_features, num_classes)\n elif combined_model_name.startswith('densenet'):\n base_model.classifier = nn.Linear(base_model.classifier.in_features, num_classes)\n return base_model\n\n\nclass SignalAsImage(nn.Module):\n def __init__(self, num_classes, base_model, combined_model_name, signals_all_max, signals_all_min):\n super().__init__()\n self.signals_all_max = signals_all_max\n self.signals_all_min = signals_all_min\n self.base_model = replace_last_layer(base_model, combined_model_name, num_classes)\n\n def forward(self, x):\n x = x - self.signals_all_min\n x = x.shape[-1] * x / (self.signals_all_max - self.signals_all_min)\n x = x.floor().long()\n out = torch.zeros(x.shape[0], 1, x.shape[-1], x.shape[-1]).to(x.device)\n for index, _ in enumerate(x):\n out[index, 0, x.shape[-1] - 1 - x[index, 0, :], range(x.shape[-1])] = 255\n out = torch.cat((out, out, out), 1)\n out = self.base_model(out)\n return out\n\n\nclass Spectrogram(nn.Module):\n def __init__(self, num_classes, base_model, combined_model_name):\n super().__init__()\n self.base_model = replace_last_layer(base_model, combined_model_name, num_classes)\n\n def forward(self, x):\n out = torch.zeros(x.shape[0], 1, x.shape[-1], x.shape[-1]).to(x.device)\n for index, signal in enumerate(x):\n _, _, Sxx = spectrogram(signal.cpu(), fs=x.shape[-1], noverlap=4, nperseg=8, nfft=64, mode='magnitude')\n out[index, 0] = F.interpolate(torch.tensor(Sxx).unsqueeze(0), x.shape[-1], mode='bilinear')\n out = torch.cat((out, out, out), 1)\n out = self.base_model(out)\n return out\n\n\nclass CNNTwoLayers(nn.Module):\n def __init__(self, num_classes, base_model, combined_model_name):\n super().__init__()\n self.conv1 = nn.Conv1d(1, 8, 3, padding=2)\n self.conv2 = nn.Conv1d(8, 16, 3, padding=2)\n self.base_model = replace_last_layer(base_model, combined_model_name, num_classes)\n\n def forward(self, x):\n out = F.relu(self.conv1(x))\n out = F.max_pool1d(out, 2)\n out = self.conv2(out)\n out.unsqueeze_(1)\n out = F.interpolate(out, x.shape[-1], mode='bilinear')\n out = torch.cat((out, out, out), 1)\n out = self.base_model(out)\n return out\n\n\nclass CNNOneLayer(nn.Module):\n def __init__(self, num_classes, base_model, combined_model_name):\n super().__init__()\n self.conv = nn.Conv1d(1, 8, 3, padding=2)\n self.base_model = replace_last_layer(base_model, combined_model_name, num_classes)\n\n def forward(self, x):\n out = self.conv(x)\n out.unsqueeze_(1)\n out = F.interpolate(out, x.shape[-1], mode='bilinear')\n out = torch.cat((out, out, out), 1)\n out = self.base_model(out)\n return out\n\n\nclass lenet(nn.Module):\n def __init__(self, num_classes):\n super().__init__()\n self.conv1 = nn.Conv1d(1, 3, 5)\n self.conv2 = nn.Conv1d(3, 16, 5)\n self.fc1 = nn.Linear(656, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, num_classes)\n\n def forward(self, x):\n out = F.relu(self.conv1(x))\n out = F.max_pool1d(out, 2)\n out = F.relu(self.conv2(out))\n out = F.max_pool1d(out, 2)\n out = out.view(out.size(0), -1)\n out = F.relu(self.fc1(out))\n out = F.relu(self.fc2(out))\n out = self.fc3(out)\n return out\n\n\nclass alexnet(nn.Module):\n def __init__(self, num_classes):\n super().__init__()\n self.features = nn.Sequential(\n nn.Conv1d(1, 64, kernel_size=11, stride=4, padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool1d(kernel_size=3, stride=2),\n nn.Conv1d(64, 192, kernel_size=5, padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool1d(kernel_size=3, stride=2),\n nn.Conv1d(192, 384, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv1d(384, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv1d(256, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool1d(kernel_size=3, stride=2),\n )\n self.classifier = nn.Sequential(\n nn.Dropout(),\n nn.Linear(256 * 4, 4096),\n nn.ReLU(inplace=True),\n nn.Dropout(),\n nn.Linear(4096, 4096),\n nn.ReLU(inplace=True),\n nn.Linear(4096, num_classes),\n )\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), 256 * 4)\n x = self.classifier(x)\n return x\n\n\nclass VGG(nn.Module):\n def __init__(self, features, num_classes):\n super().__init__()\n self.features = features\n self.classifier = nn.Sequential(\n nn.Linear(2560, 4096),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(4096, 4096),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(4096, num_classes),\n )\n self._initialize_weights()\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n return x\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv1d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, 0, 0.01)\n nn.init.constant_(m.bias, 0)\n\n\ndef make_layers(cfg, batch_norm=False):\n layers = []\n in_channels = 1\n for v in cfg:\n if v == 'M':\n layers += [nn.MaxPool1d(kernel_size=2, stride=2)]\n else:\n conv1d = nn.Conv1d(in_channels, v, kernel_size=3, padding=1)\n layers += [conv1d, nn.ReLU(inplace=True)]\n in_channels = v\n return nn.Sequential(*layers)\n\n\ncfg = {\n 'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\n 'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\n 'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],\n 'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],\n}\n\n\ndef vgg11(num_classes):\n model = VGG(make_layers(cfg['A']), num_classes)\n return model\n\n\ndef vgg13(num_classes):\n model = VGG(make_layers(cfg['B']), num_classes)\n return model\n\n\ndef vgg16(num_classes):\n model = VGG(make_layers(cfg['D']), num_classes)\n return model\n\n\ndef vgg19(num_classes):\n model = VGG(make_layers(cfg['E']), num_classes)\n return model\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n return nn.Conv1d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)\n\n\ndef conv1x1(in_planes, out_planes, stride=1):\n return nn.Conv1d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super().__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm1d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm1d(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n out = self.conv2(out)\n out = self.bn2(out)\n if self.downsample is not None:\n identity = self.downsample(x)\n out += identity\n out = self.relu(out)\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super().__init__()\n self.conv1 = conv1x1(inplanes, planes)\n self.bn1 = nn.BatchNorm1d(planes)\n self.conv2 = conv3x3(planes, planes, stride)\n self.bn2 = nn.BatchNorm1d(planes)\n self.conv3 = conv1x1(planes, planes * self.expansion)\n self.bn3 = nn.BatchNorm1d(planes * self.expansion)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n out = self.conv3(out)\n out = self.bn3(out)\n if self.downsample is not None:\n identity = self.downsample(x)\n out += identity\n out = self.relu(out)\n return out\n\n\nclass ResNet(nn.Module):\n def __init__(self, block, layers, num_classes):\n super().__init__()\n self.inplanes = 64\n self.conv1 = nn.Conv1d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)\n self.bn1 = nn.BatchNorm1d(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool1d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2)\n self.avgpool = nn.AdaptiveAvgPool1d(1)\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n for m in self.modules():\n if isinstance(m, nn.Conv1d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n elif isinstance(m, nn.BatchNorm1d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n conv1x1(self.inplanes, planes * block.expansion, stride),\n nn.BatchNorm1d(planes * block.expansion),\n )\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for _ in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n return x\n\n\ndef resnet18(num_classes):\n model = ResNet(BasicBlock, [2, 2, 2, 2], num_classes)\n return model\n\n\ndef resnet34(num_classes):\n model = ResNet(BasicBlock, [3, 4, 6, 3], num_classes)\n return model\n\n\ndef resnet50(num_classes):\n model = ResNet(Bottleneck, [3, 4, 6, 3], num_classes)\n return model\n\n\ndef resnet101(num_classes):\n model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes)\n return model\n\n\ndef resnet152(num_classes):\n model = ResNet(Bottleneck, [3, 8, 36, 3], num_classes)\n return model\n\n\nclass _DenseLayer(nn.Sequential):\n def __init__(self, num_input_features, growth_rate, bn_size):\n super().__init__()\n self.add_module('norm1', nn.BatchNorm1d(num_input_features))\n self.add_module('relu1', nn.ReLU(inplace=True))\n self.add_module('conv1', nn.Conv1d(num_input_features, bn_size * growth_rate, kernel_size=1, stride=1, bias=False))\n self.add_module('norm2', nn.BatchNorm1d(bn_size * growth_rate))\n self.add_module('relu2', nn.ReLU(inplace=True))\n self.add_module('conv2', nn.Conv1d(bn_size * growth_rate, growth_rate, kernel_size=3, stride=1, padding=1, bias=False))\n\n def forward(self, x):\n new_features = super().forward(x)\n return torch.cat([x, new_features], 1)\n\n\nclass _DenseBlock(nn.Sequential):\n def __init__(self, num_layers, num_input_features, bn_size, growth_rate):\n super().__init__()\n for i in range(num_layers):\n layer = _DenseLayer(num_input_features + i * growth_rate, growth_rate, bn_size)\n self.add_module('denselayer%d' % (i + 1), layer)\n\n\nclass _Transition(nn.Sequential):\n def __init__(self, num_input_features, num_output_features):\n super().__init__()\n self.add_module('norm', nn.BatchNorm1d(num_input_features))\n self.add_module('relu', nn.ReLU(inplace=True))\n self.add_module('conv', nn.Conv1d(num_input_features, num_output_features, kernel_size=1, stride=1, bias=False))\n self.add_module('pool', nn.AvgPool1d(kernel_size=2, stride=2))\n\n\nclass DenseNet(nn.Module):\n def __init__(self, num_classes, num_init_features, growth_rate, block_config):\n super().__init__()\n bn_size = 4\n self.features = nn.Sequential(\n nn.Conv1d(1, num_init_features, kernel_size=7, stride=2, padding=3, bias=False),\n nn.BatchNorm1d(num_init_features),\n nn.ReLU(inplace=True),\n nn.MaxPool1d(kernel_size=3, stride=2, padding=1),\n )\n num_features = num_init_features\n for i, num_layers in enumerate(block_config):\n block = _DenseBlock(num_layers=num_layers, num_input_features=num_features, bn_size=bn_size, growth_rate=growth_rate)\n self.features.add_module('denseblock%d' % (i + 1), block)\n num_features = num_features + num_layers * growth_rate\n if i != len(block_config) - 1:\n trans = _Transition(num_input_features=num_features, num_output_features=num_features // 2)\n self.features.add_module('transition%d' % (i + 1), trans)\n num_features = num_features // 2\n self.features.add_module('norm5', nn.BatchNorm1d(num_features))\n self.classifier = nn.Linear(num_features, num_classes)\n for m in self.modules():\n if isinstance(m, nn.Conv1d):\n nn.init.kaiming_normal_(m.weight)\n elif isinstance(m, nn.BatchNorm1d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.Linear):\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x):\n features = self.features(x)\n out = F.relu(features, inplace=True)\n out = F.adaptive_avg_pool1d(out, 1).view(features.size(0), -1)\n out = self.classifier(out)\n return out\n\n\ndef densenet121(num_samples):\n model = DenseNet(num_samples, num_init_features=64, growth_rate=32, block_config=(6, 12, 24, 16))\n return model\n\n\ndef densenet169(num_samples):\n model = DenseNet(num_samples, num_init_features=64, growth_rate=32, block_config=(6, 12, 32, 32))\n return model\n\n\ndef densenet201(num_samples):\n model = DenseNet(num_samples, num_init_features=64, growth_rate=32, block_config=(6, 12, 48, 32))\n return model\n\n\ndef densenet161(num_samples):\n model = DenseNet(num_samples, num_init_features=96, growth_rate=48, block_config=(6, 12, 36, 24))\n return model\n\n\nclass UCIEpilepsy(Dataset):\n def __init__(self, training_validation_test, num_samples):\n filename = f'{tmpdir}/data.csv'\n if not os.path.isfile(filename):\n with open(filename, 'wb') as file:\n response = requests.get('https://web.archive.org/web/20200318000445/http://archive.ics.uci.edu/ml/machine-learning-databases/00388/data.csv')\n file.write(response.content)\n dataset = pd.read_csv(filename)\n dataset = dataset[:num_samples]\n signals_all = dataset.drop(columns=['Unnamed: 0', 'y'])\n labels_all = dataset['y']\n last_training_index = int(signals_all.shape[0] * 0.76)\n last_validation_index = int(signals_all.shape[0] * 0.88)\n if training_validation_test == 'training':\n self.data = torch.tensor(signals_all.values[:last_training_index, :], dtype=torch.float)\n self.labels = torch.tensor(labels_all[:last_training_index].values) - 1\n elif training_validation_test == 'validation':\n self.data = torch.tensor(signals_all.values[last_training_index:last_validation_index, :], dtype=torch.float)\n self.labels = torch.tensor(labels_all[last_training_index:last_validation_index].values) - 1\n elif training_validation_test == 'test':\n self.data = torch.tensor(signals_all.values[last_validation_index:, :], dtype=torch.float)\n self.labels = torch.tensor(labels_all[last_validation_index:].values) - 1\n self.data.unsqueeze_(1)\n\n def __getitem__(self, index):\n return (self.data[index], self.labels[index])\n\n def __len__(self):\n return self.labels.shape[0]\n\n\nclass LeNet2D(nn.Module):\n def __init__(self):\n super().__init__()\n self.conv1 = nn.Conv2d(3, 3, 5)\n self.conv2 = nn.Conv2d(3, 16, 5)\n self.fc1 = nn.Linear(41 * 41 * 16, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 5)\n\n def forward(self, x):\n out = F.relu(self.conv1(x))\n out = F.max_pool2d(out, 2)\n out = F.relu(self.conv2(out))\n out = F.max_pool2d(out, 2)\n out = out.view(out.size(0), -1)\n out = F.relu(self.fc1(out))\n out = F.relu(self.fc2(out))\n out = self.fc3(out)\n return out\n\n\ndef main():\n torch.hub.set_dir(tmpdir)\n num_samples = 11500\n num_epochs = 100\n if not full:\n num_samples = 10\n num_epochs = 1\n np.random.seed(0)\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n torch.manual_seed(0)\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n num_classes = 5\n batch_size = 20\n signals_all_max = 2047\n signals_all_min = -1885\n training_dataset = UCIEpilepsy('training', num_samples)\n validation_dataset = UCIEpilepsy('validation', num_samples)\n test_dataset = UCIEpilepsy('test', num_samples)\n training_dataloader = DataLoader(dataset=training_dataset, batch_size=batch_size, shuffle=True)\n validation_dataloader = DataLoader(dataset=validation_dataset, batch_size=batch_size, shuffle=False)\n test_dataloader = DataLoader(dataset=test_dataset, batch_size=batch_size)\n criterion = nn.CrossEntropyLoss()\n base_models_names = ['lenet', 'alexnet', 'vgg11', 'vgg13', 'vgg16', 'vgg19', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152', 'densenet121', 'densenet161', 'densenet169', 'densenet201']\n base_models_1D = [lenet, alexnet, vgg11, vgg13, vgg16, vgg19, resnet18, resnet34, resnet50, resnet101, resnet152, densenet121, densenet161, densenet169, densenet201]\n base_models_2D = [LeNet2D, models.alexnet, models.vgg11, models.vgg13, models.vgg16, models.vgg19, models.resnet18, models.resnet34, models.resnet50, models.resnet101, models.resnet152, models.densenet121, models.densenet161, models.densenet169, models.densenet201]\n base_models_1D_names = [f'{model_name}-1D' for model_name in base_models_names]\n combined_models_signal_as_image_names = [f'{model_name}-signal-as-image' for model_name in base_models_names]\n combined_models_spectrogram_names = [f'{model_name}-spectrogram' for model_name in base_models_names]\n combined_models_cnn_one_layer_names = [f'{model_name}-cnn-one-layer' for model_name in base_models_names]\n combined_models_cnn_two_layers_names = [f'{model_name}-cnn-two-layers' for model_name in base_models_names]\n base_models = base_models_1D + base_models_2D + base_models_2D + base_models_2D + base_models_2D\n combined_models_names = base_models_1D_names + combined_models_signal_as_image_names + combined_models_spectrogram_names + combined_models_cnn_one_layer_names + combined_models_cnn_two_layers_names\n results = collections.defaultdict(dict)\n for combined_model_name in combined_models_names:\n results[combined_model_name]['training_loss'] = []\n results[combined_model_name]['validation_loss'] = []\n results[combined_model_name]['validation_accuracy'] = []\n for base_model, combined_model_name in zip(base_models, combined_models_names):\n if combined_model_name.endswith('-1D'):\n model = base_model(num_classes)\n elif combined_model_name.endswith('-signal-as-image'):\n model = SignalAsImage(num_classes, base_model(), combined_model_name, signals_all_max, signals_all_min)\n elif combined_model_name.endswith('-spectrogram'):\n model = Spectrogram(num_classes, base_model(), combined_model_name)\n elif combined_model_name.endswith('-cnn-one-layer'):\n model = CNNOneLayer(num_classes, base_model(), combined_model_name)\n elif combined_model_name.endswith('-cnn-two-layers'):\n model = CNNTwoLayers(num_classes, base_model(), combined_model_name)\n model = model.to(device)\n optimizer = Adam(model.parameters())\n best_validation_accuracy = -1\n for epoch in range(num_epochs):\n model.train()\n training_loss_sum = 0\n for signals, labels in training_dataloader:\n signals = signals.to(device)\n labels = labels.to(device)\n outputs = model(signals)\n loss = criterion(outputs, labels)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n training_loss_sum += loss.item()\n training_loss = training_loss_sum / (batch_size * len(training_dataloader))\n validation_loss_sum = 0\n corrects = 0\n model.eval()\n with torch.no_grad():\n for signals, labels in validation_dataloader:\n signals = signals.to(device)\n labels = labels.to(device)\n outputs = model(signals)\n loss = criterion(outputs, labels)\n corrects += sum(outputs.argmax(dim=1) == labels).item()\n validation_loss_sum += loss.item()\n validation_accuracy = 100 * corrects / (batch_size * len(validation_dataloader))\n validation_loss = validation_loss_sum / (batch_size * len(validation_dataloader))\n print(f'Model: {combined_model_name}, Epoch: {epoch}, Loss: {validation_loss:.3f}, Accuracy: {validation_accuracy:.2f}%')\n results[combined_model_name]['training_loss'].append(training_loss)\n results[combined_model_name]['validation_loss'].append(validation_loss)\n results[combined_model_name]['validation_accuracy'].append(validation_accuracy)\n if validation_accuracy > best_validation_accuracy:\n best_validation_accuracy = validation_accuracy\n torch.save(model.state_dict(), f'{tmpdir}/{combined_model_name}.pt')\n print('Saved as best model')\n model.load_state_dict(torch.load(f'{tmpdir}/{combined_model_name}.pt'))\n model.eval()\n test_loss_sum = 0\n corrects = 0\n test_confussion_matrix = torch.zeros(num_classes, num_classes)\n with torch.no_grad():\n for signals, labels in test_dataloader:\n signals = signals.to(device)\n labels = labels.to(device)\n outputs = model(signals)\n loss = criterion(outputs, labels)\n corrects += sum(outputs.argmax(dim=1) == labels).item()\n for t, p in zip(labels.view(-1), torch.argmax(outputs, 1).view(-1)):\n test_confussion_matrix[t.long(), p.long()] += 1\n test_loss_sum += loss.item()\n test_accuracy = 100 * corrects / (batch_size * len(test_dataloader))\n test_loss = test_loss_sum / (batch_size * len(test_dataloader))\n results[combined_model_name]['test_confussion_matrix'] = test_confussion_matrix\n results[combined_model_name]['test_accuracy'] = test_accuracy\n print(f'Model: {combined_model_name}, Epoch: {epoch}, Loss: {test_loss:.3f}, Accuracy: {test_accuracy:.2f}%')\n if full and combined_model_name in ['lenet-1D', 'alexnet-1D', 'resnet18-1D', 'resnet34-1D', 'resnet50-1D', 'resnet18-signal-as-image', 'resnet34-signal-as-image', 'resnet50-signal-as-image']:\n save_tfjs(model, tmpdir, combined_model_name)\n if (not full) and (combined_model_name != 'alexnet-cnn-one-layer'):\n os.remove(f'{tmpdir}/{combined_model_name}.pt')\n results_test_accuracy_for_paper = np.zeros((75,))\n for index, model in enumerate(results):\n results_test_accuracy_for_paper[index] = np.around(results[model]['test_accuracy'], 1)\n results_test_accuracy_for_paper = results_test_accuracy_for_paper.reshape(5, 15)\n df = pd.DataFrame(results_test_accuracy_for_paper, index=['1D', '2D, signal as image', '2D, spectrogram', '2D, one layer CNN', '2D, two layer CNN'])\n df.columns = base_models_names\n df.to_latex(f'{tmpdir}/results.tex', bold_rows=True, escape=False)\n dataset = pd.read_csv(f'{tmpdir}/data.csv')\n signals_all = dataset.drop(columns=['Unnamed: 0', 'y'])\n labels_all = dataset['y']\n signals_all = torch.tensor(signals_all.values, dtype=torch.float)\n labels_all = torch.tensor(labels_all.values) - 1\n labels_names = ['eyes-open', 'eyes-closed', 'healthy-area', 'tumor-area', 'epilepsy']\n for index, label_name in enumerate(labels_names):\n signal_index = (labels_all == index).nonzero()[-1]\n save_signal(signals_all, signal_index, label_name)\n save_signal_as_image(signals_all, signal_index, label_name)\n save_spectrogram(signals_all, signal_index, label_name)\n save_cnn(signals_all, signal_index, label_name, num_classes)\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "torch.nn.functional.max_pool1d", "torch.zeros", "torch.load", "torch.cat", "numpy.around", "torch.utils.data.DataLoader", "pandas.DataFrame", "torch.nn.functional.adaptive_avg_pool1d", "torch.no_grad", "torch.nn.functional.interpolate", "torch.cuda.is_available", "torch.hub.set_dir", "torch.nn.CrossEntropyLoss", "pandas.read_csv", "torch.nn.Dropout", "torch.randn", "torch.tensor", "torch.nn.MaxPool1d", "torch.nn.functional.relu", "matplotlib.pyplot.close", "matplotlib.pyplot.axis", "numpy.zeros", "torch.nn.functional.max_pool2d", "matplotlib.pyplot.figure", "matplotlib.pyplot.imsave", "torch.nn.Sequential", "torch.nn.BatchNorm1d", "torch.nn.init.constant_", "matplotlib.pyplot.ylim", "torch.nn.Conv2d", "torch.argmax", "matplotlib.pyplot.savefig", "torch.nn.Linear", "torch.nn.init.normal_", "torch.nn.Conv1d", "torch.nn.AdaptiveAvgPool1d", "numpy.random.seed", "torch.manual_seed", "scipy.signal.spectrogram", "matplotlib.pyplot.xlim", "torch.nn.ReLU", "torch.nn.AvgPool1d", "torch.nn.init.kaiming_normal_" ] ]
youjibiying/-GTOT-Tuning
[ "5d3c346bda1ad5fe1d88723a4919ebcc437667ed" ]
[ "chem/splitters.py" ]
[ "import torch\nimport random\nimport numpy as np\nfrom itertools import compress\nfrom rdkit.Chem.Scaffolds import MurckoScaffold\nfrom collections import defaultdict\nfrom sklearn.model_selection import StratifiedKFold\n\n\n# splitter function\n\ndef generate_scaffold(smiles, include_chirality=False):\n \"\"\"\n Obtain Bemis-Murcko scaffold from smiles\n :param smiles:\n :param include_chirality:\n :return: smiles of scaffold\n \"\"\"\n scaffold = MurckoScaffold.MurckoScaffoldSmiles(\n smiles=smiles, includeChirality=include_chirality)\n return scaffold\n\n\n# # test generate_scaffold\n# s = 'Cc1cc(Oc2nccc(CCC)c2)ccc1'\n# scaffold = generate_scaffold(s)\n# assert scaffold == 'c1ccc(Oc2ccccn2)cc1'\n\ndef scaffold_split(dataset, smiles_list, task_idx=None, null_value=0,\n frac_train=0.8, frac_valid=0.1, frac_test=0.1, train_radio=1.0,\n return_smiles=False):\n \"\"\"\n Adapted from https://github.com/deepchem/deepchem/blob/master/deepchem/splits/splitters.py\n Split dataset by Bemis-Murcko scaffolds\n This function can also ignore examples containing null values for a\n selected task when splitting. Deterministic split\n :param dataset: pytorch geometric dataset obj\n :param smiles_list: list of smiles corresponding to the dataset obj\n :param task_idx: column idx of the data.y tensor. Will filter out\n examples with null value in specified task column of the data.y tensor\n prior to splitting. If None, then no filtering\n :param null_value: float that specifies null value in data.y to filter if\n task_idx is provided\n :param frac_train:\n :param frac_valid:\n :param frac_test:\n :param return_smiles:\n :return: train, valid, test slices of the input dataset obj. If\n return_smiles = True, also returns ([train_smiles_list],\n [valid_smiles_list], [test_smiles_list])\n \"\"\"\n np.testing.assert_almost_equal(frac_train + frac_valid + frac_test, 1.0)\n\n if task_idx != None:\n # filter based on null values in task_idx\n # get task array\n y_task = np.array([data.y[task_idx].item() for data in dataset])\n # boolean array that correspond to non null values\n non_null = y_task != null_value\n smiles_list = list(compress(enumerate(smiles_list), non_null))\n else:\n non_null = np.ones(len(dataset)) == 1\n smiles_list = list(compress(enumerate(smiles_list), non_null))\n\n # create dict of the form {scaffold_i: [idx1, idx....]}\n all_scaffolds = {}\n for i, smiles in smiles_list:\n scaffold = generate_scaffold(smiles, include_chirality=True)\n if scaffold not in all_scaffolds:\n all_scaffolds[scaffold] = [i]\n else:\n all_scaffolds[scaffold].append(i)\n\n # sort from largest to smallest sets\n all_scaffolds = {key: sorted(value) for key, value in all_scaffolds.items()}\n all_scaffold_sets = [\n scaffold_set for (scaffold, scaffold_set) in sorted(\n all_scaffolds.items(), key=lambda x: (len(x[1]), x[1][0]), reverse=True)\n ]\n\n # get train, valid test indices\n train_cutoff = frac_train * len(smiles_list)\n valid_cutoff = (frac_train + frac_valid) * len(smiles_list)\n train_idx, valid_idx, test_idx = [], [], []\n for scaffold_set in all_scaffold_sets:\n if len(train_idx) + len(scaffold_set) > train_cutoff:\n if len(train_idx) + len(valid_idx) + len(scaffold_set) > valid_cutoff:\n test_idx.extend(scaffold_set)\n else:\n valid_idx.extend(scaffold_set)\n else:\n train_idx.extend(scaffold_set)\n import math\n train_idx = train_idx[:math.ceil(len(train_idx) * train_radio)]\n\n assert len(set(train_idx).intersection(set(valid_idx))) == 0\n assert len(set(test_idx).intersection(set(valid_idx))) == 0\n\n train_dataset = dataset[torch.tensor(train_idx)]\n valid_dataset = dataset[torch.tensor(valid_idx)]\n test_dataset = dataset[torch.tensor(test_idx)]\n\n if not return_smiles:\n return train_dataset, valid_dataset, test_dataset\n else:\n train_smiles = [smiles_list[i][1] for i in train_idx]\n valid_smiles = [smiles_list[i][1] for i in valid_idx]\n test_smiles = [smiles_list[i][1] for i in test_idx]\n return train_dataset, valid_dataset, test_dataset, (train_smiles,\n valid_smiles,\n test_smiles)\n\n\ndef random_scaffold_split(dataset, smiles_list, task_idx=None, null_value=0,\n frac_train=0.8, frac_valid=0.1, frac_test=0.1, seed=0):\n \"\"\"\n Adapted from https://github.com/pfnet-research/chainer-chemistry/blob/master/chainer_chemistry/dataset/splitters/scaffold_splitter.py\n Split dataset by Bemis-Murcko scaffolds\n This function can also ignore examples containing null values for a\n selected task when splitting. Deterministic split\n :param dataset: pytorch geometric dataset obj\n :param smiles_list: list of smiles corresponding to the dataset obj\n :param task_idx: column idx of the data.y tensor. Will filter out\n examples with null value in specified task column of the data.y tensor\n prior to splitting. If None, then no filtering\n :param null_value: float that specifies null value in data.y to filter if\n task_idx is provided\n :param frac_train:\n :param frac_valid:\n :param frac_test:\n :param seed;\n :return: train, valid, test slices of the input dataset obj\n \"\"\"\n\n np.testing.assert_almost_equal(frac_train + frac_valid + frac_test, 1.0)\n\n if task_idx != None:\n # filter based on null values in task_idx\n # get task array\n y_task = np.array([data.y[task_idx].item() for data in dataset])\n # boolean array that correspond to non null values\n non_null = y_task != null_value\n smiles_list = list(compress(enumerate(smiles_list), non_null))\n else:\n non_null = np.ones(len(dataset)) == 1\n smiles_list = list(compress(enumerate(smiles_list), non_null))\n\n rng = np.random.RandomState(seed)\n\n scaffolds = defaultdict(list)\n for ind, smiles in smiles_list:\n scaffold = generate_scaffold(smiles, include_chirality=True)\n scaffolds[scaffold].append(ind)\n\n scaffold_sets = rng.permutation(list(scaffolds.values()))\n\n n_total_valid = int(np.floor(frac_valid * len(dataset)))\n n_total_test = int(np.floor(frac_test * len(dataset)))\n\n train_idx = []\n valid_idx = []\n test_idx = []\n\n for scaffold_set in scaffold_sets:\n if len(valid_idx) + len(scaffold_set) <= n_total_valid:\n valid_idx.extend(scaffold_set)\n elif len(test_idx) + len(scaffold_set) <= n_total_test:\n test_idx.extend(scaffold_set)\n else:\n train_idx.extend(scaffold_set)\n\n train_dataset = dataset[torch.tensor(train_idx)]\n valid_dataset = dataset[torch.tensor(valid_idx)]\n test_dataset = dataset[torch.tensor(test_idx)]\n\n return train_dataset, valid_dataset, test_dataset\n\n\ndef random_split(dataset, task_idx=None, null_value=0,\n frac_train=0.8, frac_valid=0.1, frac_test=0.1, seed=0,\n smiles_list=None):\n \"\"\"\n\n :param dataset:\n :param task_idx:\n :param null_value:\n :param frac_train:\n :param frac_valid:\n :param frac_test:\n :param seed:\n :param smiles_list: list of smiles corresponding to the dataset obj, or None\n :return: train, valid, test slices of the input dataset obj. If\n smiles_list != None, also returns ([train_smiles_list],\n [valid_smiles_list], [test_smiles_list])\n \"\"\"\n np.testing.assert_almost_equal(frac_train + frac_valid + frac_test, 1.0)\n\n if task_idx != None:\n # filter based on null values in task_idx\n # get task array\n y_task = np.array([data.y[task_idx].item() for data in dataset])\n non_null = y_task != null_value # boolean array that correspond to non null values\n idx_array = np.where(non_null)[0]\n dataset = dataset[torch.tensor(idx_array)] # examples containing non\n # null labels in the specified task_idx\n else:\n pass\n\n num_mols = len(dataset)\n random.seed(seed)\n all_idx = list(range(num_mols))\n random.shuffle(all_idx)\n\n train_idx = all_idx[:int(frac_train * num_mols)]\n valid_idx = all_idx[int(frac_train * num_mols):int(frac_valid * num_mols)\n + int(frac_train * num_mols)]\n test_idx = all_idx[int(frac_valid * num_mols) + int(frac_train * num_mols):]\n\n assert len(set(train_idx).intersection(set(valid_idx))) == 0\n assert len(set(valid_idx).intersection(set(test_idx))) == 0\n assert len(train_idx) + len(valid_idx) + len(test_idx) == num_mols\n\n train_dataset = dataset[torch.tensor(train_idx)]\n if frac_train <1.0:\n valid_dataset = dataset[torch.tensor(valid_idx)]\n test_dataset = dataset[torch.tensor(test_idx)]\n else:\n valid_dataset = dataset[torch.tensor(0)]\n test_dataset = dataset[torch.tensor(0)]\n\n if not smiles_list:\n return train_dataset, valid_dataset, test_dataset\n else:\n train_smiles = [smiles_list[i] for i in train_idx]\n valid_smiles = [smiles_list[i] for i in valid_idx]\n test_smiles = [smiles_list[i] for i in test_idx]\n return train_dataset, valid_dataset, test_dataset, (train_smiles,\n valid_smiles,\n test_smiles)\n\n\ndef cv_random_split(dataset, fold_idx=0,\n frac_train=0.9, frac_valid=0.1, seed=0,\n smiles_list=None):\n \"\"\"\n\n :param dataset:\n :param task_idx:\n :param null_value:\n :param frac_train:\n :param frac_valid:\n :param frac_test:\n :param seed:\n :param smiles_list: list of smiles corresponding to the dataset obj, or None\n :return: train, valid, test slices of the input dataset obj. If\n smiles_list != None, also returns ([train_smiles_list],\n [valid_smiles_list], [test_smiles_list])\n \"\"\"\n\n np.testing.assert_almost_equal(frac_train + frac_valid, 1.0)\n\n skf = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed)\n\n labels = [data.y.item() for data in dataset]\n\n idx_list = []\n\n for idx in skf.split(np.zeros(len(labels)), labels):\n idx_list.append(idx)\n train_idx, val_idx = idx_list[fold_idx]\n\n train_dataset = dataset[torch.tensor(train_idx)]\n valid_dataset = dataset[torch.tensor(val_idx)]\n\n return train_dataset, valid_dataset\n\n\nif __name__ == \"__main__\":\n from loader import MoleculeDataset\n from rdkit import Chem\n import pandas as pd\n\n # # test scaffold_split\n dataset = MoleculeDataset('dataset/tox21', dataset='tox21')\n smiles_list = pd.read_csv('dataset/tox21/processed/smiles.csv', header=None)[0].tolist()\n\n train_dataset, valid_dataset, test_dataset = scaffold_split(dataset, smiles_list, task_idx=None, null_value=0,\n frac_train=0.8, frac_valid=0.1, frac_test=0.1)\n # train_dataset, valid_dataset, test_dataset = random_scaffold_split(dataset, smiles_list, task_idx=None, null_value=0, frac_train=0.8,frac_valid=0.1, frac_test=0.1, seed = 0)\n unique_ids = set(train_dataset.data.id.tolist() +\n valid_dataset.data.id.tolist() +\n test_dataset.data.id.tolist())\n assert len(unique_ids) == len(dataset) # check that we did not have any\n # missing or overlapping examples\n\n # test scaffold_split with smiles returned\n dataset = MoleculeDataset('dataset/bbbp', dataset='bbbp')\n smiles_list = pd.read_csv('dataset/bbbp/processed/smiles.csv', header=None)[\n 0].tolist()\n train_dataset, valid_dataset, test_dataset, (train_smiles, valid_smiles,\n test_smiles) = \\\n scaffold_split(dataset, smiles_list, task_idx=None, null_value=0,\n frac_train=0.8, frac_valid=0.1, frac_test=0.1,\n return_smiles=True)\n assert len(train_dataset) == len(train_smiles)\n for i in range(len(train_dataset)):\n data_obj_n_atoms = train_dataset[i].x.size()[0]\n smiles_n_atoms = len(list(Chem.MolFromSmiles(train_smiles[\n i]).GetAtoms()))\n assert data_obj_n_atoms == smiles_n_atoms\n assert len(valid_dataset) == len(valid_smiles)\n for i in range(len(valid_dataset)):\n data_obj_n_atoms = valid_dataset[i].x.size()[0]\n smiles_n_atoms = len(list(Chem.MolFromSmiles(valid_smiles[\n i]).GetAtoms()))\n assert data_obj_n_atoms == smiles_n_atoms\n assert len(test_dataset) == len(test_smiles)\n for i in range(len(test_dataset)):\n data_obj_n_atoms = test_dataset[i].x.size()[0]\n smiles_n_atoms = len(list(Chem.MolFromSmiles(test_smiles[\n i]).GetAtoms()))\n assert data_obj_n_atoms == smiles_n_atoms\n\n # test random_split\n from loader import MoleculeDataset\n\n dataset = MoleculeDataset('dataset/tox21', dataset='tox21')\n train_dataset, valid_dataset, test_dataset = random_split(dataset, task_idx=None, null_value=0, frac_train=0.8,\n frac_valid=0.1, frac_test=0.1)\n unique_ids = set(train_dataset.data.id.tolist() +\n valid_dataset.data.id.tolist() +\n test_dataset.data.id.tolist())\n assert len(unique_ids) == len(dataset) # check that we did not have any\n # missing or overlapping examples\n\n # test random_split with smiles returned\n dataset = MoleculeDataset('dataset/bbbp', dataset='bbbp')\n smiles_list = pd.read_csv('dataset/bbbp/processed/smiles.csv', header=None)[\n 0].tolist()\n train_dataset, valid_dataset, test_dataset, (train_smiles, valid_smiles,\n test_smiles) = \\\n random_split(dataset, task_idx=None, null_value=0,\n frac_train=0.8, frac_valid=0.1, frac_test=0.1, seed=42,\n smiles_list=smiles_list)\n assert len(train_dataset) == len(train_smiles)\n for i in range(len(train_dataset)):\n data_obj_n_atoms = train_dataset[i].x.size()[0]\n smiles_n_atoms = len(list(Chem.MolFromSmiles(train_smiles[\n i]).GetAtoms()))\n assert data_obj_n_atoms == smiles_n_atoms\n assert len(valid_dataset) == len(valid_smiles)\n for i in range(len(valid_dataset)):\n data_obj_n_atoms = valid_dataset[i].x.size()[0]\n smiles_n_atoms = len(list(Chem.MolFromSmiles(valid_smiles[\n i]).GetAtoms()))\n assert data_obj_n_atoms == smiles_n_atoms\n assert len(test_dataset) == len(test_smiles)\n for i in range(len(test_dataset)):\n data_obj_n_atoms = test_dataset[i].x.size()[0]\n smiles_n_atoms = len(list(Chem.MolFromSmiles(test_smiles[\n i]).GetAtoms()))\n assert data_obj_n_atoms == smiles_n_atoms\n" ]
[ [ "pandas.read_csv", "sklearn.model_selection.StratifiedKFold", "torch.tensor", "numpy.testing.assert_almost_equal", "numpy.random.RandomState", "numpy.where" ] ]
kornia/limbus
[ "4ff4f60dc9627199175592dc826b1f54e8a7eab3" ]
[ "tests/core/test_component.py" ]
[ "from numpy import isin\nimport pytest\nimport typing\n\nimport limbus.core.component\nfrom limbus.core import Params, Component, Pipeline, NoValue\nfrom limbus.core.component import Container, Param, IterableContainer, IterableInputContainers, IterableParam\nimport torch\n\n\nclass TestContainer:\n def test_smoke(self):\n v = Container(None)\n assert isinstance(v, Container)\n assert v.value is None\n\n\nclass TestIterableContainer:\n def test_smoke(self):\n c = IterableContainer(Container(None), 0)\n assert isinstance(c, IterableContainer)\n assert isinstance(c.container, Container)\n assert c.index == 0\n assert c.container.value is None\n # None is not a valid value inside the container. This is not controlled by the container.\n with pytest.raises(TypeError):\n c.value\n\n def test_value(self):\n c = IterableContainer(Container([1, 2]), 0)\n assert c.value == 1\n assert c.index == 0\n assert c.container.value == [1, 2]\n\n\nclass TestIterableInputContainers:\n def test_smoke(self):\n c = IterableInputContainers()\n assert isinstance(c, IterableInputContainers)\n assert c._containers == []\n\n def test_init_with_container(self):\n ic = IterableContainer(Container(None), 0)\n c = IterableInputContainers(ic)\n assert c._containers[0] is ic\n assert len(c) == 1\n\n def test_add(self):\n ic0 = IterableContainer(Container(None), 0)\n ic1 = IterableContainer(Container(None), 1)\n c = IterableInputContainers()\n c.add(ic0)\n c.add(ic1)\n assert c._containers[0] is ic0\n assert c._containers[1] is ic1\n assert len(c) == 2\n\n def test_remove(self):\n ic = IterableContainer(Container(None), 0)\n c = IterableInputContainers()\n c.add(ic)\n assert len(c) == 1\n c.remove(0)\n assert len(c) == 0\n\n def test_remove_not_found(self):\n ic = IterableContainer(Container(None), 0)\n c = IterableInputContainers()\n c.add(ic)\n assert len(c) == 1\n c.remove(1)\n assert len(c) == 1\n\n def test_get_ordered(self):\n ic0 = IterableContainer(Container(1), 0)\n ic1 = IterableContainer(Container(2), 1)\n c = IterableInputContainers()\n c.add(ic1)\n c.add(ic0)\n\n res = c.get_ordered()\n assert len(res) == 2\n assert res[0] == 1\n assert res[1] == 2\n\n def test_get_ordered_iterable(self):\n ic0 = IterableContainer(IterableContainer(Container([1, 2]), 1), 0)\n ic1 = IterableContainer(Container(3), 1)\n c = IterableInputContainers()\n c.add(ic1)\n c.add(ic0)\n\n res = c.get_ordered()\n assert len(res) == 2\n assert res[0] == 2\n assert res[1] == 3\n\n\nclass TestParam:\n def test_smoke(self):\n p = Param(\"a\")\n assert isinstance(p, Param)\n assert p.name == \"a\"\n assert p.type is typing.Any\n assert isinstance(p.value, NoValue)\n assert p.references == set()\n assert p.arg is None\n assert p._is_subscriptable is False\n\n def test_init_with_type(self):\n p = Param(\"a\", tp=int)\n assert p.type is int\n assert isinstance(p.value, NoValue)\n\n def test_init_with_value(self):\n p = Param(\"a\", tp=int, value=1)\n assert p.value == 1\n\n def test_init_with_arg(self):\n p = Param(\"a\", arg=\"arg0\")\n assert p.arg == \"arg0\"\n\n def test_set_value(self):\n p = Param(\"a\", tp=int, value=1)\n p.value = 2\n assert p.value == 2\n with pytest.raises(TypeError):\n p.value = \"a\"\n\n def test_get_iterable_value(self):\n iter_container = IterableContainer(Container([1, 2]), 0)\n p = Param(\"a\", value=iter_container)\n assert isinstance(p.container, Container)\n assert p.container.value is iter_container\n assert p.value == 1\n\n def test_get_iterable_input_value(self):\n p = Param(\"a\", tp=typing.List[int])\n p.container = IterableInputContainers(IterableContainer(Container(1), 1))\n p.container.add(IterableContainer(Container(2), 0))\n assert p.value == [2, 1]\n\n def test_select(self):\n p = Param(\"a\", typing.List[int], value=[1, 2])\n assert p._is_subscriptable\n iter_param = p.select(0)\n assert isinstance(iter_param, IterableParam)\n assert isinstance(iter_param.iter_container, IterableContainer)\n assert iter_param.iter_container.index == 0\n assert iter_param.iter_container.value == 1\n\n def test_connect_iterparam_param_no_select_raise_error(self):\n p0 = Param(\"a\", typing.List[int])\n p1 = Param(\"b\")\n with pytest.raises(ValueError):\n # mandatory connect with an index\n p0.connect(p1)\n p0.select(0).connect(p1)\n\n def test_connect_param_iterparam_no_select_raise_error(self):\n p0 = Param(\"a\", tp=typing.List[int])\n p1 = Param(\"b\", value=2)\n with pytest.raises(ValueError):\n # mandatory connect with an index\n p1.connect(p0)\n p1.connect(p0.select(0))\n\n def test_connect_param_param(self):\n p0 = Param(\"a\", value=1)\n p1 = Param(\"b\")\n p0.connect(p1)\n assert isinstance(p1.container, Container)\n assert p1.value == 1\n assert list(p0._refs.keys()) == [None]\n assert list(p0._refs[None]) == [(p1, None)]\n assert list(p1._refs.keys()) == [None]\n assert list(p1._refs[None]) == [(p0, None)]\n\n def test_disconnect_param_param(self):\n p0 = Param(\"a\", value=1)\n p1 = Param(\"b\")\n p0.connect(p1)\n p0.disconnect(p1)\n assert isinstance(p1.container, Container)\n assert isinstance(p1.value, NoValue)\n assert list(p0._refs.keys()) == [None]\n assert list(p0._refs[None]) == []\n assert list(p1._refs.keys()) == [None]\n assert list(p1._refs[None]) == []\n\n def test_connect_disconnect_iterparam_param(self):\n p0 = Param(\"a\", tp=typing.List[int], value=[1, 2])\n p1 = Param(\"b\")\n p0.select(1).connect(p1)\n assert isinstance(p1.container, Container)\n assert p1.value == 2\n assert list(p0._refs.keys()) == [1]\n assert list(p0._refs[1]) == [(p1, None)]\n assert list(p1._refs.keys()) == [None]\n assert list(p1._refs[None]) == [(p0, 1)]\n\n def test_disconnect_iterparam_param(self):\n p0 = Param(\"a\", tp=typing.List[int], value=[1, 2])\n p1 = Param(\"b\")\n p0.select(1).connect(p1)\n p0.select(1).disconnect(p1)\n assert isinstance(p1.container, Container)\n assert isinstance(p1.value, NoValue)\n assert list(p0._refs.keys()) == [1]\n assert list(p0._refs[1]) == []\n assert list(p1._refs.keys()) == [None]\n assert list(p1._refs[None]) == []\n\n def test_connect_param_iterparam(self):\n p0 = Param(\"a\", tp=typing.List[int])\n p1 = Param(\"b\", value=1)\n p2 = Param(\"c\", value=2)\n p1.connect(p0.select(1))\n p2.connect(p0.select(0))\n assert isinstance(p0.container, IterableInputContainers)\n assert p0.value == [2, 1]\n assert sorted(list(p0._refs.keys())) == sorted([0, 1])\n assert list(p0._refs[0]) == [(p2, None)]\n assert list(p0._refs[1]) == [(p1, None)]\n assert list(p1._refs.keys()) == [None]\n assert list(p1._refs[None]) == [(p0, 1)]\n assert list(p2._refs.keys()) == [None]\n assert list(p2._refs[None]) == [(p0, 0)]\n\n def test_disconnect_param_iterparam(self):\n p0 = Param(\"a\", tp=typing.List[int])\n p1 = Param(\"b\", value=1)\n p2 = Param(\"c\", value=2)\n p1.connect(p0.select(1))\n p2.connect(p0.select(0))\n p1.disconnect(p0.select(1))\n p2.disconnect(p0.select(0))\n assert isinstance(p0.container, Container)\n assert isinstance(p0.value, NoValue)\n assert sorted(list(p0._refs.keys())) == sorted([0, 1])\n assert list(p0._refs[0]) == []\n assert list(p0._refs[1]) == []\n assert list(p1._refs.keys()) == [None]\n assert list(p1._refs[None]) == []\n assert list(p2._refs.keys()) == [None]\n assert list(p2._refs[None]) == []\n\n def test_connect_iterparam_iterparam(self):\n p0 = Param(\"a\", tp=typing.List[int], value=[1, 2])\n p1 = Param(\"b\", tp=typing.List[int])\n p0.select(0).connect(p1.select(1))\n p0.select(1).connect(p1.select(0))\n assert isinstance(p1.container, IterableInputContainers)\n assert p1.value == [2, 1]\n assert sorted(list(p0._refs.keys())) == sorted([0, 1])\n assert list(p0._refs[0]) == [(p1, 1)]\n assert list(p0._refs[1]) == [(p1, 0)]\n assert sorted(list(p1._refs.keys())) == sorted([0, 1])\n assert list(p1._refs[0]) == [(p0, 1)]\n assert list(p1._refs[1]) == [(p0, 0)]\n\n def test_disconnect_iterparam_iterparam(self):\n p0 = Param(\"a\", tp=typing.List[int], value=[1, 2])\n p1 = Param(\"b\", tp=typing.List[int])\n p0.select(0).connect(p1.select(1))\n p0.select(1).connect(p1.select(0))\n p0.select(0).disconnect(p1.select(1))\n p0.select(1).disconnect(p1.select(0))\n assert isinstance(p1.container, Container)\n assert isinstance(p1.value, NoValue)\n assert sorted(list(p0._refs.keys())) == sorted([0, 1])\n assert list(p0._refs[0]) == []\n assert list(p0._refs[1]) == []\n assert sorted(list(p1._refs.keys())) == sorted([0, 1])\n assert list(p1._refs[0]) == []\n assert list(p1._refs[1]) == []\n\n def test_ref_count(self):\n p0 = Param(\"a\")\n p1 = Param(\"b\")\n p2 = Param(\"c\")\n p0.connect(p1)\n p0.connect(p2)\n assert p1.ref_counter(None) == 1\n assert p0.ref_counter(None) == 2\n assert p2.ref_counter(None) == 1\n\n def test_ref_counter(self):\n p0 = Param(\"a\")\n p1 = Param(\"b\")\n p2 = Param(\"c\")\n p0.connect(p1)\n p0.connect(p2)\n assert p1.ref_counter() == 1\n assert p0.ref_counter() == 2\n assert p2.ref_counter() == 1\n assert p1.ref_counter(None) == 1\n assert p0.ref_counter(None) == 2\n assert p2.ref_counter(None) == 1\n\n def test_ref_counter_iterable(self):\n p0 = Param(\"a\", typing.List[int], value=[1, 2])\n p1 = Param(\"b\")\n p2 = Param(\"c\")\n p0.select(0).connect(p1)\n p0.select(1).connect(p2)\n assert p1.ref_counter() == 1\n assert p2.ref_counter() == 1\n assert p0.ref_counter() == 2\n assert p0.ref_counter(0) == 1\n assert p0.ref_counter(1) == 1\n\n\nclass TestIterableParam:\n def test_smoke(self):\n p = Param(\"a\", tp=typing.List[int], value=[1, 2])\n ip = IterableParam(p, 0)\n assert ip.param is p\n assert ip.index == 0\n assert ip.value == 1\n assert isinstance(ip.iter_container, IterableContainer)\n assert ip.iter_container.index == 0\n assert ip.iter_container.value == 1\n\n def test_ref_counter(self):\n p0 = Param(\"a\", tp=typing.List[int], value=[1, 2])\n ip = IterableParam(p0, 0)\n assert ip.ref_counter() == 0\n p1 = Param(\"b\", tp=int)\n ip.connect(p1)\n assert ip.ref_counter() == 1\n\n\nclass TestParams:\n def test_smoke(self):\n p = Params()\n assert p is not None\n\n def test_declare(self):\n p = Params()\n\n with pytest.raises(AttributeError):\n p.x\n\n p.declare(\"x\")\n assert isinstance(p.x.value, NoValue)\n assert isinstance(p.get_param(\"x\"), NoValue)\n\n p.declare(\"y\", float, 1.)\n assert p.y.value == 1.\n assert p[\"y\"].value == 1.\n assert p.get_param(\"y\") == 1.\n assert isinstance(p[\"y\"], Param)\n assert isinstance(p.y, Param)\n assert isinstance(p[\"y\"].value, float)\n assert p[\"y\"].type == float\n assert p[\"y\"].name == \"y\"\n assert p[\"y\"].arg is None\n\n def test_tensor(self):\n p1 = Params()\n p2 = Params()\n\n p1.declare(\"x\", torch.Tensor, torch.tensor(1.))\n assert isinstance(p1[\"x\"].value, torch.Tensor)\n\n p2.declare(\"y\", torch.Tensor, p1.x)\n assert p1.x.value == p2.y.value\n\n\nclass TestComponent:\n def test_smoke(self):\n cmp = Component(\"yuhu\")\n assert cmp.name == \"yuhu\"\n assert cmp.inputs is not None\n assert cmp.outputs is not None\n\n\ndef test_check_subscriptable():\n assert limbus.core.component._check_subscriptable(typing.Sequence[int])\n assert limbus.core.component._check_subscriptable(typing.Iterable[int])\n assert limbus.core.component._check_subscriptable(typing.List[int])\n assert limbus.core.component._check_subscriptable(typing.Tuple[int])\n assert not limbus.core.component._check_subscriptable(int)\n assert not limbus.core.component._check_subscriptable(torch.Tensor)\n assert not limbus.core.component._check_subscriptable(str)\n" ]
[ [ "torch.tensor" ] ]
AlexShypula/preTrainingJoeynmt
[ "bf426c79a8625f259e1a44b04ca8e255ac880b3c" ]
[ "joeynmt/decoders.py" ]
[ "# coding: utf-8\n\n\"\"\"\nVarious decoders\n\"\"\"\nfrom typing import Optional\n\nimport torch\nimport torch.nn as nn\nfrom torch import Tensor\nfrom joeynmt.attention import BahdanauAttention, LuongAttention\nfrom joeynmt.encoders import Encoder\nfrom joeynmt.helpers import freeze_params, ConfigurationError, subsequent_mask\nfrom joeynmt.transformer_layers import PositionalEncoding, \\\n TransformerDecoderLayer\n\n\n# pylint: disable=abstract-method\nclass Decoder(nn.Module):\n \"\"\"\n Base decoder class\n \"\"\"\n\n @property\n def output_size(self):\n \"\"\"\n Return the output size (size of the target vocabulary)\n\n :return:\n \"\"\"\n return self._output_size\n\n\n# pylint: disable=arguments-differ,too-many-arguments\n# pylint: disable=too-many-instance-attributes, unused-argument\nclass RecurrentDecoder(Decoder):\n \"\"\"A conditional RNN decoder with attention.\"\"\"\n\n def __init__(self,\n rnn_type: str = \"gru\",\n emb_size: int = 0,\n hidden_size: int = 0,\n encoder: Encoder = None,\n attention: str = \"bahdanau\",\n num_layers: int = 1,\n vocab_size: int = 0,\n dropout: float = 0.,\n emb_dropout: float = 0.,\n hidden_dropout: float = 0.,\n init_hidden: str = \"bridge\",\n input_feeding: bool = True,\n freeze: bool = False,\n **kwargs) -> None:\n \"\"\"\n Create a recurrent decoder with attention.\n\n :param rnn_type: rnn type, valid options: \"lstm\", \"gru\"\n :param emb_size: target embedding size\n :param hidden_size: size of the RNN\n :param encoder: encoder connected to this decoder\n :param attention: type of attention, valid options: \"bahdanau\", \"luong\"\n :param num_layers: number of recurrent layers\n :param vocab_size: target vocabulary size\n :param hidden_dropout: Is applied to the input to the attentional layer.\n :param dropout: Is applied between RNN layers.\n :param emb_dropout: Is applied to the RNN input (word embeddings).\n :param init_hidden: If \"bridge\" (default), the decoder hidden states are\n initialized from a projection of the last encoder state,\n if \"zeros\" they are initialized with zeros,\n if \"last\" they are identical to the last encoder state\n (only if they have the same size)\n :param input_feeding: Use Luong's input feeding.\n :param freeze: Freeze the parameters of the decoder during training.\n :param kwargs:\n \"\"\"\n\n super(RecurrentDecoder, self).__init__()\n\n self.emb_dropout = torch.nn.Dropout(p=emb_dropout, inplace=False)\n self.type = rnn_type\n self.hidden_dropout = torch.nn.Dropout(p=hidden_dropout, inplace=False)\n self.hidden_size = hidden_size\n self.emb_size = emb_size\n\n rnn = nn.GRU if rnn_type == \"gru\" else nn.LSTM\n\n self.input_feeding = input_feeding\n if self.input_feeding: # Luong-style\n # combine embedded prev word +attention vector before feeding to rnn\n self.rnn_input_size = emb_size + hidden_size\n else:\n # just feed prev word embedding\n self.rnn_input_size = emb_size\n\n # the decoder RNN\n self.rnn = rnn(self.rnn_input_size, hidden_size, num_layers,\n batch_first=True,\n dropout=dropout if num_layers > 1 else 0.)\n\n # combine output with context vector before output layer (Luong-style)\n self.att_vector_layer = nn.Linear(\n hidden_size + encoder.output_size, hidden_size, bias=True)\n\n self.output_layer = nn.Linear(hidden_size, vocab_size, bias=False)\n self._output_size = vocab_size\n\n if attention == \"bahdanau\":\n self.attention = BahdanauAttention(hidden_size=hidden_size,\n key_size=encoder.output_size,\n query_size=hidden_size)\n elif attention == \"luong\":\n self.attention = LuongAttention(hidden_size=hidden_size,\n key_size=encoder.output_size)\n else:\n raise ConfigurationError(\"Unknown attention mechanism: %s. \"\n \"Valid options: 'bahdanau', 'luong'.\"\n % attention)\n\n self.num_layers = num_layers\n self.hidden_size = hidden_size\n\n # to initialize from the final encoder state of last layer\n self.init_hidden_option = init_hidden\n if self.init_hidden_option == \"bridge\":\n self.bridge_layer = nn.Linear(\n encoder.output_size, hidden_size, bias=True)\n elif self.init_hidden_option == \"last\":\n if encoder.output_size != self.hidden_size:\n if encoder.output_size != 2*self.hidden_size: # bidirectional\n raise ConfigurationError(\n \"For initializing the decoder state with the \"\n \"last encoder state, their sizes have to match \"\n \"(encoder: {} vs. decoder: {})\".format(\n encoder.output_size, self.hidden_size))\n if freeze:\n freeze_params(self)\n\n def _check_shapes_input_forward_step(self,\n prev_embed: Tensor,\n prev_att_vector: Tensor,\n encoder_output: Tensor,\n src_mask: Tensor,\n hidden: Tensor) -> None:\n \"\"\"\n Make sure the input shapes to `self._forward_step` are correct.\n Same inputs as `self._forward_step`.\n\n :param prev_embed:\n :param prev_att_vector:\n :param encoder_output:\n :param src_mask:\n :param hidden:\n \"\"\"\n assert prev_embed.shape[1:] == torch.Size([1, self.emb_size])\n assert prev_att_vector.shape[1:] == torch.Size(\n [1, self.hidden_size])\n assert prev_att_vector.shape[0] == prev_embed.shape[0]\n assert encoder_output.shape[0] == prev_embed.shape[0]\n assert len(encoder_output.shape) == 3\n assert src_mask.shape[0] == prev_embed.shape[0]\n assert src_mask.shape[1] == 1\n assert src_mask.shape[2] == encoder_output.shape[1]\n if isinstance(hidden, tuple): # for lstm\n hidden = hidden[0]\n assert hidden.shape[0] == self.num_layers\n assert hidden.shape[1] == prev_embed.shape[0]\n assert hidden.shape[2] == self.hidden_size\n\n def _check_shapes_input_forward(self,\n trg_embed: Tensor,\n encoder_output: Tensor,\n encoder_hidden: Tensor,\n src_mask: Tensor,\n hidden: Tensor = None,\n prev_att_vector: Tensor = None) -> None:\n \"\"\"\n Make sure that inputs to `self.forward` are of correct shape.\n Same input semantics as for `self.forward`.\n\n :param trg_embed:\n :param encoder_output:\n :param encoder_hidden:\n :param src_mask:\n :param hidden:\n :param prev_att_vector:\n \"\"\"\n assert len(encoder_output.shape) == 3\n #assert len(encoder_hidden.shape) == 2\n #assert encoder_hidden.shape[-1] == encoder_output.shape[-1]\n assert src_mask.shape[1] == 1\n assert src_mask.shape[0] == encoder_output.shape[0]\n assert src_mask.shape[2] == encoder_output.shape[1]\n assert trg_embed.shape[0] == encoder_output.shape[0]\n assert trg_embed.shape[2] == self.emb_size\n if hidden is not None:\n if isinstance(hidden, tuple): # for lstm\n hidden = hidden[0]\n assert hidden.shape[1] == encoder_output.shape[0]\n assert hidden.shape[2] == self.hidden_size\n if prev_att_vector is not None:\n assert prev_att_vector.shape[0] == encoder_output.shape[0]\n assert prev_att_vector.shape[2] == self.hidden_size\n assert prev_att_vector.shape[1] == 1\n\n def _forward_step(self,\n prev_embed: Tensor,\n prev_att_vector: Tensor, # context or att vector\n encoder_output: Tensor,\n src_mask: Tensor,\n hidden: Tensor) -> (Tensor, Tensor, Tensor):\n \"\"\"\n Perform a single decoder step (1 token).\n\n 1. `rnn_input`: concat(prev_embed, prev_att_vector [possibly empty])\n 2. update RNN with `rnn_input`\n 3. calculate attention and context/attention vector\n\n :param prev_embed: embedded previous token,\n shape (batch_size, 1, embed_size)\n :param prev_att_vector: previous attention vector,\n shape (batch_size, 1, hidden_size)\n :param encoder_output: encoder hidden states for attention context,\n shape (batch_size, src_length, encoder.output_size)\n :param src_mask: src mask, 1s for area before <eos>, 0s elsewhere\n shape (batch_size, 1, src_length)\n :param hidden: previous hidden state,\n shape (num_layers, batch_size, hidden_size)\n :return:\n - att_vector: new attention vector (batch_size, 1, hidden_size),\n - hidden: new hidden state with shape (batch_size, 1, hidden_size),\n - att_probs: attention probabilities (batch_size, 1, src_len)\n \"\"\"\n\n # shape checks\n self._check_shapes_input_forward_step(prev_embed=prev_embed,\n prev_att_vector=prev_att_vector,\n encoder_output=encoder_output,\n src_mask=src_mask,\n hidden=hidden)\n\n if self.input_feeding:\n # concatenate the input with the previous attention vector\n rnn_input = torch.cat([prev_embed, prev_att_vector], dim=2)\n else:\n rnn_input = prev_embed\n\n rnn_input = self.emb_dropout(rnn_input)\n\n # rnn_input: batch x 1 x emb+2*enc_size\n _, hidden = self.rnn(rnn_input, hidden)\n\n # use new (top) decoder layer as attention query\n if isinstance(hidden, tuple):\n query = hidden[0][-1].unsqueeze(1)\n else:\n query = hidden[-1].unsqueeze(1) # [#layers, B, D] -> [B, 1, D]\n\n # compute context vector using attention mechanism\n # only use last layer for attention mechanism\n # key projections are pre-computed\n context, att_probs = self.attention(\n query=query, values=encoder_output, mask=src_mask)\n\n # return attention vector (Luong)\n # combine context with decoder hidden state before prediction\n att_vector_input = torch.cat([query, context], dim=2)\n # batch x 1 x 2*enc_size+hidden_size\n att_vector_input = self.hidden_dropout(att_vector_input)\n\n att_vector = torch.tanh(self.att_vector_layer(att_vector_input))\n\n # output: batch x 1 x hidden_size\n return att_vector, hidden, att_probs\n\n def forward(self,\n trg_embed: Tensor,\n encoder_output: Tensor,\n encoder_hidden: Tensor,\n src_mask: Tensor,\n unroll_steps: int,\n hidden: Tensor = None,\n prev_att_vector: Tensor = None,\n **kwargs) \\\n -> (Tensor, Tensor, Tensor, Tensor):\n \"\"\"\n Unroll the decoder one step at a time for `unroll_steps` steps.\n For every step, the `_forward_step` function is called internally.\n\n During training, the target inputs (`trg_embed') are already known for\n the full sequence, so the full unrol is done.\n In this case, `hidden` and `prev_att_vector` are None.\n\n For inference, this function is called with one step at a time since\n embedded targets are the predictions from the previous time step.\n In this case, `hidden` and `prev_att_vector` are fed from the output\n of the previous call of this function (from the 2nd step on).\n\n `src_mask` is needed to mask out the areas of the encoder states that\n should not receive any attention,\n which is everything after the first <eos>.\n\n The `encoder_output` are the hidden states from the encoder and are\n used as context for the attention.\n\n The `encoder_hidden` is the last encoder hidden state that is used to\n initialize the first hidden decoder state\n (when `self.init_hidden_option` is \"bridge\" or \"last\").\n\n :param trg_embed: emdedded target inputs,\n shape (batch_size, trg_length, embed_size)\n :param encoder_output: hidden states from the encoder,\n shape (batch_size, src_length, encoder.output_size)\n :param encoder_hidden: last state from the encoder,\n shape (batch_size x encoder.output_size)\n :param src_mask: mask for src states: 0s for padded areas,\n 1s for the rest, shape (batch_size, 1, src_length)\n :param unroll_steps: number of steps to unrol the decoder RNN\n :param hidden: previous decoder hidden state,\n if not given it's initialized as in `self.init_hidden`,\n shape (num_layers, batch_size, hidden_size)\n :param prev_att_vector: previous attentional vector,\n if not given it's initialized with zeros,\n shape (batch_size, 1, hidden_size)\n :return:\n - outputs: shape (batch_size, unroll_steps, vocab_size),\n - hidden: last hidden state (num_layers, batch_size, hidden_size),\n - att_probs: attention probabilities\n with shape (batch_size, unroll_steps, src_length),\n - att_vectors: attentional vectors\n with shape (batch_size, unroll_steps, hidden_size)\n \"\"\"\n\n # shape checks\n self._check_shapes_input_forward(\n trg_embed=trg_embed,\n encoder_output=encoder_output,\n encoder_hidden=encoder_hidden,\n src_mask=src_mask,\n hidden=hidden,\n prev_att_vector=prev_att_vector)\n\n # initialize decoder hidden state from final encoder hidden state\n if hidden is None:\n hidden = self._init_hidden(encoder_hidden, batch_size = encoder_output.size(0))\n\n # pre-compute projected encoder outputs\n # (the \"keys\" for the attention mechanism)\n # this is only done for efficiency\n if hasattr(self.attention, \"compute_proj_keys\"):\n self.attention.compute_proj_keys(keys=encoder_output)\n\n # here we store all intermediate attention vectors (used for prediction)\n att_vectors = []\n att_probs = []\n\n batch_size = encoder_output.size(0)\n\n if prev_att_vector is None:\n with torch.no_grad():\n prev_att_vector = encoder_output.new_zeros(\n [batch_size, 1, self.hidden_size])\n\n # unroll the decoder RNN for `unroll_steps` steps\n for i in range(unroll_steps):\n prev_embed = trg_embed[:, i].unsqueeze(1) # batch, 1, emb\n prev_att_vector, hidden, att_prob = self._forward_step(\n prev_embed=prev_embed,\n prev_att_vector=prev_att_vector,\n encoder_output=encoder_output,\n src_mask=src_mask,\n hidden=hidden)\n att_vectors.append(prev_att_vector)\n att_probs.append(att_prob)\n\n att_vectors = torch.cat(att_vectors, dim=1)\n # att_vectors: batch, unroll_steps, hidden_size\n att_probs = torch.cat(att_probs, dim=1)\n # att_probs: batch, unroll_steps, src_length\n outputs = self.output_layer(att_vectors)\n # outputs: batch, unroll_steps, vocab_size\n return outputs, hidden, att_probs, att_vectors\n\n def _init_hidden(self, encoder_final: Tensor = None, batch_size = 0) \\\n -> (Tensor, Optional[Tensor]):\n \"\"\"\n Returns the initial decoder state,\n conditioned on the final encoder state of the last encoder layer.\n\n In case of `self.init_hidden_option == \"bridge\"`\n and a given `encoder_final`, this is a projection of the encoder state.\n\n In case of `self.init_hidden_option == \"last\"`\n and a size-matching `encoder_final`, this is set to the encoder state.\n If the encoder is twice as large as the decoder state (e.g. when\n bi-directional), just use the forward hidden state.\n\n In case of `self.init_hidden_option == \"zero\"`, it is initialized with\n zeros.\n\n For LSTMs we initialize both the hidden state and the memory cell\n with the same projection/copy of the encoder hidden state.\n\n All decoder layers are initialized with the same initial values.\n\n :param encoder_final: final state from the last layer of the encoder,\n shape (batch_size, encoder_hidden_size)\n :return: hidden state if GRU, (hidden state, memory cell) if LSTM,\n shape (batch_size, hidden_size)\n \"\"\"\n batch_size = encoder_final.size(0) if encoder_final else batch_size\n\n # for multiple layers: is the same for all layers\n if self.init_hidden_option == \"bridge\" and encoder_final is not None:\n # num_layers x batch_size x hidden_size\n hidden = torch.tanh(\n self.bridge_layer(encoder_final)).unsqueeze(0).repeat(\n self.num_layers, 1, 1)\n elif self.init_hidden_option == \"last\" and encoder_final is not None:\n # special case: encoder is bidirectional: use only forward state\n if encoder_final.shape[1] == 2*self.hidden_size: # bidirectional\n encoder_final = encoder_final[:, :self.hidden_size]\n hidden = encoder_final.unsqueeze(0).repeat(self.num_layers, 1, 1)\n else: # initialize with zeros\n with torch.no_grad():\n #hidden = encoder_final.new_zeros(\n # self.num_layers, batch_size, self.hidden_size)\n hidden = torch.zeros(self.num_layers, batch_size, self.hidden_size).cuda() \n\n return (hidden, hidden) if isinstance(self.rnn, nn.LSTM) else hidden\n\n def __repr__(self):\n return \"RecurrentDecoder(rnn=%r, attention=%r)\" % (\n self.rnn, self.attention)\n\n\n# pylint: disable=arguments-differ,too-many-arguments\n# pylint: disable=too-many-instance-attributes, unused-argument\nclass TransformerDecoder(Decoder):\n \"\"\"\n A transformer decoder with N masked layers.\n Decoder layers are masked so that an attention head cannot see the future.\n \"\"\"\n\n def __init__(self,\n num_layers: int = 4,\n num_heads: int = 8,\n hidden_size: int = 512,\n ff_size: int = 2048,\n dropout: float = 0.1,\n emb_dropout: float = 0.1,\n vocab_size: int = 1,\n freeze: bool = False,\n **kwargs):\n \"\"\"\n Initialize a Transformer decoder.\n\n :param num_layers: number of Transformer layers\n :param num_heads: number of heads for each layer\n :param hidden_size: hidden size\n :param ff_size: position-wise feed-forward size\n :param dropout: dropout probability (1-keep)\n :param emb_dropout: dropout probability for embeddings\n :param vocab_size: size of the output vocabulary\n :param freeze: set to True keep all decoder parameters fixed\n :param kwargs:\n \"\"\"\n super(TransformerDecoder, self).__init__()\n\n self._hidden_size = hidden_size\n self._output_size = vocab_size\n\n # create num_layers decoder layers and put them in a list\n self.layers = nn.ModuleList([TransformerDecoderLayer(\n size=hidden_size, ff_size=ff_size, num_heads=num_heads,\n dropout=dropout) for _ in range(num_layers)])\n\n self.pe = PositionalEncoding(hidden_size)\n self.layer_norm = nn.LayerNorm(hidden_size, eps=1e-6)\n\n self.emb_dropout = nn.Dropout(p=emb_dropout)\n self.output_layer = nn.Linear(hidden_size, vocab_size, bias=False)\n\n if freeze:\n freeze_params(self)\n\n def forward(self,\n trg_embed: Tensor = None,\n encoder_output: Tensor = None,\n encoder_hidden: Tensor = None,\n src_mask: Tensor = None,\n unroll_steps: int = None,\n hidden: Tensor = None,\n trg_mask: Tensor = None,\n **kwargs):\n \"\"\"\n Transformer decoder forward pass.\n\n :param trg_embed: embedded targets\n :param encoder_output: source representations\n :param encoder_hidden: unused\n :param src_mask:\n :param unroll_steps: unused\n :param hidden: unused\n :param trg_mask: to mask out target paddings\n Note that a subsequent mask is applied here.\n :param kwargs:\n :return:\n \"\"\"\n assert trg_mask is not None, \"trg_mask required for Transformer\"\n\n x = self.pe(trg_embed) # add position encoding to word embedding\n x = self.emb_dropout(x)\n\n trg_mask = trg_mask & subsequent_mask(\n trg_embed.size(1)).type_as(trg_mask)\n\n for layer in self.layers:\n x = layer(x=x, memory=encoder_output,\n src_mask=src_mask, trg_mask=trg_mask)\n\n x = self.layer_norm(x)\n output = self.output_layer(x)\n\n return output, x, None, None\n\n def __repr__(self):\n return \"%s(num_layers=%r, num_heads=%r)\" % (\n self.__class__.__name__, len(self.layers),\n self.layers[0].trg_trg_att.num_heads)\n" ]
[ [ "torch.Size", "torch.nn.Dropout", "torch.cat", "torch.zeros", "torch.nn.LayerNorm", "torch.nn.Linear", "torch.no_grad" ] ]
tracholar/economics-data
[ "bdb85d6baa663f7df0cf1193177f02a80aec407f" ]
[ "fund/analysis/plot_acc_net_value.py" ]
[ "# coding:utf-8\n# 绘制基金净值图\nfrom __future__ import print_function\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom fund.fund_info import get_fund_acc_net_value_by_time\nfrom os.path import dirname\n\n__ROOT__ = dirname(__file__)\n\ndf = get_fund_acc_net_value_by_time()\ndt = df.index >= '2017-01-01'\ndf = df[dt]\ndf.dropna(axis=1, inplace=True)\nprint(df.tail(5))\ndf = df/df.ix[0]\ncols = df.ix[-1].sort_values(ascending=False).index\ndf = df[cols]\n\ndf.plot(figsize=(10,5))\nplt.grid()\nplt.title(u'基金累积净值')\nfig = plt.gcf()\nfig.savefig(__ROOT__ + '/image/acc_net_value.svg')\n" ]
[ [ "matplotlib.pyplot.title", "matplotlib.pyplot.grid", "matplotlib.pyplot.gcf" ] ]
grow-yhq/PyTorch-Encoding
[ "06cb3098f67a6daa2d7a3b772d9f799a506cc5ff" ]
[ "encoding/nn/customize.py" ]
[ "##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n## Created by: Hang Zhang\n## ECE Department, Rutgers University\n## Email: [email protected]\n## Copyright (c) 2017\n##\n## This source code is licensed under the MIT-style license found in the\n## LICENSE file in the root directory of this source tree\n##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\"\"\"Encoding Custermized NN Module\"\"\"\nimport torch\nfrom torch.nn import Module, Sequential, Conv2d, ReLU, AdaptiveAvgPool2d\nfrom torch.nn import functional as F\n\nfrom .syncbn import BatchNorm2d\n\n__all__ = ['GramMatrix', 'View', 'Sum', 'Mean', 'Normalize', 'PyramidPooling']\n\n\nclass GramMatrix(Module):\n r\"\"\" Gram Matrix for a 4D convolutional featuremaps as a mini-batch\n\n .. math::\n \\mathcal{G} = \\sum_{h=1}^{H_i}\\sum_{w=1}^{W_i} \\mathcal{F}_{h,w}\\mathcal{F}_{h,w}^T\n \"\"\"\n def forward(self, y):\n (b, ch, h, w) = y.size()\n features = y.view(b, ch, w * h)\n features_t = features.transpose(1, 2)\n gram = features.bmm(features_t) / (ch * h * w)\n return gram\n\n\nclass View(Module):\n \"\"\"Reshape the input into different size, an inplace operator, support\n SelfParallel mode.\n \"\"\"\n def __init__(self, *args):\n super(View, self).__init__()\n if len(args) == 1 and isinstance(args[0], torch.Size):\n self.size = args[0]\n else:\n self.size = torch.Size(args)\n\n def forward(self, input):\n return input.view(self.size)\n\n\nclass Sum(Module):\n def __init__(self, dim, keep_dim=False):\n super(Sum, self).__init__()\n self.dim = dim\n self.keep_dim = keep_dim\n\n def forward(self, input):\n return input.sum(self.dim, self.keep_dim)\n\n\nclass Mean(Module):\n def __init__(self, dim, keep_dim=False):\n super(Mean, self).__init__()\n self.dim = dim\n self.keep_dim = keep_dim\n\n def forward(self, input):\n return input.mean(self.dim, self.keep_dim)\n\n\nclass Normalize(Module):\n r\"\"\"Performs :math:`L_p` normalization of inputs over specified dimension.\n\n Does:\n\n .. math::\n v = \\frac{v}{\\max(\\lVert v \\rVert_p, \\epsilon)}\n\n for each subtensor v over dimension dim of input. Each subtensor is\n flattened into a vector, i.e. :math:`\\lVert v \\rVert_p` is not a matrix\n norm.\n\n With default arguments normalizes over the second dimension with Euclidean\n norm.\n\n Args:\n p (float): the exponent value in the norm formulation. Default: 2\n dim (int): the dimension to reduce. Default: 1\n \"\"\"\n def __init__(self, p=2, dim=1):\n super(Normalize, self).__init__()\n self.p = p\n self.dim = dim\n\n def forward(self, x):\n return F.normalize(x, self.p, self.dim, eps=1e-10)\n\n\nclass PyramidPooling(Module):\n \"\"\"\n Reference:\n Zhao, Hengshuang, et al. *\"Pyramid scene parsing network.\"*\n \"\"\"\n def __init__(self, in_channels):\n super(PyramidPooling, self).__init__()\n self.pool1 = AdaptiveAvgPool2d(1)\n self.pool2 = AdaptiveAvgPool2d(2)\n self.pool3 = AdaptiveAvgPool2d(3)\n self.pool4 = AdaptiveAvgPool2d(6)\n\n out_channels = int(in_channels/4)\n self.conv1 = Sequential(Conv2d(in_channels, out_channels, 1),\n BatchNorm2d(out_channels),\n ReLU(True))\n self.conv2 = Sequential(Conv2d(in_channels, out_channels, 1),\n BatchNorm2d(out_channels),\n ReLU(True))\n self.conv3 = Sequential(Conv2d(in_channels, out_channels, 1),\n BatchNorm2d(out_channels),\n ReLU(True))\n self.conv4 = Sequential(Conv2d(in_channels, out_channels, 1),\n BatchNorm2d(out_channels),\n ReLU(True))\n\n def _cat_each(self, x, feat1, feat2, feat3, feat4):\n assert(len(x) == len(feat1))\n z = []\n for i in range(len(x)):\n z.append(torch.cat((x[i], feat1[i], feat2[i], feat3[i], feat4[i]), 1))\n return z\n\n def forward(self, x):\n _, _, h, w = x.size()\n feat1 = F.upsample(self.conv1(self.pool1(x)), (h, w), mode='bilinear')\n feat2 = F.upsample(self.conv2(self.pool2(x)), (h, w), mode='bilinear')\n feat3 = F.upsample(self.conv3(self.pool3(x)), (h, w), mode='bilinear')\n feat4 = F.upsample(self.conv4(self.pool4(x)), (h, w), mode='bilinear')\n return torch.cat((x, feat1, feat2, feat3, feat4), 1)\n" ]
[ [ "torch.nn.functional.normalize", "torch.Size", "torch.cat", "torch.nn.Conv2d", "torch.nn.AdaptiveAvgPool2d", "torch.nn.ReLU" ] ]
EchooooAi/gsrl
[ "1cfc73fe052c09fe05df09c92c5232e7341e9ad0" ]
[ "utils/utils.py" ]
[ "import torch\nfrom matplotlib import pyplot as plt\nimport os\nfrom sklearn.metrics import pairwise_distances, pairwise_distances_argmin\n# from sklearn.utils.linear_assignment_ import linear_assignment\nfrom scipy.optimize import linear_sum_assignment\nimport numpy as np\nimport networkx as nx\n\nimport warnings \nimport matplotlib.cbook \nwarnings.filterwarnings(\"ignore\",category=matplotlib.cbook.mplDeprecation)\n\n\nbasic_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..','..')\n\ndef visualize(feat, labels, epoch=0, y_pred=None, data=None, args=None):\n path = os.path.join(basic_path, 'res', 'visualization')\n if not os.path.exists(path):\n os.makedirs(path)\n\t# hidden = model.autoencoder.encode(data).detach().cpu().numpy()\t\n\t# np.save(\"{}data/hidden_{}.npy\".format(path, epoch), hidden)\n\t# np.save(\"{}data/centers_{}.npy\".format(path, epoch), model.cluster_centers.detach().cpu().numpy())\n\t# np.save(\"{}data/y_pred_{}.npy\".format(path, epoch), y_pred)\n\t# reducer = umap.UMAP(n_neighbors=5, min_dist=0.7, metric='correlation')\n\t# x_embedded = reducer.fit_transform(hidden)\n\t\n fig = plt.figure(figsize=(8,6))\n ax = plt.subplot(111)\n plt.scatter(feat[:,0], feat[:,1], c=labels, s=5, cmap='rainbow_r')\n\n\t# output = model(data)[1].argmax(1).detach().cpu().numpy()\n if y_pred is not None and data is not None:\n acc = Acc(y_pred, data)\n # nmi = nmi_score(labels, output)\n else:\n acc = 0\n fig.savefig( os.path.join(path, 'cora_{}_{}.png'.format(round(acc, 4), epoch)))\n print('figure save in ', path)\n plt.close(fig)\n\n\t# if epoch == 0:\n\t# \tfig = plt.figure()\n\t# \tax = plt.subplot(111)\n\t# \tplt.scatter(x_embedded[:len(y_pred), 0], x_embedded[:len(y_pred), 1], c=y_pred, s=1, cmap='rainbow_r')\n\t# \tfig.savefig('{}pics/Cluster_mnist.png'.format(path))\n\t# \tplt.close(fig)\n\n\t# \tnp.save(\"{}data/input.npy\".format(path), data.cpu().numpy())\n\t# \tnp.save(\"{}data/labels.npy\".format(path), labels)\n\n\ndef graph_visualize(feat, edge_list, labels, epoch=0, acc=0):\n '''\n edge_list: n * 2 numpy array\n '''\n G = nx.Graph()\n G.add_nodes_from(list(range(feat.shape[0])))\n G.add_edges_from(list(map(tuple, edge_list))) \n\n # zip(list(range(labels.max()+1)), list(range(labels.max()+1)))\n # val_map = {0: 1.0,\n # # 'D': 0.5714285714285714,\n # 4: 1}\n # values = [val_map.get(node, 0.5) for node in G.nodes()]\n values = list(labels)\n fig = plt.figure(figsize=(8, 8))\n for node_idx in range(feat.shape[0]):\n G.node[node_idx]['pos'] = feat[node_idx]\n # pos = nx.spring_layout(G)\n pos=nx.get_node_attributes(G,'pos')\n\n nx.draw(G, pos=pos, alpha=1 ,cmap=plt.get_cmap('rainbow'), node_color=values, style='solid',node_size=10)\n \n path = os.path.join(basic_path, 'res', 'graphVis')\n if not os.path.exists(path):\n os.makedirs(path)\n fig.savefig( os.path.join(path, 'cora_{}_{}.png'.format(round(acc, 4), epoch)))\n print('figure save in ', path)\n plt.close(fig)\n\n\n # nx.draw_networkx_edges(\n # G,\n # pos,\n # edgelist=[(0,4)],\n # width=1,\n # alpha=1,\n # edge_color=\"b\",\n # )\n\n\ndef Acc(y_pred, data):\n # y_pred = torch.IntTensor(y_pred)\n # print(y_pred)\n # logits, accs = model(), []\n # accs = []\n correct = 0\n total = 0\n\n # print(data.y[data.train_mask])\n # print(y_pred[data.train_mask])\n for _, mask in data('train_mask', 'val_mask', 'test_mask'):\n # pred = logits[mask].max(1)[1]\n # acc = y_pred[mask].eq(data_main.y[mask]).sum().item() / mask.sum().item()\n correct += y_pred[mask].eq(data.y[mask]).sum().item()\n total += mask.sum().item() \n # print('correct', correct)\n # print('total', total)\n # accs.append(acc)\n return correct/total\n\ndef compute_pairwise_similarity(x, y, dist_metrics='euclidean', std=False, to_distribution=False):\n if dist_metrics == 'euclidean':\n sim_ij = pairwise_distances(x, y, metric=dist_metrics) #n_sample, n_sample\n freedom = 1 \n sim_ij = 1.0 / (1.0 + (np.power(sim_ij, 2) / freedom))\n sim_ij = np.power(sim_ij, float(freedom + 1)/2)\n \n elif dist_metrics == 'cosine':\n sim_ij = np.matmul(x, np.transpose(y))\n sim_ij = 1/1(1+ np.exp(-sim_ij))\n # return F.cosine_similarity(x, y.unsqueeze(1), dim=-1)\n if std:\n means = sim_ij.mean(dim=1, keepdim=True)\n stds = sim_ij.std(dim=1, keepdim=True)\n sim_ij = (sim_ij - means) / stds\n if to_distribution:\n sim_ij = (sim_ij.t() / torch.sum(sim_ij, 1)).t() # (n_samples, n_clusters)\n return sim_ij\n\ndef cluster_acc(y_true, y_pred):\n \"\"\"\n Calculate clustering accuracy. Require scikit-learn installed\n # Arguments\n y: true labels, numpy.array with shape `(n_samples,)`\n y_pred: predicted labels, numpy.array with shape `(n_samples,)`\n # Return\n accuracy, in [0,1]\n https://datascience.stackexchange.com/questions/17461/how-to-test-accuracy-of-an-unsupervised-clustering-model-output\n \"\"\"\n y_true = y_true.astype(np.int64)\n assert y_pred.size == y_true.size\n D = max(y_pred.max(), y_true.max()) + 1\n w = np.zeros((D, D), dtype=np.int64)\n for i in range(y_pred.size):\n w[y_pred[i], y_true[i]] += 1\n \n ind = linear_sum_assignment(w.max() - w)\n ind = np.asarray(ind)\n ind = np.transpose(ind)\n # ind = linear_assignment(w.max() - w)\n return sum([w[i, j] for i, j in ind]) * 1.0 / y_pred.size" ]
[ [ "sklearn.metrics.pairwise_distances", "matplotlib.pyplot.scatter", "numpy.power", "numpy.asarray", "torch.sum", "matplotlib.pyplot.get_cmap", "matplotlib.pyplot.subplot", "matplotlib.pyplot.close", "numpy.transpose", "numpy.exp", "numpy.zeros", "matplotlib.pyplot.figure" ] ]
jonathanfrawley/PyAutoFit
[ "818384a6eb3926b18247e16efcf0db6008193bd4" ]
[ "autofit/mock/mock.py" ]
[ "import numpy as np\r\n\r\nimport autofit as af\r\nfrom autoconf import conf\r\nfrom autofit.non_linear.samples import Sample\r\n\r\n\r\nclass MockAnalysis(af.Analysis):\r\n prior_count = 2\r\n\r\n def __init__(self):\r\n super().__init__()\r\n self.fit_instances = list()\r\n\r\n def log_likelihood_function(self, instance):\r\n self.fit_instances.append(instance)\r\n return [1]\r\n\r\n def visualize(self, paths, instance, during_analysis):\r\n pass\r\n\r\n def log(self, instance):\r\n pass\r\n\r\n\r\nclass MockResult:\r\n def __init__(\r\n self,\r\n samples=None,\r\n instance=None,\r\n model=None,\r\n analysis=None,\r\n search=None,\r\n ):\r\n self.instance = instance or af.ModelInstance()\r\n self.model = model or af.ModelMapper()\r\n self.samples = samples or MockSamples(max_log_likelihood_instance=self.instance)\r\n\r\n self.gaussian_tuples = None\r\n self.analysis = analysis\r\n self.search = search\r\n self.model = model\r\n\r\n def model_absolute(self, absolute):\r\n return self.model\r\n\r\n def model_relative(self, relative):\r\n return self.model\r\n\r\n @property\r\n def last(self):\r\n return self\r\n\r\n\r\n\r\nclass MockSamples(af.PDFSamples):\r\n def __init__(\r\n self,\r\n model=None,\r\n samples=None,\r\n max_log_likelihood_instance=None,\r\n log_likelihood_list=None,\r\n gaussian_tuples=None,\r\n unconverged_sample_size=10,\r\n **kwargs,\r\n ):\r\n\r\n self.model = model\r\n self._samples = samples\r\n self._log_likelihood_list = log_likelihood_list\r\n\r\n super().__init__(\r\n model=model, unconverged_sample_size=unconverged_sample_size, **kwargs\r\n )\r\n\r\n self._max_log_likelihood_instance = max_log_likelihood_instance\r\n self.gaussian_tuples = gaussian_tuples\r\n\r\n @property\r\n def log_likelihood_list(self):\r\n\r\n if self._log_likelihood_list is None:\r\n return [1.0, 2.0, 3.0]\r\n\r\n return self._log_likelihood_list\r\n\r\n @property\r\n def samples(self):\r\n\r\n if self._samples is not None:\r\n return self._samples\r\n\r\n return [\r\n Sample(\r\n log_likelihood=log_likelihood,\r\n log_prior=0.0,\r\n weight=0.0\r\n )\r\n for log_likelihood\r\n in self.log_likelihood_list\r\n ]\r\n\r\n @property\r\n def max_log_likelihood_instance(self):\r\n return self._max_log_likelihood_instance\r\n\r\n def gaussian_priors_at_sigma(self, sigma=None):\r\n return self.gaussian_tuples\r\n\r\n def write_table(self, filename: str):\r\n pass\r\n\r\n def info_to_json(self, filename):\r\n pass\r\n\r\n\r\nclass MockSearch(af.NonLinearSearch):\r\n def __init__(self, samples=None, name=\"\"):\r\n self.name = name\r\n super().__init__(name=name)\r\n\r\n self.samples = samples or MockSamples()\r\n\r\n def _fit(self, model, analysis, log_likelihood_cap=None):\r\n class Fitness:\r\n def __init__(self, instance_from_vector):\r\n self.result = None\r\n self.instance_from_vector = instance_from_vector\r\n\r\n def __call__(self, vector):\r\n instance = self.instance_from_vector(vector)\r\n\r\n log_likelihood = analysis.log_likelihood_function(instance)\r\n self.result = MockResult(instance=instance)\r\n\r\n # Return Chi squared\r\n return -2 * log_likelihood\r\n\r\n analysis.save_attributes_for_aggregator(paths=self.paths)\r\n\r\n fitness_function = Fitness(model.instance_from_vector)\r\n fitness_function(model.prior_count * [0.5])\r\n\r\n return fitness_function.result\r\n\r\n @property\r\n def config_type(self):\r\n return conf.instance[\"non_linear\"][\"mock\"]\r\n\r\n def perform_update(self, model, analysis, during_analysis):\r\n self.paths.save_object(\"samples\", self.samples)\r\n return self.samples\r\n\r\n def samples_from(self, model):\r\n return self.samples\r\n\r\n\r\n### Mock Classes ###\r\n\r\nclass ListClass:\r\n def __init__(self, ls: list):\r\n self.ls = ls\r\n\r\n\r\nclass MockClassx2:\r\n def __init__(self, one=1, two=2):\r\n self.one = one\r\n self.two = two\r\n\r\n\r\nclass MockClassx4:\r\n def __init__(self, one=1, two=2, three=3, four=4):\r\n self.one = one\r\n self.two = two\r\n self.three = three\r\n self.four = four\r\n\r\n\r\nclass MockClassx3(MockClassx4):\r\n def __init__(self, one=1, two=2, three=3):\r\n super().__init__(one, two, three)\r\n\r\n\r\nclass MockClassx2Tuple:\r\n def __init__(self, one_tuple=(0.0, 0.0)):\r\n \"\"\"Abstract GeometryProfile, describing an object with y, x cartesian\r\n coordinates \"\"\"\r\n self.one_tuple = one_tuple\r\n\r\n def __eq__(self, other):\r\n return self.__dict__ == other.__dict__\r\n\r\n\r\nclass MockClassx3TupleFloat:\r\n def __init__(self, one_tuple=(0.0, 0.0), two=0.1):\r\n self.one_tuple = one_tuple\r\n self.two = two\r\n\r\n\r\nclass MockClassRelativeWidth:\r\n def __init__(self, one, two, three):\r\n self.one = one\r\n self.two = two\r\n self.three = three\r\n\r\n\r\nclass MockClassInf:\r\n def __init__(self, one, two):\r\n self.one = one\r\n self.two = two\r\n\r\n\r\nclass ComplexClass:\r\n def __init__(self, simple: MockClassx2):\r\n self.simple = simple\r\n\r\n\r\nclass DeferredClass:\r\n def __init__(self, one, two):\r\n self.one = one\r\n self.two = two\r\n\r\n\r\nclass WithFloat:\r\n def __init__(self, value):\r\n self.value = value\r\n\r\n\r\nclass WithTuple:\r\n def __init__(self, tup=(0.0, 0.0)):\r\n self.tup = tup\r\n\r\n\r\n### Real Classes ###\r\n\r\nclass MockComponents:\r\n def __init__(\r\n self,\r\n components_0: list = None,\r\n components_1: list = None,\r\n parameter=None,\r\n **kwargs\r\n ):\r\n self.parameter = parameter\r\n self.group_0 = components_0\r\n self.group_1 = components_1\r\n self.kwargs = kwargs\r\n\r\n\r\nclass HyperGalaxy:\r\n pass\r\n\r\n\r\nclass MedianPDFInstance:\r\n def __init__(self, name):\r\n self.name = name\r\n\r\n\r\nclass MockSearchOutput:\r\n def __init__(self, directory, pipeline, search, dataset):\r\n self.directory = directory\r\n self.pipeline = pipeline\r\n self.search = search\r\n self.dataset = dataset\r\n\r\n @property\r\n def median_pdf_instance(self):\r\n return MedianPDFInstance(\r\n self.search\r\n )\r\n\r\n @property\r\n def output(self):\r\n return self\r\n\r\n\r\nclass Profile:\r\n def __init__(self, centre=0.0, intensity=0.01):\r\n \"\"\"Represents an Abstract 1D profile.\r\n\r\n Parameters\r\n ----------\r\n centre : float\r\n The x coordinate of the profile centre.\r\n intensity\r\n Overall intensity normalisation of the profile.\r\n \"\"\"\r\n self.centre = centre\r\n self.intensity = intensity\r\n\r\n\r\nclass Gaussian(Profile):\r\n def __init__(\r\n self,\r\n centre=0.0, # <- PyAutoFit recognises these constructor arguments\r\n intensity=0.1, # <- are the Gaussian's model parameters.\r\n sigma=0.01,\r\n ):\r\n \"\"\"Represents a 1D Gaussian profile, which may be treated as a model-component of PyAutoFit the\r\n parameters of which are fitted for by a non-linear search.\r\n\r\n Parameters\r\n ----------\r\n centre : float\r\n The x coordinate of the profile centre.\r\n intensity\r\n Overall intensity normalisation of the Gaussian profile.\r\n sigma : float\r\n The sigma value controlling the size of the Gaussian.\r\n \"\"\"\r\n super().__init__(centre=centre, intensity=intensity)\r\n self.sigma = sigma # We still need to set sigma for the Gaussian, of course.\r\n\r\n def __eq__(self, other):\r\n return all([\r\n self.centre == other.centre,\r\n self.intensity == other.intensity,\r\n self.sigma == other.sigma\r\n ])\r\n\r\n def __call__(self, xvalues):\r\n \"\"\"\r\n Calculate the intensity of the profile on a line of Cartesian x coordinates.\r\n\r\n The input xvalues are translated to a coordinate system centred on the Gaussian, using its centre.\r\n\r\n Parameters\r\n ----------\r\n xvalues : np.ndarray\r\n The x coordinates in the original reference frame of the grid.\r\n \"\"\"\r\n transformed_xvalues = np.subtract(xvalues, self.centre)\r\n return np.multiply(\r\n np.divide(self.intensity, self.sigma * np.sqrt(2.0 * np.pi)),\r\n np.exp(-0.5 * np.square(np.divide(transformed_xvalues, self.sigma))),\r\n )\r\n" ]
[ [ "numpy.subtract", "numpy.sqrt", "numpy.divide" ] ]
tisaac/GME
[ "097bbf06b547c1428a2e25b0364ef6dae35d9642" ]
[ "gme/estimate/combine_sector_results.py" ]
[ "__Author__ = \"Peter Herman\"\n__Project__ = \"gme.estimate\"\n__Created__ = \"04-30-2018\"\n\nimport pandas as pd\nfrom typing import Dict\ndef combine_sector_results(result_dict:dict = None,\n write_path:str = None,\n significance_stars: bool = False,\n round_results: int = None,\n latex_syntax: bool = False):\n '''\n Extract key result fields (coefficients, standard errors, and p-values) and combine them in a DataFrame. Has the option to write the data to a .csv file.\n Args:\n result_dict: Dict[statsmodels.genmod.generalized_linear_model.GLMResultsWrapper]\n A dictionary of GLM fit objects as returned by gme.EsimationModel.estimate()\n write_path: (optional) str\n A system location and file name in which to write a csv file containing the combined results.\n significance_stars: bool\n If true, combined results are output with significance stars. *** <0.01, **<0.05, and *<0.10. Default is False.\n round_results: (optional) int\n Rounds combined results to the desired decimal place.\n latex_syntax: bool\n If True, reports aspects of results, such as significance stars, using standard latex syntax.\n\n Returns: Pandas.DataFrame\n A DataFrame containing combined GLM results for all results in the supplied dictionary.\n\n Examples:\n # Using a gme.EstimationModel named sample_model...\n >>> sample_results = sample_model.estimate()\n >>> combine_sector_results(sample_results)\n all_coeff all_pvalue all_stderr\n log_distance -0.739840 9.318804e-211 (0.023879411125052336)\n agree_pta 0.334219 5.134355e-15 (0.04271952339258154)\n common_language 0.128770 1.076932e-03 (0.03938367074719932)\n contiguity 0.255161 5.857612e-08 (0.04705076644539403)\n importer_year_fe_ARG2013 26.980367 0.000000e+00 (0.3612289201097519)\n\n >>> combine_sector_results(sample_results, path = 'c:\\\\Documents\\\\combined_results_saved.csv')\n '''\n\n\n keys = result_dict.keys()\n columns = []\n for column_name in keys:\n names = (str(column_name) + '_coeff',str(column_name) + '_stderr',str(column_name) + '_pvalue')\n sector = pd.DataFrame({\n names[0]: result_dict[column_name].params,\n names[1]: result_dict[column_name].bse,\n names[2]: result_dict[column_name].pvalues})\n\n one_percent = sector[names[2]] < 0.01\n five_percent = (sector[names[2]] < 0.05) & (sector[names[2]] >= 0.01)\n ten_percent = (sector[names[2]] < 0.1) & (sector[names[2]] >= 0.05)\n\n if round_results is not None:\n sector = sector.round(round_results)\n\n if significance_stars is True:\n if latex_syntax is True:\n sector.loc[one_percent, names[0]] = (sector[names[0]].astype(str) + '$^{***}$')\n sector.loc[five_percent, names[0]] = (sector[names[0]].astype(str) + '$^{**}$')\n sector.loc[ten_percent, names[0]] = (sector[names[0]].astype(str) + '$^{*}$')\n else:\n sector.loc[one_percent, names[0]] = (sector[names[0]].astype(str) + '***')\n sector.loc[five_percent, names[0]] = (sector[names[0]].astype(str) + '**')\n sector.loc[ten_percent, names[0]] = (sector[names[0]].astype(str) + '*')\n\n if latex_syntax is True:\n if round_results is not None: # Rounding and converting to a string loses trailing zeros, this readds them\n sector[names[1]] = sector[names[1]].astype(str)\n lost_zero = (sector[names[1]].str.len() - sector[names[1]].str.index('.') - 1) < round_results\n sector.loc[lost_zero, names[1]] = (sector[names[1]] + '0')\n\n sector[names[1]] = ('(' + sector[names[1]].astype(str) + ')')\n\n singletons = {'nobs':result_dict[column_name].nobs,\n 'aic':result_dict[column_name].aic,\n 'bic': result_dict[column_name].bic,\n 'likelihood':result_dict[column_name].llf}\n\n for key in singletons.keys():\n new_row = pd.DataFrame({\n names[0]: singletons[key],\n names[1]: singletons[key],\n names[2]: singletons[key]}, index = [key])\n if round_results is not None:\n new_row = new_row.round(round_results)\n\n sector = pd.concat([sector,new_row], axis = 0)\n\n columns.append(sector)\n combined_sectors = pd.concat(columns, axis = 1)\n\n if write_path is not None:\n combined_sectors.to_csv(write_path)\n\n return combined_sectors" ]
[ [ "pandas.concat", "pandas.DataFrame" ] ]
Iwan-Zotow/runEGS
[ "d95952d48c01866ee44ff40814c49e0fbd2489ad" ]
[ "XcMath/linint.py" ]
[ "# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport logging\n\nclass linint(object):\n \"\"\"\n Given the curve, produce linearly interpolated values\n \"\"\"\n \n def __init__( self, points ):\n \"\"\"\n Construct interpolator from the curve\n \n Parameters\n ----------\n points: array of points\n arrays of 2D points\n \"\"\"\n \n # make copy of points\n self._points = points[:]\n \n if not self.invariant():\n raise RuntimeError(\"linint\", \"invariant is broken in constructor\")\n \n self._len = len(points)\n \n self._zmin = self._points[-1].x()\n self._zmax = self._points[0].x()\n \n if not self.invariant():\n raise RuntimeError(\"linint\", \"from constructor\")\n \n logging.info(\"linint constructed\")\n logging.debug(str(points))\n \n def invariant(self):\n \"\"\"\n Checks validity of the input\n \n returns: boolean\n True if ok, False otherwise\n \"\"\"\n\n if self._points == None:\n return False\n\n if len(self._points) <= 1:\n return False\n \n # shall be descending\n prev = np.float32(1000000.0)\n for p in self._points:\n z = p.x()\n if z > prev:\n return False\n if z == prev:\n return False\n prev = z\n \n return True\n \n def __len__(self):\n \"\"\"\n Length \n \n returns: integer\n length\n \"\"\"\n return self._len\n\n def __getitem__(self, idx):\n \"\"\"\n Indexing operator\n \n Parameters\n ----------\n\n idx: integer\n point index\n \n returns: point\n 2D point at given index\n \"\"\"\n logging.debug(str(idx)) \n \n if idx < 0:\n raise ValueError(\"linint\", \"index is negative\")\n \n if idx >= self._len:\n raise ValueError(\"linint\", \"index is too large\")\n \n return self._points[idx]\n \n def zmin(self):\n \"\"\"\n Returns interpolator abscissa minimum\n \"\"\"\n return self._zmin\n \n def zmax(self):\n \"\"\"\n Returns interpolator abscissa maximum\n \"\"\"\n return self._zmax\n\n def interpolate(self, z):\n \"\"\"\n Interpolate value from curve having index of the bin and abscissa value\n \n Parameters\n ----------\n\n z: float\n abscissa value\n \n returns: float\n interpolated value\n \"\"\"\n logging.debug(str(z))\n\n idx = self.find_idx(z)\n# print(self._points[idx].x())\n# print(self._points[idx+1].x())\n# print(idx)\n\n # above zmax \n if (idx == -1):\n raise RuntimeError(\"interpolate\", \"index is -1\")\n \n # below zmin\n if (idx == -2):\n raise RuntimeError(\"interpolate\", \"index is -2\")\n \n p = (z - self._points[idx+1].x()) / (self._points[idx].x() - self._points[idx+1].x())\n q = 1.0 - p\n \n# print(p)\n# print(q)\n# print(self._points[idx].y())\n# print(self._points[idx+1].y())\n \n return p * self._points[idx].y() + q * self._points[idx+1].y()\n\n def extrapolate(self, z):\n \"\"\"\n Extrapolate value from curve having index of the bin and abscissa value\n \n Parameters\n ----------\n\n z: float\n abscissa value\n \n returns: float\n extrapolated value\n \"\"\"\n logging.debug(str(z))\n\n if z > self._zmax:\n return 0.0\n \n if z >= self._zmin:\n return self.interpolate(z)\n\n idx = self._len - 1\n \n p = (z - self._points[idx].x()) / (self._points[idx-1].x() - self._points[idx].x())\n q = 1.0 - p\n \n return p * self._points[idx-1].y() + q * self._points[idx].y()\n\n def find_idx(self, z):\n \"\"\"\n Given z, find index\n \n Parameters\n ----------\n\n z: float\n abscissa value\n \n returns: integer\n index of the bin\n \"\"\"\n logging.debug(str(z)) \n \n if z > self._zmax:\n return -1\n \n if z < self._zmin:\n return -2\n\n lo = self._len-1\n hi = 0 \n while True:\n me = (lo + hi) // 2\n xx = self._points[me].x()\n if xx > z:\n hi = me\n else:\n lo = me\n \n if lo - hi == 1:\n break\n \n return hi\n\nif __name__ == \"__main__\":\n \n import point2d \n \n curve = []\n curve.append(point2d.point2d(5.0, 1.0))\n curve.append(point2d.point2d(4.0, 2.0))\n curve.append(point2d.point2d(3.0, 3.0))\n curve.append(point2d.point2d(2.0, 4.0))\n curve.append(point2d.point2d(1.0, 5.0))\n \n li = linint(curve)\n v = li.extrapolate(0.1)\n \n print(v)\n\n \n" ]
[ [ "numpy.float32" ] ]
ABonnefoy/solopython
[ "ec49e924c977f9a91697e9d5c21da73c55a55fb1" ]
[ "main_solo8.py" ]
[ "# coding: utf8\nimport numpy as np\nimport argparse\nimport math\nfrom time import clock, sleep\nfrom utils.viewerClient import viewerClient\nfrom solo8 import Solo8\n\ndef example_script(name_interface):\n viewer = viewerClient()\n device = Solo8(name_interface,dt=0.001)\n nb_motors = device.nb_motors\n\n q_viewer = np.array((7 + nb_motors) * [0.,])\n\n device.Init(calibrateEncoders=False)\n #CONTROL LOOP ***************************************************\n while ((not device.hardware.IsTimeout()) and (clock() < 200)):\n device.UpdateMeasurment()\n device.SetDesiredJointTorque([0]*nb_motors)\n device.SendCommand(WaitEndOfCycle=True)\n if ((device.cpt % 100) == 0):\n device.Print()\n\n q_viewer[3:7] = device.baseOrientation # IMU Attitude\n q_viewer[7:] = device.q_mes # Encoders\n viewer.display(q_viewer)\n #****************************************************************\n \n # Whatever happened we send 0 torques to the motors.\n device.SetDesiredJointTorque([0]*nb_motors)\n device.SendCommand(WaitEndOfCycle=True)\n\n if device.hardware.IsTimeout():\n print(\"Masterboard timeout detected.\")\n print(\"Either the masterboard has been shut down or there has been a connection issue with the cable/wifi.\")\n device.hardware.Stop() # Shut down the interface between the computer and the master board\n\ndef main():\n parser = argparse.ArgumentParser(description='Example masterboard use in python.')\n parser.add_argument('-i',\n '--interface',\n required=True,\n help='Name of the interface (use ifconfig in a terminal), for instance \"enp1s0\"')\n\n example_script(parser.parse_args().interface)\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.array" ] ]
shashikg/model-tools
[ "f4cf9b39830270ca671ead368e07b33d59f77a11" ]
[ "tests/brain_transformation/test_search.py" ]
[ "import functools\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom pytest import approx\n\nfrom model_tools.brain_transformation import ModelCommitment\nfrom model_tools.activations import PytorchWrapper\nimport brainscore\nimport brainio_collection\nfrom brainscore.model_interface import BrainModel\n\ndef pytorch_custom(image_size):\n import torch\n from torch import nn\n from model_tools.activations.pytorch import load_preprocess_images\n\n class MyModel(nn.Module):\n def __init__(self):\n super(MyModel, self).__init__()\n self.conv1 = torch.nn.Conv2d(in_channels=3, out_channels=2, kernel_size=3, bias=False)\n self.relu1 = torch.nn.ReLU()\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.relu1(x)\n return x\n\n preprocessing = functools.partial(load_preprocess_images, image_size=image_size)\n return PytorchWrapper(model=MyModel(), preprocessing=preprocessing)\n\nclass TestObjectSearch:\n def test_model(self):\n target_model_pool = pytorch_custom(28)\n stimuli_model_pool = pytorch_custom(224)\n search_target_model_param = {}\n search_stimuli_model_param = {}\n search_target_model_param['target_model'] = target_model_pool\n search_stimuli_model_param['stimuli_model'] = stimuli_model_pool\n search_target_model_param['target_layer'] = 'relu1'\n search_stimuli_model_param['stimuli_layer'] = 'relu1'\n search_target_model_param['target_img_size'] = 28\n search_stimuli_model_param['search_image_size'] = 224\n\n model = ModelCommitment(identifier=stimuli_model_pool.identifier, activations_model=None, layers=['relu1'], search_target_model_param=search_target_model_param, search_stimuli_model_param=search_stimuli_model_param)\n assemblies = brainscore.get_assembly('klab.Zhang2018search_obj_array')\n stimuli = assemblies.stimulus_set\n fix = [[640, 512],\n [365, 988],\n [90, 512],\n [365, 36],\n [915, 36],\n [1190, 512],\n [915, 988]]\n max_fix = 6\n data_len = 300\n model.start_task(BrainModel.Task.visual_search_obj_arr, fix=fix, max_fix=max_fix, data_len=data_len)\n cumm_perf, saccades = model.look_at(stimuli)\n\n assert saccades.shape == (300, 8, 2)\n assert cumm_perf.shape == (7, 2)\n" ]
[ [ "torch.nn.ReLU", "torch.nn.Conv2d" ] ]
devitocodes/Devitoboundary
[ "6e4b0b02848b06336a13c6e20a6acd36df006150" ]
[ "examples/seismic_topography_example.py" ]
[ "import numpy as np\nimport pandas as pd\n\nfrom devito import Grid, TimeFunction, Eq, solve, Operator, ConditionalDimension\nfrom devitoboundary import ImmersedBoundary, BoundaryConditions\nfrom examples.seismic import TimeAxis, RickerSource\n\n# Parameters\nqc = False\ntoggle_normals = False\n\nC = 0.1 # Courant number\nVP = 1.2 # P wave velocity\n\n# Grid configuration\n# 10.8 x 10.8 x 5.4 km\n# 50m spacing\nextent = (10800., 10800., 5400.)\nshape = (217, 217, 109) # (109, 109, 55)\norigin = (0., 0., -3900.)\ngrid = Grid(shape=shape, extent=extent, origin=origin)\n\n# Time series configuration\nt0 = 0. # Simulation starts at t=0\ntn = 4000. # Simulation length in ms\ndt = C*grid.spacing[0]/(VP)\n\nsteps = int((t0+tn)/dt)+2\n\n# Configure the source\ntime_range = TimeAxis(start=t0, stop=tn, step=dt)\nf0 = 0.002 # 2Hz\nsrc = RickerSource(name='src', grid=grid, f0=f0,\n npoint=1, time_range=time_range)\n\n# First, position source centrally in x and y dimensions, then set depth\nsrc.coordinates.data[0, :-1] = 5400. # Centered\nsrc.coordinates.data[0, -1] = -500 # 500m below sea level\n\n# Set up snapshotting\nnsnaps = 100 # Want 100 snapshots\nfactor = round(steps / nsnaps)\n\ntime_subsampled = ConditionalDimension('t_sub', parent=grid.time_dim,\n factor=factor)\nusave = TimeFunction(name='usave', grid=grid, time_order=2, space_order=2,\n save=(steps + factor - 1) // factor,\n time_dim=time_subsampled)\n\nu = TimeFunction(name='u', grid=grid,\n space_order=4, time_order=2,\n coefficients='symbolic')\n\n# Surface configuration\ninfile = 'topography/crater_lake.ply'\n# Zero even derivatives on the boundary\nspec = {2*i: 0 for i in range(u.space_order)}\nbcs_u = BoundaryConditions(spec, u.space_order)\nfunctions = pd.DataFrame({'function': [u],\n 'bcs': [bcs_u]},\n columns=['function', 'bcs'])\n\n# Create the immersed boundary surface\nsurface = ImmersedBoundary('topography', infile, functions,\n interior_point=tuple(src.coordinates.data[0]),\n qc=qc, toggle_normals=toggle_normals)\n\n# Configure derivative needed\nderivs = pd.DataFrame({'function': [u],\n 'derivative': [2],\n 'eval_offset': [(0., 0., 0.)]},\n columns=['function', 'derivative', 'eval_offset'])\ncoeffs = surface.subs(derivs)\n\n# We can now write the PDE\npde = VP*u.dt2 - u.laplace\neq = Eq(pde, 0, coefficients=coeffs)\n\n# And set up the update\nstencil = solve(eq.evaluate, u.forward)\n\n# Our injection term\nsrc_term = src.inject(field=u.forward, expr=src*dt**2/VP)\n\n# Now create our operator\nop = Operator([Eq(u.forward, stencil)] + [Eq(usave, u)] + src_term)\n\n# And run\nop.apply(dt=dt)\n\noutfile = 'data/seismic_topography_wavefield.npy'\nnp.save(outfile, usave.data)\n\"\"\"\nplot_extent = [0, grid.extent[0],\n origin[2], grid.extent[2] + origin[2]]\nfor i in range(usave.data.shape[0] - 1):\n fig = plt.figure()\n plt.imshow(usave.data[i, :, int(grid.shape[1]/2), :].T,\n origin='lower', extent=plot_extent,\n vmin=-6, vmax=6, cmap='seismic')\n plt.colorbar()\n plt.xlabel(\"x (m)\")\n plt.ylabel(\"z (m)\")\n plt.savefig(\"images/image-%s\" % str(i))\n # plt.show()\n plt.close()\n\"\"\"\n" ]
[ [ "numpy.save", "pandas.DataFrame" ] ]
floscha/prophet
[ "ad095ac690e153ddcbac99af8561100894e5095d" ]
[ "python/fbprophet/plot.py" ]
[ "# Copyright (c) 2017-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree. An additional grant\n# of patent rights can be found in the PATENTS file in the same directory.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport logging\n\nimport numpy as np\nimport pandas as pd\n\nfrom fbprophet.diagnostics import performance_metrics\n\n\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\n\ntry:\n from matplotlib import pyplot as plt\n from matplotlib.dates import MonthLocator, num2date\n from matplotlib.ticker import FuncFormatter\nexcept ImportError:\n logger.error('Importing matplotlib failed. Plotting will not work.')\n\n\ndef plot(\n m, fcst, ax=None, uncertainty=True, plot_cap=True, xlabel='ds', ylabel='y',\n):\n \"\"\"Plot the Prophet forecast.\n\n Parameters\n ----------\n m: Prophet model.\n fcst: pd.DataFrame output of m.predict.\n ax: Optional matplotlib axes on which to plot.\n uncertainty: Optional boolean to plot uncertainty intervals.\n plot_cap: Optional boolean indicating if the capacity should be shown\n in the figure, if available.\n xlabel: Optional label name on X-axis\n ylabel: Optional label name on Y-axis\n\n Returns\n -------\n A matplotlib figure.\n \"\"\"\n if ax is None:\n fig = plt.figure(facecolor='w', figsize=(10, 6))\n ax = fig.add_subplot(111)\n else:\n fig = ax.get_figure()\n fcst_t = fcst['ds'].dt.to_pydatetime()\n ax.plot(m.history['ds'].dt.to_pydatetime(), m.history['y'], 'k.')\n ax.plot(fcst_t, fcst['yhat'], ls='-', c='#0072B2')\n if 'cap' in fcst and plot_cap:\n ax.plot(fcst_t, fcst['cap'], ls='--', c='k')\n if m.logistic_floor and 'floor' in fcst and plot_cap:\n ax.plot(fcst_t, fcst['floor'], ls='--', c='k')\n if uncertainty:\n ax.fill_between(fcst_t, fcst['yhat_lower'], fcst['yhat_upper'],\n color='#0072B2', alpha=0.2)\n ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n fig.tight_layout()\n return fig\n\n\ndef plot_components(\n m, fcst, uncertainty=True, plot_cap=True, weekly_start=0, yearly_start=0,\n):\n \"\"\"Plot the Prophet forecast components.\n\n Will plot whichever are available of: trend, holidays, weekly\n seasonality, yearly seasonality, and additive and multiplicative extra\n regressors.\n\n Parameters\n ----------\n m: Prophet model.\n fcst: pd.DataFrame output of m.predict.\n uncertainty: Optional boolean to plot uncertainty intervals.\n plot_cap: Optional boolean indicating if the capacity should be shown\n in the figure, if available.\n weekly_start: Optional int specifying the start day of the weekly\n seasonality plot. 0 (default) starts the week on Sunday. 1 shifts\n by 1 day to Monday, and so on.\n yearly_start: Optional int specifying the start day of the yearly\n seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts\n by 1 day to Jan 2, and so on.\n\n Returns\n -------\n A matplotlib figure.\n \"\"\"\n # Identify components to be plotted\n components = ['trend']\n if m.holidays is not None and 'holidays' in fcst:\n components.append('holidays')\n components.extend([name for name in m.seasonalities\n if name in fcst])\n regressors = {'additive': False, 'multiplicative': False}\n for name, props in m.extra_regressors.items():\n regressors[props['mode']] = True\n for mode in ['additive', 'multiplicative']:\n if regressors[mode] and 'extra_regressors_{}'.format(mode) in fcst:\n components.append('extra_regressors_{}'.format(mode))\n npanel = len(components)\n\n fig, axes = plt.subplots(npanel, 1, facecolor='w',\n figsize=(9, 3 * npanel))\n\n if npanel == 1:\n axes = [axes]\n\n multiplicative_axes = []\n\n for ax, plot_name in zip(axes, components):\n if plot_name == 'trend':\n plot_forecast_component(\n m=m, fcst=fcst, name='trend', ax=ax, uncertainty=uncertainty,\n plot_cap=plot_cap,\n )\n elif plot_name == 'weekly':\n plot_weekly(\n m=m, ax=ax, uncertainty=uncertainty, weekly_start=weekly_start,\n )\n elif plot_name == 'yearly':\n plot_yearly(\n m=m, ax=ax, uncertainty=uncertainty, yearly_start=yearly_start,\n )\n elif plot_name in [\n 'holidays',\n 'extra_regressors_additive',\n 'extra_regressors_multiplicative',\n ]:\n plot_forecast_component(\n m=m, fcst=fcst, name=plot_name, ax=ax, uncertainty=uncertainty,\n plot_cap=False,\n )\n else:\n plot_seasonality(\n m=m, name=plot_name, ax=ax, uncertainty=uncertainty,\n )\n if plot_name in m.component_modes['multiplicative']:\n multiplicative_axes.append(ax)\n\n fig.tight_layout()\n # Reset multiplicative axes labels after tight_layout adjustment\n for ax in multiplicative_axes:\n ax = set_y_as_percent(ax)\n return fig\n\n\ndef plot_forecast_component(\n m, fcst, name, ax=None, uncertainty=True, plot_cap=False,\n):\n \"\"\"Plot a particular component of the forecast.\n\n Parameters\n ----------\n m: Prophet model.\n fcst: pd.DataFrame output of m.predict.\n name: Name of the component to plot.\n ax: Optional matplotlib Axes to plot on.\n uncertainty: Optional boolean to plot uncertainty intervals.\n plot_cap: Optional boolean indicating if the capacity should be shown\n in the figure, if available.\n\n Returns\n -------\n a list of matplotlib artists\n \"\"\"\n artists = []\n if not ax:\n fig = plt.figure(facecolor='w', figsize=(10, 6))\n ax = fig.add_subplot(111)\n fcst_t = fcst['ds'].dt.to_pydatetime()\n artists += ax.plot(fcst_t, fcst[name], ls='-', c='#0072B2')\n if 'cap' in fcst and plot_cap:\n artists += ax.plot(fcst_t, fcst['cap'], ls='--', c='k')\n if m.logistic_floor and 'floor' in fcst and plot_cap:\n ax.plot(fcst_t, fcst['floor'], ls='--', c='k')\n if uncertainty:\n artists += [ax.fill_between(\n fcst_t, fcst[name + '_lower'], fcst[name + '_upper'],\n color='#0072B2', alpha=0.2)]\n ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)\n ax.set_xlabel('ds')\n ax.set_ylabel(name)\n if name in m.component_modes['multiplicative']:\n ax = set_y_as_percent(ax)\n return artists\n\n\ndef seasonality_plot_df(m, ds):\n \"\"\"Prepare dataframe for plotting seasonal components.\n\n Parameters\n ----------\n m: Prophet model.\n ds: List of dates for column ds.\n\n Returns\n -------\n A dataframe with seasonal components on ds.\n \"\"\"\n df_dict = {'ds': ds, 'cap': 1., 'floor': 0.}\n for name in m.extra_regressors:\n df_dict[name] = 0.\n df = pd.DataFrame(df_dict)\n df = m.setup_dataframe(df)\n return df\n\n\ndef plot_weekly(m, ax=None, uncertainty=True, weekly_start=0):\n \"\"\"Plot the weekly component of the forecast.\n\n Parameters\n ----------\n m: Prophet model.\n ax: Optional matplotlib Axes to plot on. One will be created if this\n is not provided.\n uncertainty: Optional boolean to plot uncertainty intervals.\n weekly_start: Optional int specifying the start day of the weekly\n seasonality plot. 0 (default) starts the week on Sunday. 1 shifts\n by 1 day to Monday, and so on.\n\n Returns\n -------\n a list of matplotlib artists\n \"\"\"\n artists = []\n if not ax:\n fig = plt.figure(facecolor='w', figsize=(10, 6))\n ax = fig.add_subplot(111)\n # Compute weekly seasonality for a Sun-Sat sequence of dates.\n days = (pd.date_range(start='2017-01-01', periods=7) +\n pd.Timedelta(days=weekly_start))\n df_w = seasonality_plot_df(m, days)\n seas = m.predict_seasonal_components(df_w)\n days = days.weekday_name\n artists += ax.plot(range(len(days)), seas['weekly'], ls='-',\n c='#0072B2')\n if uncertainty:\n artists += [ax.fill_between(range(len(days)),\n seas['weekly_lower'], seas['weekly_upper'],\n color='#0072B2', alpha=0.2)]\n ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)\n ax.set_xticks(range(len(days)))\n ax.set_xticklabels(days)\n ax.set_xlabel('Day of week')\n ax.set_ylabel('weekly')\n if m.seasonalities['weekly']['mode'] == 'multiplicative':\n ax = set_y_as_percent(ax)\n return artists\n\n\ndef plot_yearly(m, ax=None, uncertainty=True, yearly_start=0):\n \"\"\"Plot the yearly component of the forecast.\n\n Parameters\n ----------\n m: Prophet model.\n ax: Optional matplotlib Axes to plot on. One will be created if\n this is not provided.\n uncertainty: Optional boolean to plot uncertainty intervals.\n yearly_start: Optional int specifying the start day of the yearly\n seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts\n by 1 day to Jan 2, and so on.\n\n Returns\n -------\n a list of matplotlib artists\n \"\"\"\n artists = []\n if not ax:\n fig = plt.figure(facecolor='w', figsize=(10, 6))\n ax = fig.add_subplot(111)\n # Compute yearly seasonality for a Jan 1 - Dec 31 sequence of dates.\n days = (pd.date_range(start='2017-01-01', periods=365) +\n pd.Timedelta(days=yearly_start))\n df_y = seasonality_plot_df(m, days)\n seas = m.predict_seasonal_components(df_y)\n artists += ax.plot(\n df_y['ds'].dt.to_pydatetime(), seas['yearly'], ls='-', c='#0072B2')\n if uncertainty:\n artists += [ax.fill_between(\n df_y['ds'].dt.to_pydatetime(), seas['yearly_lower'],\n seas['yearly_upper'], color='#0072B2', alpha=0.2)]\n ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)\n months = MonthLocator(range(1, 13), bymonthday=1, interval=2)\n ax.xaxis.set_major_formatter(FuncFormatter(\n lambda x, pos=None: '{dt:%B} {dt.day}'.format(dt=num2date(x))))\n ax.xaxis.set_major_locator(months)\n ax.set_xlabel('Day of year')\n ax.set_ylabel('yearly')\n if m.seasonalities['yearly']['mode'] == 'multiplicative':\n ax = set_y_as_percent(ax)\n return artists\n\n\ndef plot_seasonality(m, name, ax=None, uncertainty=True):\n \"\"\"Plot a custom seasonal component.\n\n Parameters\n ----------\n m: Prophet model.\n name: Seasonality name, like 'daily', 'weekly'.\n ax: Optional matplotlib Axes to plot on. One will be created if\n this is not provided.\n uncertainty: Optional boolean to plot uncertainty intervals.\n\n Returns\n -------\n a list of matplotlib artists\n \"\"\"\n artists = []\n if not ax:\n fig = plt.figure(facecolor='w', figsize=(10, 6))\n ax = fig.add_subplot(111)\n # Compute seasonality from Jan 1 through a single period.\n start = pd.to_datetime('2017-01-01 0000')\n period = m.seasonalities[name]['period']\n end = start + pd.Timedelta(days=period)\n plot_points = 200\n days = pd.to_datetime(np.linspace(start.value, end.value, plot_points))\n df_y = seasonality_plot_df(m, days)\n seas = m.predict_seasonal_components(df_y)\n artists += ax.plot(df_y['ds'].dt.to_pydatetime(), seas[name], ls='-',\n c='#0072B2')\n if uncertainty:\n artists += [ax.fill_between(\n df_y['ds'].dt.to_pydatetime(), seas[name + '_lower'],\n seas[name + '_upper'], color='#0072B2', alpha=0.2)]\n ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)\n xticks = pd.to_datetime(np.linspace(start.value, end.value, 7)\n ).to_pydatetime()\n ax.set_xticks(xticks)\n if period <= 2:\n fmt_str = '{dt:%T}'\n elif period < 14:\n fmt_str = '{dt:%m}/{dt:%d} {dt:%R}'\n else:\n fmt_str = '{dt:%m}/{dt:%d}'\n ax.xaxis.set_major_formatter(FuncFormatter(\n lambda x, pos=None: fmt_str.format(dt=num2date(x))))\n ax.set_xlabel('ds')\n ax.set_ylabel(name)\n if m.seasonalities[name]['mode'] == 'multiplicative':\n ax = set_y_as_percent(ax)\n return artists\n\n\ndef set_y_as_percent(ax):\n yticks = 100 * ax.get_yticks()\n yticklabels = ['{0:.4g}%'.format(y) for y in yticks]\n ax.set_yticklabels(yticklabels)\n return ax\n\n\ndef add_changepoints_to_plot(\n ax, m, fcst, threshold=0.01, cp_color='r', cp_linestyle='--', trend=True,\n):\n \"\"\"Add markers for significant changepoints to prophet forecast plot.\n \n Example:\n fig = m.plot(forecast)\n add_changepoints_to_plot(fig.gca(), m, forecast)\n \n Parameters\n ----------\n ax: axis on which to overlay changepoint markers.\n m: Prophet model.\n fcst: Forecast output from m.predict.\n threshold: Threshold on trend change magnitude for significance.\n cp_color: Color of changepoint markers.\n cp_linestyle: Linestyle for changepoint markers.\n trend: If True, will also overlay the trend.\n \n Returns\n -------\n a list of matplotlib artists\n \"\"\"\n artists = []\n if trend:\n artists.append(ax.plot(fcst['ds'], fcst['trend'], c=cp_color))\n signif_changepoints = m.changepoints[\n np.abs(np.nanmean(m.params['delta'], axis=0)) >= threshold\n ]\n for cp in signif_changepoints:\n artists.append(ax.axvline(x=cp, c=cp_color, ls=cp_linestyle))\n return artists\n\n\ndef plot_cross_validation_metric(df_cv, metric, rolling_window=0.1, ax=None):\n \"\"\"Plot a performance metric vs. forecast horizon from cross validation.\n\n Cross validation produces a collection of out-of-sample model predictions\n that can be compared to actual values, at a range of different horizons\n (distance from the cutoff). This computes a specified performance metric\n for each prediction, and aggregated over a rolling window with horizon.\n\n This uses fbprophet.diagnostics.performance_metrics to compute the metrics.\n Valid values of metric are 'mse', 'rmse', 'mae', 'mape', and 'coverage'.\n\n rolling_window is the proportion of data included in the rolling window of\n aggregation. The default value of 0.1 means 10% of data are included in the\n aggregation for computing the metric.\n\n As a concrete example, if metric='mse', then this plot will show the\n squared error for each cross validation prediction, along with the MSE\n averaged over rolling windows of 10% of the data.\n\n Parameters\n ----------\n df_cv: The output from fbprophet.diagnostics.cross_validation.\n metric: Metric name, one of ['mse', 'rmse', 'mae', 'mape', 'coverage'].\n rolling_window: Proportion of data to use for rolling average of metric.\n In [0, 1]. Defaults to 0.1.\n ax: Optional matplotlib axis on which to plot. If not given, a new figure\n will be created.\n\n Returns\n -------\n a matplotlib figure.\n \"\"\"\n if ax is None:\n fig = plt.figure(facecolor='w', figsize=(10, 6))\n ax = fig.add_subplot(111)\n else:\n fig = ax.get_figure()\n # Get the metric at the level of individual predictions, and with the rolling window.\n df_none = performance_metrics(df_cv, metrics=[metric], rolling_window=0)\n df_h = performance_metrics(df_cv, metrics=[metric], rolling_window=rolling_window)\n\n # Some work because matplotlib does not handle timedelta\n # Target ~10 ticks.\n tick_w = max(df_none['horizon'].astype('timedelta64[ns]')) / 10.\n # Find the largest time resolution that has <1 unit per bin.\n dts = ['D', 'h', 'm', 's', 'ms', 'us', 'ns']\n dt_names = [\n 'days', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds',\n 'nanoseconds'\n ]\n dt_conversions = [\n 24 * 60 * 60 * 10 ** 9,\n 60 * 60 * 10 ** 9,\n 60 * 10 ** 9,\n 10 ** 9,\n 10 ** 6,\n 10 ** 3,\n 1.,\n ]\n for i, dt in enumerate(dts):\n if np.timedelta64(1, dt) < np.timedelta64(tick_w, 'ns'):\n break\n\n x_plt = df_none['horizon'].astype('timedelta64[ns]').astype(np.int64) / float(dt_conversions[i])\n x_plt_h = df_h['horizon'].astype('timedelta64[ns]').astype(np.int64) / float(dt_conversions[i])\n\n ax.plot(x_plt, df_none[metric], '.', alpha=0.5, c='gray')\n ax.plot(x_plt_h, df_h[metric], '-', c='b')\n ax.grid(True)\n\n ax.set_xlabel('Horizon ({})'.format(dt_names[i]))\n ax.set_ylabel(metric)\n return fig\n" ]
[ [ "pandas.to_datetime", "numpy.linspace", "matplotlib.pyplot.subplots", "pandas.DataFrame", "pandas.Timedelta", "numpy.timedelta64", "numpy.nanmean", "pandas.date_range", "matplotlib.dates.num2date", "matplotlib.pyplot.figure" ] ]
sidsvash26/fairseq
[ "566341e3aae9271facf6b9181b3f51b5120a2774" ]
[ "fairseq/models/roberta/model.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\"\"\"\nRoBERTa: A Robustly Optimized BERT Pretraining Approach.\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom fairseq import utils\nfrom fairseq.models import (\n FairseqDecoder,\n FairseqLanguageModel,\n register_model,\n register_model_architecture,\n)\nfrom fairseq.modules import (\n LayerNorm,\n TransformerSentenceEncoder,\n)\nfrom fairseq.modules.transformer_sentence_encoder import init_bert_params\n\nfrom .hub_interface import RobertaHubInterface\n\n\n@register_model('roberta')\nclass RobertaModel(FairseqLanguageModel):\n\n @classmethod\n def hub_models(cls):\n return {\n 'roberta.base': 'http://dl.fbaipublicfiles.com/fairseq/models/roberta.base.tar.gz',\n 'roberta.large': 'http://dl.fbaipublicfiles.com/fairseq/models/roberta.large.tar.gz',\n 'roberta.large.mnli': 'http://dl.fbaipublicfiles.com/fairseq/models/roberta.large.mnli.tar.gz',\n 'roberta.large.wsc': 'http://dl.fbaipublicfiles.com/fairseq/models/roberta.large.wsc.tar.gz',\n }\n\n def __init__(self, args, encoder):\n super().__init__(encoder)\n self.args = args\n\n # We follow BERT's random weight initialization\n self.apply(init_bert_params)\n\n self.classification_heads = nn.ModuleDict()\n\n @staticmethod\n def add_args(parser):\n \"\"\"Add model-specific arguments to the parser.\"\"\"\n parser.add_argument('--encoder-layers', type=int, metavar='L',\n help='num encoder layers')\n parser.add_argument('--encoder-embed-dim', type=int, metavar='H',\n help='encoder embedding dimension')\n parser.add_argument('--encoder-ffn-embed-dim', type=int, metavar='F',\n help='encoder embedding dimension for FFN')\n parser.add_argument('--encoder-attention-heads', type=int, metavar='A',\n help='num encoder attention heads')\n parser.add_argument('--activation-fn',\n choices=utils.get_available_activation_fns(),\n help='activation function to use')\n parser.add_argument('--pooler-activation-fn',\n choices=utils.get_available_activation_fns(),\n help='activation function to use for pooler layer')\n parser.add_argument('--encoder-normalize-before', action='store_true',\n help='apply layernorm before each encoder block')\n parser.add_argument('--dropout', type=float, metavar='D',\n help='dropout probability')\n parser.add_argument('--attention-dropout', type=float, metavar='D',\n help='dropout probability for attention weights')\n parser.add_argument('--activation-dropout', type=float, metavar='D',\n help='dropout probability after activation in FFN')\n parser.add_argument('--pooler-dropout', type=float, metavar='D',\n help='dropout probability in the masked_lm pooler layers')\n parser.add_argument('--max-positions', type=int,\n help='number of positional embeddings to learn')\n parser.add_argument('--load-checkpoint-heads', action='store_true',\n help='(re-)register and load heads when loading checkpoints')\n # args for \"Reducing Transformer Depth on Demand with Structured Dropout\" (Fan et al., 2019)\n parser.add_argument('--encoder-layerdrop', type=float, metavar='D', default=0,\n help='LayerDrop probability for encoder')\n parser.add_argument('--encoder-layers-to-keep', default=None,\n help='which layers to *keep* when pruning as a comma-separated list')\n\n @classmethod\n def build_model(cls, args, task):\n \"\"\"Build a new model instance.\"\"\"\n\n # make sure all arguments are present\n base_architecture(args)\n\n if not hasattr(args, 'max_positions'):\n args.max_positions = args.tokens_per_sample\n\n encoder = RobertaEncoder(args, task.source_dictionary)\n return cls(args, encoder)\n\n def forward(self, src_tokens, features_only=False, return_all_hiddens=False, classification_head_name=None, **kwargs):\n if classification_head_name is not None:\n features_only = True\n\n x, extra = self.decoder(src_tokens, features_only, return_all_hiddens, **kwargs)\n\n if classification_head_name is not None:\n x = self.classification_heads[classification_head_name](x)\n return x, extra\n\n def register_classification_head(self, name, num_classes=None, inner_dim=None, **kwargs):\n \"\"\"Register a classification head.\"\"\"\n if name in self.classification_heads:\n prev_num_classes = self.classification_heads[name].out_proj.out_features\n prev_inner_dim = self.classification_heads[name].dense.out_features\n if num_classes != prev_num_classes or inner_dim != prev_inner_dim:\n print(\n 'WARNING: re-registering head \"{}\" with num_classes {} (prev: {}) '\n 'and inner_dim {} (prev: {})'.format(\n name, num_classes, prev_num_classes, inner_dim, prev_inner_dim\n )\n )\n self.classification_heads[name] = RobertaClassificationHead(\n self.args.encoder_embed_dim,\n inner_dim or self.args.encoder_embed_dim,\n num_classes,\n self.args.pooler_activation_fn,\n self.args.pooler_dropout,\n )\n\n @property\n def supported_targets(self):\n return {'self'}\n\n @classmethod\n def from_pretrained(cls, model_name_or_path, checkpoint_file='model.pt', data_name_or_path='.', bpe='gpt2', **kwargs):\n from fairseq import hub_utils\n x = hub_utils.from_pretrained(\n model_name_or_path,\n checkpoint_file,\n data_name_or_path,\n archive_map=cls.hub_models(),\n bpe=bpe,\n load_checkpoint_heads=True,\n **kwargs,\n )\n return RobertaHubInterface(x['args'], x['task'], x['models'][0])\n\n def upgrade_state_dict_named(self, state_dict, name):\n prefix = name + '.' if name != '' else ''\n current_head_names = [] if not hasattr(self, 'classification_heads') else \\\n self.classification_heads.keys()\n\n # Handle new classification heads present in the state dict.\n keys_to_delete = []\n for k in state_dict.keys():\n if not k.startswith(prefix + 'classification_heads.'):\n continue\n\n head_name = k[len(prefix + 'classification_heads.'):].split('.')[0]\n num_classes = state_dict[prefix + 'classification_heads.' + head_name + '.out_proj.weight'].size(0)\n inner_dim = state_dict[prefix + 'classification_heads.' + head_name + '.dense.weight'].size(0)\n\n if getattr(self.args, 'load_checkpoint_heads', False):\n if head_name not in current_head_names:\n self.register_classification_head(head_name, num_classes, inner_dim)\n else:\n if head_name not in current_head_names:\n print(\n 'WARNING: deleting classification head ({}) from checkpoint '\n 'not present in current model: {}'.format(head_name, k)\n )\n keys_to_delete.append(k)\n elif (\n num_classes != self.classification_heads[head_name].out_proj.out_features\n or inner_dim != self.classification_heads[head_name].dense.out_features\n ):\n print(\n 'WARNING: deleting classification head ({}) from checkpoint '\n 'with different dimensions than current model: {}'.format(head_name, k)\n )\n keys_to_delete.append(k)\n for k in keys_to_delete:\n del state_dict[k]\n\n # Copy any newly-added classification heads into the state dict\n # with their current weights.\n if hasattr(self, 'classification_heads'):\n cur_state = self.classification_heads.state_dict()\n for k, v in cur_state.items():\n if prefix + 'classification_heads.' + k not in state_dict:\n print('Overwriting', prefix + 'classification_heads.' + k)\n state_dict[prefix + 'classification_heads.' + k] = v\n\n\nclass RobertaLMHead(nn.Module):\n \"\"\"Head for masked language modeling.\"\"\"\n\n def __init__(self, embed_dim, output_dim, activation_fn, weight=None):\n super().__init__()\n self.dense = nn.Linear(embed_dim, embed_dim)\n self.activation_fn = utils.get_activation_fn(activation_fn)\n self.layer_norm = LayerNorm(embed_dim)\n\n if weight is None:\n weight = nn.Linear(embed_dim, output_dim, bias=False).weight\n self.weight = weight\n self.bias = nn.Parameter(torch.zeros(output_dim))\n\n def forward(self, features, masked_tokens=None, **kwargs):\n # Only project the unmasked tokens while training,\n # saves both memory and computation\n if masked_tokens is not None:\n features = features[masked_tokens, :]\n\n x = self.dense(features)\n x = self.activation_fn(x)\n x = self.layer_norm(x)\n # project back to size of vocabulary with bias\n x = F.linear(x, self.weight) + self.bias\n return x\n\n\nclass RobertaClassificationHead(nn.Module):\n \"\"\"Head for sentence-level classification tasks.\"\"\"\n\n def __init__(self, input_dim, inner_dim, num_classes, activation_fn, pooler_dropout):\n super().__init__()\n self.dense = nn.Linear(input_dim, inner_dim)\n self.activation_fn = utils.get_activation_fn(activation_fn)\n self.dropout = nn.Dropout(p=pooler_dropout)\n self.out_proj = nn.Linear(inner_dim, num_classes)\n\n def forward(self, features, **kwargs):\n x = features[:, 0, :] # take <s> token (equiv. to [CLS])\n x = self.dropout(x)\n x = self.dense(x)\n x = self.activation_fn(x)\n x = self.dropout(x)\n x = self.out_proj(x)\n return x\n\n\nclass RobertaEncoder(FairseqDecoder):\n \"\"\"RoBERTa encoder.\n\n Implements the :class:`~fairseq.models.FairseqDecoder` interface required\n by :class:`~fairseq.models.FairseqLanguageModel`.\n \"\"\"\n\n def __init__(self, args, dictionary):\n super().__init__(dictionary)\n self.args = args\n\n # RoBERTa is a sentence encoder model, so users will intuitively trim\n # encoder layers. However, the implementation uses the fairseq decoder,\n # so we fix here.\n if args.encoder_layers_to_keep:\n args.encoder_layers = len(args.encoder_layers_to_keep.split(\",\"))\n args.decoder_layers_to_keep = args.encoder_layers_to_keep\n args.encoder_layers_to_keep = None\n\n self.sentence_encoder = TransformerSentenceEncoder(\n padding_idx=dictionary.pad(),\n vocab_size=len(dictionary),\n num_encoder_layers=args.encoder_layers,\n embedding_dim=args.encoder_embed_dim,\n ffn_embedding_dim=args.encoder_ffn_embed_dim,\n num_attention_heads=args.encoder_attention_heads,\n dropout=args.dropout,\n attention_dropout=args.attention_dropout,\n activation_dropout=args.activation_dropout,\n layerdrop=args.encoder_layerdrop,\n max_seq_len=args.max_positions,\n num_segments=0,\n encoder_normalize_before=True,\n apply_bert_init=True,\n activation_fn=args.activation_fn,\n )\n self.lm_head = RobertaLMHead(\n embed_dim=args.encoder_embed_dim,\n output_dim=len(dictionary),\n activation_fn=args.activation_fn,\n weight=self.sentence_encoder.embed_tokens.weight,\n )\n\n def forward(self, src_tokens, features_only=False, return_all_hiddens=False, masked_tokens=None, **unused):\n \"\"\"\n Args:\n src_tokens (LongTensor): input tokens of shape `(batch, src_len)`\n features_only (bool, optional): skip LM head and just return\n features. If True, the output will be of shape\n `(batch, src_len, embed_dim)`.\n return_all_hiddens (bool, optional): also return all of the\n intermediate hidden states (default: False).\n\n Returns:\n tuple:\n - the LM output of shape `(batch, src_len, vocab)`\n - a dictionary of additional data, where 'inner_states'\n is a list of hidden states.\n \"\"\"\n x, extra = self.extract_features(src_tokens, return_all_hiddens)\n if not features_only:\n x = self.output_layer(x, masked_tokens=masked_tokens)\n return x, extra\n\n def extract_features(self, src_tokens, return_all_hiddens=False, **unused):\n inner_states, _ = self.sentence_encoder(\n src_tokens,\n last_state_only=not return_all_hiddens,\n )\n features = inner_states[-1]\n return features, {'inner_states': inner_states if return_all_hiddens else None}\n\n def output_layer(self, features, masked_tokens=None, **unused):\n return self.lm_head(features, masked_tokens)\n\n def max_positions(self):\n \"\"\"Maximum output length supported by the encoder.\"\"\"\n return self.args.max_positions\n\n\n@register_model_architecture('roberta', 'roberta')\ndef base_architecture(args):\n args.encoder_layers = getattr(args, 'encoder_layers', 12)\n args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 768)\n args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 3072)\n args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 12)\n\n args.activation_fn = getattr(args, 'activation_fn', 'gelu')\n args.pooler_activation_fn = getattr(args, 'pooler_activation_fn', 'tanh')\n\n args.dropout = getattr(args, 'dropout', 0.1)\n args.attention_dropout = getattr(args, 'attention_dropout', 0.1)\n args.activation_dropout = getattr(args, 'activation_dropout', 0.0)\n args.pooler_dropout = getattr(args, 'pooler_dropout', 0.0)\n\n\n@register_model_architecture('roberta', 'roberta_base')\ndef roberta_base_architecture(args):\n base_architecture(args)\n\n\n@register_model_architecture('roberta', 'roberta_large')\ndef roberta_large_architecture(args):\n args.encoder_layers = getattr(args, 'encoder_layers', 24)\n args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024)\n args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 4096)\n args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 16)\n base_architecture(args)\n\n\n@register_model_architecture('roberta', 'xlm')\ndef xlm_architecture(args):\n args.encoder_layers = getattr(args, 'encoder_layers', 16)\n args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1280)\n args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 1280*4)\n args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 16)\n\n base_architecture(args)\n" ]
[ [ "torch.nn.Dropout", "torch.zeros", "torch.nn.ModuleDict", "torch.nn.Linear", "torch.nn.functional.linear" ] ]
Zikoat/musweeper
[ "07e3e5e5e5e4edad4d8b1b6bb05aee2f33f8d9cb" ]
[ "musweeper/musweeper/muzero/model/selfplay.py" ]
[ "from ..utils.game_history import game_event_history\nimport torch\nimport numpy as np\nfrom ..model.components import transform_input\nfrom ..tree.temperture import *\n\ndef play_game(model, env, self_play=False, custom_end_function=None, custom_reward_function=None, custom_state_function=None, extra_loss_tracker=None, timeout_steps=100):\n\t\"\"\"\n\tPLays a game with a given model\n\n\tParameters\n\t----------\n\tmodel : Muzero\n\t\tthe muzero model\n\tenv : gym.env\n\t\tthe environment\n\tself_play : bool, optional\n\t\tshould self_play be used (not fully implemented), by default False\n\tcustom_end_function : callable, optional\n\t\tshould a custom function be used for determing if a game is done, by default None\n\tcustom_reward_function : callable, optional\n\t\tshould a custom function be used for the reward function, by default None\n\tcustom_state_function : callable, optional\n\t\tshould a custom function be used to get the observation of the enviorment, by default None\n\textra_loss_tracker : callable, optional\n\t\tshould a function calculate a extra loss, by default None\n\ttimeout_steps : int, optional\n\t\tmax steps to take in a environment, by default 100\n\n\tReturns\n\t-------\n\tgame_event_history\n\t\tthe events taken place in the game\n\t\"\"\"\n\tmodel.reset()\n\tobservation = env.reset()\n\tgame_history = game_event_history()\n\tdone = False\n\tstep = 0\n\ttemperature = 1\n\twhile not done and step < timeout_steps:\n\t\tif self_play:\n\t\t\taction, policy = model.think(observation)\n\t\t\tbest_action = action.item()\n\t\t\tobservation, reward, done = env.step(best_action)[:3]\n\t\t\tgame_history.add(\n\t\t\t\taction=policy,\n\t\t\t\treward=None,\n\t\t\t\tvalue=None,\n\t\t\t\tstate=None\n\t\t\t)\n\t\telse:\n\t\t\tobservation = custom_state_function(env) if custom_state_function is not None else observation\n\t\t\tstate = transform_input(observation)\n\t\t\tinfo = extra_loss_tracker(env) if extra_loss_tracker else None\n\n\t\t\tif model.use_naive_search:\n\t\t\t\tbest_action = model.plan_action_naive(state)\n\t\t\telse:\n\t\t\t\tlegal_actions = getattr(env, \"legal_actions\", None)\n\t\t\t\tlegal_actions = legal_actions() if legal_actions is not None else None\n\t\t\t\tif legal_actions is not None and len(legal_actions) == 0:\n\t\t\t\t\tbreak\n\t\t\t\tbest_action = temperature_softmax(model.plan_action(state, legal_actions), T=(temperature), size=model.action_size)\n\t\t\t\ttemperature *= 0.9\n\t\t\tobservation, reward, done = env.step(best_action)[:3]\n\n\t\t\tif custom_end_function is not None:\n\t\t\t\tdone = custom_end_function(env)\n\t\t\tif custom_reward_function is not None:\n\t\t\t\treward = custom_reward_function(env, done)\n\n\t\t\tgame_history.add(\n\t\t\t\treward=torch.tensor([reward]).reshape((1, -1)),\n\t\t\t\taction=best_action,\n\t\t\t\tpolicy=None if model.use_naive_search else model.tree.get_policy(),\n\t\t\t\tvalue=torch.tensor([1]).reshape((1, -1)) if not done else torch.tensor([0]).reshape((1, -1)),\n\t\t\t\tstate=state,\n\t\t\t\tinfo=info\n\t\t\t)\n\t\t\tmodel.reset()\n\t\tstep += 1\n\treturn game_history\n\ndef selfplay_single_player(model, env, games=10):\n\t\"\"\"\n\tSince the model will is playing a single player game\n\tthe self play algorithm needs to be adjusted to account for this\n\n\tParameters\n\t----------\n\tmodel : muzero\n\t\tmuzero - since we are working with only one model (since it's single player) no need for model storage\n\tenv : gym.Env\n\t\tthe environment where the model will be playing\n\t\"\"\"\n\thistory = []\n\tfor _ in range(games):\n\t\thistory.append(play_game(model, env, self_play=True))\n\tsorted_history = sorted(history, key=lambda x: x.historic_reward)\n\tmiddle = len(sorted_history) // 2\n\tbad_plays = sorted_history[:middle]\n\twin_plays = sorted_history[middle:]\n\tloss = 0\n\tfor player, sign in zip([bad_plays, win_plays], [-1, 1]):\n\t\tfor game in player:\n\t\t\tfor event in game.history:\n\t\t\t\tloss += (sign * event.action).sum()\n\treturn loss\n" ]
[ [ "torch.tensor" ] ]
RACT-CF/RaCT
[ "ced06c9e3398184c82aa42d5eb0cd5679c905375" ]
[ "utils/warp_utils.py" ]
[ "\"\"\"\nCreates a function to be used in tf.py_func, which produces a faithful\nrepresentation of the WARP loss (with margin set to 0) that runs in\nalmost linear time (aside from a sorting operation).\n\"\"\"\n\nimport numpy as np\n\nfrom time import time\nimport random\n\nclass timing_decorator:\n def __init__(self, name):\n self.name = name\n\n def __call__(self, func):\n def wrapper(*args, **kwargs):\n t = time()\n v = func(*args, **kwargs)\n print(\"Time to do {} is {}\".format(self.name, time()-t))\n return v\n\n return wrapper\n\n\n\ndef create_rank_weighting_vector(dimension):\n \"\"\"This part is easy at least.\"\"\"\n transformer = np.zeros((dimension,), dtype=np.float32)\n transformer[0] = 1 # I think this is right.\n for i in range(1, dimension):\n transformer[i] = transformer[i - 1] + (1. / (1 + i))\n return transformer\n\n\ndef create_count_above_vector(target_vector=None, argsort_vector=None):\n \"\"\"\n For each index, this should tell you how many \"unseen\" items are ranked above it.\n For a \"seen\" item, this is equivalent to the number of pairs the item\n will appear in for the loss function.\n \"\"\"\n\n reverse_target_vector = -1*target_vector + 1 # So it's 1 when it was 0, and vise versa.\n sorted_reverse_target_vector = reverse_target_vector[argsort_vector]\n cumsum = np.cumsum(sorted_reverse_target_vector)\n count_above_vector = cumsum[np.argsort(argsort_vector)]\n\n count_above_vector+=target_vector\n count_above_vector-= 1\n\n count_above_vector = count_above_vector.astype(np.float32)\n\n return count_above_vector\n\n\ndef create_error_vector_with_count_above_vector(target_vector=None,\n argsort_vector=None,\n rank_weighting_vector=None,\n count_above_vector=None):\n \"\"\"\n Given the number of \"unseen\" items above each \"seen\" item, calculates the\n error vector for a single user.\n \"\"\"\n\n assert target_vector is not None\n assert argsort_vector is not None\n assert rank_weighting_vector is not None\n assert count_above_vector is not None\n\n assert target_vector.shape == argsort_vector.shape == rank_weighting_vector.shape == count_above_vector.shape\n assert len(target_vector.shape) == 1\n\n reversed_argsort_vector = np.flip(argsort_vector, axis=0)\n # reverse_argsorted_rank_weight = rank_weighting_vector[reversed_argsort_vector]\n flipped_rank_weight = np.flip(rank_weighting_vector, axis=0)\n reverse_argsorted_target_vector = target_vector[reversed_argsort_vector]\n reverse_argsorted_count_above = count_above_vector[reversed_argsort_vector]\n\n good_part_of_argsorted_error_vector = (\n reverse_argsorted_count_above *\n flipped_rank_weight * \n reverse_argsorted_target_vector\n * -1) #The target-vector part is so we only have that component.\n\n amount_per_bad_vector = np.cumsum(reverse_argsorted_target_vector * flipped_rank_weight)\n bad_part_of_argsorted_error_vector = amount_per_bad_vector * (1 - reverse_argsorted_target_vector)\n\n argsorted_error_vector = bad_part_of_argsorted_error_vector + good_part_of_argsorted_error_vector\n error_vector = argsorted_error_vector[np.argsort(reversed_argsort_vector)]\n\n return error_vector\n\n\ndef create_error_vector_from_raw_inputs(score_vector=None,\n target_vector=None,\n rank_weighting_vector=None):\n \"\"\"\n score_vector: The prediction from the model\n target_vector: 0 if an item was not seen, 1 if it was.\n rank_weighting_vector: a precomputed vector to scale the loss associated\n with a given pair of items.\n\n Outputs the WARP loss for a SINGLE user (un-batched)\n \"\"\"\n\n assert score_vector is not None\n assert target_vector is not None\n assert rank_weighting_vector is not None\n\n assert score_vector.shape == target_vector.shape\n assert len(score_vector.shape) == 1\n\n argsort_vector = np.argsort(score_vector)\n # rank_vector = np.argsort(argsort_vector)\n\n count_above_vector = create_count_above_vector(\n target_vector=target_vector, argsort_vector=argsort_vector)\n\n error_vector = create_error_vector_with_count_above_vector(\n target_vector=target_vector,\n argsort_vector=argsort_vector,\n rank_weighting_vector=rank_weighting_vector,\n count_above_vector=count_above_vector)\n\n return error_vector\n\n\ndef batch_create_error_vector(score_vector=None, target_vector=None, rank_weighting_vector=None):\n \"\"\"\n Confirms the inputs. Then makes one per\n \"\"\"\n\n assert score_vector is not None\n assert target_vector is not None\n assert rank_weighting_vector is not None\n\n assert score_vector.shape == target_vector.shape\n assert len(score_vector.shape) == 2\n\n to_return = np.zeros_like(score_vector, dtype=np.float32)\n\n for i in range(len(score_vector)):\n single_score_vector = score_vector[i]\n single_target_vector = target_vector[i]\n # t = time()\n to_return[i][...] = create_error_vector_from_raw_inputs(\n score_vector=single_score_vector,\n target_vector=single_target_vector,\n rank_weighting_vector=rank_weighting_vector)\n # print(\"Time to do single error vector from raw inputs: {}\".format(time() - t))\n return to_return\n\nclass ErrorVectorCreator:\n \"\"\"\n A truthful implementation (sans margin) of the WARP loss, described here\n http://www.thespermwhale.com/jaseweston/papers/wsabie-ijcai.pdf\n\n Because WARP loss is a piecewise linear pairwise loss, we found a\n smart way to speed it up from O(n*m) to O(n log n), which on our datasets\n is a practical increase of ~100x\n\n It works by sorting the inputs, grouping the pairwise loss terms by\n \"seen\" item, simplifying each of these groups in constant time to one term,\n and then summing them up.\n\n This will be initialized once, and then used as the py_func function.\n\n It outputs an error_scaling vector for a listwise margin-less WARP loss.\n\n You take the dot product of the prediction-vector with this output in\n order to get the WARP-loss.\n \"\"\"\n\n def __init__(self, input_dim=None, margin=0.0, verbose=False):\n assert input_dim is not None\n self.input_dim = input_dim\n self.transformer = create_rank_weighting_vector(input_dim)\n self.transformer.flags.writeable = False\n self.verbose = verbose\n\n def __call__(self, score_vector, target_vector):\n assert score_vector.shape[1] == self.input_dim\n assert target_vector.shape[1] == self.input_dim\n\n score_vector = -1 * score_vector\n\n t = time()\n to_return = batch_create_error_vector(\n score_vector=score_vector,\n target_vector=target_vector,\n rank_weighting_vector=self.transformer)\n if self.verbose:\n print(\"Time to do new error_vector_creator is {}\".format(time() - t))\n return to_return\n" ]
[ [ "numpy.cumsum", "numpy.zeros_like", "numpy.argsort", "numpy.flip", "numpy.zeros" ] ]
ttktk/tensorflow
[ "43bd3c52ad6f5e68382218cf72a0aaa7edbee0a3" ]
[ "tensorflow/python/compat/compat.py" ]
[ "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Utilities for API compatibility between TensorFlow release versions.\n\nSee [Version\nCompatibility](https://tensorflow.org/guide/version_compat#backward_forward)\n\"\"\"\n\nimport datetime\nimport os\n\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util import tf_contextlib\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n# This value changes every day with an automatic CL. It can be modified in code\n# via `forward_compatibility_horizon()` or with the environment variable\n# TF_FORWARD_COMPATIBILITY_DELTA_DAYS, which is added to the compatibility date.\n_FORWARD_COMPATIBILITY_HORIZON = datetime.date(2021, 10, 19)\n_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME = \"TF_FORWARD_COMPATIBILITY_DELTA_DAYS\"\n_FORWARD_COMPATIBILITY_DATE_NUMBER = None\n\n\ndef _date_to_date_number(year, month, day):\n return (year << 9) | (month << 5) | day\n\n\ndef _update_forward_compatibility_date_number(date_to_override=None):\n \"\"\"Update the base date to compare in forward_compatible function.\"\"\"\n\n global _FORWARD_COMPATIBILITY_DATE_NUMBER\n\n if date_to_override:\n date = date_to_override\n else:\n date = _FORWARD_COMPATIBILITY_HORIZON\n delta_days = os.getenv(_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME)\n if delta_days:\n date += datetime.timedelta(days=int(delta_days))\n\n if date < _FORWARD_COMPATIBILITY_HORIZON:\n logging.warning(\"Trying to set the forward compatibility date to the past\"\n \" date %s. This will be ignored by TensorFlow.\" % (date))\n return\n _FORWARD_COMPATIBILITY_DATE_NUMBER = _date_to_date_number(\n date.year, date.month, date.day)\n\n\n_update_forward_compatibility_date_number()\n\n\n@tf_export(\"compat.forward_compatible\")\ndef forward_compatible(year, month, day):\n \"\"\"Return true if the forward compatibility window has expired.\n\n See [Version\n compatibility](https://tensorflow.org/guide/version_compat#backward_forward).\n\n Forward-compatibility refers to scenarios where the producer of a TensorFlow\n model (a GraphDef or SavedModel) is compiled against a version of the\n TensorFlow library newer than what the consumer was compiled against. The\n \"producer\" is typically a Python program that constructs and trains a model\n while the \"consumer\" is typically another program that loads and serves the\n model.\n\n TensorFlow has been supporting a 3 week forward-compatibility window for\n programs compiled from source at HEAD.\n\n For example, consider the case where a new operation `MyNewAwesomeAdd` is\n created with the intent of replacing the implementation of an existing Python\n wrapper - `tf.add`. The Python wrapper implementation should change from\n something like:\n\n ```python\n def add(inputs, name=None):\n return gen_math_ops.add(inputs, name)\n ```\n\n to:\n\n ```python\n from tensorflow.python.compat import compat\n\n def add(inputs, name=None):\n if compat.forward_compatible(year, month, day):\n # Can use the awesome new implementation.\n return gen_math_ops.my_new_awesome_add(inputs, name)\n # To maintain forward compatibility, use the old implementation.\n return gen_math_ops.add(inputs, name)\n ```\n\n Where `year`, `month`, and `day` specify the date beyond which binaries\n that consume a model are expected to have been updated to include the\n new operations. This date is typically at least 3 weeks beyond the date\n the code that adds the new operation is committed.\n\n Args:\n year: A year (e.g., 2018). Must be an `int`.\n month: A month (1 <= month <= 12) in year. Must be an `int`.\n day: A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an\n `int`.\n\n Returns:\n True if the caller can expect that serialized TensorFlow graphs produced\n can be consumed by programs that are compiled with the TensorFlow library\n source code after (year, month, day).\n \"\"\"\n return _FORWARD_COMPATIBILITY_DATE_NUMBER > _date_to_date_number(\n year, month, day)\n\n\n@tf_export(\"compat.forward_compatibility_horizon\")\n@tf_contextlib.contextmanager\ndef forward_compatibility_horizon(year, month, day):\n \"\"\"Context manager for testing forward compatibility of generated graphs.\n\n See [Version\n compatibility](https://tensorflow.org/guide/version_compat#backward_forward).\n\n To ensure forward compatibility of generated graphs (see `forward_compatible`)\n with older binaries, new features can be gated with:\n\n ```python\n if compat.forward_compatible(year=2018, month=08, date=01):\n generate_graph_with_new_features()\n else:\n generate_graph_so_older_binaries_can_consume_it()\n ```\n\n However, when adding new features, one may want to unittest it before\n the forward compatibility window expires. This context manager enables\n such tests. For example:\n\n ```python\n from tensorflow.python.compat import compat\n\n def testMyNewFeature(self):\n with compat.forward_compatibility_horizon(2018, 08, 02):\n # Test that generate_graph_with_new_features() has an effect\n ```\n\n Args:\n year: A year (e.g., 2018). Must be an `int`.\n month: A month (1 <= month <= 12) in year. Must be an `int`.\n day: A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an\n `int`.\n\n Yields:\n Nothing.\n \"\"\"\n try:\n _update_forward_compatibility_date_number(datetime.date(year, month, day))\n yield\n finally:\n _update_forward_compatibility_date_number()\n" ]
[ [ "tensorflow.python.platform.tf_logging.warning", "tensorflow.python.util.tf_export.tf_export" ] ]
Nuevalgo/Feedbot
[ "96bdd150fcd92fa155dfc7b13d930bab394e8e47" ]
[ "site-packages/matplotlib-1.3.1/doc/sphinxext/gen_gallery.py" ]
[ "# -*- coding: UTF-8 -*-\nimport os\nimport re\nimport glob\nimport warnings\n\nimport sphinx.errors\n\nimport matplotlib.image as image\n\n\nexclude_example_sections = ['units']\nmultiimage = re.compile('(.*?)(_\\d\\d){1,2}')\n\n# generate a thumbnail gallery of examples\ngallery_template = \"\"\"\\\n{{% extends \"layout.html\" %}}\n{{% set title = \"Thumbnail gallery\" %}}\n\n\n{{% block body %}}\n\n<h3>Click on any image to see full size image and source code</h3>\n<br/>\n\n<li><a class=\"reference internal\" href=\"#\">Gallery</a>\n <ul>\n {toc}\n </ul>\n</li>\n\n{gallery}\n\n{{% endblock %}}\n\"\"\"\n\nheader_template = \"\"\"\\\n<div class=\"section\" id=\"{section}\">\n<h4>\n {title}<a class=\"headerlink\" href=\"#{section}\" title=\"Permalink to this headline\">¶</a>\n</h4>\"\"\"\n\nlink_template = \"\"\"\\\n<a href=\"{link}\"><img src=\"{thumb}\" border=\"0\" alt=\"{basename}\"/></a>\n\"\"\"\n\ntoc_template = \"\"\"\\\n<li><a class=\"reference internal\" href=\"#{section}\">{title}</a></li>\"\"\"\n\n\ndef make_thumbnail(args):\n image.thumbnail(args[0], args[1], 0.3)\n\n\ndef out_of_date(original, derived):\n return (not os.path.exists(derived) or\n os.stat(derived).st_mtime < os.stat(original).st_mtime)\n\n\ndef gen_gallery(app, doctree):\n if app.builder.name != 'html':\n return\n\n outdir = app.builder.outdir\n rootdir = 'plot_directive/mpl_examples'\n\n example_sections = list(app.builder.config.mpl_example_sections)\n for i, (subdir, title) in enumerate(example_sections):\n if subdir in exclude_example_sections:\n example_sections.pop(i)\n\n # images we want to skip for the gallery because they are an unusual\n # size that doesn't layout well in a table, or because they may be\n # redundant with other images or uninteresting\n skips = set([\n 'mathtext_examples',\n 'matshow_02',\n 'matshow_03',\n 'matplotlib_icon',\n ])\n\n thumbnails = {}\n rows = []\n toc_rows = []\n\n for subdir, title in example_sections:\n rows.append(header_template.format(title=title, section=subdir))\n toc_rows.append(toc_template.format(title=title, section=subdir))\n\n origdir = os.path.join('build', rootdir, subdir)\n thumbdir = os.path.join(outdir, rootdir, subdir, 'thumbnails')\n if not os.path.exists(thumbdir):\n os.makedirs(thumbdir)\n\n data = []\n\n for filename in sorted(glob.glob(os.path.join(origdir, '*.png'))):\n if filename.endswith(\"hires.png\"):\n continue\n\n path, filename = os.path.split(filename)\n basename, ext = os.path.splitext(filename)\n if basename in skips:\n continue\n\n # Create thumbnails based on images in tmpdir, and place\n # them within the build tree\n orig_path = str(os.path.join(origdir, filename))\n thumb_path = str(os.path.join(thumbdir, filename))\n if out_of_date(orig_path, thumb_path) or True:\n thumbnails[orig_path] = thumb_path\n\n m = multiimage.match(basename)\n if m is not None:\n basename = m.group(1)\n\n data.append((subdir, basename,\n os.path.join(rootdir, subdir, 'thumbnails', filename)))\n\n for (subdir, basename, thumbfile) in data:\n if thumbfile is not None:\n link = 'examples/%s/%s.html'%(subdir, basename)\n rows.append(link_template.format(link=link,\n thumb=thumbfile,\n basename=basename))\n\n if len(data) == 0:\n warnings.warn(\"No thumbnails were found in %s\" % subdir)\n\n # Close out the <div> opened up at the top of this loop\n rows.append(\"</div>\")\n\n content = gallery_template.format(toc='\\n'.join(toc_rows),\n gallery='\\n'.join(rows))\n\n # Only write out the file if the contents have actually changed.\n # Otherwise, this triggers a full rebuild of the docs\n\n gallery_path = os.path.join(app.builder.srcdir,\n '_templates', 'gallery.html')\n if os.path.exists(gallery_path):\n fh = open(gallery_path, 'r')\n regenerate = fh.read() != content\n fh.close()\n else:\n regenerate = True\n\n if regenerate:\n fh = open(gallery_path, 'w')\n fh.write(content)\n fh.close()\n\n for key in app.builder.status_iterator(\n iter(thumbnails.keys()), \"generating thumbnails... \",\n length=len(thumbnails)):\n if out_of_date(key, thumbnails[key]):\n image.thumbnail(key, thumbnails[key], 0.3)\n\n\ndef setup(app):\n app.connect('env-updated', gen_gallery)\n\n try: # multiple plugins may use mpl_example_sections\n app.add_config_value('mpl_example_sections', [], True)\n except sphinx.errors.ExtensionError:\n pass # mpl_example_sections already defined\n" ]
[ [ "matplotlib.image.thumbnail" ] ]
Complicateddd/CascadeRCNN
[ "019010e80411325dbde62f4d649e5a2ead8eabac" ]
[ "train_fpn.py" ]
[ "# --------------------------------------------------------\n# Pytorch FPN\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Jianwei Yang, based on code from faster R-CNN\n# --------------------------------------------------------\n# python train_fpn.py --dataset pascal_voc --net res101 --bs 2 --nw 1 --lr 0.001 --lr_decay_step 8 --cuda\n# python setup.py build develop\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport _init_paths\nimport os\nimport sys\nimport numpy as np\nimport argparse\nimport pprint\nimport pdb\nimport time\nimport logging\n\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.optim as optim\nfrom datetime import datetime\n\nimport torchvision.transforms as transforms\nfrom torch.utils.data.sampler import Sampler\n\nfrom roi_data_layer.roidb import combined_roidb\nfrom roi_data_layer.roibatchLoader import roibatchLoader\nfrom model.utils.config import cfg, cfg_from_file, cfg_from_list, get_output_dir\nfrom model.utils.net_utils import weights_normal_init, save_net, load_net, \\\n adjust_learning_rate, save_checkpoint, clip_gradient\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\nfrom model.fpn.resnet import resnet\nimport pdb\n\ndef parse_args():\n \"\"\"\n Parse input arguments\n \"\"\"\n parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')\n parser.add_argument('--dataset', dest='dataset',\n help='training dataset',\n default='pascal_voc', type=str)\n parser.add_argument('--net', dest='net',\n help='res101, res152, etc',\n default='res101', type=str)\n parser.add_argument('--start_epoch', dest='start_epoch',\n help='starting epoch',\n default=1, type=int)\n parser.add_argument('--epochs', dest='max_epochs',\n help='number of epochs to train',\n default=26, type=int)\n parser.add_argument('--disp_interval', dest='disp_interval',\n help='number of iterations to display',\n default=10, type=int)\n parser.add_argument('--checkpoint_interval', dest='checkpoint_interval',\n help='number of iterations to display',\n default=10000, type=int)\n\n parser.add_argument('--save_dir', dest='save_dir',\n help='directory to save models', default=\"models\",\n nargs=argparse.REMAINDER)\n parser.add_argument('--nw', dest='num_workers',\n help='number of worker to load data',\n default=4, type=int)\n parser.add_argument('--cuda', dest='cuda',\n help='whether use CUDA',\n action='store_true')\n parser.add_argument('--mGPUs', dest='mGPUs',\n help='whether use multiple GPUs',\n action='store_true')\n parser.add_argument('--lscale', dest='lscale',\n help='whether use large scale',\n action='store_true')\n parser.add_argument('--bs', dest='batch_size',\n help='batch_size',\n default=4, type=int)\n parser.add_argument('--cag', dest='class_agnostic',\n help='whether perform class_agnostic bbox regression',\n action='store_true')\n\n# config optimization\n parser.add_argument('--o', dest='optimizer',\n help='training optimizer',\n default=\"sgd\", type=str)\n parser.add_argument('--lr', dest='lr',\n help='starting learning rate',\n default=0.001, type=float)\n parser.add_argument('--lr_decay_step', dest='lr_decay_step',\n help='step to do learning rate decay, unit is epoch',\n default=40, type=int)\n parser.add_argument('--lr_decay_gamma', dest='lr_decay_gamma',\n help='learning rate decay ratio',\n default=0.1, type=float)\n\n# set training session\n parser.add_argument('--s', dest='session',\n help='training session',\n default=1, type=int)\n\n# resume trained model\n parser.add_argument('--r', dest='resume',\n help='resume checkpoint or not',\n default=False, type=bool)\n parser.add_argument('--checksession', dest='checksession',\n help='checksession to load model',\n default=1, type=int)\n parser.add_argument('--checkepoch', dest='checkepoch',\n help='checkepoch to load model',\n default=1, type=int)\n parser.add_argument('--checkpoint', dest='checkpoint',\n help='checkpoint to load model',\n default=0, type=int)\n# log and diaplay\n parser.add_argument('--use_tfboard', dest='use_tfboard',\n help='whether use tensorflow tensorboard',\n default=False, type=bool)\n\n args = parser.parse_args()\n return args\n\n\nclass sampler(Sampler):\n def __init__(self, train_size, batch_size):\n num_data = train_size\n self.num_per_batch = int(num_data / batch_size)\n self.batch_size = batch_size\n self.range = torch.arange(0,batch_size).view(1, batch_size).long()\n self.leftover_flag = False\n if num_data % batch_size:\n self.leftover = torch.arange(self.num_per_batch*batch_size, num_data).long()\n self.leftover_flag = True\n def __iter__(self):\n rand_num = torch.randperm(self.num_per_batch).view(-1,1) * self.batch_size\n self.rand_num = rand_num.expand(self.num_per_batch, self.batch_size) + self.range\n\n self.rand_num_view = self.rand_num.view(-1)\n\n if self.leftover_flag:\n self.rand_num_view = torch.cat((self.rand_num_view, self.leftover),0)\n\n return iter(self.rand_num_view)\n\n def __len__(self):\n return num_data\n\ndef _print(str, logger):\n print(str)\n logger.info(str)\n\nif __name__ == '__main__':\n\n args = parse_args()\n\n print('Called with args:')\n print(args)\n\n if args.use_tfboard:\n from model.utils.logger import Logger\n # Set the logger\n logger = Logger('./logs')\n\n logging.basicConfig(filename=\"logs/\"+args.net+\"_\"+args.dataset+\"_\"+str(args.session)+\".log\",\n filemode='w', level=logging.DEBUG)\n logging.info(str(datetime.now()))\n\n if args.dataset == \"pascal_voc\":\n args.imdb_name = \"voc_2007_train\"\n args.imdbval_name = \"voc_2007_test\"\n args.set_cfgs = ['FPN_ANCHOR_SCALES', '[32, 64, 128, 256, 512]', 'FPN_FEAT_STRIDES', '[4, 8, 16, 32, 64]', 'MAX_NUM_GT_BOXES', '20']\n elif args.dataset == \"pascal_voc_cap\":\n args.imdb_name = \"cap_voc_2007_train\"\n args.imdbval_name = \"cap_voc_2007_test\"\n args.set_cfgs = ['FPN_ANCHOR_SCALES', '[32, 64, 128, 256, 512]', 'FPN_FEAT_STRIDES', '[4, 8, 16, 32, 64]', 'MAX_NUM_GT_BOXES', '3']\n elif args.dataset == \"pascal_voc_bottle\":\n args.imdb_name = \"bottle_voc_2007_train\"\n args.imdbval_name = \"bottle_voc_2007_test\"\n args.set_cfgs = ['FPN_ANCHOR_SCALES', '[32, 64, 128, 256, 512]', 'FPN_FEAT_STRIDES', '[4, 8, 16, 32, 64]', 'MAX_NUM_GT_BOXES', '7']\n elif args.dataset == \"pascal_voc_0712\":\n args.imdb_name = \"voc_2007_trainval+voc_2012_trainval\"\n args.imdbval_name = \"voc_2007_test\"\n args.set_cfgs = ['FPN_ANCHOR_SCALES', '[32, 64, 128, 256, 512]', 'FPN_FEAT_STRIDES', '[4, 8, 16, 32, 64]', 'MAX_NUM_GT_BOXES', '20']\n elif args.dataset == \"coco\":\n args.imdb_name = \"coco_2014_train+coco_2014_valminusminival\"\n args.imdbval_name = \"coco_2014_minival\"\n args.set_cfgs = ['FPN_ANCHOR_SCALES', '[32, 64, 128, 256, 512]', 'FPN_FEAT_STRIDES', '[4, 8, 16, 32, 64]', 'MAX_NUM_GT_BOXES', '20']\n elif args.dataset == \"imagenet\":\n args.imdb_name = \"imagenet_train\"\n args.imdbval_name = \"imagenet_val\"\n args.set_cfgs = ['FPN_ANCHOR_SCALES', '[32, 64, 128, 256, 512]', 'FPN_FEAT_STRIDES', '[4, 8, 16, 32, 64]', 'MAX_NUM_GT_BOXES', '30']\n elif args.dataset == \"vg\":\n # train sizes: train, smalltrain, minitrain\n # train scale: ['150-50-20', '150-50-50', '500-150-80', '750-250-150', '1750-700-450', '1600-400-20']\n args.imdb_name = \"vg_150-50-50_minitrain\"\n args.imdbval_name = \"vg_150-50-50_minival\"\n args.set_cfgs = ['FPN_ANCHOR_SCALES', '[32, 64, 128, 256, 512]', 'FPN_FEAT_STRIDES', '[4, 8, 16, 32, 64]', 'MAX_NUM_GT_BOXES', '50']\n\n args.cfg_file = \"cfgs/{}_ls.yml\".format(args.net) if args.lscale else \"cfgs/{}.yml\".format(args.net)\n\n if args.cfg_file is not None:\n cfg_from_file(args.cfg_file)\n if args.set_cfgs is not None:\n cfg_from_list(args.set_cfgs)\n\n print('Using config:')\n pprint.pprint(cfg)\n logging.info(cfg)\n np.random.seed(cfg.RNG_SEED)\n\n #torch.backends.cudnn.benchmark = True\n if torch.cuda.is_available() and not args.cuda:\n print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\n\n # train set\n # -- Note: Use validation set and disable the flipped to enable faster loading.\n cfg.TRAIN.USE_FLIPPED = True\n cfg.USE_GPU_NMS = args.cuda\n imdb, roidb, ratio_list, ratio_index = combined_roidb(args.imdb_name)\n train_size = len(roidb)\n\n _print('{:d} roidb entries'.format(len(roidb)), logging)\n\n output_dir = args.save_dir + \"/\" + args.net + \"/\" + args.dataset\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n sampler_batch = sampler(train_size, args.batch_size)\n\n dataset = roibatchLoader(roidb, ratio_list, ratio_index, args.batch_size, \\\n imdb.num_classes, training=True)\n\n dataloader = torch.utils.data.DataLoader(dataset, batch_size=args.batch_size,\n sampler=sampler_batch, num_workers=args.num_workers)\n\n # initilize the tensor holder here.\n im_data = torch.FloatTensor(1)\n im_info = torch.FloatTensor(1)\n num_boxes = torch.LongTensor(1)\n gt_boxes = torch.FloatTensor(1)\n\n # ship to cuda\n if args.cuda:\n im_data = im_data.cuda()\n im_info = im_info.cuda()\n num_boxes = num_boxes.cuda()\n gt_boxes = gt_boxes.cuda()\n\n # make variable\n im_data = Variable(im_data)\n im_info = Variable(im_info)\n num_boxes = Variable(num_boxes)\n gt_boxes = Variable(gt_boxes)\n\n if args.cuda:\n cfg.CUDA = True\n\n # initilize the network here.\n if args.net == 'res101':\n FPN = resnet(imdb.classes, 101, pretrained=True, class_agnostic=args.class_agnostic)\n elif args.net == 'res50':\n print(\"here\")\n FPN = resnet(imdb.classes, 50, pretrained=True, class_agnostic=args.class_agnostic)\n elif args.net == 'res152':\n FPN = resnet(imdb.classes, 152, pretrained=True, class_agnostic=args.class_agnostic)\n else:\n print(\"network is not defined\")\n pdb.set_trace()\n\n FPN.create_architecture()\n print(FPN)\n lr = cfg.TRAIN.LEARNING_RATE\n lr = args.lr\n #tr_momentum = cfg.TRAIN.MOMENTUM\n #tr_momentum = args.momentum\n\n params = []\n for key, value in dict(FPN.named_parameters()).items():\n if value.requires_grad:\n if 'bias' in key:\n params += [{'params':[value],'lr':lr*(cfg.TRAIN.DOUBLE_BIAS + 1), \\\n 'weight_decay': cfg.TRAIN.BIAS_DECAY and cfg.TRAIN.WEIGHT_DECAY or 0}]\n else:\n params += [{'params':[value],'lr':lr, 'weight_decay': cfg.TRAIN.WEIGHT_DECAY}]\n\n if args.optimizer == \"adam\":\n lr = lr * 0.1\n optimizer = torch.optim.Adam(params)\n\n elif args.optimizer == \"sgd\":\n optimizer = torch.optim.SGD(params, momentum=cfg.TRAIN.MOMENTUM)\n\n if args.resume:\n load_name = os.path.join(output_dir,\n 'fpn_{}_{}_{}.pth'.format(args.checksession, args.checkepoch, args.checkpoint))\n _print(\"loading checkpoint %s\" % (load_name), logging)\n checkpoint = torch.load(load_name)\n args.session = checkpoint['session']\n args.start_epoch = checkpoint['epoch']\n FPN.load_state_dict(checkpoint['model'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n lr = optimizer.param_groups[0]['lr']\n if 'pooling_mode' in checkpoint.keys():\n cfg.POOLING_MODE = checkpoint['pooling_mode']\n _print(\"loaded checkpoint %s\" % (load_name), logging)\n\n if args.mGPUs:\n FPN = nn.DataParallel(FPN)\n\n if args.cuda:\n FPN.cuda()\n\n iters_per_epoch = int(train_size / args.batch_size)\n\n for epoch in range(args.start_epoch, args.max_epochs):\n # setting to train mode\n FPN.train()\n loss_temp = 0\n start = time.time()\n\n if epoch % (args.lr_decay_step + 1) == 0:\n adjust_learning_rate(optimizer, args.lr_decay_gamma)\n lr *= args.lr_decay_gamma\n\n for step, data in enumerate(dataloader, 0):\n with torch.no_grad():\n im_data.resize_(data[0].size()).copy_(data[0])\n im_info.resize_(data[1].size()).copy_(data[1])\n gt_boxes.resize_(data[2].size()).copy_(data[2])\n num_boxes.resize_(data[3].size()).copy_(data[3])\n\n FPN.zero_grad()\n _, _, _, rpn_loss_cls, rpn_loss_box, \\\n RCNN_loss_cls, RCNN_loss_bbox, \\\n rois_label = FPN(im_data, im_info, gt_boxes, num_boxes)\n# rois_label = fasterRCNN(im_data, im_info, gt_boxes, num_boxes)\n # loss = rpn_loss_cls.mean() + rpn_loss_box.mean() \\\n # + RCNN_loss_cls.mean() + RCNN_loss_bbox.mean()\n # loss_temp += loss.data[0]\n\n loss = rpn_loss_cls.mean() + rpn_loss_box.mean() \\\n + RCNN_loss_cls.mean() + RCNN_loss_bbox.mean()\n loss_temp += loss.item()\n # backward\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if step % args.disp_interval == 0:\n end = time.time()\n if step > 0:\n loss_temp /= args.disp_interval\n\n if args.mGPUs:\n loss_rpn_cls = rpn_loss_cls.mean().item()\n loss_rpn_box = rpn_loss_box.mean().item()\n loss_rcnn_cls = RCNN_loss_cls.mean().item()\n loss_rcnn_box = RCNN_loss_bbox.mean().item()\n fg_cnt = torch.sum(rois_label.data.ne(0))\n bg_cnt = rois_label.data.numel() - fg_cnt\n else:\n loss_rpn_cls = rpn_loss_cls.item()\n loss_rpn_box = rpn_loss_box.item()\n loss_rcnn_cls = RCNN_loss_cls.item()\n loss_rcnn_box = RCNN_loss_bbox.item()\n fg_cnt = torch.sum(rois_label.data.ne(0))\n bg_cnt = rois_label.data.numel() - fg_cnt\n\n _print(\"[session %d][epoch %2d][iter %4d] loss: %.4f, lr: %.2e\" \\\n % (args.session, epoch, step, loss_temp, lr), logging)\n _print(\"\\t\\t\\tfg/bg=(%d/%d), time cost: %f\" % (fg_cnt, bg_cnt, end-start), logging)\n _print(\"\\t\\t\\trpn_cls: %.4f, rpn_box: %.4f, rcnn_cls: %.4f, rcnn_box %.4f\" \\\n % (loss_rpn_cls, loss_rpn_box, loss_rcnn_cls, loss_rcnn_box), logging)\n if args.use_tfboard:\n info = {\n 'loss': loss_temp,\n 'loss_rpn_cls': loss_rpn_cls,\n 'loss_rpn_box': loss_rpn_box,\n 'loss_rcnn_cls': loss_rcnn_cls,\n 'loss_rcnn_box': loss_rcnn_box,\n }\n for tag, value in info.items():\n logger.scalar_summary(tag, value, step)\n\n loss_temp = 0\n start = time.time()\n if epoch % (24 + 1) == 0: \n if args.mGPUs:\n save_name = os.path.join(output_dir, 'fpn_{}_{}_{}.pth'.format(args.session, epoch, step))\n save_checkpoint({\n 'session': args.session,\n 'epoch': epoch + 1,\n 'model': FPN.module.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'pooling_mode': cfg.POOLING_MODE,\n 'class_agnostic': args.class_agnostic,\n }, save_name)\n else:\n save_name = os.path.join(output_dir, 'fpn_{}_{}_{}.pth'.format(args.session, epoch, step))\n save_checkpoint({\n 'session': args.session,\n 'epoch': epoch + 1,\n 'model': FPN.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'pooling_mode': cfg.POOLING_MODE,\n 'class_agnostic': args.class_agnostic,\n }, save_name)\n _print('save model: {}'.format(save_name), logging)\n\n end = time.time()\n print(end - start)\n" ]
[ [ "torch.optim.Adam", "torch.LongTensor", "numpy.random.seed", "torch.load", "torch.cat", "torch.randperm", "torch.utils.data.DataLoader", "torch.arange", "torch.FloatTensor", "torch.no_grad", "torch.cuda.is_available", "torch.optim.SGD", "torch.nn.DataParallel", "torch.autograd.Variable" ] ]
Sniper91/flink
[ "2b6dc382e495eb7ed883b1a631d73cff31e8db9d" ]
[ "flink-python/pyflink/table/tests/test_row_based_operation.py" ]
[ "################################################################################\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n################################################################################\n\nfrom pyflink.common import Row\nfrom pyflink.table.types import DataTypes\nfrom pyflink.table.udf import udf, udtf\nfrom pyflink.testing import source_sink_utils\nfrom pyflink.testing.test_case_utils import PyFlinkBlinkBatchTableTestCase, \\\n PyFlinkBlinkStreamTableTestCase\n\n\nclass RowBasedOperationTests(object):\n def test_map(self):\n t = self.t_env.from_elements(\n [(1, 2, 3), (2, 1, 3), (1, 5, 4), (1, 8, 6), (2, 3, 4)],\n DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.TINYINT()),\n DataTypes.FIELD(\"b\", DataTypes.SMALLINT()),\n DataTypes.FIELD(\"c\", DataTypes.INT())]))\n\n table_sink = source_sink_utils.TestAppendSink(\n ['a', 'b'],\n [DataTypes.BIGINT(), DataTypes.BIGINT()])\n self.t_env.register_table_sink(\"Results\", table_sink)\n\n func = udf(lambda x: Row(x + 1, x * x), result_type=DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.BIGINT()),\n DataTypes.FIELD(\"b\", DataTypes.BIGINT())]))\n\n t.map(func(t.b)).alias(\"a\", \"b\") \\\n .map(func(t.a)).alias(\"a\", \"b\") \\\n .execute_insert(\"Results\") \\\n .wait()\n actual = source_sink_utils.results()\n self.assert_equals(actual, [\"4,9\", \"3,4\", \"7,36\", \"10,81\", \"5,16\"])\n\n def test_map_with_pandas_udf(self):\n t = self.t_env.from_elements(\n [(1, Row(2, 3)), (2, Row(1, 3)), (1, Row(5, 4)), (1, Row(8, 6)), (2, Row(3, 4))],\n DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.TINYINT()),\n DataTypes.FIELD(\"b\",\n DataTypes.ROW([DataTypes.FIELD(\"a\", DataTypes.INT()),\n DataTypes.FIELD(\"b\", DataTypes.INT())]))]))\n\n table_sink = source_sink_utils.TestAppendSink(\n ['a', 'b'],\n [DataTypes.BIGINT(), DataTypes.BIGINT()])\n self.t_env.register_table_sink(\"Results\", table_sink)\n\n def func(x, y):\n import pandas as pd\n a = (x * 2).rename('b')\n res = pd.concat([a, x], axis=1) + y\n return res\n\n pandas_udf = udf(func,\n result_type=DataTypes.ROW(\n [DataTypes.FIELD(\"c\", DataTypes.BIGINT()),\n DataTypes.FIELD(\"d\", DataTypes.BIGINT())]),\n func_type='pandas')\n t.map(pandas_udf(t.a, t.b)).execute_insert(\"Results\").wait()\n actual = source_sink_utils.results()\n self.assert_equals(actual, [\"3,5\", \"3,7\", \"6,6\", \"9,8\", \"5,8\"])\n\n def test_flat_map(self):\n t = self.t_env.from_elements(\n [(1, \"2,3\", 3), (2, \"1\", 3), (1, \"5,6,7\", 4)],\n DataTypes.ROW(\n [DataTypes.FIELD(\"a\", DataTypes.TINYINT()),\n DataTypes.FIELD(\"b\", DataTypes.STRING()),\n DataTypes.FIELD(\"c\", DataTypes.INT())]))\n\n table_sink = source_sink_utils.TestAppendSink(\n ['a', 'b'],\n [DataTypes.BIGINT(), DataTypes.STRING()])\n self.t_env.register_table_sink(\"Results\", table_sink)\n\n @udtf(result_types=[DataTypes.INT(), DataTypes.STRING()])\n def split(x, string):\n for s in string.split(\",\"):\n yield x, s\n\n t.flat_map(split(t.a, t.b)) \\\n .alias(\"a, b\") \\\n .flat_map(split(t.a, t.b)) \\\n .execute_insert(\"Results\") \\\n .wait()\n actual = source_sink_utils.results()\n self.assert_equals(actual, [\"1,2\", \"1,3\", \"2,1\", \"1,5\", \"1,6\", \"1,7\"])\n\n\nclass BatchRowBasedOperationITTests(RowBasedOperationTests, PyFlinkBlinkBatchTableTestCase):\n pass\n\n\nclass StreamRowBasedOperationITTests(RowBasedOperationTests, PyFlinkBlinkStreamTableTestCase):\n pass\n\n\nif __name__ == '__main__':\n import unittest\n\n try:\n import xmlrunner\n\n testRunner = xmlrunner.XMLTestRunner(output='target/test-reports')\n except ImportError:\n testRunner = None\n unittest.main(testRunner=testRunner, verbosity=2)\n" ]
[ [ "pandas.concat" ] ]
uranc/arbitrary_style_transfer
[ "ca3ba7aa023ee06d29968c2237942c0c6c1acafb" ]
[ "infer.py" ]
[ "# Use a trained Image Transform Net to generate\n# a style transferred image with a specific style\n\nimport tensorflow as tf\n\nfrom style_transfer_net import StyleTransferNet\nfrom utils import get_images, save_images\nfrom datetime import datetime\n# import pdb\n\ndef stylize(contents_path, styles_path, output_dir, encoder_path, model_path, \n resize_height=None, resize_width=None, suffix=None, n_iter=1):\n\n if isinstance(contents_path, str):\n contents_path = [contents_path]\n if isinstance(styles_path, str):\n styles_path = [styles_path]\n\n with tf.Graph().as_default(), tf.Session() as sess:\n # build the dataflow graph\n content = tf.placeholder(\n tf.float32, shape=(1, None, None, 3), name='content')\n style = tf.placeholder(\n tf.float32, shape=(1, None, None, 3), name='style')\n\n stn = StyleTransferNet(encoder_path)\n\n output_image = stn.transform(content, style)\n\n sess.run(tf.global_variables_initializer())\n\n # restore the trained model and run the style transferring\n saver = tf.train.Saver()\n saver.restore(sess, model_path)\n\n # start_time = datetime.now()\n outputs = []\n for content_path in contents_path:\n\n content_img = get_images(content_path, \n height=resize_height, width=resize_width)\n\n for style_path in styles_path:\n\n style_img = get_images(style_path)\n\n for n_it in range(n_iter):\n \n if n_it == 0:\n result = sess.run(output_image, \n feed_dict={content: content_img, style: style_img})\n tmp_cont = result\n else:\n result = sess.run(output_image, \n feed_dict={content: tmp_cont, style: style_img})\n tmp_cont = result\n outputs.append(result[0])\n # elapsed_time = datetime.now() - start_time\n # print(elapsed_time)\n # pdb.set_trace()\n \n \n save_images(outputs, contents_path, styles_path, output_dir, suffix=suffix, n_iter=1)\n\n return outputs\n\n" ]
[ [ "tensorflow.Graph", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.Session", "tensorflow.train.Saver" ] ]
tommy19970714/fairseq
[ "ebf43d849f442f13e4c74f4f59d057363ed4d831" ]
[ "fairseq/trainer.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"\nTrain a network across multiple GPUs.\n\"\"\"\n\nimport contextlib\nimport logging\nimport sys\nimport time\nfrom argparse import Namespace\nfrom itertools import chain\nfrom typing import Any, Dict, List\n\nimport torch\nfrom fairseq import checkpoint_utils, models, optim, utils\nfrom fairseq.dataclass.configs import FairseqConfig\nfrom fairseq.dataclass.utils import convert_namespace_to_omegaconf\nfrom fairseq.distributed import utils as distributed_utils\nfrom fairseq.file_io import PathManager\nfrom fairseq.logging import meters, metrics\nfrom fairseq.nan_detector import NanDetector\nfrom fairseq.optim import lr_scheduler\n\nfrom omegaconf import OmegaConf\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Trainer(object):\n \"\"\"Main class for data parallel training.\n\n This class supports synchronous distributed data parallel training,\n where multiple workers each have a full model replica and gradients\n are accumulated across workers before each update. We use\n :class:`~torch.nn.parallel.DistributedDataParallel` to handle\n communication of the gradients across workers.\n \"\"\"\n\n def __init__(self, cfg: FairseqConfig, task, model, criterion, quantizer=None):\n\n if isinstance(cfg, Namespace):\n logger.warning(\n \"argparse.Namespace configuration is deprecated! Automatically converting to OmegaConf\"\n )\n cfg = convert_namespace_to_omegaconf(cfg)\n\n self.cfg = cfg\n self.task = task\n\n # catalog shared parameters\n shared_params = _catalog_shared_params(model)\n self.tpu = cfg.common.tpu\n self.cuda = torch.cuda.is_available() and not cfg.common.cpu and not self.tpu\n if self.cuda:\n self.device = torch.device(\"cuda\")\n elif self.tpu:\n self.device = utils.get_tpu_device()\n else:\n self.device = torch.device(\"cpu\")\n\n if self.cfg.distributed_training.ddp_backend == \"fully_sharded\":\n if self.cfg.common.bf16:\n raise ValueError(\n \"FullyShardedDataParallel is not compatible with --bf16 or \"\n \"--memory-efficient-bf16\"\n )\n if self.cfg.distributed_training.zero_sharding != \"none\":\n raise ValueError(\n \"FullyShardedDataParallel is not compatible with --zero-sharding \"\n \"option (it's already built in)\"\n )\n else:\n if self.cfg.distributed_training.cpu_offload:\n raise ValueError(\"--cpu-offload requires --ddp-backend=fully_sharded\")\n\n # copy model and criterion to current device/dtype\n self._criterion = criterion\n self._model = model\n if cfg.distributed_training.ddp_backend != \"fully_sharded\":\n if cfg.common.fp16:\n self._criterion = self._criterion.half()\n self._model = self._model.half()\n elif cfg.common.bf16:\n self._criterion = self._criterion.to(dtype=torch.bfloat16)\n self._model = self._model.to(dtype=torch.bfloat16)\n if (\n not cfg.distributed_training.pipeline_model_parallel\n # the DistributedFairseqModel wrapper will handle moving to device,\n # so only handle cases which don't use the wrapper\n and not self.use_distributed_wrapper\n ):\n self._criterion = self._criterion.to(device=self.device)\n self._model = self._model.to(device=self.device)\n self.pipeline_model_parallel = cfg.distributed_training.pipeline_model_parallel\n self.last_device = None\n if self.cuda and self.pipeline_model_parallel:\n self.last_device = torch.device(\n cfg.distributed_training.pipeline_devices[-1]\n )\n\n # check that shared parameters are preserved after device transfer\n for shared_param in shared_params:\n ref = _get_module_by_path(self._model, shared_param[0])\n for path in shared_param[1:]:\n logger.info(\n \"detected shared parameter: {} <- {}\".format(shared_param[0], path)\n )\n _set_module_by_path(self._model, path, ref)\n\n self._dummy_batch = None # indicates we don't have a dummy batch at first\n self._lr_scheduler = None\n self._num_updates = 0\n self._num_xla_compiles = 0 # for TPUs\n self._optim_history = None\n self._optimizer = None\n self._warn_once = set()\n self._wrapped_criterion = None\n self._wrapped_model = None\n\n # TODO(myleott): support tpu\n if self.cuda and self.data_parallel_world_size > 1:\n self._grad_norm_buf = torch.cuda.DoubleTensor(self.data_parallel_world_size)\n else:\n self._grad_norm_buf = None\n\n self.quantizer = quantizer\n if self.quantizer is not None:\n self.quantizer.set_trainer(self)\n\n # get detailed cuda environment\n if self.cuda:\n self.cuda_env = utils.CudaEnvironment()\n if self.data_parallel_world_size > 1:\n self.cuda_env_arr = distributed_utils.all_gather_list(\n self.cuda_env, group=distributed_utils.get_global_group()\n )\n else:\n self.cuda_env_arr = [self.cuda_env]\n if self.data_parallel_rank == 0:\n utils.CudaEnvironment.pretty_print_cuda_env_list(self.cuda_env_arr)\n else:\n self.cuda_env = None\n self.cuda_env_arr = None\n\n metrics.log_start_time(\"wall\", priority=790, round=0)\n\n self._start_time = time.time()\n self._previous_training_time = 0\n self._cumulative_training_time = None\n\n def reinitialize(self):\n \"\"\"Reinitialize the Trainer, typically after model params change.\"\"\"\n self._lr_scheduler = None\n self._optimizer = None\n self._wrapped_criterion = None\n self._wrapped_model = None\n\n @property\n def data_parallel_world_size(self):\n if self.cfg.distributed_training.distributed_world_size == 1:\n return 1\n return distributed_utils.get_data_parallel_world_size()\n\n @property\n def data_parallel_process_group(self):\n return distributed_utils.get_data_parallel_group()\n\n @property\n def data_parallel_rank(self):\n if self.cfg.distributed_training.distributed_world_size == 1:\n return 0\n return distributed_utils.get_data_parallel_rank()\n\n @property\n def is_data_parallel_master(self):\n # NOTE: this returns true for all model parallel replicas with data\n # parallel rank 0\n return self.data_parallel_rank == 0\n\n @property\n def use_distributed_wrapper(self) -> bool:\n return (\n self.data_parallel_world_size > 1\n and not self.cfg.optimization.use_bmuf\n ) or (\n self.cfg.distributed_training.ddp_backend == \"fully_sharded\"\n and self.cfg.distributed_training.cpu_offload\n )\n\n @property\n def should_save_checkpoint_on_current_rank(self) -> bool:\n \"\"\"Indicates whether to save checkpoints on the current DDP rank.\"\"\"\n if self.cfg.distributed_training.ddp_backend == \"fully_sharded\":\n return True\n else:\n return self.is_data_parallel_master\n\n @property\n def checkpoint_suffix(self) -> str:\n \"\"\"Suffix to add to the checkpoint file name.\"\"\"\n if self.cfg.distributed_training.ddp_backend == \"fully_sharded\":\n return self.cfg.checkpoint.checkpoint_suffix + \"-shard{0}\".format(self.data_parallel_rank)\n else:\n return self.cfg.checkpoint.checkpoint_suffix or \"\"\n\n @property\n def criterion(self):\n if self._wrapped_criterion is None:\n if (\n utils.has_parameters(self._criterion)\n and self.use_distributed_wrapper\n ):\n self._wrapped_criterion = models.DistributedFairseqModel(\n self.cfg.distributed_training,\n self._criterion,\n process_group=self.data_parallel_process_group,\n device=self.device,\n )\n else:\n self._wrapped_criterion = self._criterion\n return self._wrapped_criterion\n\n @property\n def model(self):\n if self._wrapped_model is None:\n if self.use_distributed_wrapper:\n self._wrapped_model = models.DistributedFairseqModel(\n self.cfg.distributed_training,\n self._model,\n process_group=self.data_parallel_process_group,\n device=self.device,\n )\n else:\n self._wrapped_model = self._model\n return self._wrapped_model\n\n @property\n def optimizer(self):\n if self._optimizer is None:\n self._build_optimizer()\n return self._optimizer\n\n @property\n def lr_scheduler(self):\n if self._lr_scheduler is None:\n self._build_optimizer() # this will initialize self._lr_scheduler\n return self._lr_scheduler\n\n def _build_optimizer(self):\n params = list(\n filter(\n lambda p: p.requires_grad,\n chain(self.model.parameters(), self.criterion.parameters()),\n )\n )\n\n if (\n self.cfg.distributed_training.ddp_backend == \"fully_sharded\"\n and self.cfg.common.fp16\n ):\n # FullyShardedDataParallel always uses MemoryEfficientFP16 wrapper,\n # mostly for the grad scaling. But if we don't have the\n # --memory-efficient-fp16 flag set, then we're effectively doing\n # regular --fp16 and can allow the use of optimizers that would\n # otherwise be unsupported by MemoryEfficientFP16Optimizer.\n allow_unsupported = not self.cfg.common.memory_efficient_fp16\n self._optimizer = optim.MemoryEfficientFP16Optimizer.build_optimizer(\n self.cfg, params, allow_unsupported=allow_unsupported\n )\n elif self.cfg.common.fp16 or self.cfg.common.bf16:\n if self.cuda and torch.cuda.get_device_capability(0)[0] < 7:\n logger.info(\n \"NOTE: your device does NOT support faster training with --fp16, \"\n \"please switch to FP32 which is likely to be faster\"\n )\n if (\n self.cfg.common.memory_efficient_fp16\n or self.cfg.common.memory_efficient_bf16\n ):\n self._optimizer = optim.MemoryEfficientFP16Optimizer.build_optimizer(\n self.cfg, params\n )\n else:\n self._optimizer = optim.FP16Optimizer.build_optimizer(self.cfg, params)\n else:\n if self.cuda and torch.cuda.get_device_capability(0)[0] >= 7:\n logger.info(\"NOTE: your device may support faster training with --fp16\")\n self._optimizer = optim.build_optimizer(self.cfg.optimizer, params)\n\n if self.cfg.distributed_training.ddp_backend == \"fully_sharded\":\n assert not self.cfg.optimization.use_bmuf, \\\n \"--ddp-backend=fully_sharded is not compatible with BMUF\"\n assert self._optimizer.supports_flat_params, (\n \"--ddp-backend=fully_sharded is only compatible with pointwise \"\n \"optimizers (e.g., Adam, AdamW, Adadelta, Adamax, SGD, etc.). \"\n \"However, the sharding will result in slightly different results when \"\n \"using non-pointwise optimizers (e.g., Adagrad, Adafactor, LAMB)\"\n )\n\n if self.cfg.optimization.use_bmuf:\n self._optimizer = optim.FairseqBMUF(\n self.cfg.bmuf,\n self._optimizer,\n )\n\n if self.cfg.distributed_training.zero_sharding == \"os\":\n if (\n self.cfg.common.fp16\n and not self.cfg.common.memory_efficient_fp16\n and not self.cfg.common.memory_efficient_bf16\n ) and not self.cfg.common.fp16_no_flatten_grads:\n raise ValueError(\n \"ZeRO is incomptabile with fp16 and flattened grads. \"\n \"Please use --fp16-no-flatten-grads\"\n )\n else:\n optim.shard_(self._optimizer, self.data_parallel_process_group)\n\n # We should initialize the learning rate scheduler immediately after\n # building the optimizer, so that the initial learning rate is set.\n self._lr_scheduler = lr_scheduler.build_lr_scheduler(\n self.cfg.lr_scheduler,\n self.optimizer,\n )\n self._lr_scheduler.step_update(0)\n\n def consolidate_optimizer(self):\n \"\"\"For OSS, we need to consolidate the state dict.\"\"\"\n if hasattr(self.optimizer.optimizer, \"consolidate_state_dict\"):\n self.optimizer.optimizer.consolidate_state_dict()\n\n def state_dict(self):\n state_dict = {\n \"args\": None, # legacy\n \"cfg\": (\n OmegaConf.to_container(self.cfg)\n if OmegaConf.is_config(self.cfg) else self.cfg\n ),\n \"model\": self.model.state_dict(),\n \"criterion\": (\n self.criterion.state_dict()\n if utils.has_parameters(self.criterion) else None\n ),\n \"optimizer_history\": (self._optim_history or [])\n + [\n {\n \"criterion_name\": self.get_criterion().__class__.__name__,\n \"optimizer_name\": self.optimizer.__class__.__name__,\n \"lr_scheduler_state\": self.lr_scheduler.state_dict(),\n \"num_updates\": self.get_num_updates(),\n }\n ],\n \"task_state\": self.task.state_dict() if self.task is not None else {},\n \"extra_state\": {\n \"metrics\": metrics.state_dict(),\n \"previous_training_time\": self.cumulative_training_time(),\n }\n }\n if not self.cfg.checkpoint.no_save_optimizer_state:\n state_dict[\"last_optimizer_state\"] = self.optimizer.state_dict()\n return state_dict\n\n def save_checkpoint(self, filename, extra_state):\n \"\"\"Save all training state in a checkpoint file.\"\"\"\n logger.info(f\"Saving checkpoint to {filename}\")\n # call state_dict on all ranks in case it needs internal communication\n state_dict = utils.move_to_cpu(self.state_dict())\n state_dict[\"extra_state\"].update(extra_state)\n if self.should_save_checkpoint_on_current_rank:\n checkpoint_utils.torch_persistent_save(\n state_dict,\n filename,\n async_write=self.cfg.checkpoint.write_checkpoints_asynchronously,\n )\n logger.info(f\"Finished saving checkpoint to {filename}\")\n\n def load_checkpoint(\n self,\n filename,\n reset_optimizer=False,\n reset_lr_scheduler=False,\n optimizer_overrides=None,\n reset_meters=False,\n ):\n \"\"\"\n Load all training state from a checkpoint file.\n rank = 0 will load the checkpoint, and then broadcast it to all\n other ranks.\n \"\"\"\n extra_state, self._optim_history, last_optim_state = None, [], None\n\n logger.info(f\"Preparing to load checkpoint {filename}\")\n is_distributed = self.data_parallel_world_size > 1\n bexists = PathManager.isfile(filename)\n if bexists:\n load_on_all_ranks = (\n self.cfg.checkpoint.load_checkpoint_on_all_dp_ranks\n # TPUs don't support broadcast yet, so load checkpoints\n # on every worker for now\n or self.tpu\n # FSDP requires loading checkpoint shards on all ranks\n or self.cfg.distributed_training.ddp_backend == \"fully_sharded\"\n )\n\n if load_on_all_ranks or self.data_parallel_rank == 0:\n state = checkpoint_utils.load_checkpoint_to_cpu(\n filename, load_on_all_ranks=load_on_all_ranks\n )\n last_optim_state = state.get(\"last_optimizer_state\", None)\n\n # If doing zero_sharding, do not broadcast global optimizer\n # state. Later we will broadcast sharded states to each rank\n # to avoid memory from exploding.\n if (\n not load_on_all_ranks\n and self.cfg.distributed_training.zero_sharding == \"os\"\n and \"last_optimizer_state\" in state\n and is_distributed\n ):\n state[\"last_optimizer_state\"] = \"SHARDED\"\n else:\n last_optim_state = None\n state = None\n\n if is_distributed and not load_on_all_ranks:\n state = distributed_utils.broadcast_object(\n state,\n src_rank=0,\n group=self.data_parallel_process_group,\n dist_device=self.device,\n )\n if self.data_parallel_rank > 0:\n last_optim_state = state.get(\"last_optimizer_state\", None)\n\n # load model parameters\n try:\n self.model.load_state_dict(\n state[\"model\"], strict=True, model_cfg=self.cfg.model\n )\n # save memory for later steps\n del state[\"model\"]\n if utils.has_parameters(self.get_criterion()):\n self.get_criterion().load_state_dict(\n state[\"criterion\"], strict=True\n )\n del state[\"criterion\"]\n\n except Exception:\n raise Exception(\n \"Cannot load model parameters from checkpoint {}; \"\n \"please ensure that the architectures match.\".format(filename)\n )\n extra_state = state[\"extra_state\"]\n self._optim_history = state[\"optimizer_history\"]\n\n if last_optim_state is not None and not reset_optimizer:\n # rebuild optimizer after loading model, since params may have changed\n self._build_optimizer()\n\n # only reload optimizer and lr_scheduler if they match\n last_optim = self._optim_history[-1]\n assert (\n last_optim[\"criterion_name\"] == self.get_criterion().__class__.__name__\n ), f\"Criterion does not match; please reset the optimizer (--reset-optimizer). {last_optim['criterion_name']} vs {self.get_criterion().__class__.__name__}\"\n assert (\n last_optim[\"optimizer_name\"] == self.optimizer.__class__.__name__\n ), f\"Optimizer does not match; please reset the optimizer (--reset-optimizer). {last_optim['optimizer_name']} vs {self.optimizer.__class__.__name__}\"\n\n if not reset_lr_scheduler:\n self.lr_scheduler.load_state_dict(last_optim[\"lr_scheduler_state\"])\n\n if not load_on_all_ranks and is_distributed:\n last_optim_state = self.optimizer.broadcast_global_state_dict(\n last_optim_state\n )\n self.optimizer.load_state_dict(last_optim_state, optimizer_overrides)\n\n self.set_num_updates(last_optim[\"num_updates\"])\n\n if extra_state is not None:\n itr_state = extra_state[\"train_iterator\"]\n epoch = itr_state[\"epoch\"]\n\n if \"previous_training_time\" in extra_state:\n self._previous_training_time = extra_state[\"previous_training_time\"]\n self._start_time = time.time()\n\n self.lr_step(epoch)\n\n if itr_state.get(\"version\", 1) >= 2 and itr_state[\"iterations_in_epoch\"] == 0:\n # reset meters at start of epoch\n reset_meters = True\n\n if \"metrics\" in extra_state and not reset_meters:\n metrics.load_state_dict(extra_state[\"metrics\"])\n\n # reset TimeMeters, since their start times don't make sense anymore\n for meter in metrics.get_meters(\"default\"):\n if isinstance(meter, meters.TimeMeter):\n meter.reset()\n\n logger.info(\n \"Loaded checkpoint {} (epoch {} @ {} updates)\".format(\n filename, epoch, self.get_num_updates()\n )\n )\n\n else:\n logger.info(\"No existing checkpoint found {}\".format(filename))\n\n return extra_state\n\n def get_train_iterator(\n self,\n epoch,\n combine=True,\n load_dataset=True,\n data_selector=None,\n shard_batch_itr=True,\n disable_iterator_cache=False,\n ):\n \"\"\"Return an EpochBatchIterator over the training set for a given epoch.\"\"\"\n if load_dataset:\n logger.info(\"loading train data for epoch {}\".format(epoch))\n self.task.load_dataset(\n self.cfg.dataset.train_subset,\n epoch=epoch,\n combine=combine,\n data_selector=data_selector,\n )\n batch_iterator = self.task.get_batch_iterator(\n dataset=self.task.dataset(self.cfg.dataset.train_subset),\n max_tokens=self.cfg.dataset.max_tokens,\n max_sentences=self.cfg.dataset.batch_size,\n max_positions=utils.resolve_max_positions(\n self.task.max_positions(),\n self.model.max_positions(),\n self.cfg.dataset.max_tokens,\n ),\n ignore_invalid_inputs=True,\n required_batch_size_multiple=self.cfg.dataset.required_batch_size_multiple,\n seed=self.cfg.common.seed,\n num_shards=self.data_parallel_world_size if shard_batch_itr else 1,\n shard_id=self.data_parallel_rank if shard_batch_itr else 0,\n num_workers=self.cfg.dataset.num_workers,\n epoch=epoch,\n data_buffer_size=self.cfg.dataset.data_buffer_size,\n disable_iterator_cache=disable_iterator_cache,\n )\n self.reset_dummy_batch(batch_iterator.first_batch)\n return batch_iterator\n\n def get_valid_iterator(\n self,\n subset,\n disable_iterator_cache=False,\n ):\n \"\"\"Return an EpochBatchIterator over given validation subset for a given epoch.\"\"\"\n batch_iterator = self.task.get_batch_iterator(\n dataset=self.task.dataset(subset),\n max_tokens=self.cfg.dataset.max_tokens_valid,\n max_sentences=self.cfg.dataset.batch_size_valid,\n max_positions=utils.resolve_max_positions(\n self.task.max_positions(),\n self.model.max_positions(),\n ),\n ignore_invalid_inputs=self.cfg.dataset.skip_invalid_size_inputs_valid_test,\n required_batch_size_multiple=self.cfg.dataset.required_batch_size_multiple,\n seed=self.cfg.common.seed,\n num_shards=self.data_parallel_world_size,\n shard_id=self.data_parallel_rank,\n num_workers=self.cfg.dataset.num_workers,\n # always pass a fixed \"epoch\" to keep validation data consistent\n # across training epochs\n epoch=1,\n data_buffer_size=self.cfg.dataset.data_buffer_size,\n disable_iterator_cache=disable_iterator_cache,\n )\n self.reset_dummy_batch(batch_iterator.first_batch)\n return batch_iterator\n\n def begin_epoch(self, epoch):\n \"\"\"Called at the beginning of each epoch.\"\"\"\n logger.info(\"begin training epoch {}\".format(epoch))\n\n self.lr_step_begin_epoch(epoch)\n\n if self.quantizer is not None:\n self.quantizer.begin_epoch(epoch)\n\n # task specific setup per epoch\n self.task.begin_epoch(epoch, self.get_model())\n\n if self.tpu:\n import torch_xla.core.xla_model as xm\n\n xm.rendezvous(\"begin_epoch\") # wait for all workers\n xm.mark_step()\n\n def begin_valid_epoch(self, epoch):\n \"\"\"Called at the beginning of each validation epoch.\"\"\"\n\n # task specific setup per validation epoch\n self.task.begin_valid_epoch(epoch, self.get_model())\n\n def reset_dummy_batch(self, batch):\n self._dummy_batch = batch\n\n @metrics.aggregate(\"train\")\n def train_step(self, samples, raise_oom=False):\n \"\"\"Do forward, backward and parameter update.\"\"\"\n self._set_seed()\n self.model.train()\n self.criterion.train()\n self.zero_grad()\n\n metrics.log_start_time(\"train_wall\", priority=800, round=0)\n\n # forward and backward pass\n logging_outputs, sample_size, ooms = [], 0, 0\n for i, sample in enumerate(samples): # delayed update loop\n sample, is_dummy_batch = self._prepare_sample(sample)\n\n def maybe_no_sync():\n \"\"\"\n Whenever *samples* contains more than one mini-batch, we\n want to accumulate gradients locally and only call\n all-reduce in the last backwards pass.\n \"\"\"\n if (\n self.data_parallel_world_size > 1\n and hasattr(self.model, \"no_sync\")\n and i < len(samples) - 1\n ):\n return self.model.no_sync()\n else:\n return contextlib.ExitStack() # dummy contextmanager\n\n try:\n with maybe_no_sync():\n # forward and backward\n loss, sample_size_i, logging_output = self.task.train_step(\n sample=sample,\n model=self.model,\n criterion=self.criterion,\n optimizer=self.optimizer,\n update_num=self.get_num_updates(),\n ignore_grad=is_dummy_batch,\n )\n del loss\n\n logging_outputs.append(logging_output)\n sample_size += sample_size_i\n\n # emptying the CUDA cache after the first step can\n # reduce the chance of OOM\n if self.cuda and self.get_num_updates() == 0:\n torch.cuda.empty_cache()\n except RuntimeError as e:\n if \"out of memory\" in str(e):\n self._log_oom(e)\n if raise_oom:\n raise e\n logger.warning(\n \"attempting to recover from OOM in forward/backward pass\"\n )\n ooms += 1\n self.zero_grad()\n if self.cuda:\n torch.cuda.empty_cache()\n if self.cfg.distributed_training.distributed_world_size == 1:\n return None\n else:\n raise e\n\n if self.tpu and i < len(samples) - 1:\n # tpu-comment: every XLA operation before marking step is\n # appended to the IR graph, and processing too many batches\n # before marking step can lead to OOM errors.\n # To handle gradient accumulation use case, we explicitly\n # mark step here for every forward pass without a backward pass\n import torch_xla.core.xla_model as xm\n\n xm.mark_step()\n\n if is_dummy_batch:\n if torch.is_tensor(sample_size):\n sample_size.zero_()\n else:\n sample_size *= 0.0\n\n if torch.is_tensor(sample_size):\n sample_size = sample_size.float()\n else:\n sample_size = float(sample_size)\n\n # gather logging outputs from all replicas\n if self._sync_stats():\n train_time = self._local_cumulative_training_time()\n logging_outputs, (\n sample_size,\n ooms,\n total_train_time,\n ) = self._aggregate_logging_outputs(\n logging_outputs, sample_size, ooms, train_time, ignore=is_dummy_batch\n )\n self._cumulative_training_time = (\n total_train_time / self.data_parallel_world_size\n )\n\n overflow = False\n try:\n with torch.autograd.profiler.record_function(\"reduce-grads\"):\n # reduce gradients across workers\n self.optimizer.all_reduce_grads(self.model)\n if utils.has_parameters(self.criterion):\n self.optimizer.all_reduce_grads(self.criterion)\n\n with torch.autograd.profiler.record_function(\"multiply-grads\"):\n # multiply gradients by (data_parallel_size / sample_size) since\n # DDP normalizes by the number of data parallel workers for\n # improved fp16 precision.\n # Thus we get (sum_of_gradients / sample_size) at the end.\n # In case of fp16, this step also undoes loss scaling.\n # (Debugging note: Some optimizers perform this scaling on the\n # fly, so inspecting model.parameters() or optimizer.params may\n # still show the original, unscaled gradients.)\n numer = (\n self.data_parallel_world_size\n if not self.cfg.optimization.use_bmuf or self._sync_stats()\n else 1\n )\n self.optimizer.multiply_grads(numer / (sample_size or 1.0))\n # Note: (sample_size or 1.0) handles the case of a zero gradient, in a\n # way that avoids CPU/device transfers in case sample_size is a GPU or\n # TPU object. The assumption is that the gradient itself is also 0.\n\n with torch.autograd.profiler.record_function(\"clip-grads\"):\n # clip grads\n grad_norm = self.clip_grad_norm(self.cfg.optimization.clip_norm)\n\n # check that grad norms are consistent across workers\n # on tpu check tensor is slow\n if not self.tpu:\n if (\n not self.cfg.optimization.use_bmuf\n and self.cfg.distributed_training.ddp_backend != \"slow_mo\"\n ):\n self._check_grad_norms(grad_norm)\n if not torch.isfinite(grad_norm).all():\n # check local gradnorm single GPU case, trigger NanDetector\n raise FloatingPointError(\"gradients are Nan/Inf\")\n\n with torch.autograd.profiler.record_function(\"optimizer\"):\n # take an optimization step\n self.task.optimizer_step(\n self.optimizer, model=self.model, update_num=self.get_num_updates()\n )\n\n except FloatingPointError:\n # re-run the forward and backward pass with hooks attached to print\n # out where it fails\n self.zero_grad()\n with NanDetector(self.get_model()):\n for _, sample in enumerate(samples):\n sample, _ = self._prepare_sample(sample)\n self.task.train_step(\n sample,\n self.model,\n self.criterion,\n self.optimizer,\n self.get_num_updates(),\n ignore_grad=False,\n )\n raise\n except OverflowError as e:\n overflow = True\n logger.info(f\"NOTE: gradient overflow detected, ignoring gradient, {str(e)}\")\n grad_norm = torch.tensor(0.0).cuda()\n self.zero_grad()\n except RuntimeError as e:\n if \"out of memory\" in str(e):\n self._log_oom(e)\n logger.error(\"OOM during optimization, irrecoverable\")\n raise e\n\n # Some distributed wrappers (e.g., SlowMo) need access to the optimizer\n # after the step\n if hasattr(self.model, \"perform_additional_optimizer_actions\"):\n if hasattr(self.optimizer, \"fp32_params\"):\n self.model.perform_additional_optimizer_actions(\n self.optimizer.optimizer, self.optimizer.fp32_params\n )\n else:\n self.model.perform_additional_optimizer_actions(\n self.optimizer.optimizer\n )\n\n logging_output = None\n if not overflow or self.cfg.distributed_training.ddp_backend == \"slow_mo\":\n self.set_num_updates(self.get_num_updates() + 1)\n\n if self.tpu:\n # mark step on TPUs\n import torch_xla.core.xla_model as xm\n\n xm.mark_step()\n\n # only log stats every log_interval steps\n # this causes wps to be misreported when log_interval > 1\n logging_output = {}\n if self.get_num_updates() % self.cfg.common.log_interval == 0:\n # log memory usage\n mem_info = xm.get_memory_info(self.device)\n gb_free = mem_info[\"kb_free\"] / 1024 / 1024\n gb_total = mem_info[\"kb_total\"] / 1024 / 1024\n metrics.log_scalar(\n \"gb_free\", gb_free, priority=1500, round=1, weight=0\n )\n metrics.log_scalar(\n \"gb_total\", gb_total, priority=1600, round=1, weight=0\n )\n\n logging_output = self._reduce_and_log_stats(\n logging_outputs, sample_size, grad_norm\n )\n\n # log whenever there's an XLA compilation, since these\n # slow down training and may indicate opportunities for\n # optimization\n self._check_xla_compilation()\n else:\n if self.cuda and self.cuda_env is not None:\n # log minimum free memory over the iteration\n gb_used = torch.cuda.max_memory_allocated() / 1024 / 1024 / 1024\n torch.cuda.reset_peak_memory_stats()\n gb_free = self.cuda_env.total_memory_in_GB - gb_used\n metrics.log_scalar(\n \"gb_free\", gb_free, priority=1500, round=1, weight=0\n )\n\n # log stats\n logging_output = self._reduce_and_log_stats(\n logging_outputs, sample_size, grad_norm\n )\n\n # clear CUDA cache to reduce memory fragmentation\n if (\n self.cuda\n and self.cfg.common.empty_cache_freq > 0\n and (\n (self.get_num_updates() + self.cfg.common.empty_cache_freq - 1)\n % self.cfg.common.empty_cache_freq\n )\n == 0\n ):\n torch.cuda.empty_cache()\n\n if self.cfg.common.fp16:\n metrics.log_scalar(\n \"loss_scale\",\n self.optimizer.scaler.loss_scale,\n priority=700,\n round=4,\n weight=0,\n )\n\n metrics.log_stop_time(\"train_wall\")\n return logging_output\n\n @metrics.aggregate(\"valid\")\n def valid_step(self, sample, raise_oom=False):\n \"\"\"Do forward pass in evaluation mode.\"\"\"\n if self.tpu:\n import torch_xla.core.xla_model as xm\n\n xm.rendezvous(\"valid_step\") # wait for all workers\n xm.mark_step()\n\n with torch.no_grad():\n self.model.eval()\n self.criterion.eval()\n\n sample, is_dummy_batch = self._prepare_sample(sample)\n\n try:\n _loss, sample_size, logging_output = self.task.valid_step(\n sample, self.model, self.criterion\n )\n except RuntimeError as e:\n if \"out of memory\" in str(e):\n self._log_oom(e)\n if not raise_oom:\n logger.warning(\n \"ran out of memory in validation step, retrying batch\"\n )\n for p in self.model.parameters():\n if p.grad is not None:\n p.grad = None # free some memory\n if self.cuda:\n torch.cuda.empty_cache()\n return self.valid_step(sample, raise_oom=True)\n raise e\n\n logging_outputs = [logging_output]\n if is_dummy_batch:\n if torch.is_tensor(sample_size):\n sample_size.zero_()\n else:\n sample_size *= 0.0\n\n # gather logging outputs from all replicas\n if self.data_parallel_world_size > 1:\n logging_outputs, (sample_size,) = self._aggregate_logging_outputs(\n logging_outputs,\n sample_size,\n ignore=is_dummy_batch,\n )\n\n # log validation stats\n logging_output = self._reduce_and_log_stats(logging_outputs, sample_size)\n\n return logging_output\n\n def zero_grad(self):\n self.optimizer.zero_grad()\n\n def lr_step_begin_epoch(self, epoch):\n \"\"\"Adjust the learning rate at the beginning of the epoch.\"\"\"\n self.lr_scheduler.step_begin_epoch(epoch)\n # prefer updating the LR based on the number of steps\n return self.lr_step_update()\n\n def lr_step(self, epoch, val_loss=None):\n \"\"\"Adjust the learning rate at the end of the epoch.\"\"\"\n self.lr_scheduler.step(epoch, val_loss)\n # prefer updating the LR based on the number of steps\n return self.lr_step_update()\n\n def lr_step_update(self):\n \"\"\"Update the learning rate after each update.\"\"\"\n new_lr = self.lr_scheduler.step_update(self.get_num_updates())\n if isinstance(new_lr, dict):\n for k, v in new_lr.items():\n metrics.log_scalar(f\"lr_{k}\", v, weight=0, priority=300)\n new_lr = new_lr.get(\"default\", next(iter(new_lr.values())))\n else:\n metrics.log_scalar(\"lr\", new_lr, weight=0, priority=300)\n return new_lr\n\n def get_lr(self):\n \"\"\"Get the current learning rate.\"\"\"\n return self.optimizer.get_lr()\n\n def get_model(self):\n \"\"\"Get the (non-wrapped) model instance.\"\"\"\n return self._model\n\n def get_criterion(self):\n \"\"\"Get the (non-wrapped) criterion instance.\"\"\"\n return self._criterion\n\n def get_meter(self, name):\n \"\"\"[deprecated] Get a specific meter by name.\"\"\"\n from fairseq import meters\n\n if \"get_meter\" not in self._warn_once:\n self._warn_once.add(\"get_meter\")\n utils.deprecation_warning(\n \"Trainer.get_meter is deprecated. Please use fairseq.metrics instead.\"\n )\n\n train_meters = metrics.get_meters(\"train\")\n if train_meters is None:\n train_meters = {}\n\n if name == \"train_loss\" and \"loss\" in train_meters:\n return train_meters[\"loss\"]\n elif name == \"train_nll_loss\":\n # support for legacy train.py, which assumed this meter is\n # always initialized\n m = train_meters.get(\"nll_loss\", None)\n return m or meters.AverageMeter()\n elif name == \"wall\":\n # support for legacy train.py, which assumed this meter is\n # always initialized\n m = metrics.get_meter(\"default\", \"wall\")\n return m or meters.TimeMeter()\n elif name == \"wps\":\n m = metrics.get_meter(\"train\", \"wps\")\n return m or meters.TimeMeter()\n elif name in {\"valid_loss\", \"valid_nll_loss\"}:\n # support for legacy train.py, which assumed these meters\n # are always initialized\n k = name[len(\"valid_\") :]\n m = metrics.get_meter(\"valid\", k)\n return m or meters.AverageMeter()\n elif name == \"oom\":\n return meters.AverageMeter()\n elif name in train_meters:\n return train_meters[name]\n return None\n\n def get_num_updates(self):\n \"\"\"Get the number of parameters updates.\"\"\"\n return self._num_updates\n\n def set_num_updates(self, num_updates):\n \"\"\"Set the number of parameters updates.\"\"\"\n self._num_updates = num_updates\n self.lr_step_update()\n if self.quantizer:\n self.quantizer.step_update(self._num_updates)\n metrics.log_scalar(\"num_updates\", self._num_updates, weight=0, priority=200)\n\n def clip_grad_norm(self, clip_norm):\n\n def agg_norm_fn(total_norm):\n total_norm = total_norm.cuda().float() ** 2\n total_norm = distributed_utils.all_reduce(\n total_norm, group=self.data_parallel_process_group\n )\n return total_norm ** 0.5\n\n should_agg_norm = (\n self.cfg.distributed_training.ddp_backend == \"fully_sharded\"\n and (\n self.data_parallel_process_group is not None\n or torch.distributed.is_initialized()\n )\n )\n return self.optimizer.clip_grad_norm(\n clip_norm, aggregate_norm_fn=agg_norm_fn if should_agg_norm else None\n )\n\n def cumulative_training_time(self):\n if self._cumulative_training_time is None:\n # single GPU\n return self._local_cumulative_training_time()\n else:\n return self._cumulative_training_time\n\n def _local_cumulative_training_time(self):\n \"\"\"Aggregate training time in seconds.\"\"\"\n return time.time() - self._start_time + self._previous_training_time\n\n def _prepare_sample(self, sample, is_dummy=False):\n if sample == \"DUMMY\":\n raise Exception(\n \"Trying to use an uninitialized 'dummy' batch. This usually indicates \"\n \"that the total number of batches is smaller than the number of \"\n \"participating GPUs. Try reducing the batch size or using fewer GPUs.\"\n )\n\n if sample is None or len(sample) == 0:\n assert (\n self._dummy_batch is not None and len(self._dummy_batch) > 0\n ), \"Invalid dummy batch: {}\".format(self._dummy_batch)\n sample, _ = self._prepare_sample(self._dummy_batch, is_dummy=True)\n return sample, True\n\n if self.cuda:\n if self.pipeline_model_parallel:\n if \"target\" in sample:\n sample[\"target\"] = utils.move_to_cuda(\n sample[\"target\"], device=self.last_device\n )\n else:\n sample = utils.move_to_cuda(sample)\n elif self.tpu and is_dummy:\n # the dummy batch may not be on the appropriate device\n sample = utils.move_to_cuda(sample, device=self.device)\n\n def apply_half(t):\n if t.dtype is torch.float32:\n return t.half()\n return t\n\n def apply_bfloat16(t):\n if t.dtype is torch.float32:\n return t.to(dtype=torch.bfloat16)\n return t\n\n if self.cfg.common.fp16:\n sample = utils.apply_to_sample(apply_half, sample)\n\n if self.cfg.common.bf16:\n sample = utils.apply_to_sample(apply_bfloat16, sample)\n\n if self._dummy_batch == \"DUMMY\":\n self._dummy_batch = sample\n\n return sample, False\n\n def _set_seed(self):\n # Set seed based on args.seed and the update number so that we get\n # reproducible results when resuming from checkpoints\n seed = self.cfg.common.seed + self.get_num_updates()\n utils.set_torch_seed(seed)\n\n def _sync_stats(self):\n # Return True if it's using multiple GPUs and DDP or multiple GPUs with\n # BMUF and it's a bmuf sync with warmup iterations completed before.\n if self.data_parallel_world_size == 1:\n return False\n elif self.cfg.optimization.use_bmuf:\n return (\n self.get_num_updates() + 1\n ) % self.cfg.bmuf.global_sync_iter == 0 and (\n self.get_num_updates() + 1\n ) > self.cfg.bmuf.warmup_iterations\n else:\n return True\n\n def _log_oom(self, exc):\n msg = \"OOM: Ran out of memory with exception: {}\".format(exc)\n logger.warning(msg)\n if torch.cuda.is_available() and hasattr(torch.cuda, \"memory_summary\"):\n for device_idx in range(torch.cuda.device_count()):\n logger.warning(torch.cuda.memory_summary(device=device_idx))\n sys.stderr.flush()\n\n def _aggregate_logging_outputs(\n self,\n logging_outputs: List[Dict[str, Any]],\n *extra_stats_to_sum,\n ignore=False,\n ):\n if self.task.__class__.logging_outputs_can_be_summed(self.get_criterion()):\n return self._fast_stat_sync_sum(\n logging_outputs, *extra_stats_to_sum, ignore=ignore\n )\n else:\n return self._all_gather_list_sync(\n logging_outputs, *extra_stats_to_sum, ignore=ignore\n )\n\n def _all_gather_list_sync(\n self,\n logging_outputs: List[Dict[str, Any]],\n *extra_stats_to_sum,\n ignore=False,\n ):\n \"\"\"\n Sync logging outputs across workers. all_gather_list_sync is\n suitable when logging outputs are complex types.\n \"\"\"\n if self.tpu:\n raise NotImplementedError\n if ignore:\n logging_outputs = []\n results = list(\n zip(\n *distributed_utils.all_gather_list(\n [logging_outputs] + list(extra_stats_to_sum),\n max_size=getattr(self.cfg.common, \"all_gather_list_size\", 16384),\n group=self.data_parallel_process_group,\n )\n )\n )\n logging_outputs, extra_stats_to_sum = results[0], results[1:]\n logging_outputs = list(chain.from_iterable(logging_outputs))\n extra_stats_to_sum = [sum(s) for s in extra_stats_to_sum]\n return logging_outputs, extra_stats_to_sum\n\n def _fast_stat_sync_sum(\n self, logging_outputs: List[Dict[str, Any]], *extra_stats_to_sum, ignore=False,\n ):\n \"\"\"\n Sync logging outputs across workers. fast_stat_sync_sum is\n faster than all_gather_list_sync, but is only suitable when\n logging outputs are scalars and can be summed. Note that\n *logging_outputs* cannot contain any nested dicts/lists.\n \"\"\"\n data = {}\n for i, stat in enumerate(extra_stats_to_sum):\n data[\"extra_stats_\" + str(i)] = stat\n if len(logging_outputs) > 0:\n log_keys = list(logging_outputs[0].keys())\n for k in log_keys:\n if not ignore:\n v = sum(log[k] for log in logging_outputs if k in log)\n else:\n v = logging_outputs[0][k]\n v = torch.zeros_like(v) if torch.is_tensor(v) else 0\n data[\"logging_outputs_\" + k] = v\n else:\n log_keys = None\n\n data = distributed_utils.all_reduce_dict(\n data, device=self.device, group=self.data_parallel_process_group\n )\n\n extra_stats_to_sum = [\n data[\"extra_stats_\" + str(i)] for i in range(len(extra_stats_to_sum))\n ]\n if log_keys is not None:\n logging_outputs = [{k: data[\"logging_outputs_\" + k] for k in log_keys}]\n else:\n logging_outputs = []\n return logging_outputs, extra_stats_to_sum\n\n def _check_grad_norms(self, grad_norm):\n \"\"\"Check that grad norms are consistent across workers.\"\"\"\n if self._grad_norm_buf is not None:\n self._grad_norm_buf.zero_()\n self._grad_norm_buf[self.data_parallel_rank] = grad_norm\n distributed_utils.all_reduce(\n self._grad_norm_buf, group=self.data_parallel_process_group\n )\n\n def is_consistent(tensor):\n max_abs_diff = torch.max(torch.abs(tensor - tensor[0]))\n return (\n torch.isfinite(tensor).all()\n and (max_abs_diff / (tensor[0] + 1e-6) < 1e-6).all()\n )\n\n if not is_consistent(self._grad_norm_buf):\n pretty_detail = \"\\n\".join(\n \"rank {:3d} = {:.8f}\".format(r, n)\n for r, n in enumerate(self._grad_norm_buf.tolist())\n )\n error_detail = \"grad_norm across the workers:\\n{}\\n\".format(\n pretty_detail\n )\n # use FloatingPointError to trigger NanDetector\n raise FloatingPointError(\n \"Fatal error: gradients are inconsistent between workers. \"\n \"Try --ddp-backend=legacy_ddp. \"\n \"Or are you mixing up different generation of GPUs in training?\"\n + \"\\n\"\n + \"-\" * 80\n + \"\\n{}\\n\".format(error_detail)\n + \"-\" * 80\n )\n\n def _reduce_and_log_stats(self, logging_outputs, sample_size, grad_norm=None):\n if grad_norm is not None and (\n not torch.is_tensor(grad_norm) or torch.isfinite(grad_norm)\n ):\n metrics.log_speed(\"ups\", 1.0, priority=100, round=2)\n metrics.log_scalar(\"gnorm\", grad_norm, priority=400, round=3)\n if self.cfg.optimization.clip_norm > 0:\n metrics.log_scalar(\n \"clip\",\n torch.where(\n grad_norm > self.cfg.optimization.clip_norm,\n grad_norm.new_tensor(100),\n grad_norm.new_tensor(0),\n ),\n priority=500,\n round=1,\n )\n\n with metrics.aggregate() as agg:\n if logging_outputs is not None:\n self.task.reduce_metrics(logging_outputs, self.get_criterion())\n del logging_outputs\n\n # extra warning for criterions that don't properly log a loss value\n if \"loss\" not in agg:\n if \"loss\" not in self._warn_once:\n self._warn_once.add(\"loss\")\n logger.warning(\n \"Criterion.reduce_metrics did not log a 'loss' value, \"\n \"which may break some functionality\"\n )\n metrics.log_scalar(\"loss\", -1)\n\n # support legacy interface\n if self.tpu:\n logging_output = {}\n else:\n logging_output = agg.get_smoothed_values()\n logging_output[\"sample_size\"] = sample_size\n for key_to_delete in [\"ppl\", \"wps\", \"wpb\", \"bsz\"]:\n if key_to_delete in logging_output:\n del logging_output[key_to_delete]\n return logging_output\n\n def _check_xla_compilation(self):\n import torch_xla.debug.metrics as met\n\n compile_stats = met.metric_data(\"CompileTime\")\n if compile_stats is None:\n return\n num_xla_compiles = compile_stats[0]\n if num_xla_compiles > self._num_xla_compiles:\n logger.warning(\n \"XLA compilation detected on device #{}; too many of these can lead \"\n \"to slow training, but we expect a few in the beginning\".format(\n self.cfg.distributed_training.distributed_rank\n )\n )\n self._num_xla_compiles = num_xla_compiles\n\n\ndef _catalog_shared_params(module, memo=None, prefix=\"\"):\n if memo is None:\n first_call = True\n memo = {}\n else:\n first_call = False\n for name, param in module._parameters.items():\n param_prefix = prefix + (\".\" if prefix else \"\") + name\n if param not in memo:\n memo[param] = []\n memo[param].append(param_prefix)\n for name, m in module._modules.items():\n if m is None:\n continue\n submodule_prefix = prefix + (\".\" if prefix else \"\") + name\n _catalog_shared_params(m, memo, submodule_prefix)\n if first_call:\n return [x for x in memo.values() if len(x) > 1]\n\n\ndef _get_module_by_path(module, path):\n path = path.split(\".\")\n for name in path:\n module = getattr(module, name)\n return module\n\n\ndef _set_module_by_path(module, path, value):\n path = path.split(\".\")\n for name in path[:-1]:\n module = getattr(module, name)\n setattr(module, path[-1], value)\n" ]
[ [ "torch.autograd.profiler.record_function", "torch.abs", "torch.cuda.get_device_capability", "torch.cuda.memory_summary", "torch.distributed.is_initialized", "torch.cuda.DoubleTensor", "torch.is_tensor", "torch.cuda.empty_cache", "torch.tensor", "torch.zeros_like", "torch.isfinite", "torch.cuda.max_memory_allocated", "torch.no_grad", "torch.cuda.reset_peak_memory_stats", "torch.cuda.is_available", "torch.device", "torch.cuda.device_count" ] ]
falkishi/Python-HWs
[ "04504c21a7fc5dc4b9fe7820549d9cdf98c7aa91" ]
[ "homework-3-su21-falkishi-main/testbin.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom problem1 import *\n\ndata = np.loadtxt('input.txt')\nlo = min(data)\nhi = max(data)\n\nprint('Uncomment the first segment to verify the histogram you have generated')\n\nhisto = plt.hist(data, 10, (lo, hi))[0]\nprint(histo)\n\n\n\nprint('Uncomment the second segment to verify the normalized histogram you have generated')\n\nnorm_h = norm_histogram(histo)\nprint(norm_h)\n\n\nprint('Uncomment the third segment to verify the J value you have generated')\n\nch = compute_j(plt.hist(data, 5, (lo, hi))[0], (hi - lo) / 5)\nprint(ch)\n\n\nprint('Uncomment the fourth segment to verify the sweep of J values you have generated')\n\nro = sweep_n(data, lo, hi, 1, 100)\nprint(ro)\n\n\nprint('Uncomment the fifth segment to verify the min J score you have generated')\n\nminV = find_min(sweep_n(data, lo, hi, 1, 100))\nprint(minV)\n\n" ]
[ [ "matplotlib.pyplot.hist", "numpy.loadtxt" ] ]
john-hawkins/textplainer
[ "89ab0ac21e4db0fd53184fb431dc730b7940de62" ]
[ "experiments/Pipeline_Simple_WordLabel_Count_LogisticReg.py" ]
[ "import pandas as pd\nimport numpy as np\nimport math\n\n##############################################################################################\n# Pipeline_Simple_WordLabel_Count_LogisticReg \n#\n# A Simple ML Pipeline for classifying text data.\n#\n# The fit function will train a model by applying the following stages\n# - Word Counts by Label Dictionary\n# - Simple Logistic Regression on Sums of Positive and Negative Class Words\n#\n\nclass Pipeline_Simple_WordLabel_Count_LogisticReg():\n\n\n ###################################################################################################\n\n def __init__(self, results_dir):\n self.results_dir = results_dir\n\n ###################################################################################################\n\n def fit(self, df, text, label):\n \"\"\"\n This function expects a pandas dataframe and two strings that determine the names of\n of the text features column and the target column. From this, we will build a model.\n \"\"\"\n self.text_col_name = text\n self.label_col_name = label \n self.freqs = self.build_word_dictionary(df, text, label)\n\n X = np.zeros((len(df), 3))\n i = 0\n for index, row in df.iterrows():\n X[i, :]= self.extract_features(row[text], self.freqs)\n i = i + 1\n\n Y = df[label].to_numpy()\n Y.shape = (len(Y),1)\n\n J, self.theta = self.gradientDescent(X, Y, np.zeros((3, 1)), 1e-7, 1005000)\n print(f\"The cost after training is {J:.8f}.\")\n print(f\"The resulting vector of weights is {[round(t, 8) for t in np.squeeze(self.theta)]}\")\n\n return self\n\n\n ###################################################################################################\n\n def predict(self, df):\n \"\"\"\n Given a DataFrame that has the required field from training, make predictions for\n each row.\n \"\"\"\n x = df[self.text_col_name].tolist()\n return self.predict_from_vectors(x)\n\n ###################################################################################################\n\n def build_word_dictionary(self, df, text, label):\n freqs = {}\n for index, row in df.iterrows():\n word_l = self.process_text(row[text])\n lab = row[label]\n for word in word_l:\n key = (word, lab)\n val = freqs.get(key,0)\n freqs[key] = val + 1\n return freqs\n\n ###################################################################################################\n\n def sigmoid(self, z): \n '''\n Input:\n z: is the input (can be a scalar or an array)\n Output:\n h: the sigmoid of z\n ''' \n def sigm(inp):\n return 1/(1 + math.exp(-inp))\n vsigm = np.vectorize(sigm)\n x = np.asarray(z)\n scalar_input = False\n if x.ndim == 0:\n x = x[None] # Makes x 1D\n scalar_input = True\n ret = vsigm(x)\n if scalar_input:\n h = np.squeeze(ret)\n else:\n h = ret\n return np.array(h)\n \n \n ###################################################################################################\n def gradientDescent(self, x, y, theta, alpha, num_iters):\n '''\n Input:\n x: matrix of features which is (m,n+1)\n y: corresponding labels of the input matrix x, dimensions (m,1)\n theta: weight vector of dimension (n+1,1)\n alpha: learning rate\n num_iters: number of iterations you want to train your model for\n Output:\n J: the final cost\n theta: your final weight vector\n Hint: you might want to print the cost to make sure that it is going down.\n '''\n m = None\n lowest_cost = np.inf\n best_theta = theta \n for i in range(0, num_iters):\n \n z = np.dot(x, theta)\n \n h = self.sigmoid(z)\n \n def cost(ys, preds):\n logpreds = np.log(preds)\n logonempreds = np.log(1-preds)\n pt1 = np.dot(np.transpose(ys), logpreds)\n pt2 = np.dot(np.transpose(1-ys), logonempreds)\n return -(pt1+pt2)/len(ys)\n \n J = cost(y,h)\n \n def theta_delta(xs, ys, preds):\n return np.dot( np.transpose(xs), (preds-ys) ) / len(ys)\n if J < lowest_cost:\n lowest_cost = J\n best_theta = theta\n elif lowest_cost < (J*1.05):\n print(f\"Applying early stopping after {i} rounds\") \n return float(lowest_cost), best_theta\n\n theta = theta - alpha*theta_delta(x, y, h)\n \n J = float(J)\n return J, theta\n \n \n ###################################################################################################\n def extract_features(self, text, freqs):\n '''\n Input: \n text: a list of words for one text\n freqs: a dictionary corresponding to the frequencies of each tuple (word, label)\n Output: \n x: a feature vector of dimension (1,3)\n '''\n # process_text tokenizes, stems, and removes stopwords\n word_l = self.process_text(text)\n # 3 elements in the form of a 1 x 3 vector\n x = np.zeros((1, 3)) \n #bias term is set to 1\n x[0,0] = 1 \n # loop through each word in the list of words\n for word in word_l:\n # increment the word count for the positive label 1\n x[0,1] += freqs.get( (word, 1.0), 0)\n # increment the word count for the negative label 0\n x[0,2] += freqs.get( (word, 0.0), 0)\n \n return x\n \n ###################################################################################################\n def process_text(self, text):\n #tweet2 = re.sub(r'https?:\\/\\/.*[\\r\\n]*', '', tweet2)\n #!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\n stop_words = ['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', \"you're\", \"you've\", \"you'll\", \"you'd\", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', \"she's\", 'her', 'hers', 'herself', 'it', \"it's\", 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', \"that'll\", 'these', 'those', 'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don', \"don't\", 'should', \"should've\", 'now', 'd', 'll', 'm', 'o', 're', 've', 'y', 'ain', 'aren', \"aren't\", 'couldn', \"couldn't\", 'didn', \"didn't\", 'doesn', \"doesn't\", 'hadn', \"hadn't\", 'hasn', \"hasn't\", 'haven', \"haven't\", 'isn', \"isn't\", 'ma', 'mightn', \"mightn't\", 'mustn', \"mustn't\", 'needn', \"needn't\", 'shan', \"shan't\", 'shouldn', \"shouldn't\", 'wasn', \"wasn't\", 'weren', \"weren't\", 'won', \"won't\", 'wouldn', \"wouldn't\"]\n return text.split()\n \n ###################################################################################################\n def predict_text(self, text, freqs, theta):\n '''\n Input: \n text: a string\n freqs: a dictionary corresponding to the frequencies of each tuple (word, label)\n theta: (3,1) vector of weights\n Output: \n y_pred: the probability of a text being positive or negative\n '''\n x = self.extract_features(text, freqs)\n z = np.dot(x, theta)\n y_pred = self.sigmoid(z)\n return y_pred\n\n" ]
[ [ "numpy.dot", "numpy.log", "numpy.asarray", "numpy.squeeze", "numpy.vectorize", "numpy.transpose", "numpy.array", "numpy.zeros" ] ]
adrn/TwoBody
[ "3af41d642e3485aec9ddc18e582e73c561c4df96" ]
[ "twobody/tests/test_reference_plane.py" ]
[ "# Third-party\nimport astropy.units as u\nimport astropy.coordinates as coord\nfrom astropy.tests.helper import quantity_allclose\nimport numpy as np\nimport pytest\n\n# Project\nfrom ..reference_plane import ReferencePlaneFrame\n\n\ndef test_sanity():\n\n rep1 = coord.CartesianRepresentation(x=[0, 1.],\n y=0,\n z=0, unit=u.pc)\n\n rep2 = coord.CartesianRepresentation(x=0,\n y=[0, 1.],\n z=0, unit=u.pc)\n\n rep3 = coord.CartesianRepresentation(x=0,\n y=0,\n z=[0, 1.], unit=u.pc)\n\n # Try for many origins:\n rnd = np.random.RandomState(seed=42)\n\n for _ in range(128):\n origin = coord.ICRS(ra=rnd.uniform(0, 360)*u.deg,\n dec=rnd.uniform(-90, 90)*u.deg,\n distance=rnd.uniform(10, 100)*u.pc)\n\n ref_c = ReferencePlaneFrame(rep1, origin=origin)\n icrs = ref_c.transform_to(coord.ICRS)\n assert icrs.dec[1] > icrs.dec[0]\n assert quantity_allclose(icrs.ra[0], icrs.ra[1])\n\n ref_c = ReferencePlaneFrame(rep2, origin=origin)\n icrs = ref_c.transform_to(coord.ICRS)\n assert icrs.ra[1] > icrs.ra[0]\n\n ref_c = ReferencePlaneFrame(rep3, origin=origin)\n icrs = ref_c.transform_to(coord.ICRS)\n assert icrs.distance[0] > icrs.distance[1]\n assert quantity_allclose(icrs.ra[0], icrs.ra[1])\n assert quantity_allclose(icrs.dec[0], icrs.dec[1])\n\n\ndef test_transform():\n rep = coord.CartesianRepresentation(x=1, y=2, z=3, unit=u.pc)\n ref_c1 = ReferencePlaneFrame(rep)\n\n with pytest.raises(ValueError):\n ref_c1.transform_to(coord.ICRS)\n\n with pytest.raises(ValueError):\n ref_c2 = ReferencePlaneFrame(rep, origin=coord.Galactic())\n" ]
[ [ "numpy.random.RandomState" ] ]
Zhong-J/azureml-examples
[ "5b9bbc5eb2a37d39d8f46ea9d88b320d298473d9" ]
[ "cli/jobs/pipelines/cifar-10/src/train-model/main.py" ]
[ "# Copyright (c) 2017 Facebook, Inc. All rights reserved.\n# BSD 3-Clause License\n#\n# Script adapted from: https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py\n# ==============================================================================\n\n# imports\nimport os\nimport mlflow\nimport argparse\n\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n# TODO - add mlflow logging\n\n# define network architecture\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(3, 32, 3)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(32, 64, 3)\n self.conv3 = nn.Conv2d(64, 128, 3)\n self.fc1 = nn.Linear(128 * 6 * 6, 120)\n self.dropout = nn.Dropout(p=0.2)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = self.pool(F.relu(self.conv2(x)))\n x = self.pool(F.relu(self.conv3(x)))\n x = x.view(-1, 128 * 6 * 6)\n x = self.dropout(F.relu(self.fc1(x)))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\n# define functions\ndef train(train_loader, model, criterion, optimizer, epoch, device, print_freq, rank):\n running_loss = 0.0\n for i, data in enumerate(train_loader, 0):\n # get the inputs; data is a list of [inputs, labels]\n inputs, labels = data[0].to(device), data[1].to(device)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n # print statistics\n running_loss += loss.item()\n if i % print_freq == 0: # print every print_freq mini-batches\n print(\n \"Rank %d: [%d, %5d] loss: %.3f\"\n % (rank, epoch + 1, i + 1, running_loss / print_freq)\n )\n running_loss = 0.0\n\n\ndef main(args):\n # get PyTorch environment variables\n world_size = int(os.environ[\"WORLD_SIZE\"])\n rank = int(os.environ[\"RANK\"])\n local_rank = int(os.environ[\"LOCAL_RANK\"])\n\n distributed = world_size > 1\n\n # set device\n if distributed and torch.cuda.is_available():\n device = torch.device(\"cuda\", local_rank)\n else:\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n # initialize distributed process group using default env:// method\n if distributed:\n torch.distributed.init_process_group(\n backend=\"nccl\" if torch.cuda.is_available() else \"gloo\"\n )\n\n # define train and dataset DataLoaders\n transform = transforms.Compose(\n [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]\n )\n\n train_set = torchvision.datasets.CIFAR10(\n root=args.data_dir, train=True, download=False, transform=transform\n )\n\n if distributed:\n train_sampler = torch.utils.data.distributed.DistributedSampler(train_set)\n else:\n train_sampler = None\n\n train_loader = torch.utils.data.DataLoader(\n train_set,\n batch_size=args.batch_size,\n shuffle=(train_sampler is None),\n num_workers=args.workers,\n sampler=train_sampler,\n )\n\n model = Net().to(device)\n\n # wrap model with DDP\n if distributed and torch.cuda.is_available():\n model = nn.parallel.DistributedDataParallel(\n model, device_ids=[local_rank], output_device=local_rank\n )\n\n # define loss function and optimizer\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.SGD(\n model.parameters(), lr=args.learning_rate, momentum=args.momentum\n )\n\n # train the model\n for epoch in range(args.epochs):\n print(\"Rank %d: Starting epoch %d\" % (rank, epoch))\n if distributed:\n train_sampler.set_epoch(epoch)\n model.train()\n train(\n train_loader,\n model,\n criterion,\n optimizer,\n epoch,\n device,\n args.print_freq,\n rank,\n )\n\n print(\"Rank %d: Finished Training\" % (rank))\n\n if not distributed or rank == 0:\n # log model\n mlflow.pytorch.save_model(model, f\"{args.model_dir}/model\")\n\n\ndef parse_args():\n # setup argparse\n parser = argparse.ArgumentParser()\n\n # add arguments\n parser.add_argument(\n \"--data-dir\", type=str, help=\"directory containing CIFAR-10 dataset\"\n )\n parser.add_argument(\n \"--model-dir\", type=str, default=\"./\", help=\"output directory for model\"\n )\n parser.add_argument(\"--epochs\", default=10, type=int, help=\"number of epochs\")\n parser.add_argument(\n \"--batch-size\",\n default=16,\n type=int,\n help=\"mini batch size for each gpu/process\",\n )\n parser.add_argument(\n \"--workers\",\n default=2,\n type=int,\n help=\"number of data loading workers for each gpu/process\",\n )\n parser.add_argument(\n \"--learning-rate\", default=0.001, type=float, help=\"learning rate\"\n )\n parser.add_argument(\"--momentum\", default=0.9, type=float, help=\"momentum\")\n parser.add_argument(\n \"--print-freq\",\n default=200,\n type=int,\n help=\"frequency of printing training statistics\",\n )\n\n # parse args\n args = parser.parse_args()\n\n # return args\n return args\n\n\n# run script\nif __name__ == \"__main__\":\n # parse args\n args = parse_args()\n\n # call main function\n main(args)\n" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.nn.Dropout", "torch.utils.data.distributed.DistributedSampler", "torch.nn.Conv2d", "torch.utils.data.DataLoader", "torch.nn.Linear", "torch.nn.MaxPool2d", "torch.cuda.is_available", "torch.device", "torch.nn.parallel.DistributedDataParallel" ] ]
PesceJonathan/BlockShame
[ "bea3d3cfc91a0842a7f871ce2e6e5d417fea08cd" ]
[ "VirtualWebcam/VirtualWebcam.py" ]
[ "from threading import Thread\nfrom datetime import datetime\nimport csv\nimport cv2 as cv\nimport pyvirtualcam\nimport numpy as np\nimport win32api\nimport pathlib\nimport math\nfrom threading import Thread\nfrom queue import Queue, Empty\nfrom SpeechToText import main\nimport textwrap\n\n# Constants\nIMG_W = 640\nIMG_H = 480\nWM_APPCOMMAND = 0x319\nAPPCOMMAND_MIC_MAX = 0x1A\nAPPCOMMAND_MIC_MIN = 0x19\nERROR_THRESHOLD = 8\n\n\nclass VirtualWebcam(Thread):\n def __init__(\n self,\n lock,\n errImgPath=None,\n notPresent=False,\n isSleeping=False,\n controlMic=False,\n transcribe=False,\n faceRecognition=False,\n asl_regconition=False,\n ):\n self.notPresent = notPresent\n self.isSleeping = isSleeping\n self.controlMic = controlMic\n self.errImg = (None, cv.imread(errImgPath))[errImgPath is not None]\n\n self.transcribe = transcribe\n self.blockFrame = None\n self.notPresentCounter = 0\n self.NotUser = False\n self.transcript_queue = Queue()\n self.startLookAwayTime = None\n self.transcript_curr_message = \"\"\n self.transcriptTimeout = None\n self.message_queue = None\n # Import all the cascades\n self.face_cascade = cv.CascadeClassifier(\n str(pathlib.Path(__file__).resolve().parent)\n + \"./Haarcascades/haarcascade_frontalface_default.xml\"\n )\n self.open_eyes_cascade = cv.CascadeClassifier(\n str(pathlib.Path(__file__).resolve().parent)\n + \"./Haarcascades/haarcascade_eye.xml\"\n )\n self.right_eyes_cascade = cv.CascadeClassifier(\n str(pathlib.Path(__file__).resolve().parent)\n + \"./Haarcascades/haarcascade_righteye_2splits.xml\"\n )\n self.left_eyes_cascade = cv.CascadeClassifier(\n str(pathlib.Path(__file__).resolve().parent)\n + \"./Haarcascades/haarcascade_lefteye_2splits.xml\"\n )\n self.faceRecognition = faceRecognition\n if faceRecognition or False:\n print(\"NOT NONE\")\n self.face_recognizer = cv.face.LBPHFaceRecognizer_create()\n self.face_recognizer.read(\n str(pathlib.Path(__file__).resolve().parent)\n + \"/Data/JonathanPesce_Model.yml\"\n )\n else:\n self.face_recognizer = None\n self.asl_regconition = asl_regconition\n self.speech_thread = None\n self.lock = lock\n\n # Create the csv that will contain the concentration data\n createCSV()\n\n def sync_config(self):\n try:\n if self.message_queue.qsize() > 0:\n value = self.message_queue.get()\n print(f\"Value: {value}\")\n settings = value.get(\"payload\")\n self.lock.acquire()\n if value.get(\"type\") == \"webcam\":\n print(f\"SYNC------------Webcam: {settings}\")\n self.notPresent = (\n settings.get(\"videoAwaydetection\", self.notPresent)\n # if settings.get(\"videoAwaydetection\", False)\n # else self.notPresent\n )\n if settings.get(\"useCustomAwayImage\"):\n self.errImg = (\n cv.imread(settings.get(\"customImagePath\"))\n if settings.get(\"useCustomAwayImage\")\n else self.errImg\n )\n else:\n self.errImg = None\n\n self.isSleeping = (\n settings.get(\"videoSleepingDetection\", self.isSleeping)\n # if settings.get(\"videoSleepingDetection\")\n # else self.isSleeping\n )\n\n self.faceRecognition = settings.get(\n \"videoNotUserDetection\", self.faceRecognition\n )\n\n print(\"---------------\")\n print(self.notPresent)\n print(self.errImg)\n print(self.isSleeping)\n print(self.faceRecognition)\n print(\"---------------\")\n elif value.get(\"type\") == \"accessibility\":\n self.transcribe = settings.get(\n \"audioTranscriber\", self.transcribe\n )\n self.toggle_audio_thread()\n\n print(\"---------------\")\n print(self.asl_regconition)\n print(self.transcribe)\n print(\"---------------\")\n elif value.get(\"type\") == \"audio\":\n self.controlMic = settings.get(\n \"muteAudioWhenVideoIsDisabled\", self.controlMic\n )\n print(\"---------------\")\n print(self.controlMic)\n print(\"---------------\")\n else:\n pass\n self.lock.release()\n except Empty:\n pass\n \n def toggle_audio_thread(self):\n if not self.speech_thread:\n if self.transcribe:\n self.speech_thread = Thread(target=main, args=(self.transcript_queue,), daemon = True)\n self.speech_thread.start()\n else:\n if self.transcribe:\n self.speech_thread.__exit__()\n\n def start(self, message_queue):\n self.message_queue = message_queue\n # Use OpenCV to grab the webcam video feed\n video_feed = cv.VideoCapture(0)\n \n \n \n if self.transcribe:\n self.speech_thread = Thread(target=main, args=(self.transcript_queue,))\n self.speech_thread.start()\n \n \n \n # Check if the webcam can be opened\n if (video_feed.isOpened() == False):\n return \"ERROR - Could not connect to webcam!!!\"\n\n with pyvirtualcam.Camera(width=IMG_W, height=IMG_H, fps=30) as cam:\n counter = 0\n while True:\n\n frame = self.processFrame(video_feed, counter)\n\n counter = (counter + 1, 0)[counter == 30]\n \n if counter == 29:\n self.sync_config()\n\n # Send to virtual cam\n cam.send(frame)\n\n # Wait until it's time for the next frame\n cam.sleep_until_next_frame()\n\n cv.waitKey(0)\n video_feed.release()\n \n\n def processFrame(self, video_feed, counter, isPython=False):\n # Read the frame from the webcam\n isTrue, frame = video_feed.read()\n\n if counter % 5 == 0:\n if (\n self.updateShouldShowCame(\n frame, counter == 30 and self.face_recognizer is not None\n )\n == False\n ):\n frame = self.getBlockFrame(frame, self.notPresent)\n\n if self.startLookAwayTime is None:\n self.startLookAwayTime = datetime.now()\n\n elif self.blockFrame is not None:\n self.blockFrame = None\n\n if self.startLookAwayTime is not None:\n writeTimeFrame(self.startLookAwayTime, datetime.now())\n self.startLookAwayTime = None\n\n if self.controlMic:\n turnOnMic()\n elif self.blockFrame is not None:\n frame = self.blockFrame\n cv.flip(frame, -1)\n\n # If we are pushing to OBS convert to RGBA\n if isPython == False:\n frame = convert2RGBA(frame)\n\n if self.transcribe:\n if self.transcript_queue.qsize() > 0:\n self.transcript_curr_message = self.transcript_queue.get()\n self.transcript_curr_message = textwrap.wrap(\n self.transcript_curr_message, width=30\n )\n self.transcriptTimeout = 0\n\n if self.transcriptTimeout is not None:\n if self.transcriptTimeout < 2 * 15 * len(self.transcript_curr_message):\n for i, v in enumerate(self.transcript_curr_message):\n frame = cv.putText(\n frame,\n v.strip(),\n (\n 20,\n IMG_H\n - (len(self.transcript_curr_message) * 25)\n + (20 * (i) + (5 * i)),\n ),\n cv.FONT_HERSHEY_SIMPLEX,\n 0.8,\n (255, 255, 255),\n 2,\n cv.LINE_AA,\n )\n\n self.transcriptTimeout += 1\n\n return frame\n\n def updateShouldShowCame(self, frame, checkFace):\n if (\n self.notPresent == False\n and self.isSleeping == False\n and checkFace == False\n and self.NotUser == False\n ):\n return True\n\n # Convert the frame to grayscale\n frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n\n # Grab all the faces found\n face_rects = self.face_cascade.detectMultiScale(\n frame_gray, scaleFactor=1.2, minNeighbors=10\n )\n\n # Check based on restrictions passed in if conditions to turn off are met\n shouldTurnOff = False\n\n if checkFace:\n for (x, y, w, h) in face_rects:\n faces_roi = frame_gray[y : y + h, x : x + w]\n label, confidence = self.face_recognizer.predict(faces_roi)\n\n if label != 1:\n self.NotUser = True\n return False\n else:\n self.NotUser = False\n elif self.NotUser == True:\n return False\n\n # If user is not present turn off the webcam\n if self.notPresent and len(face_rects) < 1:\n shouldTurnOff = True\n\n if (\n shouldTurnOff == False\n and self.isSleeping\n and self.detectSleeping(face_rects, frame_gray)\n ):\n shouldTurnOff = True\n\n self.notPresentCounter = (0, self.notPresentCounter + 1)[shouldTurnOff]\n\n return self.notPresentCounter < ERROR_THRESHOLD\n\n def getBlockFrame(self, frame, notPresent):\n if self.blockFrame is not None:\n return self.blockFrame\n\n if self.errImg is not None:\n self.blockFrame = self.errImg\n else:\n self.blockFrame = cv.blur(frame, (131, 131))\n\n if notPresent:\n self.blockFrame = cv.putText(\n self.blockFrame,\n \"LEFT THE SCREEN\",\n (50, 50),\n cv.FONT_HERSHEY_SIMPLEX,\n 1.5,\n (255, 255, 255),\n 2,\n cv.LINE_AA,\n )\n\n # Turn off the mic\n if self.controlMic:\n turnOffMic()\n\n return self.blockFrame\n\n def detectSleeping(self, faces_rect, frame_gray):\n # Check if there was a face that was detected\n if len(faces_rect) < 0:\n return False\n\n for (x, y, w, h) in faces_rect:\n # Get the ROI of the image\n roi = frame_gray[y : y + h, x : x + w]\n\n oeyes = self.open_eyes_cascade.detectMultiScale(roi, 1.3, 30)\n reyes = self.right_eyes_cascade.detectMultiScale(roi, 1.3, 20)\n leyes = self.left_eyes_cascade.detectMultiScale(roi, 1.3, 20)\n\n if (len(leyes) != 0 or len(reyes) != 0) and len(oeyes) == 0:\n return True\n\n return False\n\n def startPython(self):\n # Use OpenCV to grab the webcam video feed\n video_feed = cv.VideoCapture(0)\n\n # Check if the webcam can be opened\n if video_feed.isOpened() == False:\n return \"ERROR - Could not connect to webcam!!!\"\n\n counter = 0\n while True:\n frame = self.processFrame(video_feed, counter, isPython=True)\n\n counter = (counter + 1, 0)[counter == 30]\n\n cv.imshow(\"Title\", frame)\n cv.waitKey(1)\n\n cv.waitKey(0)\n video_feed.release()\n writeTimeFrame(None, datetime.now())\n\n\ndef toggleMic(val):\n win32api.SendMessage(-1, WM_APPCOMMAND, 0x30292, val * 0x10000)\n\n\ndef turnOffMic():\n thread = Thread(target=toggleMic, args=([APPCOMMAND_MIC_MIN]))\n thread.start()\n\n\ndef turnOnMic():\n thread = Thread(target=toggleMic, args=([APPCOMMAND_MIC_MAX]))\n thread.start()\n\n\ndef appendToCSV(startTime, endTime):\n print(\"Append to csv\")\n with open(\n str(pathlib.Path(__file__).resolve().parent) + \"./Data/ConcentrationData.csv\",\n \"a+\",\n newline=\"\",\n ) as file:\n csvWriter = csv.writer(file, delimiter=\",\")\n csvWriter.writerow([startTime, endTime])\n\n\ndef createCSV():\n with open(\n str(pathlib.Path(__file__).resolve().parent) + \"./Data/ConcentrationData.csv\",\n \"w+\",\n newline=\"\",\n ) as file:\n csvWriter = csv.writer(file, delimiter=\",\")\n csvWriter.writerows([[\"StartTime\", \"EndTime\"], [datetime.now(), None]])\n\n\ndef writeTimeFrame(startTime, endTime):\n thread = Thread(target=appendToCSV, args=([startTime, endTime]))\n thread.start()\n\n\ndef convert2RGBA(frame):\n # convert to RGBA\n out_frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB)\n out_frame_rgba = np.zeros((IMG_H, IMG_W, 4), np.uint8)\n out_frame_rgba[:, :, :3] = out_frame\n out_frame_rgba[:, :, 3] = 255\n return out_frame_rgba\n\n\nif __name__ == \"__main__\":\n t = VirtualWebcam(\n notPresent=True,\n isSleeping=True,\n errImgPath=\"ErrorImage.png\",\n controlMic=False,\n faceRecognition=False,\n )\n #t.startPython()\n t.start()\n" ]
[ [ "numpy.zeros" ] ]
dragomirradev/ctc-gen-eval
[ "d26c24734626298ba2ed9062e2789594edfae347" ]
[ "ctc_score/scorer.py" ]
[ "import os\n\nfrom ctc_score.download import maybe_download\nfrom ctc_score.configs import ALIGNS, E_MODEL_CONFIGS, DR_MODEL_LINKS\n\nfrom ctc_score.models.discriminative_aligner import DiscriminativeAligner\nfrom ctc_score.models.bert_aligner import BERTAligner\nfrom ctc_score.models.bleurt_aligner_pt import BLEURTAligner\nimport torch\n\n\nclass Scorer:\n def __init__(self, align, aggr_type, device):\n assert align in ALIGNS\n\n self._align = align\n self._aligners = {}\n\n self._aggr_type = aggr_type\n self._device = device\n\n def score(self, *args, **kwargs):\n raise NotImplementedError\n\n def _get_aligner(self, aligner_name):\n if aligner_name in self._aligners:\n return self._aligners[aligner_name]\n\n if self._align.startswith('E'):\n aligner = BERTAligner(\n **E_MODEL_CONFIGS[self._align[2:]],\n aggr_type=self._aggr_type,\n lang='en',\n device=self._device)\n else:\n aligner_link = DR_MODEL_LINKS[self._align][aligner_name]\n\n os.makedirs(\n f'{os.getenv(\"HOME\")}/.cache/ctc_score_models/{self._align}/',\n exist_ok=True)\n maybe_download(\n urls=aligner_link,\n path=f'{os.getenv(\"HOME\")}/.cache/',\n filenames=f'ctc_score_models/{self._align}/{aligner_name}.ckpt')\n ckpt_path = f'{os.getenv(\"HOME\")}/.cache/' \\\n f'ctc_score_models/{self._align}/{aligner_name}.ckpt'\n\n if self._align.startswith('D'):\n aligner = DiscriminativeAligner(\n aggr_type=self._aggr_type).to(self._device)\n aligner.load_state_dict(torch.load(ckpt_path))\n aligner.eval()\n else:\n assert self._align.startswith('R')\n aligner = BLEURTAligner(\n aggr_type=self._aggr_type,\n checkpoint=ckpt_path,\n device=self._device)\n\n self._aligners[aligner_name] = aligner\n return self._aligners[aligner_name]\n" ]
[ [ "torch.load" ] ]
TomaszZamacinski/causalml
[ "10c766e6b12530bec39c9f85ffe87f14de738b12" ]
[ "causalml/metrics/classification.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport logging\nfrom sklearn.metrics import log_loss, roc_auc_score\n\nfrom .const import EPS\nfrom .regression import regression_metrics\n\n\nlogger = logging.getLogger('causalml')\n\n\ndef logloss(y, p):\n \"\"\"Bounded log loss error.\n Args:\n y (numpy.array): target\n p (numpy.array): prediction\n Returns:\n bounded log loss error\n \"\"\"\n\n p[p < EPS] = EPS\n p[p > 1 - EPS] = 1 - EPS\n return log_loss(y, p)\n\n\ndef classification_metrics(y, p, w=None, metrics={'AUC': roc_auc_score, 'Log Loss': logloss}):\n \"\"\"Log metrics for classifiers.\n\n Args:\n y (numpy.array): target\n p (numpy.array): prediction\n w (numpy.array, optional): a treatment vector (1 or True: treatment, 0 or False: control). If given, log\n metrics for the treatment and control group separately\n metrics (dict, optional): a dictionary of the metric names and functions\n \"\"\"\n regression_metrics(y=y, p=p, w=w, metrics=metrics)\n" ]
[ [ "sklearn.metrics.log_loss" ] ]
DavidGillsjo/bssc-net
[ "e1ffa643a2c8e3df34225f0756bad0dec9f801a2" ]
[ "ssc/data/suncg_mapping.py" ]
[ "import ssc.data.suncg as suncg\nimport yaml\nimport numpy as np\nfrom collections import OrderedDict\nimport os.path as osp\nfrom multiprocessing.managers import BaseManager\n\ndef setup_yaml():\n \"\"\" https://stackoverflow.com/a/8661021 \"\"\"\n represent_dict_order = lambda self, data: self.represent_mapping('tag:yaml.org,2002:map', data.items())\n yaml.add_representer(OrderedDict, represent_dict_order)\n\nclass MappingManager(BaseManager):\n pass\n\n#Store as many variables as np arrays as possible to reduce copy on access memory leak during multiprocessing.\nclass SUNCGMapping:\n def __init__(self, yaml_map=None):\n self.all_labels = np.array(suncg.SUNCGLabels().getClasses())\n\n self.wrapper = yaml_map is None\n if self.wrapper:\n return\n\n with open(osp.join(osp.dirname(suncg.__file__), 'mappings', '{}.yaml'.format(yaml_map))) as f:\n y = yaml.safe_load(f)\n labels = y['labels']\n mapping = y['mapping']\n\n\n self.labels = np.array(labels)\n self.int_mapping = np.array([labels.index(mapping[suncg_label]) for suncg_label in self.all_labels])\n\n\n @classmethod\n def create_proxy(cls, yaml_map = None):\n manager = MappingManager()\n manager.register('SUNCGMapping', cls, exposed = ['map', 'get_nbr_classes', 'get_classes', 'get_class_id'])\n manager.start()\n return manager, manager.SUNCGMapping(yaml_map)\n\n def map(self, np_array, dtype = None):\n if self.wrapper:\n return np_array.astype(dtype) if dtype else np_array\n\n new_array = np.zeros_like(np_array, dtype = dtype)\n for old_int, new_int in enumerate(self.int_mapping):\n new_array[np_array == old_int] = new_int\n\n return new_array\n\n def get_nbr_classes(self):\n return len(self.get_classes())\n\n def get_class_id(self, name):\n if self.wrapper:\n return np.flatnonzero(self.all_labels==name)[0]\n else:\n return np.flatnonzero(self.labels==name)[0]\n\n def get_classes(self):\n if self.wrapper:\n return self.all_labels\n else:\n return self.labels\n\n\n# Just generate a template if called as script\nif __name__ == '__main__':\n sl = suncg.SUNCGLabels()\n labels = sl.getClasses()\n\n all_NYU_mappings = sl.get_NYU_mapping()\n NYU_labels = ['free', *all_NYU_mappings['elevenClass']]\n NYU_mapping = ['free', *all_NYU_mappings['map36to11']]\n\n mapping = OrderedDict.fromkeys(labels)\n for li, l in enumerate(labels):\n mapping[l] = NYU_mapping[li]\n\n setup_yaml()\n with open('suncg11.yaml', 'w') as f:\n yaml.dump({'labels': NYU_labels, 'mapping': mapping}, f)\n" ]
[ [ "numpy.array", "numpy.zeros_like", "numpy.flatnonzero" ] ]
ishandutta2007/qiskit-sdk-py
[ "69ae9c3cb276e5aa097a5cc4ee4eabe31c4f04ca" ]
[ "qiskit/tools/visualization.py" ]
[ "# -*- coding: utf-8 -*-\n\n# Copyright 2017 IBM RESEARCH. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\n\"\"\"\nVisualization functions for quantum states.\n\"\"\"\n\nimport numpy as np\nfrom functools import reduce\nfrom scipy import linalg as la\nfrom collections import Counter\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom mpl_toolkits.mplot3d import proj3d\nfrom matplotlib.patches import FancyArrowPatch\nfrom qiskit.tools.qi.pauli import pauli_group, pauli_singles\n\n###############################################################\n# Plotting historgram\n###############################################################\n\n\ndef plot_histogram(data, number_to_keep=False):\n \"\"\"Plot a histogram of data.\n\n data is a dictionary of {'000': 5, '010': 113, ...}\n number_to_keep is the number of terms to plot and rest is made into a\n single bar called other values\n \"\"\"\n if number_to_keep is not False:\n data_temp = dict(Counter(data).most_common(number_to_keep))\n data_temp[\"rest\"] = sum(data.values()) - sum(data_temp.values())\n data = data_temp\n\n labels = sorted(data)\n values = np.array([data[key] for key in labels], dtype=float)\n pvalues = values / sum(values)\n numelem = len(values)\n ind = np.arange(numelem) # the x locations for the groups\n width = 0.35 # the width of the bars\n fig, ax = plt.subplots()\n rects = ax.bar(ind, pvalues, width, color='seagreen')\n # add some text for labels, title, and axes ticks\n ax.set_ylabel('Probabilities', fontsize=12)\n ax.set_xticks(ind)\n ax.set_xticklabels(labels, fontsize=12, rotation=70)\n ax.set_ylim([0., min([1.2, max([1.2 * val for val in pvalues])])])\n # attach some text labels\n for rect in rects:\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * height,\n '%f' % float(height),\n ha='center', va='bottom')\n plt.show()\n\n\n###############################################################\n# Plotting states\n###############################################################\n\nclass Arrow3D(FancyArrowPatch):\n \"\"\"Standard 3D arrow.\"\"\"\n\n def __init__(self, xs, ys, zs, *args, **kwargs):\n \"\"\"Create arrow.\"\"\"\n FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)\n self._verts3d = xs, ys, zs\n\n def draw(self, renderer):\n \"\"\"Draw the arrow.\"\"\"\n xs3d, ys3d, zs3d = self._verts3d\n xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))\n FancyArrowPatch.draw(self, renderer)\n\n\ndef plot_bloch_vector(bloch, title=\"\"):\n \"\"\"Plot the Bloch sphere.\n\n Plot a sphere, axes, the Bloch vector, and its projections onto each axis.\n\n Args:\n bloch (list[double]): array of three elements where [<x>, <y>,<z>]\n title (str): a string that represents the plot title\n\n Returns:\n none: plot is shown with matplotlib to the screen\n\n \"\"\"\n # Set arrow lengths\n arlen = 1.3\n\n # Plot semi-transparent sphere\n u = np.linspace(0, 2 * np.pi, 100)\n v = np.linspace(0, np.pi, 100)\n x = np.outer(np.cos(u), np.sin(v))\n y = np.outer(np.sin(u), np.sin(v))\n z = np.outer(np.ones(np.size(u)), np.cos(v))\n\n fig = plt.figure(figsize=(6, 6))\n ax = fig.add_subplot(111, projection='3d')\n ax.set_aspect(\"equal\")\n ax.plot_surface(x, y, z, color=(.5, .5, .5), alpha=0.1)\n\n # Plot arrows (axes, Bloch vector, its projections)\n xa = Arrow3D([0, arlen], [0, 0], [0, 0], mutation_scale=20, lw=1,\n arrowstyle=\"-|>\", color=(.5, .5, .5))\n ya = Arrow3D([0, 0], [0, arlen], [0, 0], mutation_scale=20, lw=1,\n arrowstyle=\"-|>\", color=(.5, .5, .5))\n za = Arrow3D([0, 0], [0, 0], [0, arlen], mutation_scale=20, lw=1,\n arrowstyle=\"-|>\", color=(.5, .5, .5))\n a = Arrow3D([0, bloch[0]], [0, bloch[1]], [0, bloch[2]], mutation_scale=20,\n lw=2, arrowstyle=\"simple\", color=\"k\")\n bax = Arrow3D([0, bloch[0]], [0, 0], [0, 0], mutation_scale=20, lw=2,\n arrowstyle=\"-\", color=\"r\")\n bay = Arrow3D([0, 0], [0, bloch[1]], [0, 0], mutation_scale=20, lw=2,\n arrowstyle=\"-\", color=\"g\")\n baz = Arrow3D([0, 0], [0, 0], [0, bloch[2]], mutation_scale=20, lw=2,\n arrowstyle=\"-\", color=\"b\")\n arrowlist = [xa, ya, za, a, bax, bay, baz]\n for arr in arrowlist:\n ax.add_artist(arr)\n\n # Rotate the view\n ax.view_init(30, 30)\n\n # Annotate the axes, shifts are ad-hoc for this (30, 30) view\n xp, yp, _ = proj3d.proj_transform(arlen, 0, 0, ax.get_proj())\n plt.annotate(\"x\", xy=(xp, yp), xytext=(-3, -8), textcoords='offset points',\n ha='right', va='bottom')\n xp, yp, _ = proj3d.proj_transform(0, arlen, 0, ax.get_proj())\n plt.annotate(\"y\", xy=(xp, yp), xytext=(6, -5), textcoords='offset points',\n ha='right', va='bottom')\n xp, yp, _ = proj3d.proj_transform(0, 0, arlen, ax.get_proj())\n plt.annotate(\"z\", xy=(xp, yp), xytext=(2, 0), textcoords='offset points',\n ha='right', va='bottom')\n\n plt.title(title)\n plt.show()\n\n\ndef plot_state_city(rho, title=\"\"):\n \"\"\"Plot the cityscape of quantum state.\n\n Plot two 3d bargraphs (two dimenstional) of the mixed state rho\n\n Args:\n rho (np.array[[complex]]): array of dimensions 2**n x 2**nn complex\n numbers\n title (str): a string that represents the plot title\n\n Returns:\n none: plot is shown with matplotlib to the screen\n\n \"\"\"\n num = int(np.log2(len(rho)))\n\n # get the real and imag parts of rho\n datareal = np.real(rho)\n dataimag = np.imag(rho)\n\n # get the labels\n column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]\n row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]\n\n lx = len(datareal[0]) # Work out matrix dimensions\n ly = len(datareal[:, 0])\n xpos = np.arange(0, lx, 1) # Set up a mesh of positions\n ypos = np.arange(0, ly, 1)\n xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)\n\n xpos = xpos.flatten()\n ypos = ypos.flatten()\n zpos = np.zeros(lx*ly)\n\n dx = 0.5 * np.ones_like(zpos) # width of bars\n dy = dx.copy()\n dzr = datareal.flatten()\n dzi = dataimag.flatten()\n\n fig = plt.figure(figsize=(8, 8))\n ax1 = fig.add_subplot(2, 1, 1, projection='3d')\n ax1.bar3d(xpos, ypos, zpos, dx, dy, dzr, color=\"g\", alpha=0.5)\n ax2 = fig.add_subplot(2, 1, 2, projection='3d')\n ax2.bar3d(xpos, ypos, zpos, dx, dy, dzi, color=\"g\", alpha=0.5)\n\n ax1.set_xticks(np.arange(0.5, lx+0.5, 1))\n ax1.set_yticks(np.arange(0.5, ly+0.5, 1))\n ax1.axes.set_zlim3d(-1.0, 1.0001)\n ax1.set_zticks(np.arange(-1, 1, 0.5))\n ax1.w_xaxis.set_ticklabels(row_names, fontsize=12, rotation=45)\n ax1.w_yaxis.set_ticklabels(column_names, fontsize=12, rotation=-22.5)\n # ax1.set_xlabel('basis state', fontsize=12)\n # ax1.set_ylabel('basis state', fontsize=12)\n ax1.set_zlabel(\"Real[rho]\")\n\n ax2.set_xticks(np.arange(0.5, lx+0.5, 1))\n ax2.set_yticks(np.arange(0.5, ly+0.5, 1))\n ax2.axes.set_zlim3d(-1.0, 1.0001)\n ax2.set_zticks(np.arange(-1, 1, 0.5))\n ax2.w_xaxis.set_ticklabels(row_names, fontsize=12, rotation=45)\n ax2.w_yaxis.set_ticklabels(column_names, fontsize=12, rotation=-22.5)\n # ax2.set_xlabel('basis state', fontsize=12)\n # ax2.set_ylabel('basis state', fontsize=12)\n ax2.set_zlabel(\"Imag[rho]\")\n plt.title(title)\n plt.show()\n\n\ndef plot_state_paulivec(rho, title=\"\"):\n \"\"\"Plot the paulivec representation of a quantum state.\n\n Plot a bargraph of the mixed state rho over the pauli matricies\n\n Args:\n rho (np.array[[complex]]): array of dimensions 2**n x 2**nn complex\n numbers\n title (str): a string that represents the plot title\n\n Returns:\n none: plot is shown with matplotlib to the screen\n\n \"\"\"\n num = int(np.log2(len(rho)))\n labels = list(map(lambda x: x.to_label(), pauli_group(num)))\n values = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),\n pauli_group(num)))\n numelem = len(values)\n ind = np.arange(numelem) # the x locations for the groups\n width = 0.5 # the width of the bars\n fig, ax = plt.subplots()\n ax.grid(zorder=0)\n ax.bar(ind, values, width, color='seagreen')\n\n # add some text for labels, title, and axes ticks\n ax.set_ylabel('Expectation value', fontsize=12)\n ax.set_xticks(ind)\n ax.set_yticks([-1, -0.5, 0, 0.5, 1])\n ax.set_xticklabels(labels, fontsize=12, rotation=70)\n ax.set_xlabel('Pauli', fontsize=12)\n ax.set_ylim([-1, 1])\n plt.title(title)\n plt.show()\n\n\ndef n_choose_k(n, k):\n \"\"\"Return the number of combinations for n choose k.\n\n Args:\n n (int): the total number of options .\n k (int): The number of elements.\n\n Returns:\n int: returns the binomial coefficient\n\n \"\"\"\n if n == 0:\n return 0\n else:\n return reduce(lambda x, y: x * y[0] / y[1],\n zip(range(n - k + 1, n + 1),\n range(1, k + 1)), 1)\n\n\ndef lex_index(n, k, lst):\n \"\"\"Return the lex index of a combination..\n\n Args:\n n (int): the total number of options .\n k (int): The number of elements.\n lst\n\n Returns:\n int: returns int index for lex order\n\n \"\"\"\n assert len(lst) == k, \"list should have length k\"\n comb = list(map(lambda x: n - 1 - x, lst))\n dualm = sum([n_choose_k(comb[k - 1 - i], i + 1) for i in range(k)])\n return int(dualm)\n\n\ndef bit_string_index(s):\n \"\"\"Return the index of a string of 0s and 1s.\"\"\"\n n = len(s)\n k = s.count(\"1\")\n assert s.count(\"0\") == n - k, \"s must be a string of 0 and 1\"\n ones = [pos for pos, char in enumerate(s) if char == \"1\"]\n return lex_index(n, k, ones)\n\n\ndef phase_to_color_wheel(complex_number):\n \"\"\"Map a phase of a complexnumber to a color in (r,g,b).\n\n complex_number is phase is first mapped to angle in the range\n [0, 2pi] and then to a color wheel with blue at zero phase.\n \"\"\"\n angles = np.angle(complex_number)\n angle_round = int(((angles + 2 * np.pi) % (2 * np.pi))/np.pi*6)\n # print(angleround)\n color_map = {0: (0, 0, 1), # blue,\n 1: (0.5, 0, 1), # blue-violet\n 2: (1, 0, 1), # violet\n 3: (1, 0, 0.5), # red-violet,\n 4: (1, 0, 0), # red\n 5: (1, 0.5, 0), # red-oranage,\n 6: (1, 1, 0), # orange\n 7: (0.5, 1, 0), # orange-yellow\n 8: (0, 1, 0), # yellow,\n 9: (0, 1, 0.5), # yellow-green,\n 10: (0, 1, 1), # green,\n 11: (0, 0.5, 1) # green-blue,\n }\n return color_map[angle_round]\n\n\ndef plot_state_qsphere(rho):\n \"\"\"Plot the qsphere representation of a quantum state.\"\"\"\n num = int(np.log2(len(rho)))\n # get the eigenvectors and egivenvalues\n we, stateall = la.eigh(rho)\n for i in range(2**num):\n # start with the max\n probmix = we.max()\n prob_location = we.argmax()\n if probmix > 0.001:\n print(\"The \" + str(i) + \"th eigenvalue = \" + str(probmix))\n # get the max eigenvalue\n state = stateall[:, prob_location]\n loc = np.absolute(state).argmax()\n # get the element location closes to lowest bin representation.\n for j in range(2**num):\n test = np.absolute(np.absolute(state[j])\n - np.absolute(state[loc]))\n if test < 0.001:\n loc = j\n break\n # remove the global phase\n angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)\n angleset = np.exp(-1j*angles)\n # print(state)\n # print(angles)\n state = angleset*state\n # print(state)\n state.flatten()\n # start the plotting\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(111, projection='3d')\n ax.axes.set_xlim3d(-1.0, 1.0)\n ax.axes.set_ylim3d(-1.0, 1.0)\n ax.axes.set_zlim3d(-1.0, 1.0)\n ax.set_aspect(\"equal\")\n ax.axes.grid(False)\n # Plot semi-transparent sphere\n u = np.linspace(0, 2 * np.pi, 25)\n v = np.linspace(0, np.pi, 25)\n x = np.outer(np.cos(u), np.sin(v))\n y = np.outer(np.sin(u), np.sin(v))\n z = np.outer(np.ones(np.size(u)), np.cos(v))\n ax.plot_surface(x, y, z, rstride=1, cstride=1, color='k',\n alpha=0.05, linewidth=0)\n # wireframe\n # Get rid of the panes\n ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n\n # Get rid of the spines\n ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))\n ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))\n ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))\n # Get rid of the ticks\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_zticks([])\n\n d = num\n for i in range(2**num):\n # get x,y,z points\n element = bin(i)[2:].zfill(num)\n weight = element.count(\"1\")\n zvalue = -2 * weight / d + 1\n number_of_divisions = n_choose_k(d, weight)\n weight_order = bit_string_index(element)\n # if weight_order >= number_of_divisions / 2:\n # com_key = compliment(element)\n # weight_order_temp = bit_string_index(com_key)\n # weight_order = np.floor(\n # number_of_divisions / 2) + weight_order_temp + 1\n angle = (weight_order) * 2 * np.pi / number_of_divisions\n xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)\n yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)\n ax.plot([xvalue], [yvalue], [zvalue],\n markerfacecolor=(.5, .5, .5),\n markeredgecolor=(.5, .5, .5),\n marker='o', markersize=10, alpha=1)\n # get prob and angle - prob will be shade and angle color\n prob = np.real(np.dot(state[i], state[i].conj()))\n colorstate = phase_to_color_wheel(state[i])\n a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue],\n mutation_scale=20, alpha=prob, arrowstyle=\"-\",\n color=colorstate, lw=10)\n ax.add_artist(a)\n # add weight lines\n for weight in range(d + 1):\n theta = np.linspace(-2 * np.pi, 2 * np.pi, 100)\n z = -2 * weight / d + 1\n r = np.sqrt(1 - z**2)\n x = r * np.cos(theta)\n y = r * np.sin(theta)\n ax.plot(x, y, z, color=(.5, .5, .5))\n # add center point\n ax.plot([0], [0], [0], markerfacecolor=(.5, .5, .5),\n markeredgecolor=(.5, .5, .5), marker='o', markersize=10,\n alpha=1)\n plt.show()\n we[prob_location] = 0\n else:\n break\n\n\ndef plot_state(rho, method='city'):\n \"\"\"Plot the quantum state.\"\"\"\n num = int(np.log2(len(rho)))\n # Need updating to check its a matrix\n if method == 'city':\n plot_state_city(rho)\n elif method == \"paulivec\":\n plot_state_paulivec(rho)\n elif method == \"qsphere\":\n plot_state_qsphere(rho)\n elif method == \"bloch\":\n for i in range(num):\n bloch_state = list(map(lambda x: np.real(np.trace(\n np.dot(x.to_matrix(), rho))),\n pauli_singles(i, num)))\n plot_bloch_vector(bloch_state, \"qubit \" + str(i))\n elif method == \"wigner\":\n plot_wigner_function(rho)\n\n\n###############################################################\n# Plotting Wigner functions\n###############################################################\n\ndef plot_wigner_function(state, res=100):\n \"\"\"Plot the equal angle slice spin Wigner function of an arbitrary\n quantum state.\n\n Args:\n state (np.matrix[[complex]]):\n - Matrix of 2**n x 2**n complex numbers\n - State Vector of 2**n x 1 complex numbers\n res (int) : number of theta and phi values in meshgrid\n on sphere (creates a res x res grid of points)\n Returns:\n none: plot is shown with matplotlib on the screen\n References:\n [1] T. Tilma, M. J. Everitt, J. H. Samson, W. J. Munro,\n and K. Nemoto, Phys. Rev. Lett. 117, 180401 (2016).\n [2] R. P. Rundle, P. W. Mills, T. Tilma, J. H. Samson, and\n M. J. Everitt, Phys. Rev. A 96, 022117 (2017).\n \"\"\"\n state = np.array(state)\n if state.ndim == 1:\n state = np.outer(state,\n state) # turns state vector to a density matrix\n state = np.matrix(state)\n num = int(np.log2(len(state))) # number of qubits\n phi_vals = np.linspace(0, np.pi, num=res,\n dtype=np.complex_)\n theta_vals = np.linspace(0, 0.5*np.pi, num=res,\n dtype=np.complex_) # phi and theta values for WF\n w = np.empty([res, res])\n harr = np.sqrt(3)\n delta_su2 = np.zeros((2, 2), dtype=np.complex_)\n\n # create the spin Wigner function\n for theta in range(res):\n costheta = harr*np.cos(2*theta_vals[theta])\n sintheta = harr*np.sin(2*theta_vals[theta])\n\n for phi in range(res):\n delta_su2[0, 0] = 0.5*(1+costheta)\n delta_su2[0, 1] = -0.5*(np.exp(2j*phi_vals[phi])*sintheta)\n delta_su2[1, 0] = -0.5*(np.exp(-2j*phi_vals[phi])*sintheta)\n delta_su2[1, 1] = 0.5*(1-costheta)\n kernel = 1\n for i in range(num):\n kernel = np.kron(kernel,\n delta_su2) # creates phase point kernel\n\n w[phi, theta] = np.real(np.trace(state*kernel)) # Wigner function\n\n # Plot a sphere (x,y,z) with Wigner function facecolor data stored in Wc\n fig = plt.figure(figsize=(11, 9))\n ax = fig.gca(projection='3d')\n w_max = np.amax(w)\n # Color data for plotting\n w_c = cm.seismic_r((w+w_max)/(2*w_max)) # color data for sphere\n w_c2 = cm.seismic_r((w[0:res, int(res/2):res]+w_max)/(2*w_max)) # bottom\n w_c3 = cm.seismic_r((w[int(res/4):int(3*res/4),\n 0:res]+w_max)/(2*w_max)) # side\n w_c4 = cm.seismic_r((w[int(res/2):res, 0:res]+w_max)/(2*w_max)) # back\n\n u = np.linspace(0, 2 * np.pi, res)\n v = np.linspace(0, np.pi, res)\n x = np.outer(np.cos(u), np.sin(v))\n y = np.outer(np.sin(u), np.sin(v))\n z = np.outer(np.ones(np.size(u)), np.cos(v)) # creates a sphere mesh\n\n ax.plot_surface(x, y, z, facecolors=w_c,\n vmin=-w_max, vmax=w_max,\n rcount=res, ccount=res,\n linewidth=0, zorder=0.5,\n antialiased=False) # plots Wigner Bloch sphere\n\n ax.plot_surface(x[0:res, int(res/2):res],\n y[0:res, int(res/2):res],\n -1.5*np.ones((res, int(res/2))),\n facecolors=w_c2,\n vmin=-w_max, vmax=w_max,\n rcount=res/2, ccount=res/2,\n linewidth=0, zorder=0.5,\n antialiased=False) # plots bottom reflection\n\n ax.plot_surface(-1.5*np.ones((int(res/2), res)),\n y[int(res/4):int(3*res/4), 0:res],\n z[int(res/4):int(3*res/4), 0:res],\n facecolors=w_c3,\n vmin=-w_max, vmax=w_max,\n rcount=res/2, ccount=res/2,\n linewidth=0, zorder=0.5,\n antialiased=False) # plots side reflection\n\n ax.plot_surface(x[int(res/2):res, 0:res],\n 1.5*np.ones((int(res/2), res)),\n z[int(res/2):res, 0:res],\n facecolors=w_c4,\n vmin=-w_max, vmax=w_max,\n rcount=res/2, ccount=res/2,\n linewidth=0, zorder=0.5,\n antialiased=False) # plots back reflection\n\n ax.w_xaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))\n ax.w_yaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))\n ax.w_zaxis.set_pane_color((0.4, 0.4, 0.4, 1.0))\n ax.set_xticks([], [])\n ax.set_yticks([], [])\n ax.set_zticks([], [])\n ax.grid(False)\n ax.xaxis.pane.set_edgecolor('black')\n ax.yaxis.pane.set_edgecolor('black')\n ax.zaxis.pane.set_edgecolor('black')\n ax.set_xlim(-1.5, 1.5)\n ax.set_ylim(-1.5, 1.5)\n ax.set_zlim(-1.5, 1.5)\n m = cm.ScalarMappable(cmap=cm.seismic_r)\n m.set_array([-w_max, w_max])\n plt.colorbar(m, shrink=0.5, aspect=10)\n\n plt.show()\n\n\ndef plot_wigner_curve(wigner_data, xaxis=None):\n \"\"\"Plots a curve for points in phase space of the spin Wigner function.\n\n Args:\n wigner_data(np.array): an array of points to plot as a 2d curve\n xaxis (np.array): the range of the x axis\n\n Returns:\n none: plot is shown with matplotlib to the screen\n \"\"\"\n if not xaxis:\n xaxis = np.linspace(0, len(wigner_data)-1, num=len(wigner_data))\n\n plt.plot(xaxis, wigner_data)\n plt.show()\n\n\ndef plot_wigner_plaquette(wigner_data, max_wigner='local'):\n \"\"\"Plots plaquette of wigner function data, the plaquette will\n consist of cicles each colored to match the value of the Wigner\n function at the given point in phase space.\n\n Args:\n wigner_data (matrix): array of Wigner function data where the\n rows are plotted along the x axis and the\n columns are plotted along the y axis\n max_wigner: - 'local' puts the maximum value to maximum of the points\n - 'unit' sets maximum to 1\n - float for a custom maximum.\n\n Returns:\n none: plot is shown with matplotlib to the screen\n \"\"\"\n wigner_data = np.matrix(wigner_data)\n dim = wigner_data.shape\n\n if max_wigner == 'local':\n w_max = np.amax(wigner_data)\n elif max_wigner == 'unit':\n w_max = 1\n else:\n w_max = max_wigner # For a float input\n\n cmap = plt.cm.get_cmap('seismic_r')\n\n xax = dim[1]-0.5\n yax = dim[0]-0.5\n norm = np.amax(dim)\n\n fig = plt.figure(figsize=((xax+0.5)*6/norm, (yax+0.5)*6/norm))\n ax = fig.gca()\n\n for x in range(int(dim[1])):\n for y in range(int(dim[0])):\n circle = plt.Circle(\n (x, y), 0.49, color=cmap((wigner_data[y, x]+w_max)/(2*w_max)))\n ax.add_artist(circle)\n\n ax.set_xlim(-1, xax+0.5)\n ax.set_ylim(-1, yax+0.5)\n ax.set_xticks([], [])\n ax.set_yticks([], [])\n m = cm.ScalarMappable(cmap=cm.seismic_r)\n m.set_array([-w_max, w_max])\n plt.colorbar(m, shrink=0.5, aspect=10)\n plt.show()\n\n\ndef plot_wigner_data(wigner_data, phis=None, method=None):\n \"\"\"Plots Wigner results in appropriate format.\n\n Args:\n wigner_data: Output returned from the wigner_data function\n phis: Values of phi\n method: how the data is to be plotted,\n methods are:\n point: a single point in phase space\n curve: a two dimensional curve\n plaquette: points plotted as circles\n\n Returns:\n none: plot is shown with matplotlib to the screen\n \"\"\"\n if not method:\n wig_dim = len(np.shape(wigner_data))\n if wig_dim == 1:\n if np.shape(wigner_data) == 1:\n method = 'point'\n else:\n method = 'curve'\n elif wig_dim == 2:\n method = 'plaquette'\n\n if method == 'curve':\n plot_wigner_curve(wigner_data, xaxis=phis)\n elif method == 'plaquette':\n plot_wigner_plaquette(wigner_data)\n elif method == 'state':\n plot_wigner_function(wigner_data)\n elif method == 'point':\n plot_wigner_plaquette(wigner_data)\n print('point in phase space is '+str(wigner_data))\n else:\n print(\"No method given\")\n" ]
[ [ "numpy.matrix", "numpy.amax", "numpy.imag", "numpy.sqrt", "numpy.linspace", "numpy.kron", "matplotlib.pyplot.plot", "matplotlib.patches.FancyArrowPatch.__init__", "numpy.exp", "numpy.trace", "numpy.ones_like", "numpy.arange", "numpy.sin", "scipy.linalg.eigh", "numpy.real", "numpy.size", "matplotlib.cm.ScalarMappable", "numpy.outer", "numpy.zeros", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "matplotlib.pyplot.cm.get_cmap", "matplotlib.pyplot.annotate", "numpy.meshgrid", "numpy.array", "matplotlib.pyplot.show", "matplotlib.patches.FancyArrowPatch.draw", "numpy.absolute", "matplotlib.pyplot.subplots", "numpy.cos", "matplotlib.cm.seismic_r", "matplotlib.pyplot.colorbar", "numpy.shape", "numpy.angle", "numpy.empty" ] ]
swipswaps/OpenBBTerminal
[ "9d33f638f10fdbc77ae461b1838462571faee138" ]
[ "bots/stocks/options/oi.py" ]
[ "import logging\n\nimport pandas as pd\nimport plotly.graph_objects as go\n\nfrom bots import imps\nfrom openbb_terminal.decorators import log_start_end\nfrom openbb_terminal.stocks.options import op_helpers, yfinance_model\n\nlogger = logging.getLogger(__name__)\n\n\n@log_start_end(log=logger)\ndef oi_command(\n ticker: str = None,\n expiry: str = \"\",\n min_sp: float = None,\n max_sp: float = None,\n):\n \"\"\"Options OI\"\"\"\n\n # Debug\n if imps.DEBUG:\n logger.debug(\"opt oi %s %s %s %s\", ticker, expiry, min_sp, max_sp)\n\n # Check for argument\n if ticker is None:\n raise Exception(\"Stock ticker is required\")\n\n dates = yfinance_model.option_expirations(ticker)\n\n if not dates:\n raise Exception(\"Stock ticker is invalid\")\n\n options = yfinance_model.get_option_chain(ticker, expiry)\n calls = options.calls\n puts = options.puts\n current_price = yfinance_model.get_price(ticker)\n\n min_strike = 0.75 * current_price\n max_strike = 1.95 * current_price\n\n if len(calls) > 40:\n min_strike = 0.75 * current_price\n max_strike = 1.25 * current_price\n\n if min_sp:\n min_strike = min_sp\n if max_sp:\n max_strike = max_sp\n\n call_oi = calls.set_index(\"strike\")[\"openInterest\"] / 1000\n put_oi = puts.set_index(\"strike\")[\"openInterest\"] / 1000\n call_oi = call_oi.fillna(0.0)\n put_oi = put_oi.fillna(0.0)\n\n df_opt = pd.merge(call_oi, put_oi, left_index=True, right_index=True)\n df_opt = df_opt.rename(\n columns={\"openInterest_x\": \"OI_call\", \"openInterest_y\": \"OI_put\"}\n )\n\n max_pain = op_helpers.calculate_max_pain(df_opt)\n fig = go.Figure()\n\n dmax = df_opt[[\"OI_call\", \"OI_put\"]].values.max()\n dmin = df_opt[[\"OI_call\", \"OI_put\"]].values.min()\n fig.add_trace(\n go.Scatter(\n x=df_opt.index,\n y=df_opt[\"OI_call\"],\n name=\"Calls\",\n mode=\"lines+markers\",\n line=dict(color=\"#00ACFF\", width=3),\n )\n )\n\n fig.add_trace(\n go.Scatter(\n x=df_opt.index,\n y=df_opt[\"OI_put\"],\n name=\"Puts\",\n mode=\"lines+markers\",\n line=dict(color=\"#e4003a\", width=3),\n )\n )\n fig.add_trace(\n go.Scatter(\n x=[current_price, current_price],\n y=[dmin, dmax],\n mode=\"lines\",\n line=dict(color=\"gold\", width=2),\n name=\"Current Price\",\n )\n )\n fig.add_trace(\n go.Scatter(\n x=[max_pain, max_pain],\n y=[dmin, dmax],\n mode=\"lines\",\n line=dict(color=\"grey\", width=3, dash=\"dash\"),\n name=f\"Max Pain: {max_pain}\",\n )\n )\n if imps.PLT_WATERMARK:\n fig.add_layout_image(imps.PLT_WATERMARK)\n fig.update_xaxes(\n range=[min_strike, max_strike],\n constrain=\"domain\",\n )\n fig.update_layout(\n margin=dict(l=0, r=0, t=60, b=20),\n template=imps.PLT_SCAT_STYLE_TEMPLATE,\n title=f\"Open Interest for {ticker.upper()} expiring {expiry}\",\n title_x=0.5,\n legend_title=\"\",\n xaxis_title=\"Strike\",\n yaxis_title=\"Open Interest (1k)\",\n yaxis=dict(\n fixedrange=False,\n nticks=20,\n ),\n xaxis=dict(\n rangeslider=dict(visible=False),\n ),\n legend=dict(yanchor=\"top\", y=0.99, xanchor=\"left\", x=0.01),\n dragmode=\"pan\",\n )\n\n imagefile = \"opt_oi.png\"\n\n # Check if interactive settings are enabled\n plt_link = \"\"\n if imps.INTERACTIVE:\n plt_link = imps.inter_chart(fig, imagefile, callback=False)\n\n fig.update_layout(\n width=800,\n height=500,\n )\n\n imagefile = imps.image_border(imagefile, fig=fig)\n\n return {\n \"title\": f\"Open Interest for {ticker.upper()} expiring {expiry}\",\n \"description\": plt_link,\n \"imagefile\": imagefile,\n }\n" ]
[ [ "pandas.merge" ] ]
KWB-R/maxflow
[ "10230586838a794cfdbd639a359fc7cd40dfa96d" ]
[ "wellfield.py" ]
[ "import numpy as np\r\nimport os\r\nimport flopy\r\nimport pandas as pd\r\nimport flopy.utils.binaryfile as bf\r\nfrom create_model import *\r\nfrom analyse_model import *\r\nfrom get_layerBudget import *\r\n\r\n# 0) Creating MNW file with R (still open to be integrated!)\r\n\r\nLy = 5400.\r\nLx = 5000. \r\n\r\nupleft_coord = calc_model_wellcoordinates(Ly = Ly, \r\n Lx = Lx, \r\n csvDir = '.',\r\n csvFile = 'wells_nodes.csv',\r\n exp_dir = '.')\r\n\r\nxul = upleft_coord['xul']\r\nyul = upleft_coord['yul']\r\nproj4_str = 'ESPG:31466'\r\n\r\n###############################################################################\r\n##### Scenario 1: Combined leakage with constant kf for 9 stress periods\r\n###############################################################################\r\n\r\n\r\nprint(\"###############################################################################\")\r\nprint(\"Scenario 1: Combined leakage with constant kf for 9 stress periods\")\r\nprint(\"###############################################################################\\n\")\r\n# 1) Create model \r\nprint(\"Step 1: Create MODFLOW model\")\r\nmf = create_model(Ly = Ly, \r\n Lx = Lx,\r\n ztop = 200.,\r\n zbot_north = 0.,\r\n nlay = 3,\r\n grid_spacing = 50,\r\n delv = np.array([155, 15, 30], dtype = np.float32),\r\n botm_gradient_northSouth = 65/5400, \r\n head_north = [160, 160, 110],\r\n head_gradient_northSouth = -40/5400, \r\n hk = np.array([2e-5*3600*24, 5e-10*3600*24, 3e-5*3600*24], #horizontal conductivity\r\n dtype=np.float32),\r\n vka = np.array([2e-5*3600*24, 5e-10*3600*24, 3e-5*3600*24], #vertical conductivity\r\n dtype=np.float32),\r\n area_borehole = 0.3, ###meter^2\r\n kf_borehole = 1e-4*24*3600, #### meter / day\r\n sy = np.array([0.123, 0.023, 0.123], #specific yield\r\n dtype=np.float32),\r\n ss = np.array([1.e-4, 1.e-4, 1.e-4], #specific storage\r\n dtype=np.float32),\r\n laytyp = np.int_([1, 1, 1]), # 1 - ungespannt, 0 - gespannt):\r\n totsim = 12*365, ### Desired total simulation time\r\n nper = 12, #number of stress periods\r\n hclose = 1E-4, \r\n rclose = 5E-4, \r\n constantcv = True,\r\n each_time_step = True, ### if True (for all time steps), if False only for last time \r\n #for each stress period \r\n modelname = 'wellfield', \r\n model_ws = '.',\r\n xul = xul,\r\n yul = yul,\r\n proj4_str = proj4_str,\r\n start_datetime = '1/1/2007')\r\n \r\n \r\n# 2) Run the model\r\nprint(\"Step 2: Run MODFLOW model\")\r\nsuccess, mfoutput = mf.run_model(silent=False, pause=False)\r\nif not success:\r\n raise Exception('MODFLOW did not terminate normally.')\r\n \r\n# 3) Analyse model results (see analyse_model.py)\r\nprint(\"Step 3: Analyse MODFLOW results (see analyse_model.py)\")\r\nanalyse_model(modelname = 'wellfield', \r\n plot_layer = 2,\r\n obs_start_date = '1/01/2007')\r\n\r\n \r\n\r\n################################################################################\r\n###### Scenario 2: Combined leakage with varying kf for each of the 9 stress periods\r\n###### (dep)\r\n################################################################################ \r\n#print(\"###############################################################################\")\r\n#print(\"Scenario 2: Combined leakage with varying kf for each of the 9 stress periods\")\r\n#print(\"###############################################################################\\n\")\r\n## 0) Creating well_times.csv & well_nodes.csv for each stress period \r\n#### (based on well_times.csv & well_nodes.csv in project folder root)\r\n#\r\n#create_mnw2_csv_perPeriod(csvdir = '.', ### location of org. well_times.csv & well_nodes.csv (default: project root)\r\n# basedir = 'SP' ### base subdir for exporting both files for each stress period (default: 'SP')\r\n# )\r\n#\r\n##### Define constant model parameters:\r\n#ztop = 200.\r\n#zbot_north = 0.\r\n#nlay = 3\r\n#grid_spacing = 50\r\n#delv = np.array([160, 20, 20], dtype = np.float32)\r\n#botm_gradient_northSouth = 65/5400\r\n#hk = np.array([2e-5*3600*24, 5e-10*3600*24, 3e-5*3600*24], #horizontal conductivity\r\n# dtype=np.float32)\r\n#vka = np.array([2e-5*3600*24, 5e-10*3600*24, 3e-5*3600*24], #vertical conductivity\r\n# dtype=np.float32)\r\n#area_borehole = 0.3 ###meter^2\r\n#kf_borehole = 1e-4*24*3600 #### meter / day\r\n#sy = np.array([0.123, 0.023, 0.123], #specific yield\r\n# dtype=np.float32)\r\n#ss = np.array([1.e-4, 1.e-4, 1.e-4], #specific storage\r\n# dtype=np.float32)\r\n#laytyp = np.int_([1, 1, 1]) # 1 - ungespannt, 0 - gespannt):\r\n#totsim = 1*365 ### Desired total simulation time\r\n#nper = 1 #number of stress periods\r\n#hclose = 1E-4\r\n#rclose = 5E-4\r\n#constantcv = True\r\n#each_time_step = True ### if True (for all time steps), if False only for last time for each stress period \r\n#modelname = 'wellfield'\r\n#\r\n#\r\n#for stress_period in range(0,9):\r\n# ### Define model folder for each stress period\r\n# model_ws = 'SP' + str(stress_period)\r\n# start_datetime = '1/1/' + str(2007 + stress_period)\r\n# # 1) Create model \r\n# print(\"Step 1: Create MODFLOW model for stress period \" + str(stress_period))\r\n#\r\n# if stress_period == 0:\r\n# mf = create_model(Ly = Ly,\r\n# Lx = Lx, \r\n# ztop = ztop,\r\n# zbot_north = zbot_north,\r\n# nlay = nlay,\r\n# grid_spacing = grid_spacing,\r\n# delv = delv,\r\n# botm_gradient_northSouth = 65/5400, \r\n# head_north = [160, 160, 115], ### will be used if 'head_array' is 'None' \r\n# head_gradient_northSouth = -40/5400, \r\n# head_array = None, ### takes an array as starting hea, if 'None: head_north and/or head_gradient_northSouth will be used\r\n# hk = hk,\r\n# vka = vka,\r\n# area_borehole = area_borehole, \r\n# kf_borehole = kf_borehole, \r\n# sy = sy,\r\n# ss = ss, \r\n# laytyp = laytyp, \r\n# totsim = totsim, \r\n# nper = nper,\r\n# hclose = hclose, \r\n# rclose = rclose, \r\n# constantcv = constantcv,\r\n# each_time_step = each_time_step, \r\n# modelname = modelname, \r\n# model_ws = model_ws,\r\n# xul = xul,\r\n# yul = yul,\r\n# proj4_str = proj4_str, \r\n# start_datetime = start_datetime)\r\n# \r\n# \r\n# else:\r\n# old_model_dir = os.path.dirname(mf.dis.fn_path)\r\n# headobj = bf.HeadFile(os.path.join(old_model_dir, modelname+'.hds'))\r\n# times = headobj.get_times()\r\n# head = headobj.get_data(totim=times[len(times)-1])\r\n# mf = create_model(Ly = Ly,\r\n# Lx = Lx, \r\n# ztop = ztop,\r\n# zbot_north = zbot_north,\r\n# nlay = nlay,\r\n# grid_spacing = grid_spacing,\r\n# delv = delv,\r\n# botm_gradient_northSouth = 65/5400, \r\n# head_north = None, ### will be used if 'head_array' is 'None' \r\n# head_gradient_northSouth = -40/5400, \r\n# head_array = head, ### takes an array as starting hea, if 'None: head_north and/or head_gradient_northSouth will be used\r\n# hk = hk,\r\n# vka = vka,\r\n# area_borehole = area_borehole, \r\n# kf_borehole = kf_borehole, \r\n# sy = sy,\r\n# ss = ss, \r\n# laytyp = laytyp, \r\n# totsim = totsim, \r\n# nper = nper,\r\n# hclose = hclose, \r\n# rclose = rclose, \r\n# constantcv = constantcv,\r\n# each_time_step = each_time_step, \r\n# modelname = modelname, \r\n# model_ws = model_ws,\r\n# xul = xul,\r\n# yul = yul,\r\n# proj4_str = proj4_str, \r\n# start_datetime = start_datetime)\r\n# \r\n# # 2) Run the model\r\n# print(\"Step 2: Run MODFLOW model for stress period \" + str(stress_period))\r\n# success, mfoutput = mf.run_model(silent=False, pause=False)\r\n# if not success:\r\n# raise Exception('MODFLOW did not terminate normally.')\r\n# \r\n# # 3) Analyse model results (see analyse_model.py)\r\n# print(\"Step 3: Analyse MODFLOW results (see analyse_model.py)\")\r\n# analyse_model(modelname = modelname, \r\n# model_ws = model_ws,\r\n# plot_layer = 2,\r\n# obs_start_date = '1/01/2007')\r\n#\r\n#\r\n# \r\n\r\n\r\n" ]
[ [ "numpy.array", "numpy.int_" ] ]
duarteocarmo/CervicalCancer
[ "10b787d007ec6890c9c8c671287f9966f5146ae8" ]
[ "Characteristics/Normally_dist_fixed.py" ]
[ "from matplotlib.pyplot import (figure, hold, subplots, plot, xlabel, ylabel,\n xticks, yticks,legend, show, title, hist, savefig, close, setp, tight_layout, locator_params)\nimport numpy as np\n# requires data from exercise 4.1.1\nfrom Project_Clean_data import raw\nfrom Project_Clean_data import header\nfrom textwrap import wrap\nfrom scipy import stats\n\n# Keep main attributes and header\nimportant_attributes = [0, 1, 2, 3, 5, 8]\nmain_raw = raw[:,important_attributes]\nmain_header = header[important_attributes]\n\n# Compute values of N, M and C.\nM = len(important_attributes)\nX = main_raw\n\ngen = []\nfor col in range(M):\n un = []\n for i in range(len(X[:,0])):\n if X[i,col] not in un:\n un.append(X[i,col])\n gen.append(un)\n\nc = 0 \nsc = 6 \nf, axarr = subplots(3, 2)\nfor nx in range(3):\n for ny in range(2):\n attribute = X[:,c]\n mean_attribute = attribute.mean()\n std_attribute = attribute.std(ddof=1)\n x = np.linspace(attribute.min(), attribute.max(), 500)\n pdf = stats.norm.pdf(x, loc=mean_attribute, scale=sc)\n axarr[nx,ny].hist(attribute, bins=len(un), normed=True, color='blue')\n axarr[nx,ny].set_title(main_header[c])\n axarr[nx,ny].plot(x, pdf,'.', color='red')\n c += 1\n sc = 1 \ntight_layout()\n" ]
[ [ "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.subplots", "scipy.stats.norm.pdf" ] ]
lemmonation/fcl-nat
[ "47069ca45bdf309f96ea3c60b52aa56e3fea8471" ]
[ "tensor2tensor/data_generators/problem.py" ]
[ "# coding=utf-8\n# Copyright 2017 The Tensor2Tensor Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Base class for problem/dataset definitions.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport collections\nimport os\nimport random\n# Dependency imports\nimport six\nfrom tensor2tensor.data_generators import generator_utils\nfrom tensor2tensor.data_generators import text_encoder\nfrom tensor2tensor.utils import metrics\nfrom tensor2tensor.utils import registry\nimport tensorflow as tf\n\n\n\nclass SpaceID(object):\n \"\"\"Input and target space ids. Add more as needed.\"\"\"\n # Generic / unknown output space (default)\n GENERIC = 0\n # Image labels\n IMAGE_LABEL = 1\n # English characters\n EN_CHR = 2\n # English tokens\n EN_TOK = 3\n # English bpe tokens\n EN_BPE_TOK = 4\n # French characters\n FR_CHR = 5\n # French tokens\n FR_TOK = 6\n # German characters\n DE_CHR = 7\n # German tokens\n DE_TOK = 8\n # German bpe tokens\n DE_BPE_TOK = 9\n # Digit cipher lexicon 0\n DIGIT_0 = 10\n # Digit cipher lexicon 1\n DIGIT_1 = 11\n # Audio waveform domain\n AUDIO_WAV = 12\n # Audio spectral domain\n AUDIO_SPECTRAL = 13\n # Parse characters\n PARSE_CHR = 14\n # Parse tokens\n PARSE_TOK = 15\n # Chinese tokens\n ZH_TOK = 16\n # Icelandic characters\n ICE_CHAR = 17\n # Icelandic tokens\n ICE_TOK = 18\n # Icelandic parse tokens\n ICE_PARSE_TOK = 19\n # Macedonian tokens\n MK_TOK = 20\n # Czech tokens\n CS_TOK = 21\n # Czech characters\n CS_CHR = 22\n # Genetic bases (ACTG)\n DNA = 23\n # Real numbers\n REAL = 24\n # Images\n IMAGE = 25\n # Peptide\n PEPTIDE = 26\n # Python\n PY_TOK = 27\n # C++\n CPP_TOK = 28\n # Strokes\n STROKES = 29\n # Pickled Python\n PICKLED_PYTHON = 30\n RO_BPE_TOK = 31\n\n\ndef default_model_hparams():\n return tf.contrib.training.HParams(\n max_input_seq_length=0,\n max_target_seq_length=0,\n prepend_mode=\"none\",\n data_dir=None)\n\n\ndef preprocess_example_common(example, hparams, mode):\n \"\"\"Preprocessing steps common to all models.\"\"\"\n if hparams.max_input_seq_length > 0:\n example[\"inputs\"] = example[\"inputs\"][:hparams.max_input_seq_length]\n if hparams.max_target_seq_length > 0:\n example[\"targets\"] = example[\"targets\"][:hparams.max_target_seq_length]\n if hparams.prepend_mode != \"none\":\n if mode == tf.estimator.ModeKeys.PREDICT:\n example[\"partial_targets\"] = tf.concat([example[\"inputs\"], [0]], 0)\n else:\n example[\"targets\"] = tf.concat(\n [example[\"inputs\"], [0], example[\"targets\"]], 0)\n return example\n\n\nclass Problem(object):\n \"\"\"Problem base class. Specifies a T2T problem.\n\n Problems unify the specification of a problem for data generation, training,\n and inference.\n\n New problems are specified by the following methods:\n\n Data generation:\n * generate_data(data_dir, tmp_dir)\n - Generate training and dev datasets into data_dir.\n - Additional files, e.g. vocabulary files, should also be written to\n data_dir. Vocab files are newline-separated files with each line\n containing a token. The standard convention for the filename is to\n set it to be\n ${Problem.vocab_name}.${Problem.targeted_vocab_size}\n - Downloads and other files can be written to tmp_dir\n - If you have a training and dev generator, you can generate the\n training and dev datasets with\n generator_utils.generate_dataset_and_shuffle.\n - Use the self.training_filepaths and self.dev_filepaths functions to\n get sharded filenames. If shuffled=False, the filenames will contain\n an \"unshuffled\" suffix; you should then shuffle the data\n shard-by-shard with generator_utils.shuffle_dataset.\n - Allows to specify the number of shards, optionally (can be omitted).\n - Subclasses must override\n * dataset_filename()\n - Base filename for problem.\n - Defaults to registered name (self.name).\n\n Training:\n * hparams(defaults, model_hparams)\n - Specify the problem hyperparameters (see _default_hparams)\n - Mutate defaults as needed\n * example_reading_spec\n - Specify the names and types of the features on disk.\n - Specify tf.contrib.slim.tfexample_decoder\n * preprocess_example(example, mode)\n - Preprocess the example feature dict from feature name to Tensor or\n SparseTensor.\n - Used in training, eval, and inference (specified by mode).\n\n Eval:\n * eval_metrics\n - Specify the set of evaluation metrics for this problem.\n\n Inference:\n * feature_encoders(data_dir)\n - Return a dict of <feature name, TextEncoder> for encoding and decoding\n inference input/output.\n - Defaults to TextEncoder for inputs and targets.\n \"\"\"\n\n # ============================================================================\n # BEGIN SUBCLASS INTERFACE\n # ============================================================================\n\n def generate_data(self, data_dir, tmp_dir, task_id=-1):\n raise NotImplementedError()\n\n def hparams(self, defaults, model_hparams):\n pass\n\n def dataset_filename(self):\n return self.name\n\n def feature_encoders(self, data_dir):\n del data_dir\n return {\n \"inputs\": text_encoder.TextEncoder(),\n \"targets\": text_encoder.TextEncoder()\n }\n\n def example_reading_spec(self):\n data_fields = {\n \"inputs\": tf.VarLenFeature(tf.int64),\n \"targets\": tf.VarLenFeature(tf.int64)\n }\n data_items_to_decoders = None\n return (data_fields, data_items_to_decoders)\n\n def preprocess_example(self, example, mode, hparams):\n return preprocess_example_common(example, hparams, mode)\n\n def eval_metrics(self):\n return [\n metrics.Metrics.ACC, metrics.Metrics.ACC_TOP5,\n metrics.Metrics.ACC_PER_SEQ, metrics.Metrics.NEG_LOG_PERPLEXITY\n ]\n\n # ============================================================================\n # END SUBCLASS INTERFACE\n # ============================================================================\n\n def training_filepaths(self, data_dir, num_shards, shuffled):\n file_basename = self.dataset_filename()\n if not shuffled:\n file_basename += generator_utils.UNSHUFFLED_SUFFIX\n return generator_utils.train_data_filenames(file_basename, data_dir,\n num_shards)\n\n def dev_filepaths(self, data_dir, num_shards, shuffled):\n file_basename = self.dataset_filename()\n if not shuffled:\n file_basename += generator_utils.UNSHUFFLED_SUFFIX\n return generator_utils.dev_data_filenames(file_basename, data_dir,\n num_shards)\n\n def test_filepaths(self, data_dir, num_shards, shuffled):\n file_basename = self.dataset_filename()\n if not shuffled:\n file_basename += generator_utils.UNSHUFFLED_SUFFIX\n return generator_utils.test_data_filenames(file_basename, data_dir,\n num_shards)\n\n def filepattern(self, data_dir, mode, shard=None):\n \"\"\"Get filepattern for data files for mode.\n\n Matches mode to a suffix.\n * TRAIN: train\n * EVAL: dev\n * PREDICT: dev\n * test: test\n\n Args:\n data_dir: str, data directory.\n mode: tf.estimator.ModeKeys or \"test\".\n shard: int, if provided, will only read data from the specified shard.\n\n Returns:\n filepattern str\n \"\"\"\n path = os.path.join(data_dir, self.dataset_filename())\n shard_str = \"-%05d\" % shard if shard is not None else \"\"\n if mode == tf.estimator.ModeKeys.TRAIN:\n suffix = \"train\"\n elif mode in [tf.estimator.ModeKeys.EVAL, tf.estimator.ModeKeys.PREDICT]:\n suffix = \"dev\"\n else:\n assert mode == \"test\"\n suffix = \"test\"\n\n return \"%s-%s%s*\" % (path, suffix, shard_str)\n\n def __init__(self, was_reversed=False, was_copy=False):\n \"\"\"Create a Problem.\n\n Args:\n was_reversed: bool, whether to reverse inputs and targets.\n was_copy: bool, whether to copy inputs to targets. Can be composed with\n was_reversed so that if both are true, the targets become the inputs,\n which are then copied to targets so that the task is targets->targets.\n \"\"\"\n self._was_reversed = was_reversed\n self._was_copy = was_copy\n self._encoders = None\n self._hparams = None\n self._feature_info = None\n\n def get_feature_encoders(self, data_dir=None):\n if self._encoders is None:\n self._encoders = self.feature_encoders(data_dir)\n return self._encoders\n\n def get_hparams(self, model_hparams=None):\n \"\"\"Returns problem_hparams.\"\"\"\n if self._hparams is not None:\n return self._hparams\n\n if self._encoders is None:\n data_dir = (model_hparams and model_hparams.data_dir) or None\n self.get_feature_encoders(data_dir)\n\n hp = _default_hparams()\n ret = self.hparams(hp, model_hparams)\n if ret is not None:\n raise ValueError(\"The Problem subclass hparams function should mutate \"\n \"the defaults passed in and return None.\")\n\n hp.add_hparam(\"vocabulary\", self._encoders)\n hp.add_hparam(\"was_reversed\", self._was_reversed)\n hp.add_hparam(\"was_copy\", self._was_copy)\n\n if self._was_reversed:\n _reverse_problem_hparams(hp)\n if self._was_copy:\n _copy_problem_hparams(hp)\n\n self._hparams = hp\n return self._hparams\n\n def maybe_reverse_features(self, feature_map):\n if not self._was_reversed:\n return\n inputs, targets = feature_map[\"inputs\"], feature_map[\"targets\"]\n feature_map[\"inputs\"], feature_map[\"targets\"] = targets, inputs\n\n def maybe_copy_features(self, feature_map):\n if not self._was_copy:\n return\n feature_map[\"targets\"] = feature_map[\"inputs\"]\n\n def dataset(self,\n mode,\n data_dir=None,\n num_threads=None,\n output_buffer_size=None,\n shuffle_files=None,\n hparams=None,\n preprocess=True,\n dataset_split=None,\n shard=None):\n \"\"\"Build a Dataset for this problem.\n\n Args:\n mode: tf.estimator.ModeKeys; determines which files to read from.\n data_dir: directory that contains data files.\n num_threads: int, number of threads to use for decode and preprocess\n Dataset.map calls.\n output_buffer_size: int, how many elements to prefetch in Dataset.map\n calls.\n shuffle_files: whether to shuffle input files. Default behavior (i.e. when\n shuffle_files=None) is to shuffle if mode == TRAIN.\n hparams: tf.contrib.training.HParams; hparams to be passed to\n Problem.preprocess_example and Problem.hparams. If None, will use a\n default set that is a no-op.\n preprocess: bool, whether to map the Dataset through\n Problem.preprocess_example.\n dataset_split: tf.estimator.ModeKeys + [\"test\"], which split to read data\n from (TRAIN:\"-train\", EVAL:\"-dev\", \"test\":\"-test\"). Defaults to mode.\n shard: int, if provided, will only read data from the specified shard.\n\n Returns:\n Dataset containing dict<feature name, Tensor>.\n \"\"\"\n dataset_split = dataset_split or mode\n assert data_dir\n\n if hparams is None:\n hparams = default_model_hparams()\n\n if not hasattr(hparams, \"data_dir\"):\n hparams.add_hparam(\"data_dir\", data_dir)\n if not hparams.data_dir:\n hparams.data_dir = data_dir\n # Construct the Problem's hparams so that items within it are accessible\n _ = self.get_hparams(hparams)\n\n data_fields, data_items_to_decoders = self.example_reading_spec()\n if data_items_to_decoders is None:\n data_items_to_decoders = {\n field: tf.contrib.slim.tfexample_decoder.Tensor(field)\n for field in data_fields\n }\n\n is_training = mode == tf.estimator.ModeKeys.TRAIN\n data_filepattern = self.filepattern(data_dir, dataset_split, shard=shard)\n tf.logging.info(\"Reading data files from %s\", data_filepattern)\n data_files = tf.contrib.slim.parallel_reader.get_data_files(\n data_filepattern)\n if shuffle_files or shuffle_files is None and is_training:\n random.shuffle(data_files)\n dataset = tf.contrib.data.TFRecordDataset(data_files)\n\n def decode_record(record):\n \"\"\"Serialized Example to dict of <feature name, Tensor>.\"\"\"\n decoder = tf.contrib.slim.tfexample_decoder.TFExampleDecoder(\n data_fields, data_items_to_decoders)\n\n decode_items = list(data_items_to_decoders)\n decoded = decoder.decode(record, items=decode_items)\n return dict(zip(decode_items, decoded))\n\n def _preprocess(example):\n example = self.preprocess_example(example, mode, hparams)\n self.maybe_reverse_features(example)\n self.maybe_copy_features(example)\n return example\n\n dataset = dataset.map(decode_record, num_threads=num_threads)\n\n if preprocess:\n dataset = dataset.map(\n _preprocess,\n num_threads=num_threads,\n output_buffer_size=output_buffer_size)\n\n return dataset\n\n @property\n def has_inputs(self):\n return \"inputs\" in self.get_feature_encoders()\n\n @property\n def feature_info(self):\n \"\"\"Retrieve dict<feature name, FeatureInfo>.\n\n Must first call Problem.get_hparams or Problem.dataset to have the problem's\n internal hparams already constructed.\n\n Returns:\n dict<feature name, FeatureInfo>\n \"\"\"\n if self._feature_info is not None:\n return self._feature_info\n\n assert self._hparams is not None\n\n hp = self.get_hparams()\n input_mods = hp.input_modality\n target_mod = hp.target_modality\n vocabs = hp.vocabulary\n if self.has_inputs:\n in_id = hp.input_space_id\n out_id = hp.target_space_id\n\n features = collections.defaultdict(FeatureInfo)\n\n for name, mod_spec in six.iteritems(input_mods):\n mod, vocab_size = mod_spec\n finfo = features[name]\n finfo.modality = mod\n finfo.vocab_size = vocab_size\n\n mod, vocab_size = target_mod\n features[\"targets\"].modality = mod\n features[\"targets\"].vocab_size = vocab_size\n\n for name, encoder in six.iteritems(vocabs):\n features[name].encoder = encoder\n\n if self.has_inputs:\n features[\"inputs\"].space_id = in_id\n features[\"targets\"].space_id = out_id\n\n self._feature_info = features\n return features\n\n\nclass FeatureInfo(object):\n\n def __init__(self,\n encoder=None,\n modality=None,\n vocab_size=None,\n space_id=None):\n self.encoder = encoder\n self.modality = modality\n self.vocab_size = vocab_size\n self.space_id = space_id\n\n\ndef _copy_problem_hparams(p_hparams):\n \"\"\"Use input modality, vocab, and space id for target.\"\"\"\n p = p_hparams\n # Duplicate input modality.\n p.target_modality = p.input_modality[\"inputs\"]\n # Duplicate input vocabulary.\n p.vocabulary[\"targets\"] = p.vocabulary[\"inputs\"]\n # Duplicate input space ids.\n p.target_space_id = p.input_space_id\n # Mark that p was reversed.\n p.was_copy = True\n\n\ndef _reverse_problem_hparams(p_hparams):\n \"\"\"Swap input/output modalities, vocab, and space ids.\"\"\"\n p = p_hparams\n\n # Swap modalities.\n input_modality = p.input_modality[\"inputs\"]\n target_modality = p.target_modality\n p.input_modality[\"inputs\"] = target_modality\n p.target_modality = input_modality\n\n # Swap vocabularies.\n input_vocabulary = p.vocabulary[\"inputs\"]\n target_vocabulary = p.vocabulary[\"targets\"]\n p.vocabulary[\"inputs\"] = target_vocabulary\n p.vocabulary[\"targets\"] = input_vocabulary\n\n # Swap input/target space ids.\n input_space_id = p.input_space_id\n target_space_id = p.target_space_id\n p.input_space_id = target_space_id\n p.target_space_id = input_space_id\n\n # Mark that p was reversed.\n p.was_reversed = True\n\n\ndef _default_hparams():\n \"\"\"A set of basic model hyperparameters.\"\"\"\n return tf.contrib.training.HParams(\n # Use this parameter to get comparable perplexity numbers with different\n # tokenizations. This value should be set to the ratio of the number of\n # tokens in the test set according to the tokenization used to the number\n # of tokens in the test set in the \"official\" tokenization. For\n # example, if we are using a word-piece based model and we want to\n # compute per-word perplexity, then we set loss_multiplier to the number\n # of wordpieces per word in the test set.\n loss_multiplier=1.0,\n\n # Use this parameter to allow for larger sequences in the batch. Without\n # the use of this parameter, the size of the inner two dimensions will\n # be used to judge the sequence length.\n batch_size_multiplier=1,\n\n # To make queues of the right capacity, it's good to know the maximal\n # expected batch size, as it can vary a lot. It only affects performance\n # of input readers and memory use. The defaults should be safe and fast,\n # but decrease if your reader uses a lot of memory and increase if slow.\n max_expected_batch_size_per_shard=64,\n\n # During inference for autoregressive problems, if the batch_size is 1,\n # the inference will stop when the model predict a text_encoder.EOS_ID\n # token.\n stop_at_eos=False,\n\n # Modalities used to map from input features to a space compatible with\n # chosen model architecture. One modality spec (which is a 2-tuple,\n # (modality_full_name, vocab_size)) per feature key. modality_full_name\n # is a string type:name, e.g. class_label:class_label_2d. Leaving off\n # the name uses the default modality for that type (e.g. class_label ==\n # class_label:default).\n input_modality={},\n\n # Modality used to map from hidden representation to the target space.\n # Specified as a modality spec, a 2-tuple described above.\n target_modality=None,\n\n # Identifiers used to tell the model which input/target space will be\n # expected. For example, it can tell that we expect French as characters\n # as output, or Spanish as sound. Spaces defined as constants in SpaceID\n # class.\n input_space_id=SpaceID.GENERIC,\n target_space_id=SpaceID.GENERIC)\n\n\nclass Text2TextProblem(Problem):\n \"\"\"Base class for text-to-text problems.\"\"\"\n\n @property\n def is_character_level(self):\n \"\"\"Whether the inputs and targets are sequences of characters.\"\"\"\n raise NotImplementedError()\n\n @property\n def targeted_vocab_size(self):\n raise NotImplementedError() # Not needed if self.is_character_level.\n\n def generator(self, data_dir, tmp_dir, is_training):\n \"\"\"Generator for the training and evaluation data.\n\n Args:\n data_dir: The directory in which to assets, e.g. the vocab file.\n tmp_dir: A scratch directory (if needed).\n is_training: A boolean indicating if we should generate training data\n (True) or dev set data (False).\n\n Yields:\n dicts with keys \"inputs\" and \"targets\", with values being lists of token\n ids.\n \"\"\"\n raise NotImplementedError()\n\n @property\n def use_train_shards_for_dev(self):\n \"\"\"If true, we only generate training data and hold out shards for dev.\"\"\"\n return False\n\n @property\n def input_space_id(self):\n raise NotImplementedError()\n\n @property\n def target_space_id(self):\n raise NotImplementedError()\n\n @property\n def num_shards(self):\n raise NotImplementedError()\n\n @property\n def num_dev_shards(self):\n return 1\n\n @property\n def vocab_name(self):\n raise NotImplementedError()\n\n @property\n def vocab_file(self):\n return \"%s.%d\" % (self.vocab_name, self.targeted_vocab_size)\n\n @property\n def use_subword_tokenizer(self):\n raise NotImplementedError()\n\n @property\n def has_inputs(self):\n return True # Set to False for language models.\n\n def generate_data(self, data_dir, tmp_dir, task_id=-1):\n train_paths = self.training_filepaths(\n data_dir, self.num_shards, shuffled=False)\n dev_paths = self.dev_filepaths(\n data_dir, self.num_dev_shards, shuffled=False)\n if self.use_train_shards_for_dev:\n all_paths = train_paths + dev_paths\n generator_utils.generate_files(\n self.generator(data_dir, tmp_dir, True), all_paths)\n generator_utils.shuffle_dataset(all_paths)\n else:\n generator_utils.generate_dataset_and_shuffle(\n self.generator(data_dir, tmp_dir, True), train_paths,\n self.generator(data_dir, tmp_dir, False), dev_paths)\n\n def feature_encoders(self, data_dir):\n if self.is_character_level:\n encoder = text_encoder.ByteTextEncoder()\n elif self.use_subword_tokenizer:\n vocab_filename = os.path.join(data_dir, self.vocab_file)\n encoder = text_encoder.SubwordTextEncoder(vocab_filename)\n else:\n vocab_filename = os.path.join(data_dir, self.vocab_file)\n encoder = text_encoder.TokenTextEncoder(vocab_filename)\n if self.has_inputs:\n return {\"inputs\": encoder, \"targets\": encoder}\n return {\"targets\": encoder}\n\n def hparams(self, defaults, unused_model_hparams):\n p = defaults\n p.stop_at_eos = int(True)\n\n if self.has_inputs:\n source_vocab_size = self._encoders[\"inputs\"].vocab_size\n p.input_modality = {\n \"inputs\": (registry.Modalities.SYMBOL, source_vocab_size)\n }\n target_vocab_size = self._encoders[\"targets\"].vocab_size\n p.target_modality = (registry.Modalities.SYMBOL, target_vocab_size)\n if self.has_inputs:\n p.input_space_id = self.input_space_id\n p.target_space_id = self.target_space_id\n if self.is_character_level:\n p.loss_multiplier = 2.0\n\n def eval_metrics(self):\n return [\n metrics.Metrics.ACC, metrics.Metrics.ACC_TOP5,\n metrics.Metrics.ACC_PER_SEQ, metrics.Metrics.NEG_LOG_PERPLEXITY,\n metrics.Metrics.APPROX_BLEU, metrics.Metrics.ROUGE_2_F,\n metrics.Metrics.ROUGE_L_F\n ]\n" ]
[ [ "tensorflow.concat", "tensorflow.contrib.slim.tfexample_decoder.TFExampleDecoder", "tensorflow.contrib.data.TFRecordDataset", "tensorflow.logging.info", "tensorflow.contrib.slim.parallel_reader.get_data_files", "tensorflow.contrib.slim.tfexample_decoder.Tensor", "tensorflow.VarLenFeature", "tensorflow.contrib.training.HParams" ] ]
leonidas228/neurolib
[ "a7aa6f487db73c3b64471007ac5a965da4a65f9a" ]
[ "tests/test_evolutionUtils.py" ]
[ "import logging\nimport time\nimport sys\nimport unittest\nimport pytest\n\nimport random\nimport numpy as np\n\nfrom neurolib.utils.parameterSpace import ParameterSpace\nfrom neurolib.optimize.evolution import Evolution\n\nimport neurolib.optimize.evolution.evolutionaryUtils as eu\nimport neurolib.optimize.evolution.deapUtils as du\n\n\nclass TestEvolutinUtils(unittest.TestCase):\n \"\"\"\n Test functions in neurolib/utils/functions.py\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n pars = ParameterSpace(\n [\"mue_ext_mean\", \"mui_ext_mean\", \"b\"],\n [[0.0, 3.0], [0.0, 3.0], [0.0, 100.0]],\n )\n evolution = Evolution(\n lambda v: v,\n pars,\n weightList=[1.0],\n POP_INIT_SIZE=4,\n POP_SIZE=4,\n NGEN=2,\n filename=\"TestEvolutinUtils.hdf\",\n )\n\n cls.evolution = evolution\n\n # fake population\n pop = evolution.toolbox.population(n=100)\n fitness_length = 3\n\n for i, p in enumerate(pop):\n if random.random() < 0.1:\n fitnessesResult = [np.nan] * fitness_length\n else:\n fitnessesResult = np.random.random(fitness_length)\n p.id = i\n p.fitness.values = fitnessesResult\n p.fitness.score = np.nansum(p.fitness.wvalues) / (len(p.fitness.wvalues))\n p.gIdx = 0\n\n cls.pop = pop\n cls.evolution.pop = pop\n cls.evolution.gIdx = 1\n\n def test_getValidPopulation(self):\n self.evolution.getValidPopulation(self.pop)\n self.evolution.getInvalidPopulation(self.pop)\n\n def test_individualToDict(self):\n self.evolution.individualToDict(self.pop[0])\n\n def test_randomParametersAdaptive(self):\n du.randomParametersAdaptive(self.evolution.paramInterval)\n\n def test_mutateUntilValid(self):\n du.mutateUntilValid(\n self.pop, self.evolution.paramInterval, self.evolution.toolbox, maxTries=10\n )\n\n @pytest.mark.skipif(\n sys.platform == \"darwin\", reason=\"plotting does not work on macOS\"\n )\n def test_plots(self):\n matplotlib = pytest.importorskip(\"matplotlib\")\n eu.plotPopulation(self.evolution, plotScattermatrix=True)\n\n\nclass TestEvolutionCrossover(unittest.TestCase):\n def test_all_crossovers(self):\n def evo(traj):\n return (1,), {}\n\n pars = ParameterSpace([\"x\"], [[0.0, 4.0]])\n evolution = Evolution(\n evalFunction=evo, parameterSpace=pars, filename=\"TestEvolutionCrossover.hdf\"\n )\n evolution.runInitial()\n init_pop = evolution.pop.copy()\n\n # perform crossover methods\n ind1, ind2 = init_pop[:2]\n du.cxNormDraw_adapt(ind1, ind2, 0.4)\n du.cxUniform_adapt(ind1, ind2, 0.4)\n du.cxUniform_normDraw_adapt(ind1, ind2, 0.4)\n" ]
[ [ "numpy.nansum", "numpy.random.random" ] ]
gxz98/ARFlow
[ "a554d2367baf915e31321c124e9a41a046b8fcf6" ]
[ "trainer/kitti_trainer_ar.py" ]
[ "import time\nimport torch\nimport numpy as np\nfrom copy import deepcopy\nfrom .base_trainer import BaseTrainer\nfrom utils.flow_utils import load_flow, evaluate_flow\nfrom utils.misc_utils import AverageMeter\nfrom transforms.ar_transforms.sp_transfroms import RandomAffineFlow\nfrom transforms.ar_transforms.oc_transforms import run_slic_pt, random_crop\n\n\nclass TrainFramework(BaseTrainer):\n def __init__(self, train_loader, valid_loader, model, loss_func,\n _log, save_root, config):\n super(TrainFramework, self).__init__(\n train_loader, valid_loader, model, loss_func, _log, save_root, config)\n\n self.sp_transform = RandomAffineFlow(\n self.cfg.st_cfg, addnoise=self.cfg.st_cfg.add_noise).to(self.device)\n\n def _run_one_epoch(self):\n am_batch_time = AverageMeter()\n am_data_time = AverageMeter()\n\n key_meter_names = ['Loss', 'l_ph', 'l_sm', 'flow_mean', 'l_atst', 'l_ot']\n key_meters = AverageMeter(i=len(key_meter_names), precision=4)\n\n self.model.train()\n end = time.time()\n\n # without augmenting transformation\n if 'stage1' in self.cfg: \n if self.i_epoch == self.cfg.stage1.epoch:\n self.loss_func.cfg.update(self.cfg.stage1.loss)\n\n for i_step, data in enumerate(self.train_loader):\n if i_step > self.cfg.epoch_size:\n break\n # read data to device\n img1, img2 = data['img1'].to(self.device), data['img2'].to(self.device)\n img_pair = torch.cat([img1, img2], 1)\n\n # measure data loading time\n am_data_time.update(time.time() - end)\n\n # run 1st pass\n res_dict = self.model(img_pair, with_bk=True)\n flows_12, flows_21 = res_dict['flows_fw'], res_dict['flows_bw']\n flows = [torch.cat([flo12, flo21], 1) for flo12, flo21 in\n zip(flows_12, flows_21)]\n loss, l_ph, l_sm, flow_mean = self.loss_func(flows, img_pair)\n\n flow_ori = res_dict['flows_fw'][0].detach()\n\n if self.cfg.run_atst:\n img1, img2 = data['img1_ph'].to(self.device), data['img2_ph'].to(\n self.device)\n\n # construct augment sample by spatial transformation\n noc_ori = self.loss_func.pyramid_occu_mask1[0] # non-occluded region\n s = {'imgs': [img1, img2], 'flows_f': [flow_ori], 'masks_f': [noc_ori]}\n st_res = self.sp_transform(deepcopy(s)) if self.cfg.run_st else deepcopy(s) # transformed image,flow,mask\n flow_t, noc_t = st_res['flows_f'][0], st_res['masks_f'][0]\n\n # run 2nd pass\n img_pair = torch.cat(st_res['imgs'], 1)\n flow_t_pred = self.model(img_pair, with_bk=False)['flows_fw'][0]\n\n if not self.cfg.mask_st:\n noc_t = torch.ones_like(noc_t)\n l_atst = ((flow_t_pred - flow_t).abs() + self.cfg.ar_eps) ** self.cfg.ar_q\n l_atst = (l_atst * noc_t).mean() / (noc_t.mean() + 1e-7)\n\n loss += self.cfg.w_ar * l_atst\n else:\n l_atst = torch.zeros_like(loss)\n\n if self.cfg.run_ot:\n img1, img2 = data['img1_ph'].to(self.device), data['img2_ph'].to(\n self.device)\n # run 3rd pass\n img_pair = torch.cat([img1, img2], 1)\n\n # random crop images\n img_pair, flow_t, occ_t = random_crop(img_pair, flow_ori, 1 - noc_ori,\n self.cfg.ot_size)\n\n # slic 200, random select 8~16\n if self.cfg.ot_slic:\n img2 = img_pair[:, 3:]\n seg_mask = run_slic_pt(img2, n_seg=200,\n compact=self.cfg.ot_compact, rd_select=[8, 16],\n fast=self.cfg.ot_fast).type_as(img2) # Nx1xHxW\n noise = torch.rand(img2.size()).type_as(img2)\n img2 = img2 * (1 - seg_mask) + noise * seg_mask\n img_pair[:, 3:] = img2\n\n flow_t_pred = self.model(img_pair, with_bk=False)['flows_fw'][0]\n noc_t = 1 - occ_t\n l_ot = ((flow_t_pred - flow_t).abs() + self.cfg.ar_eps) ** self.cfg.ar_q\n l_ot = (l_ot * noc_t).mean() / (noc_t.mean() + 1e-7)\n\n loss += self.cfg.w_ar * l_ot\n else:\n l_ot = torch.zeros_like(loss)\n\n # update meters\n key_meters.update(\n [loss.item(), l_ph.item(), l_sm.item(), flow_mean.item(),\n l_atst.item(), l_ot.item()],\n img_pair.size(0))\n\n # compute gradient and do optimization step\n self.optimizer.zero_grad()\n # loss.backward()\n\n scaled_loss = 1024. * loss\n scaled_loss.backward()\n\n for param in [p for p in self.model.parameters() if p.requires_grad]:\n param.grad.data.mul_(1. / 1024)\n\n self.optimizer.step()\n\n # measure elapsed time\n am_batch_time.update(time.time() - end)\n end = time.time()\n\n if self.i_iter % self.cfg.record_freq == 0:\n for v, name in zip(key_meters.val, key_meter_names):\n self.summary_writer.add_scalar('Train_' + name, v, self.i_iter)\n\n if self.i_iter % self.cfg.print_freq == 0:\n istr = '{}:{:04d}/{:04d}'.format(\n self.i_epoch, i_step, self.cfg.epoch_size) + \\\n ' Time {} Data {}'.format(am_batch_time, am_data_time) + \\\n ' Info {}'.format(key_meters)\n self._log.info(istr)\n\n self.i_iter += 1\n self.i_epoch += 1\n\n @torch.no_grad()\n def _validate_with_gt(self):\n batch_time = AverageMeter()\n\n if type(self.valid_loader) is not list:\n self.valid_loader = [self.valid_loader]\n\n # only use the first GPU to run validation, multiple GPUs might raise error.\n # https://github.com/Eromera/erfnet_pytorch/issues/2#issuecomment-486142360\n self.model = self.model.module\n self.model.eval()\n\n end = time.time()\n\n all_error_names = []\n all_error_avgs = []\n\n n_step = 0\n for i_set, loader in enumerate(self.valid_loader):\n error_names = ['EPE', 'E_noc', 'E_occ', 'F1_all']\n error_meters = AverageMeter(i=len(error_names))\n for i_step, data in enumerate(loader):\n img1, img2 = data['img1'], data['img2']\n img_pair = torch.cat([img1, img2], 1).to(self.device)\n\n res = list(map(load_flow, data['flow_occ']))\n gt_flows, occ_masks = [r[0] for r in res], [r[1] for r in res]\n res = list(map(load_flow, data['flow_noc']))\n _, noc_masks = [r[0] for r in res], [r[1] for r in res]\n\n gt_flows = [np.concatenate([flow, occ_mask, noc_mask], axis=2) for\n flow, occ_mask, noc_mask in\n zip(gt_flows, occ_masks, noc_masks)]\n\n # compute output\n flows = self.model(img_pair)['flows_fw']\n pred_flows = flows[0].detach().cpu().numpy().transpose([0, 2, 3, 1])\n\n es = evaluate_flow(gt_flows, pred_flows)\n error_meters.update([l.item() for l in es], img_pair.size(0))\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i_step % self.cfg.print_freq == 0 or i_step == len(loader) - 1:\n self._log.info('Test: {0}[{1}/{2}]\\t Time {3}\\t '.format(\n i_set, i_step, self.cfg.valid_size, batch_time) + ' '.join(\n map('{:.2f}'.format, error_meters.avg)))\n\n if i_step > self.cfg.valid_size:\n break\n n_step += len(loader)\n\n # write error to tf board.\n for value, name in zip(error_meters.avg, error_names):\n self.summary_writer.add_scalar(\n 'Valid_{}_{}'.format(name, i_set), value, self.i_epoch)\n\n all_error_avgs.extend(error_meters.avg)\n all_error_names.extend(['{}_{}'.format(name, i_set) for name in error_names])\n\n self.model = torch.nn.DataParallel(self.model, device_ids=self.device_ids)\n # In order to reduce the space occupied during debugging,\n # only the model with more than cfg.save_iter iterations will be saved.\n if self.i_iter > self.cfg.save_iter:\n self.save_model(all_error_avgs[0], name='KITTI_Flow')\n\n return all_error_avgs, all_error_names\n" ]
[ [ "torch.cat", "torch.zeros_like", "numpy.concatenate", "torch.no_grad", "torch.nn.DataParallel", "torch.ones_like" ] ]
Tarang74/manim
[ "df34d6fc0470916cfba63534b023addb69cdec9a" ]
[ "from_3b1b/old/hilbert/section2.py" ]
[ "from manimlib.imports import *\nimport displayer as disp\nfrom hilbert.curves import \\\n TransformOverIncreasingOrders, FlowSnake, HilbertCurve, \\\n SnakeCurve, PeanoCurve\nfrom hilbert.section1 import get_mathy_and_bubble\nfrom scipy.spatial.distance import cdist\n\n\ndef get_time_line():\n length = 2.6 * FRAME_WIDTH\n year_range = 400\n time_line = NumberLine(numerical_radius=year_range / 2,\n unit_length_to_spatial_width=length / year_range,\n tick_frequency=10,\n leftmost_tick=1720,\n number_at_center=1870,\n numbers_with_elongated_ticks=list(\n range(1700, 2100, 100)))\n time_line.sort_points(lambda p: p[0])\n time_line.set_color_by_gradient(PeanoCurve.CONFIG[\"start_color\"],\n PeanoCurve.CONFIG[\"end_color\"])\n time_line.add_numbers(2020, *list(range(1800, 2050, 50)))\n return time_line\n\n\nclass SectionTwo(Scene):\n def construct(self):\n self.add(TextMobject(\"Section 2: Filling space\"))\n self.wait()\n\n\nclass HilbertCurveIsPerfect(Scene):\n def construct(self):\n curve = HilbertCurve(order=6)\n curve.set_color(WHITE)\n colored_curve = curve.copy()\n colored_curve.thin_out(3)\n lion = ImageMobject(\"lion\", invert=False)\n lion.replace(curve, stretch=True)\n sparce_lion = lion.copy()\n sparce_lion.thin_out(100)\n distance_matrix = cdist(colored_curve.points, sparce_lion.points)\n closest_point_indices = np.apply_along_axis(np.argmin, 1,\n distance_matrix)\n colored_curve.rgbas = sparce_lion.rgbas[closest_point_indices]\n line = Line(5 * LEFT, 5 * RIGHT)\n Mobject.align_data(line, colored_curve)\n line.rgbas = colored_curve.rgbas\n\n self.add(lion)\n self.play(ShowCreation(curve, run_time=3))\n self.play(FadeOut(lion), Transform(curve, colored_curve), run_time=3)\n self.wait()\n self.play(Transform(curve, line, run_time=5))\n self.wait()\n\n\nclass AskMathematicianFriend(Scene):\n def construct(self):\n mathy, bubble = get_mathy_and_bubble()\n bubble.sort_points(lambda p: np.dot(p, UP + RIGHT))\n\n self.add(mathy)\n self.wait()\n self.play(\n ApplyMethod(mathy.blink,\n rate_func=squish_rate_func(there_and_back)))\n self.wait()\n self.play(ShowCreation(bubble))\n self.wait()\n self.play(ApplyMethod(mathy.shift, 3 * (DOWN + LEFT)),\n ApplyPointwiseFunction(lambda p: 15 * p / get_norm(p),\n bubble),\n run_time=3)\n\n\nclass TimeLineAboutSpaceFilling(Scene):\n def construct(self):\n curve = PeanoCurve(order=5)\n curve.stretch_to_fit_width(FRAME_WIDTH)\n curve.stretch_to_fit_height(FRAME_HEIGHT)\n curve_start = curve.copy()\n curve_start.apply_over_attr_arrays(lambda arr: arr[:200])\n time_line = get_time_line()\n time_line.shift(-time_line.number_to_point(2000))\n\n self.add(time_line)\n self.play(\n ApplyMethod(time_line.shift,\n -time_line.number_to_point(1900),\n run_time=3))\n brace = Brace(\n Mobject(\n Point(time_line.number_to_point(1865)),\n Point(time_line.number_to_point(1888)),\n ), UP)\n words = TextMobject(\"\"\"\n Cantor drives himself (and the \\\\\\\\\n mathematical community at large) \\\\\\\\\n crazy with research on infinity.\n \"\"\")\n words.next_to(brace, UP)\n self.play(GrowFromCenter(brace), ShimmerIn(words))\n self.wait()\n self.play(Transform(time_line, curve_start), FadeOut(brace),\n FadeOut(words))\n self.play(ShowCreation(curve, run_time=5, rate_func=linear))\n self.wait()\n\n\nclass NotPixelatedSpace(Scene):\n def construct(self):\n grid = Grid(64, 64)\n space_region = Region()\n space_mobject = MobjectFromRegion(space_region, DARK_GREY)\n curve = PeanoCurve(order=5).replace(space_mobject)\n line = Line(5 * LEFT, 5 * RIGHT)\n line.set_color_by_gradient(curve.start_color, curve.end_color)\n for mob in grid, space_mobject:\n mob.sort_points(get_norm)\n infinitely = TextMobject(\"Infinitely\")\n detailed = TextMobject(\"detailed\")\n extending = TextMobject(\"extending\")\n detailed.next_to(infinitely, RIGHT)\n extending.next_to(infinitely, RIGHT)\n Mobject(extending, infinitely, detailed).center()\n arrows = Mobject(*[\n Arrow(2 * p, 4 * p)\n for theta in np.arange(np.pi / 6, 2 * np.pi, np.pi / 3)\n for p in [rotate_vector(RIGHT, theta)]\n ])\n\n self.add(grid)\n self.wait()\n self.play(Transform(grid, space_mobject, run_time=5))\n self.remove(grid)\n self.set_color_region(space_region, DARK_GREY)\n self.wait()\n self.add(infinitely, detailed)\n self.wait()\n self.play(DelayByOrder(Transform(detailed, extending)))\n self.play(ShowCreation(arrows))\n self.wait()\n self.clear()\n self.set_color_region(space_region, DARK_GREY)\n self.play(ShowCreation(line))\n self.play(Transform(line, curve, run_time=5))\n\n\nclass HistoryOfDiscover(Scene):\n def construct(self):\n time_line = get_time_line()\n time_line.shift(-time_line.number_to_point(1900))\n hilbert_curve = HilbertCurve(order=3)\n peano_curve = PeanoCurve(order=2)\n for curve in hilbert_curve, peano_curve:\n curve.scale(0.5)\n hilbert_curve.to_corner(DOWN + RIGHT)\n peano_curve.to_corner(UP + LEFT)\n squares = Mobject(*[\n Square(side_length=3, color=WHITE).replace(curve)\n for curve in (hilbert_curve, peano_curve)\n ])\n\n self.add(time_line)\n self.wait()\n for year, curve, vect, text in [\n (1890, peano_curve, UP, \"Peano Curve\"),\n (1891, hilbert_curve, DOWN, \"Hilbert Curve\"),\n ]:\n point = time_line.number_to_point(year)\n point[1] = 0.2\n arrow = Arrow(point + 2 * vect, point, buff=0.1)\n arrow.set_color_by_gradient(curve.start_color, curve.end_color)\n year_mob = TexMobject(str(year))\n year_mob.next_to(arrow, vect)\n words = TextMobject(text)\n words.next_to(year_mob, vect)\n\n self.play(ShowCreation(arrow), ShimmerIn(year_mob),\n ShimmerIn(words))\n self.play(ShowCreation(curve))\n self.wait()\n self.play(ShowCreation(squares))\n self.wait()\n self.play(\n ApplyMethod(Mobject(*self.mobjects).shift, 20 * (DOWN + RIGHT)))\n\n\nclass DefinitionOfCurve(Scene):\n def construct(self):\n start_words = TextMobject([\n \"``\",\n \"Space Filling\",\n \"Curve ''\",\n ]).to_edge(TOP, buff=0.25)\n quote, space_filling, curve_quote = start_words.copy().split()\n curve_quote.shift(\n space_filling.get_left()-\\\n curve_quote.get_left()\n )\n space_filling = Point(space_filling.get_center())\n end_words = Mobject(\n *[quote, space_filling, curve_quote]).center().to_edge(TOP,\n buff=0.25)\n space_filling_fractal = TextMobject(\"\"\"\n ``Space Filling Fractal''\n \"\"\").to_edge(UP)\n curve = HilbertCurve(order=2).shift(DOWN)\n fine_curve = HilbertCurve(order=8)\n fine_curve.replace(curve)\n dots = Mobject(*[\n Dot(curve.points[n * curve.get_num_points() / 15], color=YELLOW_C)\n for n in range(1, 15) if n not in [4, 11]\n ])\n\n start_words.shift(2 * (UP + LEFT))\n self.play(ApplyMethod(start_words.shift, 2 * (DOWN + RIGHT)))\n self.wait()\n self.play(Transform(start_words, end_words))\n self.wait()\n self.play(ShowCreation(curve))\n self.wait()\n self.play(ShowCreation(\n dots,\n run_time=3,\n ))\n self.wait()\n self.clear()\n self.play(ShowCreation(fine_curve, run_time=5))\n self.wait()\n self.play(ShimmerIn(space_filling_fractal))\n self.wait()\n\n\nclass PseudoHilbertCurvesDontFillSpace(Scene):\n def construct(self):\n curve = HilbertCurve(order=1)\n grid = Grid(2, 2, stroke_width=1)\n self.add(grid, curve)\n for order in range(2, 6):\n self.wait()\n new_grid = Grid(2**order, 2**order, stroke_width=1)\n self.play(ShowCreation(new_grid), Animation(curve))\n self.remove(grid)\n grid = new_grid\n self.play(Transform(curve, HilbertCurve(order=order)))\n\n square = Square(side_length=6, color=WHITE)\n square.corner = Mobject1D()\n square.corner.add_line(3 * DOWN, ORIGIN)\n square.corner.add_line(ORIGIN, 3 * RIGHT)\n square.digest_mobject_attrs()\n square.scale(2**(-5))\n square.corner.set_color(\n Color(rgb=curve.rgbas[curve.get_num_points() / 3]))\n square.shift(\n grid.get_corner(UP+LEFT)-\\\n square.get_corner(UP+LEFT)\n )\n self.wait()\n self.play(FadeOut(grid), FadeOut(curve), FadeIn(square))\n self.play(ApplyMethod(square.replace, grid))\n self.wait()\n\n\nclass HilbertCurveIsLimit(Scene):\n def construct(self):\n mathy, bubble = get_mathy_and_bubble()\n bubble.write(\"A Hilbert curve is the \\\\\\\\ limit of all these \\\\dots\")\n\n self.add(mathy, bubble)\n self.play(ShimmerIn(bubble.content))\n self.wait()\n\n\nclass DefiningCurves(Scene):\n def construct(self):\n words = TextMobject([\n \"One does not simply define the limit \\\\\\\\ \\\n of a sequence of\", \"curves\", \"\\\\dots\"\n ])\n top_words = TextMobject([\"curves\", \"are functions\"]).to_edge(UP)\n curves1 = words.split()[1]\n curves2 = top_words.split()[0]\n words.ingest_submobjects()\n number = TexMobject(\"0.27\")\n pair = TexMobject(\"(0.53, 0.02)\")\n pair.next_to(number, buff=2)\n arrow = Arrow(number, pair)\n Mobject(number, arrow, pair).center().shift(UP)\n number_line = UnitInterval()\n number_line.stretch_to_fit_width(5)\n number_line.to_edge(LEFT).shift(DOWN)\n grid = Grid(4, 4).scale(0.4)\n grid.next_to(number_line, buff=2)\n low_arrow = Arrow(number_line, grid)\n\n self.play(ShimmerIn(words))\n self.wait()\n self.play(FadeOut(words), ApplyMethod(curves1.replace, curves2),\n ShimmerIn(top_words.split()[1]))\n self.wait()\n self.play(FadeIn(number))\n self.play(ShowCreation(arrow))\n self.play(FadeIn(pair))\n self.wait()\n self.play(ShowCreation(number_line))\n self.play(ShowCreation(low_arrow))\n self.play(ShowCreation(grid))\n self.wait()\n\n\nclass PseudoHilbertCurveAsFunctionExample(Scene):\n args_list = [(2, ), (3, )]\n\n # For subclasses to turn args in the above\n # list into stings which can be appended to the name\n @staticmethod\n def args_to_string(order):\n return \"Order%d\" % order\n\n @staticmethod\n def string_to_args(order_str):\n return int(order_str)\n\n def construct(self, order):\n if order == 2:\n result_tex = \"(0.125, 0.75)\"\n elif order == 3:\n result_tex = \"(0.0758, 0.6875)\"\n\n phc, arg, result = TexMobject(\n [\"\\\\text{PHC}_%d\" % order, \"(0.3)\",\n \"= %s\" % result_tex]).to_edge(UP).split()\n function = TextMobject(\"Function\", size=\"\\\\normal\")\n function.shift(phc.get_center() + DOWN + 2 * LEFT)\n function_arrow = Arrow(function, phc)\n\n line = Line(5 * LEFT, 5 * RIGHT)\n curve = HilbertCurve(order=order)\n line.match_colors(curve)\n grid = Grid(2**order, 2**order)\n grid.fade()\n for mob in curve, grid:\n mob.scale(0.7)\n index = int(0.3 * line.get_num_points())\n dot1 = Dot(line.points[index])\n arrow1 = Arrow(arg, dot1, buff=0.1)\n dot2 = Dot(curve.points[index])\n arrow2 = Arrow(result.get_bottom(), dot2, buff=0.1)\n\n self.add(phc)\n self.play(ShimmerIn(function), ShowCreation(function_arrow))\n self.wait()\n self.remove(function_arrow, function)\n self.play(ShowCreation(line))\n self.wait()\n self.play(ShimmerIn(arg), ShowCreation(arrow1), ShowCreation(dot1))\n self.wait()\n self.remove(arrow1)\n self.play(FadeIn(grid),\n Transform(line, curve),\n Transform(dot1, dot2),\n run_time=2)\n self.wait()\n self.play(ShimmerIn(result), ShowCreation(arrow2))\n self.wait()\n\n\nclass ContinuityRequired(Scene):\n def construct(self):\n words = TextMobject([\n \"A function must be\", \"\\\\emph{continuous}\",\n \"if it is to represent a curve.\"\n ])\n words.split()[1].set_color(YELLOW_C)\n self.add(words)\n self.wait()\n\n\nclass FormalDefinitionOfContinuity(Scene):\n def construct(self):\n self.setup()\n self.label_spaces()\n self.move_dot()\n self.label_jump()\n self.draw_circles()\n self.vary_circle_sizes()\n self.discontinuous_point()\n\n def setup(self):\n self.input_color = YELLOW_C\n self.output_color = RED\n\n def spiril(t):\n theta = 2 * np.pi * t\n return t * np.cos(theta) * RIGHT + t * np.sin(theta) * UP\n\n self.spiril1 = ParametricFunction(\n lambda t: 1.5 * RIGHT + DOWN + 2 * spiril(t),\n density=5 * DEFAULT_POINT_DENSITY_1D,\n )\n self.spiril2 = ParametricFunction(\n lambda t: 5.5 * RIGHT + UP - 2 * spiril(1 - t),\n density=5 * DEFAULT_POINT_DENSITY_1D,\n )\n Mobject.align_data(self.spiril1, self.spiril2)\n self.output = Mobject(self.spiril1, self.spiril2)\n self.output.ingest_submobjects()\n self.output.set_color(GREEN_A)\n\n self.interval = UnitInterval()\n self.interval.set_width(FRAME_X_RADIUS - 1)\n self.interval.to_edge(LEFT)\n\n self.input_dot = Dot(color=self.input_color)\n self.output_dot = self.input_dot.copy().set_color(self.output_color)\n left, right = self.interval.get_left(), self.interval.get_right()\n self.input_homotopy = lambda x_y_z_t: (x_y_z_t[0], x_y_z_t[1], x_y_z_t[\n 3]) + interpolate(left, right, x_y_z_t[3])\n output_size = self.output.get_num_points() - 1\n output_points = self.output.points\n self.output_homotopy = lambda x_y_z_t1: (x_y_z_t1[0], x_y_z_t1[\n 1], x_y_z_t1[2]) + output_points[int(x_y_z_t1[3] * output_size)]\n\n def get_circles_and_points(self, min_input, max_input):\n input_left, input_right = [\n self.interval.number_to_point(num)\n for num in (min_input, max_input)\n ]\n input_circle = Circle(radius=get_norm(input_left - input_right) / 2,\n color=WHITE)\n input_circle.shift((input_left + input_right) / 2)\n\n input_points = Line(input_left, input_right, color=self.input_color)\n output_points = Mobject(color=self.output_color)\n n = self.output.get_num_points()\n output_points.add_points(self.output.points[int(min_input *\n n):int(max_input * n)])\n output_center = output_points.points[int(\n 0.5 * output_points.get_num_points())]\n max_distance = get_norm(output_center - output_points.points[-1])\n output_circle = Circle(radius=max_distance, color=WHITE)\n output_circle.shift(output_center)\n return (input_circle, input_points, output_circle, output_points)\n\n def label_spaces(self):\n input_space = TextMobject(\"Input Space\")\n input_space.to_edge(UP)\n input_space.shift(LEFT * FRAME_X_RADIUS / 2)\n output_space = TextMobject(\"Output Space\")\n output_space.to_edge(UP)\n output_space.shift(RIGHT * FRAME_X_RADIUS / 2)\n line = Line(UP * FRAME_Y_RADIUS, DOWN * FRAME_Y_RADIUS, color=WHITE)\n self.play(\n ShimmerIn(input_space),\n ShimmerIn(output_space),\n ShowCreation(line),\n ShowCreation(self.interval),\n )\n self.wait()\n\n def move_dot(self):\n kwargs = {\"rate_func\": None, \"run_time\": 3}\n self.play(Homotopy(self.input_homotopy, self.input_dot, **kwargs),\n Homotopy(self.output_homotopy, self.output_dot, **kwargs),\n ShowCreation(self.output, **kwargs))\n self.wait()\n\n def label_jump(self):\n jump_points = Mobject(Point(self.spiril1.points[-1]),\n Point(self.spiril2.points[0]))\n self.brace = Brace(jump_points, RIGHT)\n self.jump = TextMobject(\"Jump\")\n self.jump.next_to(self.brace, RIGHT)\n self.play(GrowFromCenter(self.brace), ShimmerIn(self.jump))\n self.wait()\n self.remove(self.brace, self.jump)\n\n def draw_circles(self):\n input_value = 0.45\n input_radius = 0.04\n for dot in self.input_dot, self.output_dot:\n dot.center()\n kwargs = {\n \"rate_func\": lambda t: interpolate(1, input_value, smooth(t))\n }\n self.play(Homotopy(self.input_homotopy, self.input_dot, **kwargs),\n Homotopy(self.output_homotopy, self.output_dot, **kwargs))\n\n A, B = list(map(Mobject.get_center, [self.input_dot, self.output_dot]))\n A_text = TextMobject(\"A\")\n A_text.shift(A + 2 * (LEFT + UP))\n A_arrow = Arrow(A_text, self.input_dot, color=self.input_color)\n B_text = TextMobject(\"B\")\n B_text.shift(B + 2 * RIGHT + DOWN)\n B_arrow = Arrow(B_text, self.output_dot, color=self.output_color)\n tup = self.get_circles_and_points(input_value - input_radius,\n input_value + input_radius)\n input_circle, input_points, output_circle, output_points = tup\n\n for text, arrow in [(A_text, A_arrow), (B_text, B_arrow)]:\n self.play(ShimmerIn(text), ShowCreation(arrow))\n self.wait()\n self.remove(A_text, A_arrow, B_text, B_arrow)\n self.play(ShowCreation(input_circle))\n self.wait()\n self.play(ShowCreation(input_points))\n self.wait()\n input_points_copy = input_points.copy()\n self.play(Transform(input_points_copy, output_points), run_time=2)\n self.wait()\n self.play(ShowCreation(output_circle))\n self.wait()\n self.wait()\n self.remove(\n *[input_circle, input_points, output_circle, input_points_copy])\n\n def vary_circle_sizes(self):\n input_value = 0.45\n radius = 0.04\n vary_circles = VaryCircles(\n self,\n input_value,\n radius,\n run_time=5,\n )\n self.play(vary_circles)\n self.wait()\n text = TextMobject(\"Function is ``Continuous at A''\")\n text.shift(2 * UP).to_edge(LEFT)\n arrow = Arrow(text, self.input_dot)\n self.play(ShimmerIn(text), ShowCreation(arrow))\n self.wait()\n self.remove(vary_circles.mobject, text, arrow)\n\n def discontinuous_point(self):\n point_description = TextMobject(\"Point where the function jumps\")\n point_description.shift(3 * RIGHT)\n discontinuous_at_A = TextMobject(\"``Discontinuous at A''\",\n size=\"\\\\Large\")\n discontinuous_at_A.shift(2 * UP).to_edge(LEFT)\n text = TextMobject(\"\"\"\n Circle around ouput \\\\\\\\ \n points can never \\\\\\\\\n be smaller than \\\\\\\\\n the jump\n \"\"\")\n text.scale(0.75)\n text.shift(3.5 * RIGHT)\n\n input_value = 0.5\n input_radius = 0.04\n vary_circles = VaryCircles(\n self,\n input_value,\n input_radius,\n run_time=5,\n )\n for dot in self.input_dot, self.output_dot:\n dot.center()\n kwargs = {\n \"rate_func\": lambda t: interpolate(0.45, input_value, smooth(t))\n }\n self.play(Homotopy(self.input_homotopy, self.input_dot, **kwargs),\n Homotopy(self.output_homotopy, self.output_dot, **kwargs))\n discontinuous_arrow = Arrow(discontinuous_at_A, self.input_dot)\n arrow = Arrow(point_description,\n self.output_dot,\n buff=0.05,\n color=self.output_color)\n self.play(ShimmerIn(point_description), ShowCreation(arrow))\n self.wait()\n self.remove(point_description, arrow)\n\n tup = self.get_circles_and_points(input_value - input_radius,\n input_value + input_radius)\n input_circle, input_points, output_circle, output_points = tup\n input_points_copy = input_points.copy()\n self.play(ShowCreation(input_circle))\n self.play(ShowCreation(input_points))\n self.play(Transform(input_points_copy, output_points), run_time=2)\n self.play(ShowCreation(output_circle))\n self.wait()\n self.play(ShimmerIn(text))\n self.remove(input_circle, input_points, output_circle,\n input_points_copy)\n self.play(vary_circles)\n self.wait()\n self.play(ShimmerIn(discontinuous_at_A),\n ShowCreation(discontinuous_arrow))\n self.wait(3)\n self.remove(vary_circles.mobject, discontinuous_at_A,\n discontinuous_arrow)\n\n def continuous_point(self):\n pass\n\n\nclass VaryCircles(Animation):\n def __init__(self, scene, input_value, radius, **kwargs):\n digest_locals(self)\n Animation.__init__(self, Mobject(), **kwargs)\n\n def interpolate_mobject(self, alpha):\n radius = self.radius + 0.9 * self.radius * np.sin(1.5 * np.pi * alpha)\n self.mobject = Mobject(\n *self.scene.get_circles_and_points(self.input_value -\n radius, self.input_value +\n radius)).ingest_submobjects()\n\n\nclass FunctionIsContinuousText(Scene):\n def construct(self):\n all_points = TextMobject(\"$f$ is continuous at every input point\")\n continuous = TextMobject(\"$f$ is continuous\")\n all_points.shift(UP)\n continuous.shift(DOWN)\n arrow = Arrow(all_points, continuous)\n\n self.play(ShimmerIn(all_points))\n self.play(ShowCreation(arrow))\n self.play(ShimmerIn(continuous))\n self.wait()\n\n\nclass DefineActualHilbertCurveText(Scene):\n def construct(self):\n self.add(\n TextMobject(\"\"\"\n Finally define a Hilbert Curve\\\\dots\n \"\"\"))\n self.wait()\n\n\nclass ReliesOnWonderfulProperty(Scene):\n def construct(self):\n self.add(\n TextMobject(\"\"\"\n \\\\dots which relies on a certain property\n of Pseudo-Hilbert-curves.\n \"\"\"))\n self.wait()\n\n\nclass WonderfulPropertyOfPseudoHilbertCurves(Scene):\n def construct(self):\n val = 0.3\n text = TextMobject([\n \"PHC\", \"$_n\", \"(\",\n \"%3.1f\" % val, \")$\", \" has a \", \"limit point \",\n \"as $n \\\\to \\\\infty$\"\n ])\n func_parts = text.copy().split()[:5]\n Mobject(*func_parts).center().to_edge(UP)\n num_str, val_str = func_parts[1], func_parts[3]\n curve = UnitInterval()\n curve.sort_points(lambda p: p[0])\n dot = Dot().shift(curve.number_to_point(val))\n arrow = Arrow(val_str, dot, buff=0.1)\n curve.add_numbers(0, 1)\n\n self.play(ShowCreation(curve))\n self.play(ShimmerIn(val_str), ShowCreation(arrow), ShowCreation(dot))\n self.wait()\n self.play(FadeOut(arrow),\n *[FadeIn(func_parts[i]) for i in (0, 1, 2, 4)])\n for num in range(2, 9):\n new_curve = HilbertCurve(order=num)\n new_curve.scale(0.8)\n new_dot = Dot(new_curve.points[int(val *\n new_curve.get_num_points())])\n new_num_str = TexMobject(str(num)).replace(num_str)\n self.play(Transform(curve, new_curve), Transform(dot, new_dot),\n Transform(num_str, new_num_str))\n self.wait()\n\n text.to_edge(UP)\n text_parts = text.split()\n for index in 1, -1:\n text_parts[index].set_color()\n starters = Mobject(*func_parts + [\n Point(mob.get_center(), stroke_width=1) for mob in text_parts[5:]\n ])\n self.play(Transform(starters, text))\n arrow = Arrow(text_parts[-2].get_bottom(), dot, buff=0.1)\n self.play(ShowCreation(arrow))\n self.wait()\n\n\nclass FollowManyPoints(Scene):\n def construct(self):\n text = TextMobject([\n \"PHC\", \"_n\", \"(\", \"x\", \")$\", \" has a limit point \",\n \"as $n \\\\to \\\\infty$\", \"\\\\\\\\ for all $x$\"\n ])\n parts = text.split()\n parts[-1].next_to(Mobject(*parts[:-1]), DOWN)\n parts[-1].set_color(BLUE)\n parts[3].set_color(BLUE)\n parts[1].set_color()\n parts[-2].set_color()\n text.to_edge(UP)\n curve = UnitInterval()\n curve.sort_points(lambda p: p[0])\n vals = np.arange(0.1, 1, 0.1)\n dots = Mobject(*[Dot(curve.number_to_point(val)) for val in vals])\n curve.add_numbers(0, 1)\n starter_dots = dots.copy().ingest_submobjects()\n starter_dots.shift(2 * UP)\n\n self.add(curve, text)\n self.wait()\n self.play(DelayByOrder(ApplyMethod(starter_dots.shift, 2 * DOWN)))\n self.wait()\n self.remove(starter_dots)\n self.add(dots)\n for num in range(1, 10):\n new_curve = HilbertCurve(order=num)\n new_curve.scale(0.8)\n new_dots = Mobject(*[\n Dot(new_curve.points[int(val * new_curve.get_num_points())])\n for val in vals\n ])\n self.play(\n Transform(curve, new_curve),\n Transform(dots, new_dots),\n )\n # self.wait()\n\n\nclass FormalDefinitionOfHilbertCurve(Scene):\n def construct(self):\n val = 0.7\n text = TexMobject([\n \"\\\\text{HC}(\", \"x\", \")\", \"=\\\\lim_{n \\\\to \\\\infty}\\\\text{PHC}_n(\",\n \"x\", \")\"\n ])\n text.to_edge(UP)\n x1 = text.split()[1]\n x2 = text.split()[-2]\n x2.set_color(BLUE)\n explanation = TextMobject(\"Actual Hilbert curve function\")\n exp_arrow = Arrow(explanation, text.split()[0])\n curve = UnitInterval()\n dot = Dot(curve.number_to_point(val))\n x_arrow = Arrow(x1.get_bottom(), dot, buff=0)\n curve.sort_points(lambda p: p[0])\n curve.add_numbers(0, 1)\n\n self.add(*text.split()[:3])\n self.play(ShimmerIn(explanation), ShowCreation(exp_arrow))\n self.wait()\n self.remove(explanation, exp_arrow)\n self.play(ShowCreation(curve))\n self.play(ApplyMethod(x1.set_color, BLUE), ShowCreation(x_arrow),\n ShowCreation(dot))\n self.wait()\n self.remove(x_arrow)\n limit = Mobject(*text.split()[3:]).ingest_submobjects()\n limit.stroke_width = 1\n self.play(ShimmerIn(limit))\n for num in range(1, 9):\n new_curve = HilbertCurve(order=num)\n new_curve.scale(0.8)\n new_dot = Dot(new_curve.points[int(val *\n new_curve.get_num_points())])\n self.play(\n Transform(curve, new_curve),\n Transform(dot, new_dot),\n )\n\n\nclass CouldNotDefineForSnakeCurve(Scene):\n def construct(self):\n self.add(\n TextMobject(\"\"\"\n You could not define a limit curve from\n snake curves.\n \"\"\"))\n self.wait()\n\n\nclass ThreeThingsToProve(Scene):\n def construct(self):\n definition = TexMobject([\n \"\\\\text{HC}(\", \"x\", \")\", \"=\\\\lim_{n \\\\to \\\\infty}\\\\text{PHC}_n(\",\n \"x\", \")\"\n ])\n definition.to_edge(UP)\n definition.split()[1].set_color(BLUE)\n definition.split()[-2].set_color(BLUE)\n intro = TextMobject(\"Three things need to be proven\")\n prove_that = TextMobject(\"Prove that HC is $\\\\dots$\")\n prove_that.scale(0.7)\n prove_that.to_edge(LEFT)\n items = TextMobject([\n \"\\\\begin{enumerate}\",\n \"\\\\item Well-defined: \",\n \"Points on Pseudo-Hilbert-curves really do converge\",\n \"\\\\item A Curve: \",\n \"HC is continuous\",\n \"\\\\item Space-filling: \",\n \"Each point in the unit square is an output of HC\",\n \"\\\\end{enumerate}\",\n ]).split()\n items[1].set_color(GREEN)\n items[3].set_color(YELLOW_C)\n items[5].set_color(MAROON)\n Mobject(*items).to_edge(RIGHT)\n\n self.add(definition)\n self.play(ShimmerIn(intro))\n self.wait()\n self.play(Transform(intro, prove_that))\n for item in items[1:-1]:\n self.play(ShimmerIn(item))\n self.wait()\n\n\nclass TilingSpace(Scene):\n def construct(self):\n coords_set = [ORIGIN]\n for n in range(int(FRAME_WIDTH)):\n for vect in UP, RIGHT:\n for k in range(n):\n new_coords = coords_set[-1] + ((-1)**n) * vect\n coords_set.append(new_coords)\n square = Square(side_length=1, color=WHITE)\n squares = Mobject(\n *[square.copy().shift(coords)\n for coords in coords_set]).ingest_submobjects()\n self.play(DelayByOrder(FadeIn(squares)), run_time=3)\n curve = HilbertCurve(order=6).scale(1. / 6)\n all_curves = Mobject(\n *[curve.copy().shift(coords)\n for coords in coords_set]).ingest_submobjects()\n all_curves.thin_out(10)\n self.play(ShowCreation(all_curves, rate_func=linear, run_time=15))\n\n\nclass ColorIntervals(Scene):\n def construct(self):\n number_line = NumberLine(numerical_radius=5,\n number_at_center=5,\n leftmost_tick=0,\n density=2 * DEFAULT_POINT_DENSITY_1D)\n number_line.shift(2 * RIGHT)\n number_line.add_numbers()\n number_line.scale(2)\n brace = Brace(Mobject(*number_line.submobjects[:2]))\n\n self.add(number_line)\n for n in range(0, 10, 2):\n if n == 0:\n brace_anim = GrowFromCenter(brace)\n else:\n brace_anim = ApplyMethod(brace.shift, 2 * RIGHT)\n self.play(\n ApplyMethod(\n number_line.set_color, RED,\n lambda p: p[0] > n - 6.2 and p[0] < n - 4 and p[1] > -0.4),\n brace_anim)\n" ]
[ [ "scipy.spatial.distance.cdist" ] ]
aptsunny/pycls
[ "a3caff1519891e5cf3a4032dd4b68b7330f8b321" ]
[ "pycls/utils/checkpoint.py" ]
[ "#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"Functions that handle saving and loading of checkpoints.\"\"\"\n\nimport os\n\nimport pycls.utils.distributed as du\nimport torch\nfrom pycls.core.config import cfg\n\n\n# Common prefix for checkpoint file names\n_NAME_PREFIX = \"model_epoch_\"\n# Checkpoints directory name\n_DIR_NAME = \"checkpoints\"\n\n\ndef get_checkpoint_dir():\n \"\"\"Retrieves the location for storing checkpoints.\"\"\"\n return os.path.join(cfg.OUT_DIR, _DIR_NAME)\n\n\ndef get_checkpoint(epoch):\n \"\"\"Retrieves the path to a checkpoint file.\"\"\"\n name = \"{}{:04d}.pyth\".format(_NAME_PREFIX, epoch)\n return os.path.join(get_checkpoint_dir(), name)\n\n\ndef get_last_checkpoint():\n \"\"\"Retrieves the most recent checkpoint (highest epoch number).\"\"\"\n checkpoint_dir = get_checkpoint_dir()\n # Checkpoint file names are in lexicographic order\n checkpoints = [f for f in os.listdir(checkpoint_dir) if _NAME_PREFIX in f]\n last_checkpoint_name = sorted(checkpoints)[-1]\n return os.path.join(checkpoint_dir, last_checkpoint_name)\n\n\ndef has_checkpoint():\n \"\"\"Determines if there are checkpoints available.\"\"\"\n checkpoint_dir = get_checkpoint_dir()\n if not os.path.exists(checkpoint_dir):\n return False\n return any(_NAME_PREFIX in f for f in os.listdir(checkpoint_dir))\n\n\ndef is_checkpoint_epoch(cur_epoch):\n \"\"\"Determines if a checkpoint should be saved on current epoch.\"\"\"\n return (cur_epoch + 1) % cfg.TRAIN.CHECKPOINT_PERIOD == 0\n\n\ndef save_checkpoint(model, optimizer, epoch):\n \"\"\"Saves a checkpoint.\"\"\"\n # Save checkpoints only from the master process\n if not du.is_master_proc():\n return\n # Ensure that the checkpoint dir exists\n os.makedirs(get_checkpoint_dir(), exist_ok=True)\n # Omit the DDP wrapper in the multi-gpu setting\n sd = model.module.state_dict() if cfg.NUM_GPUS > 1 else model.state_dict()\n # Record the state\n checkpoint = {\n \"epoch\": epoch,\n \"model_state\": sd,\n \"optimizer_state\": optimizer.state_dict(),\n \"cfg\": cfg.dump(),\n }\n # Write the checkpoint\n checkpoint_file = get_checkpoint(epoch + 1)\n torch.save(checkpoint, checkpoint_file)\n return checkpoint_file\n\n\ndef load_checkpoint(checkpoint_file, model, optimizer=None):\n \"\"\"Loads the checkpoint from the given file.\"\"\"\n assert os.path.exists(checkpoint_file), \"Checkpoint '{}' not found\".format(\n checkpoint_file\n )\n # Load the checkpoint on CPU to avoid GPU mem spike\n checkpoint = torch.load(checkpoint_file, map_location=\"cpu\")\n # Account for the DDP wrapper in the multi-gpu setting\n ms = model.module if cfg.NUM_GPUS > 1 else model\n ms.load_state_dict(checkpoint[\"model_state\"])\n # Load the optimizer state (commonly not done when fine-tuning)\n if optimizer:\n optimizer.load_state_dict(checkpoint[\"optimizer_state\"])\n return checkpoint[\"epoch\"]\n" ]
[ [ "torch.load", "torch.save" ] ]
qingyuanchen1997/Dual-Model-Integration
[ "86b1166a1ccd3f7caf085e2737a4091b4d85de69" ]
[ "code/main_sunspot2_x.py" ]
[ "from PIL import Image\nfrom torchvision import models\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport numpy as np\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nimport torch.utils.data as data\nimport os\n\n# set up gpu\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\n\n# 图片文件夹目录 ps 最后不要加 \"/\" 例 /train/img 而不是 /train/img/\nbasedir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))\nIMG_DIR_PATH = ''\n# 保存模型路径\ncheckpoint_path = basedir+'/user_data/model_data/test_betax.pt'\n# 训练 txt file\ntrain_txt = basedir+'/user_data/tmp_data/train_input/continuum_train.txt'\n# 验证 txt file\nval_txt = basedir+'/user_data/tmp_data/train_input/continuum_val.txt'\n\n\n# data loader\nclass ImageDataset(data.Dataset):\n def __init__(self, path, transform=None):\n with open(path, 'r') as f:\n self.annotations = f.read().split(\"\\n\")\n self.transform = transform\n\n def __getitem__(self, index):\n img_path, label = self.annotations[index].split(' ')\n image = Image.open(basedir + '/user_data/tmp_data/train_input/continuum' + os.path.splitext(img_path)[0] + '.jpg').convert('RGB').resize((500, 375))\n\n if self.transform is not None:\n image = self.transform(image)\n return image, int(label)\n\n def __len__(self):\n return len(self.annotations)\n\n\nclass Net(nn.Module):\n def __init__(self, alexnet):\n super(Net, self).__init__()\n self.alexnet = alexnet\n self.backbone = alexnet.features\n self.avgpool = alexnet.avgpool\n # in_features = alexnet.classifier[1].in_features\n self.logit = nn.Linear(2304, 3)\n # self.classifer[6].out_features = 3\n\n def forward(self,x):\n batch_size, C, H, W = x.shape\n x = self.backbone(x)\n # print(x.shape)\n x = self.avgpool(x)\n # print(x.shape)\n # x = F.dropout(x, 0.25, self.training)\n x = F.adaptive_avg_pool2d(x, 3).reshape(batch_size, -1)\n # print(x.shape)\n x = self.logit(x)\n return x\n\n\ntrain_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n])\nvalid_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n])\ntrainset = ImageDataset(train_txt, transform=train_transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=16, shuffle=True, num_workers=4)\nvalidset = ImageDataset(val_txt, transform=valid_transform)\nvalidloader = torch.utils.data.DataLoader(validset, batch_size=8, shuffle=False, num_workers=4)\n\n# model build\ndevice = torch.device('cuda' if torch.cuda.is_available() else \"cpu\")\nalexnet = models.alexnet(pretrained=True)\nalexnet = Net(alexnet)\n\n# train\nalexnet.to(device)\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(alexnet.parameters(), lr=0.0008, momentum=0.9)\nvalid_accuracy = 0\nfor epoch in range(10):\n running_loss = 0\n train_correct = 0\n train_total = 0\n for i, data in enumerate(trainloader):\n images, labels = data[0].to(device), data[1].to(device, dtype=torch.int64)\n optimizer.zero_grad()\n outputs = alexnet(images)\n\n m = nn.LogSoftmax()\n logit = m(outputs)\n\n t_logit = logit/torch.Tensor([1.0, 1.0, 1.0]).to(device)\n softmax = t_logit / 20.00\n nllloss = nn.NLLLoss()\n loss = nllloss(softmax, labels)\n\n _, predicted = torch.max(outputs.data, 1)\n train_total += labels.size(0)\n train_correct += (predicted == labels).sum().item()\n\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n if i % 200 == 199:\n print('[%d, %5d] loss: %.3f' % (epoch+1, i+1, running_loss/200))\n running_loss = 0.0\n train_accuracy = 100 * train_correct / train_total\n print('train dataset accuracy %.4f' % train_accuracy)\n\n test_correct = 0\n test_total = 0\n with torch.no_grad():\n for data in validloader:\n images, labels = data[0].to(device), data[1].to(device, dtype=torch.int64)\n outputs = alexnet(images)\n _, predicted = torch.max(outputs.data, 1)\n test_total += labels.size(0)\n test_correct += (predicted == labels).sum().item()\n valided_accuracy = 100*test_correct/test_total\n print('valid dataset accuracy %.4f' % valided_accuracy)\n if valided_accuracy > valid_accuracy:\n torch.save(alexnet.state_dict(), checkpoint_path)\n valid_accuracy = valided_accuracy\n" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.nn.LogSoftmax", "torch.nn.NLLLoss", "torch.max", "torch.Tensor", "torch.utils.data.DataLoader", "torch.nn.functional.adaptive_avg_pool2d", "torch.nn.Linear", "torch.no_grad", "torch.cuda.is_available" ] ]
hdl730/Limbo
[ "ab60172ee35e3d4377d87869dacadd143ce449c9" ]
[ "model/vgg.py" ]
[ "# coding:utf-8\n\nimport tensorflow as tf\nimport scipy.io as sio\nimport numpy as np\nimport PIL.Image as Image\nimport scipy\nfrom model.swap import swap_batch\nfrom config import VGG_PATH\nimport os\nimport sys\n\ndata_path = VGG_PATH\nif not os.path.exists(data_path):\n print('Error: VGG-19 is not loaded because there\\'s no file at {}'.format(data_path))\n sys.exit(1)\n\nVGG19_LAYERS = (\n 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',\n\n 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',\n\n 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3',\n 'relu3_3', 'conv3_4', 'relu3_4', 'pool3',\n\n 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3',\n 'relu4_3', 'conv4_4', 'relu4_4', 'pool4',\n\n 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3',\n 'relu5_3', 'conv5_4', 'relu5_4'\n)\n\nmean_pixel = np.array([123.68, 116.779, 103.939], np.float32)\n_vgg_params = None\n\n\ndef load_net(data_path):\n global _vgg_params\n if _vgg_params is None:\n _vgg_params = scipy.io.loadmat(data_path)\n # mean = data['normalization'][0][0][0]\n # mean_pixel = np.mean(mean, axis=(0, 1))\n weights = _vgg_params['layers'][0]\n return weights, mean_pixel\n\n\ndef net_preloaded(weights, input_image, pooling='avg'):\n net = {}\n current = input_image\n for i, name in enumerate(VGG19_LAYERS):\n kind = name[:4]\n if kind == 'conv':\n kernels, bias = weights[i][0][0][0][0]\n # matconvnet: weights are [width, height, in_channels, out_channels]\n # tensorflow: weights are [height, width, in_channels, out_channels]\n kernels = np.transpose(kernels, (1, 0, 2, 3))\n bias = bias.reshape(-1)\n current = _conv_layer(current, kernels, bias)\n elif kind == 'relu':\n current = tf.nn.relu(current)\n elif kind == 'pool':\n current = _pool_layer(current, pooling)\n net[name] = current\n return net\n\n\ndef net_preloaded_with_swap(weights, input_image, patch_size_dict, pooling='avg', use_one_hot=False, with_style=True):\n net = {}\n current = input_image\n for i, name in enumerate(VGG19_LAYERS):\n kind = name[:4]\n if kind == 'conv':\n kernels, bias = weights[i][0][0][0][0]\n # matconvnet: weights are [width, height, in_channels, out_channels]\n # tensorflow: weights are [height, width, in_channels, out_channels]\n kernels = np.transpose(kernels, (1, 0, 2, 3))\n bias = bias.reshape(-1)\n current = _conv_layer(current, kernels, bias)\n elif kind == 'relu':\n current = tf.nn.relu(current)\n elif kind == 'pool':\n current = _pool_layer(current, pooling)\n if name in patch_size_dict.keys():\n current = swap(current, patch_size=patch_size_dict[name], one_hot=use_one_hot, with_style=with_style)\n net[name] = current\n return net\n\n\ndef _conv_layer(input, weights, bias):\n conv = tf.nn.conv2d(input, tf.constant(weights), strides=(1, 1, 1, 1),\n padding='SAME')\n return tf.nn.bias_add(conv, tf.constant(bias))\n\n\ndef _pool_layer(input, pooling):\n if pooling == 'avg':\n return tf.nn.avg_pool(input, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1),\n padding='SAME')\n else:\n return tf.nn.max_pool(input, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1),\n padding='SAME')\n\n\ndef preprocess_image(image_path):\n image = Image.open(image_path)\n image = np.array(image)\n image = np.cast(image, np.float32)\n # image = image - mean_pixel\n image = np.expand_dims(image, axis=0)\n return image\n\n\ndef preprocess_tensor(image_tensor, size):\n image_tensor = tf.cast(image_tensor, tf.float32)\n # image_tensor = image_tensor - tf.constant(mean_pixel)\n resized = tf.expand_dims(image_tensor, 0)\n return tf.image.resize_images(resized, size)\n\n\ndef deprocess_tensor(image_tensor):\n # image_tensor = image_tensor + tf.constant(mean_pixel)\n # image_tensor += tf.constant([255.0, 255.0, 255.0])\n cliped = tf.clip_by_value(image_tensor, 0, 255)\n casted = tf.cast(cliped, tf.uint8)\n # features = K.batch_flatten(K.permute_dimensions(x, (2, 0, 1)))\n # gram = K.dot(features, K.transpose(features))\n # return gram\n return casted\n\n\ndef deprocess_single_image(image):\n shape = image.shape\n image = image.reshape(shape[1:])\n # image += mean_pixel\n # image += [255.0, 255.0, 255.0]\n image = np.clip(image, 0, 255).astype(np.uint8)\n return image\n\n\ndef vgg19(input_img, output_layer='conv3_1'):\n if output_layer not in VGG19_LAYERS:\n print('Error, there\\'s no layer named', output_layer)\n weights, mean = load_net(data_path)\n return net_preloaded(weights, input_img)[output_layer]\n\n\ndef vgg19_and_swap(input_img, output_layer='conv3_1', patch_size_dict=None, use_one_hot=False, with_style=True):\n if output_layer not in VGG19_LAYERS:\n print('Error, there\\'s no layer named', output_layer)\n weights, mean = load_net(data_path)\n if patch_size_dict is not None:\n for name, arg in patch_size_dict.items():\n print('Swap style with %d^2 patch' % arg)\n else:\n patch_size_dict = {}\n if len(patch_size_dict.keys()) > 1 and not with_style:\n print('Warn: Must keep style feature if more than 1 swap will be done.')\n with_style = True\n return net_preloaded_with_swap(weights, input_img, patch_size_dict=patch_size_dict, use_one_hot=use_one_hot,\n with_style=with_style)[output_layer]\n" ]
[ [ "tensorflow.clip_by_value", "tensorflow.nn.relu", "numpy.expand_dims", "tensorflow.constant", "numpy.clip", "tensorflow.nn.max_pool", "tensorflow.image.resize_images", "tensorflow.cast", "scipy.io.loadmat", "tensorflow.expand_dims", "numpy.cast", "tensorflow.nn.avg_pool", "numpy.transpose", "numpy.array" ] ]
muneebaadil/sisr-irl
[ "29ccf9ad970ade22fc8e158b83f952504db71a7b" ]
[ "code/loss/charbonnier.py" ]
[ "import torch \nimport torch.nn as nn\n\nclass Charbonnier(nn.Module):\n \"\"\"L1 Charbonnierloss.\"\"\"\n def __init__(self):\n super(Charbonnier, self).__init__()\n self.eps = 1e-6\n\n def forward(self, X, Y):\n diff = torch.add(X, -Y)\n error = torch.sqrt( diff * diff + self.eps )\n loss = torch.mean(error)\n return loss " ]
[ [ "torch.sqrt", "torch.mean", "torch.add" ] ]
dienthaipham103/Zalo_Challenge_2021
[ "9a6159c6692bac5c2f090a91f691e798c52da2b5" ]
[ "lib/SSH_pytorch/model/utils/test_utils.py" ]
[ "# --------------------------------------------------------------------------------------------------\n# SSH: Single Stage Headless Face Detector\n# Utilities used in SSH test modules\n# Written by Mahyar Najibi\n# --------------------------------------------------------------------------------------------------\nimport os\nimport matplotlib\n\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom lib.SSH_pytorch.model.utils.config import cfg\nimport numpy as np\nimport cv2\nfrom lib.SSH_pytorch.model.utils.blob import im_list_to_blob\n\n\ndef _compute_scaling_factor(im_shape, target_size, max_size):\n \"\"\"\n :param im_shape: The shape of the image\n :param target_size: The min side is resized to the target_size\n :param max_size: The max side is kept less than max_size\n :return: The scale factor\n \"\"\"\n\n if cfg.TEST.ORIG_SIZE:\n return 1.0\n\n im_size_min = np.min(im_shape[0:2])\n im_size_max = np.max(im_shape[0:2])\n\n im_scale = float(target_size) / float(im_size_min)\n # Prevent the biggest axis from being more than MAX_SIZE\n if np.round(im_scale * im_size_max) > max_size:\n im_scale = float(max_size) / float(im_size_max)\n return im_scale\n\n\ndef _get_image_blob(im, im_scales):\n \"\"\"\n :param im: input image\n :param im_scales: a list of scale coefficients\n :return: A list of network blobs each containing a resized ver. of the image\n \"\"\"\n # Subtract the mean\n im_copy = im.astype(np.float32, copy=True) - cfg.PIXEL_MEANS\n\n # Append all scales to form a blob\n blobs = []\n for scale in im_scales:\n if scale == 1.0:\n blobs.append({'data': im_list_to_blob([im_copy])})\n else:\n blobs.append({'data': im_list_to_blob([cv2.resize(im_copy, None, None, fx=scale, fy=scale,\n interpolation=cv2.INTER_LINEAR)])})\n return blobs\n\n\ndef visusalize_detections(im, bboxes, plt_name='output', ext='.png', visualization_folder=None, thresh=0.5):\n \"\"\"\n A function to visualize the detections\n :param im: The image\n :param bboxes: The bounding box detections\n :param plt_name: The name of the plot\n :param ext: The save extension (if visualization_folder is not None)\n :param visualization_folder: The folder to save the results\n :param thresh: The detections with a score less than thresh are not visualized\n \"\"\"\n inds = np.where(bboxes[:, -1] >= thresh)[0]\n bboxes = bboxes[inds]\n fig, ax = plt.subplots(figsize=(12, 12))\n\n if im.shape[0] == 3:\n im_cp = im.copy()\n im_cp = im_cp.transpose((1, 2, 0))\n if im.min() < 0:\n pixel_means = cfg.PIXEL_MEANS\n im_cp = im_cp + pixel_means\n\n im = im_cp.astype(dtype=np.uint8)\n\n im = im[:, :, (2, 1, 0)]\n\n ax.imshow(im, aspect='equal')\n if bboxes.shape[0] != 0:\n\n for i in range(bboxes.shape[0]):\n bbox = bboxes[i, :]\n ax.add_patch(\n plt.Rectangle((bbox[0], bbox[1]),\n bbox[2] - bbox[0],\n bbox[3] - bbox[1], fill=False,\n edgecolor=(0, bbox[4], 0), linewidth=3)\n )\n\n plt.axis('off')\n plt.tight_layout()\n plt.draw()\n if visualization_folder is not None:\n if not os.path.exists(visualization_folder):\n os.makedirs(visualization_folder)\n plt_name += ext\n plt.savefig(os.path.join(visualization_folder, plt_name), bbox_inches='tight')\n print('Saved {}'.format(os.path.join(visualization_folder, plt_name)))\n else:\n print('Visualizing {}!'.format(plt_name))\n plt.show()\n plt.clf()\n plt.cla()\n plt.close()\n" ]
[ [ "matplotlib.pyplot.Rectangle", "matplotlib.pyplot.tight_layout", "numpy.min", "matplotlib.use", "matplotlib.pyplot.cla", "matplotlib.pyplot.subplots", "matplotlib.pyplot.draw", "numpy.round", "numpy.max", "matplotlib.pyplot.clf", "matplotlib.pyplot.close", "matplotlib.pyplot.axis", "matplotlib.pyplot.show", "numpy.where" ] ]
lpereira95/geomstats
[ "c63a4cf28e6c09f6a6b9926e8a712838362017ba" ]
[ "geomstats/_backend/pytorch/autodiff.py" ]
[ "\"\"\"Automatic differentiation in PyTorch.\"\"\"\n\nimport numpy as _np\nimport torch as _torch\nfrom torch.autograd.functional import jacobian as _torch_jac\n\n\ndef detach(x):\n \"\"\"Return a new tensor detached from the current graph.\n\n Parameters\n ----------\n x : array-like\n Tensor to detach.\n\n Returns\n -------\n x : array-like\n Detached tensor.\n \"\"\"\n return x.detach()\n\n\ndef custom_gradient(*grad_funcs):\n \"\"\"Create a decorator that allows a function to define its custom gradient(s).\n\n Parameters\n ----------\n *grad_funcs : callables\n Custom gradient functions.\n\n Returns\n -------\n decorator : callable\n This decorator, used on any function func, associates the\n input grad_funcs as the gradients of func.\n \"\"\"\n\n def decorator(func):\n \"\"\"Decorate a function to define its custome gradient(s).\n\n Parameters\n ----------\n func : callable\n Function whose gradients will be assigned by grad_funcs.\n\n Returns\n -------\n wrapped_function : callable\n Function func with gradients specified by grad_funcs.\n \"\"\"\n\n class func_with_grad(_torch.autograd.Function):\n \"\"\"Wrapper class for a function with custom grad.\"\"\"\n\n @staticmethod\n def forward(ctx, *args):\n ctx.save_for_backward(*args)\n return func(*args)\n\n @staticmethod\n def backward(ctx, grad_output):\n inputs = ctx.saved_tensors\n\n grads = ()\n for custom_grad in grad_funcs:\n grads = (*grads, grad_output * custom_grad(*inputs))\n\n if len(grads) == 1:\n return grads[0]\n return grads\n\n def wrapped_function(*args, **kwargs):\n new_inputs = args + tuple(kwargs.values())\n return func_with_grad.apply(*new_inputs)\n\n return wrapped_function\n\n return decorator\n\n\ndef jacobian(func):\n \"\"\"Return a function that returns the jacobian of func.\n\n Parameters\n ----------\n func : callable\n Function whose Jacobian is computed.\n\n Returns\n -------\n _ : callable\n Function taking x as input and returning\n the jacobian of func at x.\n \"\"\"\n return lambda x: _torch_jac(func, x)\n\n\ndef value_and_grad(func, to_numpy=False):\n \"\"\"Return a function that returns func's value and gradients' values.\n\n Suitable for use in scipy.optimize with to_numpy=True.\n\n Parameters\n ----------\n func : callable\n Function whose value and gradient values\n will be computed. It must be real-valued.\n to_numpy : bool\n Determines if the outputs value and grad will be cast\n to numpy arrays. Set to \"True\" when using scipy.optimize.\n Optional, default: False.\n\n Returns\n -------\n func_with_grad : callable\n Function that returns func's value and\n func's gradients' values at its inputs args.\n \"\"\"\n\n def func_with_grad(*args, **kwargs):\n \"\"\"Return func's value and func's gradients' values at args.\n\n Parameters\n ----------\n args : list\n Argument to function func and its gradients.\n kwargs : dict\n Keyword arguments to function func and its gradients.\n\n Returns\n -------\n value : any\n Value of func at input arguments args.\n all_grads : list or any\n Values of func's gradients at input arguments args.\n \"\"\"\n new_args = ()\n for one_arg in args:\n if isinstance(one_arg, float):\n one_arg = _torch.from_numpy(_np.array(one_arg))\n if isinstance(one_arg, _np.ndarray):\n one_arg = _torch.from_numpy(one_arg)\n one_arg = one_arg.clone().requires_grad_(True)\n new_args = (*new_args, one_arg)\n args = new_args\n\n value = func(*args, **kwargs)\n if value.ndim > 0:\n value.backward(gradient=_torch.ones_like(one_arg), retain_graph=True)\n else:\n value.backward(retain_graph=True)\n\n all_grads = ()\n for one_arg in args:\n all_grads = (\n *all_grads,\n _torch.autograd.grad(value, one_arg, retain_graph=True)[0],\n )\n\n if to_numpy:\n value = detach(value).numpy()\n all_grads = [detach(one_grad).numpy() for one_grad in all_grads]\n\n if len(args) == 1:\n return value, all_grads[0]\n return value, all_grads\n\n return func_with_grad\n" ]
[ [ "torch.autograd.functional.jacobian", "torch.from_numpy", "numpy.array", "torch.autograd.grad", "torch.ones_like" ] ]
krutarthjoshi18/CNN-for-Twitter-Sentiment-Analysis
[ "5c404aabb21dec4bb1b7c4fcb77cf4bc3f4d7661" ]
[ "eval.py" ]
[ "#! /usr/bin/env python\n\nimport csv\nimport os\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib import learn\n\nimport data_helpers\n\n# Parameters\n# ==================================================\n\n# Data Parameters\ntf.flags.DEFINE_string(\"positive_data_file\", \"./data/rt-polaritydata/test.pos\",\n \"Data source for the positive data.\")\ntf.flags.DEFINE_string(\"neutral_data_file\", \"./data/rt-polaritydata/test.neu\",\n \"Data source for the neutral data.\")\ntf.flags.DEFINE_string(\"negative_data_file\", \"./data/rt-polaritydata/test.neg\",\n \"Data source for the negative data.\")\n\n# Eval Parameters\ntf.flags.DEFINE_integer(\"batch_size\", 64, \"Batch Size (default: 64)\")\ntf.flags.DEFINE_string(\"checkpoint_dir\", \"\", \"Checkpoint directory from training run\")\ntf.flags.DEFINE_boolean(\"eval_train\", False, \"Evaluate on all training data\")\n\n# Misc Parameters\ntf.flags.DEFINE_boolean(\"allow_soft_placement\", True, \"Allow device soft device placement\")\ntf.flags.DEFINE_boolean(\"log_device_placement\", False, \"Log placement of ops on devices\")\n\nFLAGS = tf.flags.FLAGS\nFLAGS._parse_flags()\nprint(\"\\nParameters:\")\nfor attr, value in sorted(FLAGS.__flags.items()):\n print(\"{}={}\".format(attr.upper(), value))\nprint(\"\")\n\n# CHANGE THIS: Load data. Load your own data here\nif FLAGS.eval_train:\n x_raw, y_test = data_helpers.load_data_and_labels(FLAGS.positive_data_file,\n FLAGS.positive_data_file,\n FLAGS.negative_data_file)\n y_test = np.argmax(y_test, axis=1)\nelse:\n x_raw = [\"a masterpiece four years in the making\", \"everything is off.\"]\n y_test = [1, 0]\n\n# Map data into vocabulary\nvocab_path = os.path.join(FLAGS.checkpoint_dir, '../vocab')\nvocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path)\nx_test = np.array(list(vocab_processor.transform(x_raw)))\n\nprint(\"\\nEvaluating...\\n\")\n\n# Evaluation\n# ==================================================\ncheckpoint_file = tf.train.latest_checkpoint(FLAGS.checkpoint_dir)\ngraph = tf.Graph()\nwith graph.as_default():\n session_conf = tf.ConfigProto(\n allow_soft_placement=FLAGS.allow_soft_placement,\n log_device_placement=FLAGS.log_device_placement)\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n # Load the saved meta graph and restore variables\n saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file))\n saver.restore(sess, checkpoint_file)\n\n # Get the placeholders from the graph by name\n input_x = graph.get_operation_by_name(\"input_x\").outputs[0]\n # input_y = graph.get_operation_by_name(\"input_y\").outputs[0]\n dropout_keep_prob = graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0]\n\n # Tensors we want to evaluate\n predictions = graph.get_operation_by_name(\"output/predictions\").outputs[0]\n\n # Generate batches for one epoch\n batches = data_helpers.batch_iter(list(x_test), FLAGS.batch_size, 1, shuffle=False)\n\n # Collect the predictions here\n all_predictions = []\n\n for x_test_batch in batches:\n batch_predictions = sess.run(predictions, {input_x: x_test_batch, dropout_keep_prob: 1.0})\n all_predictions = np.concatenate([all_predictions, batch_predictions])\n\n# Print accuracy if y_test is defined\nif y_test is not None:\n correct_predictions = float(sum(all_predictions == y_test))\n print(\"Total number of test examples: {}\".format(len(y_test)))\n print(\"Accuracy: {:g}\".format(correct_predictions / float(len(y_test))))\n\n# Save the evaluation to a csv\npredictions_human_readable = np.column_stack((np.array(x_raw), all_predictions))\nout_path = os.path.join(FLAGS.checkpoint_dir, \"..\", \"prediction.csv\")\nprint(\"Saving evaluation to {0}\".format(out_path))\nwith open(out_path, 'w') as f:\n csv.writer(f).writerows(predictions_human_readable)\n" ]
[ [ "tensorflow.flags.DEFINE_boolean", "tensorflow.Graph", "tensorflow.train.latest_checkpoint", "tensorflow.flags.DEFINE_string", "tensorflow.ConfigProto", "numpy.concatenate", "numpy.argmax", "tensorflow.Session", "numpy.array", "tensorflow.contrib.learn.preprocessing.VocabularyProcessor.restore", "tensorflow.flags.DEFINE_integer" ] ]
bubbliiiing/classification-pytorch
[ "1937599ae6e688ed7af7470f69964fb6f97241c4" ]
[ "utils/utils_fit.py" ]
[ "import torch\r\nimport torch.nn.functional as F\r\nfrom torch import nn\r\nfrom tqdm import tqdm\r\n\r\nfrom .utils import get_lr\r\n\r\n\r\ndef fit_one_epoch(model_train, model, loss_history, optimizer, epoch, epoch_step, epoch_step_val, gen, gen_val, Epoch, cuda):\r\n total_loss = 0\r\n total_accuracy = 0\r\n\r\n val_loss = 0\r\n\r\n model_train.train()\r\n print('Start Train')\r\n with tqdm(total=epoch_step,desc=f'Epoch {epoch + 1}/{Epoch}',postfix=dict,mininterval=0.3) as pbar:\r\n for iteration, batch in enumerate(gen):\r\n if iteration >= epoch_step: \r\n break\r\n images, targets = batch\r\n with torch.no_grad():\r\n images = torch.from_numpy(images).type(torch.FloatTensor)\r\n targets = torch.from_numpy(targets).type(torch.FloatTensor).long()\r\n if cuda:\r\n images = images.cuda()\r\n targets = targets.cuda()\r\n\r\n optimizer.zero_grad()\r\n outputs = model_train(images)\r\n loss_value = nn.CrossEntropyLoss()(outputs, targets)\r\n loss_value.backward()\r\n optimizer.step()\r\n\r\n total_loss += loss_value.item()\r\n with torch.no_grad():\r\n accuracy = torch.mean((torch.argmax(F.softmax(outputs, dim=-1), dim=-1) == targets).type(torch.FloatTensor))\r\n total_accuracy += accuracy.item()\r\n\r\n pbar.set_postfix(**{'total_loss': total_loss / (iteration + 1), \r\n 'accuracy' : total_accuracy / (iteration + 1), \r\n 'lr' : get_lr(optimizer)})\r\n pbar.update(1)\r\n\r\n print('Finish Train')\r\n\r\n model_train.eval()\r\n print('Start Validation')\r\n with tqdm(total=epoch_step_val, desc=f'Epoch {epoch + 1}/{Epoch}',postfix=dict,mininterval=0.3) as pbar:\r\n for iteration, batch in enumerate(gen_val):\r\n if iteration >= epoch_step_val:\r\n break\r\n images, targets = batch\r\n with torch.no_grad():\r\n images = torch.from_numpy(images).type(torch.FloatTensor)\r\n targets = torch.from_numpy(targets).type(torch.FloatTensor).long()\r\n if cuda:\r\n images = images.cuda()\r\n targets = targets.cuda()\r\n\r\n optimizer.zero_grad()\r\n\r\n outputs = model_train(images)\r\n loss_value = nn.CrossEntropyLoss()(outputs, targets)\r\n \r\n val_loss += loss_value.item()\r\n \r\n pbar.set_postfix(**{'total_loss': val_loss / (iteration + 1),\r\n 'lr' : get_lr(optimizer)})\r\n pbar.update(1)\r\n \r\n loss_history.append_loss(total_loss / epoch_step, val_loss / epoch_step_val)\r\n print('Finish Validation')\r\n print('Epoch:' + str(epoch + 1) + '/' + str(Epoch))\r\n print('Total Loss: %.3f || Val Loss: %.3f ' % (total_loss / epoch_step, val_loss / epoch_step_val))\r\n torch.save(model.state_dict(), 'logs/ep%03d-loss%.3f-val_loss%.3f.pth'%((epoch + 1), total_loss / epoch_step, val_loss / epoch_step_val))\r\n" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.no_grad", "torch.from_numpy", "torch.nn.functional.softmax" ] ]
bracca95/Probabilistic-Face-Embeddings
[ "23191e9b068dbf495a37daa071a1383f12f2799b" ]
[ "utils/utils.py" ]
[ "\"\"\"Utilities for training and testing\n\"\"\"\n# MIT License\n# \n# Copyright (c) 2019 Yichun Shi\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport sys\nimport os\nimport numpy as np\nfrom scipy import misc\nimport time\nimport math\nimport random\nfrom datetime import datetime\nimport shutil\n\ndef create_log_dir(config, config_file):\n subdir = datetime.strftime(datetime.now(), '%Y%m%d-%H%M%S')\n log_dir = os.path.join(os.path.expanduser(config.log_base_dir), config.name, subdir)\n if not os.path.isdir(log_dir): # Create the log directory if it doesn't exist\n os.makedirs(log_dir)\n shutil.copyfile(config_file, os.path.join(log_dir,'config.py'))\n\n return log_dir\n\n\ndef get_updated_learning_rate(global_step, config):\n if config.learning_rate_strategy == 'step':\n max_step = -1\n learning_rate = 0.0\n for step, lr in config.learning_rate_schedule.items():\n if global_step >= step and step > max_step:\n learning_rate = lr\n max_step = step\n if max_step == -1:\n raise ValueError('cannot find learning rate for step %d' % global_step)\n elif config.learning_rate_strategy == 'cosine':\n initial = config.learning_rate_schedule['initial']\n interval = config.learning_rate_schedule['interval']\n end_step = config.learning_rate_schedule['end_step']\n step = math.floor(float(global_step) / interval) * interval\n assert step <= end_step\n learning_rate = initial * 0.5 * (math.cos(math.pi * step / end_step) + 1)\n elif config.learning_rate_strategy == 'linear':\n initial = config.learning_rate_schedule['initial']\n start = config.learning_rate_schedule['start']\n end_step = config.learning_rate_schedule['end_step']\n assert global_step <= end_step\n assert start < end_step\n if global_step < start:\n learning_rate = initial\n else:\n learning_rate = 1.0 * initial * (end_step - global_step) / (end_step - start)\n else:\n raise ValueError(\"Unkown learning rate strategy!\")\n\n return learning_rate\n\ndef display_info(epoch, step, duration, watch_list):\n sys.stdout.write('[%d][%d] time: %2.2f' % (epoch+1, step+1, duration))\n for item in watch_list.items():\n if type(item[1]) in [float, np.float32, np.float64]:\n sys.stdout.write(' %s: %2.3f' % (item[0], item[1]))\n elif type(item[1]) in [int, bool, np.int32, np.int64, np.bool]:\n sys.stdout.write(' %s: %d' % (item[0], item[1]))\n sys.stdout.write('\\n')\n\ndef l2_normalize(x, axis=None, eps=1e-8):\n x = x / (eps + np.linalg.norm(x, axis=axis))\n return x\n\ndef pair_euc_score(x1, x2):\n x1, x2 = np.array(x1), np.array(x2)\n dist = np.sum(np.square(x1 - x2), axis=1)\n return -dist\n\ndef pair_MLS_score(x1, x2, sigma_sq1=None, sigma_sq2=None):\n if sigma_sq1 is None:\n x1, x2 = np.array(x1), np.array(x2)\n assert sigma_sq2 is None, 'either pass in concated features, or mu, sigma_sq for both!'\n D = int(x1.shape[1] / 2)\n mu1, sigma_sq1 = x1[:,:D], x1[:,D:]\n mu2, sigma_sq2 = x2[:,:D], x2[:,D:]\n else:\n x1, x2 = np.array(x1), np.array(x2)\n sigma_sq1, sigma_sq2 = np.array(sigma_sq1), np.array(sigma_sq2)\n mu1, mu2 = x1, x2\n sigma_sq_mutual = sigma_sq1 + sigma_sq2\n dist = np.sum(np.square(mu1 - mu2) / sigma_sq_mutual + np.log(sigma_sq_mutual), axis=1)\n return -dist\n\n\ndef aggregate_PFE(x, sigma_sq=None, normalize=True, concatenate=False):\n if sigma_sq is None:\n D = int(x.shape[1] / 2)\n mu, sigma_sq = x[:,:D], x[:,D:]\n else:\n mu = x\n attention = 1. / sigma_sq\n attention = attention / np.sum(attention, axis=0, keepdims=True)\n \n mu_new = np.sum(mu * attention, axis=0)\n sigma_sq_new = np.min(sigma_sq, axis=0)\n\n if normalize:\n mu_new = l2_normalize(mu_new)\n\n if concatenate:\n return np.concatenate([mu_new, sigma_sq_new])\n else:\n return mu_new, sigma_sq_new\n \n" ]
[ [ "numpy.square", "numpy.log", "numpy.min", "numpy.linalg.norm", "numpy.concatenate", "numpy.array", "numpy.sum" ] ]
Digital-Twin-Operational-Platform/Cristallo
[ "20e21f6ae0f0f99002a229c8c966fd72020698c3", "20e21f6ae0f0f99002a229c8c966fd72020698c3" ]
[ "dtApp/dtCode/unquant.py", "dtLib/crossval/example.py" ]
[ "'''\n\n`dtApp/dtCode/unquant.py`\n\n\n:Author: \n Marco De Angelis\n\n:Organisation: \n University of Liverpool\n\n:Copyright: \n BSD Licence\n\nThis single python file ``unquant.py`` is the backend code for the uncertainty page.\n\nA single function ``unquant()`` wrangles all the data requests from the html template. \nThe function takes care of the data sent by user performing a few actions:\n\n* The data is converted in SI units;\n* The slider position is converted to an interval;\n* The uncertainty propagation function is invoked;\n* The output is captured and plotted with Plotly.\n\nThis file makes sure that when no data are provided by the user, the page displays and plots the nominal values.\n\nThe default values that populate the page on load are defined at the top of document as persistent variables.\n\n.. code-block:: python\n\n MASS = [5.362, 5.144, 5.142] # *1e4 kg\n\n STFF = [3.846, 4.464, 4.589] # *1e8 N/m\n\n DAMP = [1.699, 1.016, 1.34] # *1e4 Ns/m\n\n\nThis page makes use of the following dependencies.\n\nExternal dependencies \n\n.. code-block:: python\n\n from flask import render_template, request, redirect, Response, url_for\n import importlib.util\n import numpy\n import plotly\n import plotly.graph_objects as go\n from plotly.subplots import make_subplots\n import json\n\n\nThe internal dependency is imported from the scientific code library.\n\n.. code-block:: python\n\n import dtLib.unquant.msd3 as msd3\n\n\n\n\n\nIf not otherwise specified: \n\n| * The excitation is applied at floor 2. \n| * The frequency range is [5,200] Hz.\n| * The FRF plots 350 frequencies.\n| * The number of MonteCarlo samples is 50.\n\n'''\n# Import external packages\nfrom flask import render_template, request, redirect, Response, url_for\nimport importlib.util\nimport numpy\nimport plotly\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport json\n\n# Import internal packages\nfrom dtApp import app\nfrom dtApp import date\nimport dtLib.unquant.msd3 as msd3\n\n\nM_INP_1, M_INP_2, M_INP_3 = 5.36, 5.14, 5.14\nK_INP_1, K_INP_2, K_INP_3 = 3.85, 4.46, 4.59\nC_INP_1, C_INP_2, C_INP_3 = 1.70, 1.02, 1.34\n\nSLIDER_SCALE = 10000\n\nPLOT_DEFINITION = 350\n\nPLOT_WIDTH = 900\nPLOT_HEIGHT = 800\n\nW_PLOT_RANGE = [5,200]\n\[email protected]('/unquant', methods=['GET','POST'])\ndef unquant(): # Properties displayed on landing\n '''\n Although this function takes explicit inputs, it is responsible for dispatching the data requests from the html page. \n\n The html inputs are dispathed from the Flask's request object ``request``, as follows:\n\n .. code-block:: python\n\n for key,val in request.form.items():\n if key == \"input1\":\n input1 = int(val)\n if key == 'input2':\n input2 = float(val)\n\n '''\n M_inp_1, M_inp_2, M_inp_3 = M_INP_1, M_INP_2, M_INP_3\n eM_slider_1, eM_slider_2, eM_slider_3 = 0,0,0\n K_inp_1, K_inp_2, K_inp_3 = K_INP_1, K_INP_2, K_INP_3\n eK_slider_1,eK_slider_2,eK_slider_3 = 0,0,0\n C_inp_1, C_inp_2, C_inp_3 = C_INP_1, C_INP_2, C_INP_3\n eC_slider_1, eC_slider_2, eC_slider_3 = 0,0,0\n MCsamp = 50\n maxUnc = int(10) # percent\n Exci = '2' # excitation at floor 2\n if request.method=='POST':\n fig = make_subplots(rows=3, cols=1, subplot_titles=(\"Floor 3\", \"Floor 2\", \"Floor 1\"), shared_xaxes=False)\n fig.update_layout(width=PLOT_WIDTH, height=PLOT_HEIGHT) \n for key,val in request.form.items():\n if key == \"maxU\":\n maxUnc = int(val)\n if key == 'exci':\n Exci = val\n # Mass\n if key == \"M_centre_3\":\n M_inp_3 = float(val)\n if key == \"M_centre_2\":\n M_inp_2 = float(val)\n if key == \"M_centre_1\":\n M_inp_1 = float(val)\n if key == \"eM_slider_3\":\n eM_slider_3 = float(val) \n if key == \"eM_slider_2\":\n eM_slider_2 = float(val)\n if key == \"eM_slider_1\":\n eM_slider_1 = float(val)\n # Stiff\n if key == \"K_centre_3\":\n K_inp_3 = float(val)\n if key == \"K_centre_2\":\n K_inp_2 = float(val)\n if key == \"K_centre_1\":\n K_inp_1 = float(val)\n if key == \"eK_slider_3\":\n eK_slider_3 = float(val) \n if key == \"eK_slider_2\":\n eK_slider_2 = float(val) \n if key == \"eK_slider_1\":\n eK_slider_1 = float(val) \n # Damp\n if key == \"C_centre_3\":\n C_inp_3 = float(val)\n if key == \"C_centre_2\":\n C_inp_2 = float(val)\n if key == \"C_centre_1\":\n C_inp_1 = float(val)\n if key == \"eC_slider_3\":\n eC_slider_3 = float(val)\n if key == \"eC_slider_2\":\n eC_slider_2 = float(val)\n if key == \"eC_slider_1\":\n eC_slider_1 = float(val)\n if key == \"MC_samples\":\n MCsamp = int(val)\n if key == \"Subintervals\":\n Subintervals = val\n \n def Lo(c,e):\n '''\n Function retrieving the lower bound of an interval provided in central notation.\n\n :param c: Midpoint of the interval\n :param e: Relative half-width of the interval \n\n :returns: The lower bound of the interval\n '''\n return c * (1-e)\n def Hi(c,e):\n '''\n Function retrieving the lower bound of an interval provided in central notation.\n\n :param c: Midpoint of the interval\n :param e: Relative half-width of the interval \n\n :returns: The upper bound of the interval\n '''\n return c * (1+e)\n\n M_inp = [M_inp_1, M_inp_2, M_inp_3]\n M_inp_SI = [1e4 * mi for mi in M_inp]\n M_slider = [eM_slider_1,eM_slider_2,eM_slider_3]\n M_e = [float(ms) * maxUnc / SLIDER_SCALE for ms in M_slider] \n mI = [[Lo(m,e), Hi(m,e)] for m,e in zip(M_inp_SI,M_e)]\n\n K_inp = [ K_inp_1, K_inp_2, K_inp_3]\n K_inp_SI = [1e8 * ki for ki in K_inp]\n K_slider = [eK_slider_1,eK_slider_2,eK_slider_3]\n K_e = [ks * maxUnc / SLIDER_SCALE for ks in K_slider] \n kI = [[Lo(k,e), Hi(k,e)] for k,e in zip(K_inp_SI,K_e)]\n\n C_inp = [ C_inp_1, C_inp_2, C_inp_3]\n C_inp_SI = [1e4 * ci for ci in C_inp]\n C_slider = [eC_slider_1,eC_slider_2,eC_slider_3]\n C_e = [cs * maxUnc / SLIDER_SCALE for cs in C_slider] \n cI = [[Lo(c,e), Hi(c,e)] for c,e in zip(C_inp_SI,C_e)]\n \n\n U = sum([em + ek + ec for em,ek,ec in zip(M_e,K_e,C_e)])\n uncertainty = True\n if abs(U)<1e-5:\n uncertainty = False\n\n if uncertainty:\n kwargs = { # inputs required by the library module\n 'w_range':W_PLOT_RANGE,\n 'mI':mI,\n 'kI':kI,\n 'cI':cI,\n 'exci_floor':Exci,\n }\n\n kwargs['n1'] = 200\n kwargs['n2'] = 30\n ww,Y_cart = msd3.displacement_bounds_cartesian_MK(**kwargs) \n fig.add_trace(go.Scatter(name='',x=ww, y=numpy.log10(Y_cart)[:,0,0],\n fill=None,\n mode='lines',\n line_color='indigo',\n showlegend=False), row=1, col=1)\n fig.add_trace(go.Scatter(name='',x=ww, y=numpy.log10(Y_cart)[:,1,0],\n fill=None,\n mode='lines',\n line_color='indigo',\n showlegend=False), row=2, col=1)\n fig.add_trace(go.Scatter(name='',x=ww, y=numpy.log10(Y_cart)[:,2,0],\n fill=None,\n mode='lines',\n line_color='indigo',\n showlegend=False), row=3, col=1)\n \n fig.add_trace(go.Scatter(name='Cartesian',x=ww, y=numpy.log10(Y_cart)[:,0,1],\n fill='tonexty',\n mode='lines',\n line_color='indigo'), row=1, col=1)\n fig.add_trace(go.Scatter(name='',x=ww, y=numpy.log10(Y_cart)[:,1,1],\n fill='tonexty',\n mode='lines',\n line_color='indigo',\n showlegend=False), row=2, col=1)\n fig.add_trace(go.Scatter(name='',x=ww, y=numpy.log10(Y_cart)[:,2,1],\n fill='tonexty',\n mode='lines',\n line_color='indigo',\n showlegend=False), row=3, col=1)\n\n kwargs['n1'] = 200\n kwargs['n2'] = MCsamp\n\n ww,Y_in = msd3.displacement_bounds_montecarlo(**kwargs) \n fig.add_trace(go.Scatter(name='',x=ww, y=numpy.log10(Y_in)[:,0,0],\n fill=None,\n mode='lines',\n line_color='limegreen',\n showlegend=False), row=1, col=1)\n fig.add_trace(go.Scatter(name='',x=ww, y=numpy.log10(Y_in)[:,1,0], \n fill=None,\n mode='lines',\n line_color='limegreen',\n showlegend=False), row=2, col=1)\n fig.add_trace(go.Scatter(name='',x=ww, y=numpy.log10(Y_in)[:,2,0],\n fill=None,\n mode='lines',\n line_color='limegreen',\n showlegend=False), row=3, col=1)\n\n fig.add_trace(go.Scatter(name='MonteCarlo',x=ww, y=numpy.log10(Y_in)[:,0,1],\n fill='tonexty',\n mode='lines',\n line_color='limegreen'), row=1, col=1)\n fig.add_trace(go.Scatter(name='',x=ww, y=numpy.log10(Y_in)[:,1,1],\n fill='tonexty',\n mode='lines',\n line_color='limegreen',\n showlegend=False), row=2, col=1)\n fig.add_trace(go.Scatter(name='',x=ww, y=numpy.log10(Y_in)[:,2,1],\n fill='tonexty',\n mode='lines',\n line_color='limegreen',\n showlegend=False), row=3, col=1)\n\n # Case without uncertainty\n kwargs = { # inputs required by the library module\n 'w_range':W_PLOT_RANGE,\n 'm':M_inp_SI,\n 'k':K_inp_SI,\n 'c':C_inp_SI,\n 'n':PLOT_DEFINITION,\n 'exci_floor':Exci,\n }\n ww,Y_pr = msd3.displacement_msd_numpy_abs_ww(**kwargs) \n fig.add_trace(go.Scatter(name = 'Nominal',x=ww, y=numpy.log10(Y_pr)[:,0],line_color='orangered'), row=1, col=1)\n fig.add_trace(go.Scatter(x=ww, y=numpy.log10(Y_pr)[:,1],line_color='orangered',showlegend=False), row=2, col=1)\n fig.add_trace(go.Scatter(x=ww, y=numpy.log10(Y_pr)[:,2],line_color='orangered',showlegend=False), row=3, col=1) \n \n # Update xaxis properties\n fig.update_xaxes(title_text='[Hz]', titlefont=dict(size=14), row=3, col=1) # fig.update_xaxes(type=\"log\")\n fig.update_yaxes(title_text='[dB]', titlefont=dict(size=14), row=1, col=1)\n fig.update_yaxes(title_text='[dB]', titlefont=dict(size=14), row=2, col=1)\n fig.update_yaxes(title_text='[dB]', titlefont=dict(size=14), row=3, col=1)\n # fig.update_yaxes(range=[-150, 0])\n fig.update_layout(title_text=\"Bounds on displacement Frequency Response Function (FRF)\",\\\n showlegend=True,\\\n font=dict(size=14),\\\n plot_bgcolor= 'rgba(0, 0, 0, 0.1)',paper_bgcolor= 'rgba(0, 0, 0, 0)') #paper_bgcolor= 'rgba(0, 0, 0, 0.05)'\n\n sideplot = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)\n\n def Lo(inp,e):\n return inp * (1-e)\n def Hi(inp,e):\n return inp * (1+e)\n\n M_lo = [Lo(mi,me) for mi,me in zip(M_inp,M_e)]#, Lo(M_inp_2,M_e), Lo(M_inp_3,M_e)]\n M_hi = [Hi(mi,me) for mi,me in zip(M_inp,M_e)]#, Hi(M_inp_2,M_e), Hi(M_inp_3,M_e)]\n K_lo = [Lo(ki,ke) for ki,ke in zip(K_inp,K_e)]#[Lo(K_inp_1,K_e), Lo(K_inp_2,K_e), Lo(K_inp_3,K_e)]\n K_hi = [Hi(ki,ke) for ki,ke in zip(K_inp,K_e)]#[Lo(K_inp_1,K_e), Lo(K_inp_2,K_e), Lo(K_inp_3,K_e)]\n C_lo = [Lo(ci,ce) for ci,ce in zip(C_inp,C_e)]#C_lo = [Lo(C_inp_1,C_e), Lo(C_inp_2,C_e), Lo(C_inp_3,C_e)]\n C_hi = [Hi(ci,ce) for ci,ce in zip(C_inp,C_e)]#C_hi = [Hi(C_inp_1,C_e), Hi(C_inp_2,C_e), Hi(C_inp_3,C_e)]\n\n M_val = [float(M_inp_1), float(M_inp_2), float(M_inp_3)]\n K_val = [float(K_inp_1), float(K_inp_2), float(K_inp_3)]\n C_val = [float(C_inp_1), float(C_inp_2), float(C_inp_3)]\n\n return render_template(\"unquant.html\", UNC = maxUnc, MCsamp=MCsamp, \\\n M_val = M_val, M_e = M_e, M_slider = M_slider, M_lo = M_lo, M_hi = M_hi,\\\n K_val = K_val, K_e = K_e, K_slider = K_slider, K_lo = K_lo, K_hi = K_hi,\\\n C_val = C_val, C_e = C_e, C_slider = C_slider, C_lo = C_lo, C_hi = C_hi,\\\n Exci = Exci, plot = sideplot,date=date) #, \\\n else: # on page re-load and landing\n fig = make_subplots(rows=3, cols=1, subplot_titles=(\"Floor 3\", \"Floor 2\", \"Floor 1\"),shared_xaxes=False)\n fig.update_layout(width=PLOT_WIDTH, height=PLOT_HEIGHT) \n\n M_inp = [M_inp_1, M_inp_2, M_inp_3]\n M_inp_SI = [1e4 * mi for mi in M_inp]\n K_inp = [ K_inp_1, K_inp_2, K_inp_3]\n K_inp_SI = [1e8 * ki for ki in K_inp]\n C_inp = [ C_inp_1, C_inp_2, C_inp_3]\n C_inp_SI = [1e4 * ci for ci in C_inp]\n\n kwargs = { # inputs required by the library module\n 'w_range':W_PLOT_RANGE,\n 'm':M_inp_SI,\n 'k':K_inp_SI,\n 'c':C_inp_SI,\n 'n':PLOT_DEFINITION,\n 'exci_floor':Exci,\n }\n\n ww,Y_pr = msd3.displacement_msd_numpy_abs_ww(**kwargs) \n\n fig.add_scatter(x=ww, y=numpy.log10(Y_pr)[:,0], name='', mode = 'lines', row=1, col=1)\n fig.add_scatter(x=ww, y=numpy.log10(Y_pr)[:,1], name='', mode = 'lines', row=2, col=1)\n fig.add_scatter(x=ww, y=numpy.log10(Y_pr)[:,2], name='', mode = 'lines', row=3, col=1)\n\n # Update xaxis properties\n fig.update_xaxes(title_text='Frequency [Hz]', titlefont=dict(size=14), row=3, col=1)\n fig.update_yaxes(title_text='[dB]', titlefont=dict(size=14), row=1, col=1)\n fig.update_yaxes(title_text='[dB]', titlefont=dict(size=14), row=2, col=1)\n fig.update_yaxes(title_text='[dB]', titlefont=dict(size=14), row=3, col=1)\n\n fig.update_layout(title_text=\"Bounds on displacement Frequency Response Function (FRF)\",\\\n showlegend=False,\\\n font=dict(size=14),\\\n plot_bgcolor= 'rgba(0, 0, 0, 0.1)', paper_bgcolor= 'rgba(0, 0, 0, 0.0)')\n \n sideplot = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)\n\n M_val = [float(M_INP_1), float(M_INP_2), float(M_INP_3)]\n K_val = [float(K_INP_1), float(K_INP_2), float(K_INP_3)]\n C_val = [float(C_INP_1), float(C_INP_2), float(C_INP_3)]\n return render_template(\"unquant.html\", UNC = maxUnc, MCsamp=MCsamp,\\\n M_val = M_val, M_e = [0]*3, M_slider = [0]*3, M_lo = M_val, M_hi = M_val,\\\n K_val = K_val, K_e = [0]*3, K_slider = [0]*3, K_lo = K_val, K_hi = K_val,\\\n C_val = C_val, C_e = [0]*3, C_slider = [0]*3, C_lo = C_val, C_hi = C_val,\\\n Exci=Exci, plot=sideplot,date=date)", "'''\nThis function compares the experimental data of each structure with the simulation results of their respective numerical model.\n'''\nimport numpy as np\nimport plotly\nimport plotly.graph_objs as go\nfrom plotly.subplots import make_subplots\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport json\n\ndataSwExp = pd.read_csv('dtLib/crossval/Data/Experimental Data/ExpDataSw.csv',header=None,sep=\",\")\ndataShExp = pd.read_csv('dtLib/crossval/Data/Experimental Data/ExpDataSh.csv',header=None,sep=\",\")\ndataSoExp = pd.read_csv('dtLib/crossval/Data/Experimental Data/ExpDataSo.csv',header=None,sep=\",\")\ndataBrExp = pd.read_csv('dtLib/crossval/Data/Experimental Data/ExpDataBr.csv',header=None,sep=\",\")\n\ndataSwNum = pd.read_csv('dtLib/crossval/Data/Numerical Data/NumDataSw.csv',header=None,sep=\",\")\ndataShNum = pd.read_csv('dtLib/crossval/Data/Numerical Data/NumDataSh.csv',header=None,sep=\",\")\ndataSoNum = pd.read_csv('dtLib/crossval/Data/Numerical Data/NumDataSo.csv',header=None,sep=\",\")\ndataBrNum = pd.read_csv('dtLib/crossval/Data/Numerical Data/NumDataBr.csv',header=None,sep=\",\")\n\nLimitsExp = np.array([0,322,6561,1313,80002]) #0/Sw/Sh/So/Br\nLimitsNum = np.array([0,3998,3998,3992,400]) #0/Sw/Sh/So/Br\n\n################################ Experimental Data ######################\ntSW=dataSwExp.iloc[LimitsExp[0]:LimitsExp[1],0]\nyoutSW = [dataSwExp.iloc[LimitsExp[0]:LimitsExp[1],1],dataSwExp.iloc[LimitsExp[0]:LimitsExp[1],2],dataSwExp.iloc[LimitsExp[0]:LimitsExp[1],3]]\n\ntSH=dataShExp.iloc[LimitsExp[0]:LimitsExp[2],0]\nyoutSH = [dataShExp.iloc[LimitsExp[0]:LimitsExp[2],1],dataShExp.iloc[LimitsExp[0]:LimitsExp[2],2],dataShExp.iloc[LimitsExp[0]:LimitsExp[2],3]]\n\ntSO=dataSoExp.iloc[LimitsExp[0]:LimitsExp[3],0]\nyoutSO = [dataSoExp.iloc[LimitsExp[0]:LimitsExp[3],1],dataSoExp.iloc[LimitsExp[0]:LimitsExp[3],2],dataSoExp.iloc[LimitsExp[0]:LimitsExp[3],3]]\n\ntBR=dataBrExp.iloc[LimitsExp[0]:LimitsExp[4],0]\nyoutBR = [dataBrExp.iloc[LimitsExp[0]:LimitsExp[4],1],dataBrExp.iloc[LimitsExp[0]:LimitsExp[4],2],dataBrExp.iloc[LimitsExp[0]:LimitsExp[4],3]]\n################################ Numerical Data ######################\ntNumSW=dataSwNum.iloc[LimitsNum[0]:LimitsNum[1],0]\ntNumSWmiddle=dataSwNum.iloc[LimitsNum[0]:LimitsNum[1],1]\nyoutNumSW = [dataSwNum.iloc[LimitsNum[0]:LimitsNum[1],2],dataSwNum.iloc[LimitsNum[0]:LimitsNum[1],3],dataSwNum.iloc[LimitsNum[0]:LimitsNum[1],4]]\n\ntNumSH=dataShNum.iloc[LimitsNum[0]:LimitsNum[2],0]\ntNumSHmiddle=dataShNum.iloc[LimitsNum[0]:LimitsNum[2],1]\nyoutNumSH = [dataShNum.iloc[LimitsNum[0]:LimitsNum[2],2],dataShNum.iloc[LimitsNum[0]:LimitsNum[2],3],dataShNum.iloc[LimitsNum[0]:LimitsNum[2],4]]\n\ntNumSO=dataSoNum.iloc[LimitsNum[0]:LimitsNum[3],0]\nyoutNumSO = [dataSoNum.iloc[LimitsNum[0]:LimitsNum[3],1],dataSoNum.iloc[LimitsNum[0]:LimitsNum[3],2],dataSoNum.iloc[LimitsNum[0]:LimitsNum[3],3]]\n\ntNumBR=dataBrNum.iloc[LimitsNum[0]:LimitsNum[4],0]\nyoutNumBR = [dataBrNum.iloc[LimitsNum[0]:LimitsNum[4],1],dataBrNum.iloc[LimitsNum[0]:LimitsNum[4],2],dataBrNum.iloc[LimitsNum[0]:LimitsNum[4],3]]\n\n" ]
[ [ "numpy.log10" ], [ "numpy.array", "pandas.read_csv" ] ]
nephilim2016/AutoEncoder-for-GPR-Denoise
[ "b55be16bd0b6af785efcf072d68dd5523a72f964" ]
[ "DisplayForward.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 22 20:29:07 2020\n\n@author: nephilim\n\"\"\"\n\nimport numpy as np\nimport skimage.transform\nimport T_PowerGain\nimport DataNormalized\nfrom matplotlib import pyplot,cm\n\n\n# Read Target Profile\nProfileTarget=np.load('./GPR_Modelling/ProfileAutoEncoder/33_iter_record_0_comp.npy')\nProfileTargetGain=T_PowerGain.tpowGain(ProfileTarget,np.arange(7000),1.2)\nProfileTargetGain=DataNormalized.DataNormalized(ProfileTargetGain)/255 \npyplot.imshow(ProfileTargetGain,vmin=np.min(ProfileTargetGain),vmax=np.max(ProfileTargetGain),extent=(0,5,5,0))" ]
[ [ "numpy.load", "numpy.max", "numpy.arange", "numpy.min" ] ]
canerturkmen/tensorseason
[ "d0b5331867705b388209e5f47122780a2b784bd1" ]
[ "src/tensorseason/experiment.py" ]
[ "import json\nfrom pathlib import Path\nfrom random import sample\nfrom typing import List, Dict, Type, Tuple, Callable\nfrom uuid import uuid4\n\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom .forecaster import (\n CPForecaster,\n DCTForecaster,\n DFTForecaster,\n FourierBasisRegressionForecaster,\n HoltWintersForecaster,\n SeasonalForecaster,\n TuckerForecaster, SmoothingTuckerForecaster, SmoothingCPForecaster,\n)\nfrom .utils import (\n get_param_sweep, mad, rmse, trend_cycle_decompose\n)\n\n\nclass SingleForecasterExperiment:\n\n def __init__(\n self,\n forecaster_class: Type[SeasonalForecaster],\n param_sweep: List[int],\n folds: Tuple[int],\n error_callbacks: Tuple[Callable] = (rmse, mad)\n ):\n self.fcaster_getter = lambda x: forecaster_class(\n nr_params=x, folds=folds, error_callbacks=error_callbacks\n )\n self.param_sweep = param_sweep\n self.error_callbacks = error_callbacks\n self.forecaster_class = forecaster_class\n\n def __call__(self, vals: pd.Series, nr_in_cycles: int) -> Tuple[Dict, Dict, List, List]:\n\n in_errors, out_errors, results = [], [], []\n total_params = []\n\n for n in self.param_sweep:\n fcaster = self.fcaster_getter(n)\n result = fcaster(vals, nr_in_cycles=nr_in_cycles)\n\n results.append(result)\n in_errors.append(result.in_errors)\n out_errors.append(result.out_errors)\n total_params.append(result.nr_total_params)\n\n in_errors_dict, out_errors_dict = [\n dict(\n zip(\n [f.__name__ for f in self.error_callbacks],\n zip(*errors)\n )\n ) for errors in [in_errors, out_errors]\n ]\n\n return in_errors_dict, out_errors_dict, total_params, results\n\n\nclass TensorSeasonExperiment:\n \"\"\"\n\n Parameters\n ----------\n dataset_name: str\n The dataset name to run the experiments on. There must be a directory under\n `datasets/` with a matching name, which contains JSON files in GluonTS data set\n format (with \"start\" and \"target\" keys).\n folds: Tuple[int]\n Number of `folds` in the multiple seasonal pattern, with the fastest index first.\n For example, (24, 7).\n nr_in_cycles: int\n Number of cycles (a cycle has np.prod(folds) length) to consider in sample.\n nr_examples: int\n `nr_examples` many time series will be sampled (without replacement) from the data set\n in order to perform experiments. If -1, all time series will be used.\n dft_sweep_length: int\n number of parameters in DFT and DCT\n tensor_sweep_length: int\n number of parameters (ranks) for tensor based methods\n n_jobs: int\n If greater than 1, joblib will be used to parallelize the experiment on `n_jobs`\n workers.\n \"\"\"\n def __init__(\n self,\n dataset_name: str,\n folds: Tuple[int],\n nr_in_cycles: int,\n nr_examples: int = 10,\n dft_sweep_length: int = 100,\n tensor_sweep_length: int = 8,\n data_freq: str = \"1h\",\n n_jobs: int = 1,\n dataset_path: str = \"datasets/\",\n ) -> None:\n self.dataset_name = dataset_name\n self.nr_in_cycles = nr_in_cycles\n self.folds = folds\n self.nr_examples = nr_examples\n self.dft_sweep_length = dft_sweep_length\n self.tensor_sweep_length = tensor_sweep_length\n self.data_freq = data_freq\n self.n_jobs = n_jobs\n\n data_path = Path.iterdir(Path(dataset_path) / self.dataset_name)\n self.data_path_list = [\n d for d in data_path if \".DS_Store\" not in str(d)\n ]\n self.data_indices = (\n sample(range(len(self.data_path_list)), nr_examples)\n if nr_examples > 0\n else list(range(len(self.data_path_list)))\n )\n\n def _get_dataset(self) -> List[Dict]:\n dataset = []\n for i in self.data_indices:\n with open(self.data_path_list[i]) as fp:\n dataset.append(json.load(fp))\n return dataset\n\n def _get_experiments(self) -> List[SingleForecasterExperiment]:\n dft_sweep = get_param_sweep(\n int(np.prod(self.folds)), \"log\", self.dft_sweep_length\n )\n tensor_sweep = list(range(1, self.tensor_sweep_length))\n fbm_sweep = list(range(1, 40))\n\n experiments = [\n SingleForecasterExperiment(DCTForecaster, dft_sweep, folds=self.folds),\n SingleForecasterExperiment(DFTForecaster, dft_sweep, folds=self.folds),\n SingleForecasterExperiment(CPForecaster, tensor_sweep, folds=self.folds),\n SingleForecasterExperiment(SmoothingCPForecaster, tensor_sweep, folds=self.folds),\n SingleForecasterExperiment(TuckerForecaster, tensor_sweep, folds=self.folds),\n SingleForecasterExperiment(SmoothingTuckerForecaster, tensor_sweep, folds=self.folds),\n SingleForecasterExperiment(FourierBasisRegressionForecaster, fbm_sweep, folds=self.folds),\n SingleForecasterExperiment(HoltWintersForecaster, [1], folds=self.folds),\n ]\n\n return experiments\n\n def run(self):\n def process_dataset(data, exp_id_):\n frames_ = []\n\n time_index = pd.date_range(\n start=pd.Timestamp(data[\"start\"]),\n periods=len(data[\"target\"]),\n freq=self.data_freq,\n )\n\n orig_data_df = pd.Series(\n data[\"target\"],\n index=time_index,\n )\n tc, vals = trend_cycle_decompose(orig_data_df, w=int(2 * np.prod(self.folds)))\n vals = vals / (vals.max() - vals.min()) # scale the residuals\n\n exps_ = self._get_experiments()\n\n for experiment in exps_:\n try:\n ins, outs, pars, _ = experiment(vals, nr_in_cycles=self.nr_in_cycles)\n\n result_columns = {}\n for err in ins:\n result_columns[f\"in_{err}\"] = ins[err]\n for err in outs:\n result_columns[f\"out_{err}\"] = outs[err]\n\n results = pd.DataFrame(\n dict(\n parameters=pars,\n **result_columns,\n )\n )\n results[\"experiment_id\"] = exp_id_\n results[\"dataset\"] = self.dataset_name\n results[\"model\"] = experiment.forecaster_class.__name__\n results[\"data_id\"] = data[\"id\"]\n\n frames_.append(results)\n\n except Exception as e:\n print(f\"Exception encountered at {experiment.forecaster_class}, data id: {data['id']}\")\n\n return pd.concat(frames_)\n\n dataset = self._get_dataset()\n experiment_id = str(uuid4())\n\n if self.n_jobs > 1:\n from joblib import Parallel, delayed\n frames = Parallel(n_jobs=self.n_jobs)(\n delayed(process_dataset)(dataset[i], experiment_id) for i in tqdm(range(len(dataset)))\n )\n else:\n frames = [process_dataset(data, experiment_id) for data in tqdm(dataset)]\n\n return pd.concat(frames)\n" ]
[ [ "pandas.concat", "pandas.Timestamp", "pandas.Series", "numpy.prod" ] ]
silviaclaire/image-classifier-for-flowers
[ "040a1d6425bde6f7f375890b1023f4d5be60843a" ]
[ "predict.py" ]
[ "import os\r\nimport glob\r\nimport json\r\nimport torch\r\nimport random\r\nimport argparse\r\nimport numpy as np\r\nfrom PIL import Image\r\n\r\nfrom model import create_model\r\nfrom utils import line, Params\r\n\r\n\r\nparser = argparse.ArgumentParser(description='Predict flower name from an image.')\r\n\r\nparser.add_argument('image_filepath', action='store',\r\n help='Filepath of an image')\r\n\r\nparser.add_argument('checkpoint_filepath', action='store',\r\n help='Filepath of a checkpoint created by train.py')\r\n\r\nparser.add_argument('--category_names ', action='store',\r\n dest='category_names', default='cat_to_name.json',\r\n help='Use a mapping of categories to real names')\r\n\r\nparser.add_argument('--top_k', action='store',\r\n dest='top_k', default=5, type=int,\r\n help='Return top K most likely classes')\r\n\r\nparser.add_argument('--gpu', action='store_true',\r\n dest='use_gpu', default=False,\r\n help='Use GPU for training')\r\n\r\ncfg = parser.parse_args()\r\n# random_idx = str(random.randint(1, 102))\r\n# image_list = glob.glob(f'flowers/test/{random_idx}/*.jpg')\r\n# image_path = random.choice(image_list)\r\n# with open('cat_to_name.json', 'r') as f:\r\n# cat_to_name = json.load(f)\r\n# line()\r\n# print(f'answer: {cat_to_name[random_idx]}')\r\n# cfg = parser.parse_args([image_path, 'checkpoint_cli.pth', '--gpu'])\r\n\r\nline()\r\nprint('Configs:')\r\nprint('image_filepath = {!r}'.format(cfg.image_filepath))\r\nprint('checkpoint_filepath = {!r}'.format(cfg.checkpoint_filepath))\r\nprint('category_names = {!r}'.format(cfg.category_names))\r\nprint('top_k = {!r}'.format(cfg.top_k))\r\nprint('use_gpu = {!r}'.format(cfg.use_gpu))\r\nline()\r\n\r\n# get device\r\nif cfg.use_gpu:\r\n device = torch.device('cuda')\r\nelse:\r\n device = torch.device('cpu')\r\n\r\n\r\ndef process_image(image_filepath):\r\n ''' Scales, crops, and normalizes a PIL image for a PyTorch model,\r\n returns an Numpy array\r\n '''\r\n image = Image.open(image_filepath)\r\n\r\n # resize the images where the shortest side is 256 pixels, keeping the aspect ratio\r\n if image.width > image.height:\r\n target_height = 256\r\n target_width = image.width * 256 / image.height\r\n else:\r\n target_width = 256\r\n target_height = image.height * 256 / image.width\r\n image.thumbnail((target_width, target_height))\r\n\r\n # center crop 224x224\r\n left = (image.width - 224) / 2\r\n top = (image.height - 224) / 2\r\n right = (image.width + 224) / 2\r\n bottom = (image.height + 224) / 2\r\n image = image.crop((left, top, right, bottom))\r\n\r\n # convert to numpy array\r\n image = np.array(image)\r\n\r\n # Scale all values between 0 and 1\r\n image = image / 255\r\n\r\n # Normalize based on the preset mean and standard deviation\r\n mean = np.array([0.485, 0.456, 0.406])\r\n std = np.array([0.229, 0.224, 0.225])\r\n for i in range(2):\r\n image[i] = (image[i] - mean[i]) / std[i]\r\n\r\n # reorder dimensions\r\n image = image.transpose((2, 0, 1))\r\n\r\n return image\r\n\r\n\r\ndef predict(image_filepath, model, topk=5):\r\n ''' Predict the class (or classes) of an image using a trained deep learning model.\r\n '''\r\n # preprocess image\r\n image = process_image(image_filepath)\r\n image = torch.from_numpy(image).float().to(device)\r\n\r\n # add a fourth dimension to the beginning to indicate batch size\r\n image.unsqueeze_(0)\r\n\r\n # pass the image through our model\r\n model.eval()\r\n output = model.forward(image)\r\n\r\n # reverse the log function in our output\r\n output = torch.exp(output)\r\n\r\n # get the top predicted class, and the output percentage for that class\r\n probs, idxs = output.topk(topk, dim=1)\r\n probs = probs.data.cpu().numpy()[0]\r\n idxs = idxs.data.cpu().numpy()[0]\r\n\r\n # map index to class\r\n idx_to_class = {v: k for k, v in model.class_to_idx.items()}\r\n classes = [idx_to_class[idx] for idx in idxs]\r\n\r\n return probs, classes\r\n\r\n\r\n# create model from checkpoint\r\ncheckpoint = torch.load(cfg.checkpoint_filepath)\r\nmodel, _, _ = create_model(Params(checkpoint))\r\nmodel.class_to_idx = checkpoint['class_to_idx']\r\nmodel.load_state_dict(checkpoint['model_state_dict'])\r\nmodel.to(device)\r\n\r\n# predict image\r\nprobs, classes = predict(cfg.image_filepath, model, topk=cfg.top_k)\r\n\r\n# covert classes to names\r\nwith open(cfg.category_names, 'r') as f:\r\n cat_to_name = json.load(f)\r\nlabels = [cat_to_name[c] for c in classes]\r\n\r\n# output prediction result\r\ntop_k_result = {label: prob for label, prob in zip(labels, probs)}\r\nprint('prediction:')\r\nprint(top_k_result)\r\nline()\r\n" ]
[ [ "torch.load", "torch.from_numpy", "torch.exp", "torch.device", "numpy.array" ] ]
nomad-coe/nomad-parser-quantum-espresso
[ "25362db6dc24fc106596fedc043c6ad564bc160f" ]
[ "quantumespressoparser/metainfo/quantum_espresso.py" ]
[ "#\n# Copyright The NOMAD Authors.\n#\n# This file is part of NOMAD.\n# See https://nomad-lab.eu for further info.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport numpy as np # pylint: disable=unused-import\nimport typing # pylint: disable=unused-import\nfrom nomad.metainfo import ( # pylint: disable=unused-import\n MSection, MCategory, Category, Package, Quantity, Section, SubSection, SectionProxy,\n Reference\n)\nfrom nomad.metainfo.legacy import LegacyDefinition\n\nfrom nomad.datamodel.metainfo import public\n\nm_package = Package(\n name='quantum_espresso_nomadmetainfo_json',\n description='None',\n a_legacy=LegacyDefinition(name='quantum_espresso.nomadmetainfo.json'))\n\n\nclass x_qe_section_parallel(MSection):\n '''\n section for run-time parallization options of Quantum Espresso\n '''\n\n m_def = Section(validate=False, a_legacy=LegacyDefinition(name='x_qe_section_parallel'))\n\n x_qe_nthreads = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Number of OpenMP threads\n ''',\n a_legacy=LegacyDefinition(name='x_qe_nthreads'))\n\n x_qe_nproc = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Number of MPI ranks\n ''',\n a_legacy=LegacyDefinition(name='x_qe_nproc'))\n\n x_qe_npool = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Number of K-Point pools\n ''',\n a_legacy=LegacyDefinition(name='x_qe_npool'))\n\n\nclass x_qe_section_compile_options(MSection):\n '''\n section for compile-time options of Quantum Espresso\n '''\n\n m_def = Section(validate=False, a_legacy=LegacyDefinition(name='x_qe_section_compile_options'))\n\n x_qe_ntypx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Maximum number of different atom species\n ''',\n a_legacy=LegacyDefinition(name='x_qe_ntypx'))\n\n x_qe_ndmx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Maximum dimension of radial grid (Pseudopotential)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_ndmx'))\n\n x_qe_npk = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Maximum number of k-points\n ''',\n a_legacy=LegacyDefinition(name='x_qe_npk'))\n\n x_qe_lmaxx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Maximum non local angular momentum (Pseudopotential)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_lmaxx'))\n\n x_qe_nbrx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Maximum number of beta functions (Pseudopotential)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_nbrx'))\n\n x_qe_nqfx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Maximum number of coefficients in Q smoothing (Pseudopotential)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_nqfx'))\n\n x_qe_nchix = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Maximum number of atomic wavefunctions per Pseudopotential\n ''',\n a_legacy=LegacyDefinition(name='x_qe_nchix'))\n\n x_qe_compile_parallel_version = Quantity(\n type=str,\n shape=[],\n description='''\n Parallelization compile-time options\n ''',\n a_legacy=LegacyDefinition(name='x_qe_compile_parallel_version'))\n\n\nclass x_qe_t_section_pp_report(MSection):\n '''\n section to collect 'pseudopotential report' information in new QE, used only for\n 'old', non-UPF pseudopotentials\n '''\n\n m_def = Section(validate=False, a_legacy=LegacyDefinition(name='x_qe_t_section_pp_report'))\n\n x_qe_t_pp_report_species = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: PP report: species number\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_report_species'))\n\n x_qe_t_pp_report_version = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: PP report: pp version\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_report_version'))\n\n x_qe_t_pp_report_line = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: PP report: parsed line\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_report_line'))\n\n\nclass x_qe_t_section_pp_warning(MSection):\n '''\n section to collect 'pseudopotential warning' information in old QE\n '''\n\n m_def = Section(validate=False, a_legacy=LegacyDefinition(name='x_qe_t_section_pp_warning'))\n\n x_qe_t_pp_warning_idx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: renormalized WFCs in pseudopotential: pp index\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_warning_idx'))\n\n x_qe_t_pp_warning_filename = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: renormalized WFCs in pseudopotential: filename\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_warning_filename'))\n\n x_qe_t_pp_warning_wfcidx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: renormalized WFCs in pseudopotential: pseudo-wavefunction index\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_warning_wfcidx'))\n\n x_qe_t_pp_warning_wfclabel = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: renormalized WFCs in pseudopotential: pseudo-wavefunction label\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_warning_wfclabel'))\n\n x_qe_t_pp_warning_wfcnorm = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: renormalized WFCs in pseudopotential: pseudo-wavefunction original norm\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_warning_wfcnorm'))\n\n\nclass x_qe_t_section_pseudopotential(MSection):\n '''\n pseudo-section for collecting pseudopotential data (atomic number lookup requires\n table printed later in output)\n '''\n\n m_def = Section(validate=False, a_legacy=LegacyDefinition(name='x_qe_t_section_pseudopotential'))\n\n x_qe_t_pp_idx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: Index of Pseudopotential on Espresso side\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_idx'))\n\n x_qe_t_pp_ndmx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: Radial grid of Pseudopotential on Espresso side\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_ndmx'))\n\n x_qe_t_pp_label = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: Label of Pseudopotential on Espresso side\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_label'))\n\n x_qe_t_pp_filename = Quantity(\n type=str,\n shape=[],\n description='''\n Filename of pseudopotential\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_filename'))\n\n x_qe_t_pp_type = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: Type of pseudopotential, e.g. 'Norm-conserving' or 'Ultrasoft'\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_type'))\n\n x_qe_t_pp_md5sum = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: MD5 checksum of pseudopotential file\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_md5sum'))\n\n x_qe_t_pp_comment = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: comment about pseudopotential\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_comment'))\n\n x_qe_t_pp_integral_ndirections = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: number of integration directions (PAW)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_integral_ndirections'))\n\n x_qe_t_pp_integral_lmax_exact = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: maximum l for which integration is exact (PAW)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_integral_lmax_exact'))\n\n x_qe_t_pp_augmentation_shape = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: shape of augmentation charge\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_augmentation_shape'))\n\n x_qe_t_pp_valence = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: Number of Valence electrons in pseudopotential\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_valence'))\n\n x_qe_t_pp_nbeta = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: Number of beta functions in pseudopotential on Espresso side\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_nbeta'))\n\n x_qe_t_pp_l_idx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: beta function l index in pseudopotential on Espresso side\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_l_idx'))\n\n x_qe_t_pp_l = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: beta function l in pseudopotential on Espresso side\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_l'))\n\n x_qe_t_pp_ncoefficients = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: Number of coefficients in pseudopotential\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_ncoefficients'))\n\n x_qe_t_rinner = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: Inner Radii of pseudopotential\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_rinner'))\n\n\nclass x_qe_section_scf_diagonalization(MSection):\n '''\n section for diagonalization info in QE scf iterations\n '''\n\n m_def = Section(validate=False, a_legacy=LegacyDefinition(name='x_qe_section_scf_diagonalization'))\n\n x_qe_t_scf_diagonalization_algorithm = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: Diagonalization algorithm\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_scf_diagonalization_algorithm'))\n\n x_qe_scf_diagonalization_algorithm = Quantity(\n type=str,\n shape=[],\n description='''\n Diagonalization algorithm\n ''',\n a_legacy=LegacyDefinition(name='x_qe_scf_diagonalization_algorithm'))\n\n x_qe_scf_diagonalization_warn_n_unconverged_eigenvalues = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Number of uncoverged eigenvalues (Warning)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_scf_diagonalization_warn_n_unconverged_eigenvalues'))\n\n x_qe_scf_diagonalization_c_bands_n_unconverged_eigenvalues = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Number of uncoverged eigenvalues (Warning from function c_bands)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_scf_diagonalization_c_bands_n_unconverged_eigenvalues'))\n\n x_qe_scf_diagonalization_ethr = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Convergence Threshold in scf diagonalization\n ''',\n a_legacy=LegacyDefinition(name='x_qe_scf_diagonalization_ethr'))\n\n x_qe_scf_diagonalization_iteration_avg = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Average of iterations in scf diagonalization\n ''',\n a_legacy=LegacyDefinition(name='x_qe_scf_diagonalization_iteration_avg'))\n\n\nclass x_qe_section_bands_diagonalization(MSection):\n '''\n section for diagonalization info in QE band structure calculation\n '''\n\n m_def = Section(validate=False, a_legacy=LegacyDefinition(name='x_qe_section_bands_diagonalization'))\n\n x_qe_t_bands_diagonalization_algorithm = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: Diagonalization algorithm\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_bands_diagonalization_algorithm'))\n\n x_qe_bands_diagonalization_algorithm = Quantity(\n type=str,\n shape=[],\n description='''\n Diagonalization algorithm\n ''',\n a_legacy=LegacyDefinition(name='x_qe_bands_diagonalization_algorithm'))\n\n x_qe_bands_diagonalization_warn_n_unconverged_eigenvalues = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Number of uncoverged eigenvalues (Warning)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_bands_diagonalization_warn_n_unconverged_eigenvalues'))\n\n x_qe_bands_diagonalization_c_bands_n_unconverged_eigenvalues = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Number of uncoverged eigenvalues (Warning from function c_bands)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_bands_diagonalization_c_bands_n_unconverged_eigenvalues'))\n\n x_qe_bands_diagonalization_ethr = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Convergence Threshold in bands diagonalization\n ''',\n a_legacy=LegacyDefinition(name='x_qe_bands_diagonalization_ethr'))\n\n x_qe_bands_diagonalization_iteration_avg = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Average of iterations in bands diagonalization\n ''',\n a_legacy=LegacyDefinition(name='x_qe_bands_diagonalization_iteration_avg'))\n\n\nclass x_qe_t_section_input_occupations(MSection):\n '''\n Temporary: Section for User-specified band occupations\n '''\n\n m_def = Section(validate=False, a_legacy=LegacyDefinition(name='x_qe_t_section_input_occupations'))\n\n x_qe_t_input_occupations_spin = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: User-specified band occupations, spin channel\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_input_occupations_spin'))\n\n x_qe_t_input_occupations = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: User-specified band occupations\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_input_occupations'))\n\n\nclass section_single_configuration_calculation(public.section_single_configuration_calculation):\n\n m_def = Section(validate=False, extends_base_section=True, a_legacy=LegacyDefinition(name='section_single_configuration_calculation'))\n\n x_qe_extra_SCF = Quantity(\n type=bool,\n shape=[],\n description='''\n Extra SCF without electronic history at the end of relaxation. Triggered in\n magnetic simulations when relax converges to non-magnetic solution\n ''',\n a_legacy=LegacyDefinition(name='x_qe_extra_SCF'))\n\n x_qe_t_spin_channel = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary storage for spin channel\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_spin_channel'))\n\n x_qe_t_k_x = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for k-point, x-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_k_x'))\n\n x_qe_t_k_y = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for k-point, y-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_k_y'))\n\n x_qe_t_k_z = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for k-point, z-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_k_z'))\n\n x_qe_t_k_pw = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: number of plane waves for this k-point\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_k_pw'))\n\n x_qe_t_k_point_energies = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: k-point band energies\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_k_point_energies'))\n\n x_qe_energy_total_harris_foulkes_estimate = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Harris-Foulkes estimate of total energy\n ''',\n a_legacy=LegacyDefinition(name='x_qe_energy_total_harris_foulkes_estimate'))\n\n x_qe_energy_total_accuracy_estimate = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Accuracy estimate of total energy\n ''',\n a_legacy=LegacyDefinition(name='x_qe_energy_total_accuracy_estimate'))\n\n x_qe_energy_exchange_error_estimate = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Estimated error on exchange\n ''',\n a_legacy=LegacyDefinition(name='x_qe_energy_exchange_error_estimate'))\n\n x_qe_energy_exchange_average_fock_potential = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Averaged Fock potential\n ''',\n a_legacy=LegacyDefinition(name='x_qe_energy_exchange_average_fock_potential'))\n\n x_qe_energy_fock = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Fock energy\n ''',\n a_legacy=LegacyDefinition(name='x_qe_energy_fock'))\n\n x_qe_energy_total_paw_all_electron = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n All-electron total energy from PAW\n ''',\n a_legacy=LegacyDefinition(name='x_qe_energy_total_paw_all_electron'))\n\n x_qe_t_energy_reference_highest_occupied = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: Energy of highest occupied state\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_energy_reference_highest_occupied'))\n\n x_qe_t_energy_reference_lowest_unoccupied = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Energy of lowest unoccupied state\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_energy_reference_lowest_unoccupied'))\n\n x_qe_t_energy_reference_fermi = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: Fermi Energy\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_energy_reference_fermi'))\n\n x_qe_t_energy_reference_fermi_up = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: Fermi Energy (spin up)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_energy_reference_fermi_up'))\n\n x_qe_t_energy_reference_fermi_down = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: Fermi Energy (spin down)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_energy_reference_fermi_down'))\n\n x_qe_t_energy_decomposition_name = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: Total energy decomposition: contribution name\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_energy_decomposition_name'))\n\n x_qe_t_energy_decomposition_value = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: Total energy decomposition: contribution value\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_energy_decomposition_value'))\n\n x_qe_energy_decomposition_name = Quantity(\n type=str,\n shape=['x_qe_number_of_energy_components'],\n description='''\n Total energy decomposition: contribution name\n ''',\n a_legacy=LegacyDefinition(name='x_qe_energy_decomposition_name'))\n\n x_qe_energy_decomposition_value = Quantity(\n type=np.dtype(np.float64),\n shape=['x_qe_number_of_energy_components'],\n description='''\n Total energy decomposition: contribution value\n ''',\n a_legacy=LegacyDefinition(name='x_qe_energy_decomposition_value'))\n\n x_qe_magnetization_total = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Total per-cell magnetization\n ''',\n a_legacy=LegacyDefinition(name='x_qe_magnetization_total'))\n\n x_qe_magnetization_absolute = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Absolute per-cell magnetization\n ''',\n a_legacy=LegacyDefinition(name='x_qe_magnetization_absolute'))\n\n x_qe_convergence_iterations = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Number of iterations after which self-consistency has been achieved\n ''',\n a_legacy=LegacyDefinition(name='x_qe_convergence_iterations'))\n\n x_qe_exx_refine = Quantity(\n type=bool,\n shape=[],\n description='''\n Flag: Exact-exchange refinement is active\n ''',\n a_legacy=LegacyDefinition(name='x_qe_exx_refine'))\n\n x_qe_exx_self_consistency = Quantity(\n type=bool,\n shape=[],\n description='''\n Exact-exchange has been reached (flag)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_exx_self_consistency'))\n\n x_qe_output_datafile = Quantity(\n type=str,\n shape=[],\n description='''\n Output datafile\n ''',\n a_legacy=LegacyDefinition(name='x_qe_output_datafile'))\n\n x_qe_t_force_atom_idx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_force_atom_idx'))\n\n x_qe_t_force_x = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_force_x'))\n\n x_qe_t_force_y = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_force_y'))\n\n x_qe_t_force_z = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_force_z'))\n\n x_qe_t_dispersion_force_atom_idx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_dispersion_force_atom_idx'))\n\n x_qe_atom_dispersion_force = Quantity(\n type=np.dtype(np.float64),\n shape=['number_of_atoms', 3],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_atom_dispersion_force'))\n\n x_qe_t_dispersion_force_x = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_dispersion_force_x'))\n\n x_qe_t_dispersion_force_y = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_dispersion_force_y'))\n\n x_qe_t_dispersion_force_z = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_dispersion_force_z'))\n\n x_qe_dispersion_force_total = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_dispersion_force_total'))\n\n x_qe_force_total = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_force_total'))\n\n x_qe_force_total_scf_correction = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_force_total_scf_correction'))\n\n x_qe_pressure = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pressure'))\n\n x_qe_t_stress_x = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_stress_x'))\n\n x_qe_t_stress_y = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_stress_y'))\n\n x_qe_t_stress_z = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_stress_z'))\n\n x_qe_stress_unimplemented = Quantity(\n type=str,\n shape=[],\n description='''\n Reason why stress tensor is not implemented\n ''',\n a_legacy=LegacyDefinition(name='x_qe_stress_unimplemented'))\n\n x_qe_t_md_iteration = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: MD step: iteration number\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_iteration'))\n\n x_qe_t_projected_velocity = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: MD step: projected velocity\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_projected_velocity'))\n\n x_qe_t_md_time = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n MD step: time\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_time'))\n\n x_qe_t_md_vec_a_units = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary storage for new direct lattice vectors (vc-relax), units\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_vec_a_units'))\n\n x_qe_t_md_vec_a_alat = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for new direct lattice vectors (vc-relax), lattice parameter a\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_vec_a_alat'))\n\n x_qe_t_md_vec_a_x = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for new direct lattice vectors (vc-relax), x-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_vec_a_x'))\n\n x_qe_t_md_vec_a_y = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for new direct lattice vectors (vc-relax), y-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_vec_a_y'))\n\n x_qe_t_md_vec_a_z = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for new direct lattice vectors (vc-relax), z-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_vec_a_z'))\n\n x_qe_t_md_atom_positions_units = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary storage for new atom positions (MD, (vc-)relax), units\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_atom_positions_units'))\n\n x_qe_t_md_atom_positions_units_vcsmd = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary storage for new atom positions (MD, (vc-)relax via VCSMD), units\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_atom_positions_units_vcsmd'))\n\n x_qe_t_md_atom_labels = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary storage for new atom positions (MD, (vc-)relax), atom labels\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_atom_labels'))\n\n x_qe_t_md_atom_positions_x = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for new atom positions (MD, (vc-)relax), x-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_atom_positions_x'))\n\n x_qe_t_md_atom_positions_y = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for new atom positions (MD, (vc-)relax), y-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_atom_positions_y'))\n\n x_qe_t_md_atom_positions_z = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for new atom positions (MD, (vc-)relax), z-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_atom_positions_z'))\n\n x_qe_t_md_atom_free_x = Quantity(\n type=bool,\n shape=[],\n description='''\n Temporary storage for new atom fixed flag (MD, (vc-)relax), x-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_atom_free_x'))\n\n x_qe_t_md_atom_free_y = Quantity(\n type=bool,\n shape=[],\n description='''\n Temporary storage for new atom fixed flag (MD, (vc-)relax), y-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_atom_free_y'))\n\n x_qe_t_md_atom_free_z = Quantity(\n type=bool,\n shape=[],\n description='''\n Temporary storage for new atom fixed flag (MD, (vc-)relax), z-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_atom_free_z'))\n\n x_qe_t_new_nat2_distance = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for new 2-atom distance (MD, (vc-)relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_new_nat2_distance'))\n\n x_qe_t_md_atom_mass_label = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary storage for MD setup, atom mass, labels\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_atom_mass_label'))\n\n x_qe_t_md_atom_mass_value = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for MD setup, atom mass, value\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_atom_mass_value'))\n\n x_qe_t_md_timestep_size = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for MD setup, timestep size\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_timestep_size'))\n\n x_qe_t_md_kinetic_energy = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for MD, kinetic energy\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_kinetic_energy'))\n\n x_qe_t_md_temperature = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for MD, temperature\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_temperature'))\n\n x_qe_t_md_total_energy = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for MD, total energy\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_total_energy'))\n\n x_qe_t_md_ekin_etot = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for MD, sum of energies\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_ekin_etot'))\n\n x_qe_t_md_linear_momentum_x = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for linear momentum (MD, (vc-)relax), x-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_linear_momentum_x'))\n\n x_qe_t_md_linear_momentum_y = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for linear momentum (MD, (vc-)relax), y-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_linear_momentum_y'))\n\n x_qe_t_md_linear_momentum_z = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for linear momentum (MD, (vc-)relax), z-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_linear_momentum_z'))\n\n x_qe_t_md_write_datafile_cputime = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for cpu time after write-datafile (MD, (vc-)relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_write_datafile_cputime'))\n\n x_qe_t_md_write_datafile_mem_dynamical = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for dynamical memory after write-datafile (MD, (vc-)relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_write_datafile_mem_dynamical'))\n\n x_qe_t_md_extrapolation_charge = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary storage for charge extrapolation scheme (MD, (vc-)relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_extrapolation_charge'))\n\n x_qe_t_md_extrapolation_wfc = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary storage for wave function extrapolation scheme (MD, (vc-)relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_extrapolation_wfc'))\n\n x_qe_t_md_starting_charge = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for extrapolated starting charge (MD, (vc-)relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_starting_charge'))\n\n x_qe_t_md_starting_charge_renormalized = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for extrapolated starting charge, renormalized (MD, (vc-)relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_starting_charge_renormalized'))\n\n x_qe_t_md_max_steps_reached = Quantity(\n type=bool,\n shape=[],\n description='''\n Temporary storage for max_steps-reached flag (MD, (vc-)relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_max_steps_reached'))\n\n x_qe_t_md_end = Quantity(\n type=bool,\n shape=[],\n description='''\n Temporary storage for end-of-md flag (MD, (vc-)relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_end'))\n\n x_qe_t_md_diffusion_atomidx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary storage for diffusion coeffients (MD), atom index\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_diffusion_atomidx'))\n\n x_qe_t_md_diffusion_coefficient = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for diffusion coeffients (MD), atom coeffient\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_diffusion_coefficient'))\n\n x_qe_t_md_diffusion_coefficient_mean = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for diffusion coeffients (MD), mean coeffient\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_diffusion_coefficient_mean'))\n\n x_qe_t_md_bfgs_scf_cycles = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary storage for number of scf cycles (relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_bfgs_scf_cycles'))\n\n x_qe_t_md_bfgs_steps = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary storage for number of steps (relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_bfgs_steps'))\n\n x_qe_t_md_bfgs_energy_old = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for 'old' energy (relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_bfgs_energy_old'))\n\n x_qe_t_md_bfgs_energy_new = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for 'new' energy (relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_bfgs_energy_new'))\n\n x_qe_t_md_bfgs_enthalpy_old = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for 'old' enthalpy (relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_bfgs_enthalpy_old'))\n\n x_qe_t_md_bfgs_enthalpy_new = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for 'new' enthalpy (relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_bfgs_enthalpy_new'))\n\n x_qe_t_md_bfgs_case = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary storage for BFGS case, energy comparison (relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_bfgs_case'))\n\n x_qe_t_md_bfgs_reset = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary storage for BFGS history reset reason (relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_bfgs_reset'))\n\n x_qe_t_md_bfgs_trust_new = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for new trust radius (relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_bfgs_trust_new'))\n\n x_qe_t_md_bfgs_conv_thr_new = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for new electronic convergence threshold (relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_bfgs_conv_thr_new'))\n\n x_qe_t_md_starting_charge_negative_old = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for old negative starting charge (MD, (vc-)relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_starting_charge_negative_old'))\n\n x_qe_t_md_starting_charge_negative_new = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for new negative starting charge (MD, (vc-)relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_starting_charge_negative_new'))\n\n x_qe_t_md_starting_charge_negative_new_up = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for new negative starting charge (MD, (vc-)relax), spin up\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_starting_charge_negative_new_up'))\n\n x_qe_t_md_starting_charge_negative_new_down = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for new negative starting charge (MD, (vc-)relax), spin down\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_starting_charge_negative_new_down'))\n\n x_qe_t_md_bfgs_converged = Quantity(\n type=bool,\n shape=[],\n description='''\n Temporary storage for 'converged' flag ((vc-)relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_bfgs_converged'))\n\n x_qe_t_md_bfgs_converged_criteria = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary storage for converged criteria ((vc-)relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_bfgs_converged_criteria'))\n\n x_qe_t_md_bfgs_final_energy = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for final energy ((vc-)relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_bfgs_final_energy'))\n\n x_qe_t_md_bfgs_final_enthalpy = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for final enthalpy ((vc-)relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_bfgs_final_enthalpy'))\n\n x_qe_t_md_new_volume = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for new cell volume ((vc-)relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_new_volume'))\n\n x_qe_t_md_isolated_system_method_martyna_tuckerman_alpha = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary MD: Isolated system with Martyna-Tuckerman method, parameter alpha\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_isolated_system_method_martyna_tuckerman_alpha'))\n\n x_qe_t_md_isolated_system_method_martyna_tuckerman_beta = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary MD: Isolated system with Martyna-Tuckerman method, parameter beta\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_isolated_system_method_martyna_tuckerman_beta'))\n\n x_qe_t_md_core_charge_negative = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary MD: QE check: negative core charge\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_core_charge_negative'))\n\n x_qe_t_md_core_charge_imaginary = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary MD: QE check: imaginary core charge\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_core_charge_imaginary'))\n\n x_qe_t_relax_converged_steps = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary Relax: number of steps after which structure relaxation converged\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_relax_converged_steps'))\n\n x_qe_t_relax_final_energy = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary Relax: final energy in relaxation\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_relax_final_energy'))\n\n x_qe_t_relax_threshold_energy = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary Relax: convergence threshold on energy in relaxation\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_relax_threshold_energy'))\n\n x_qe_t_relax_threshold_force = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary Relax: convergence threshold on force components in relaxation\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_relax_threshold_force'))\n\n x_qe_t_relax_threshold_pressure = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary Relax: convergence threshold on pressure in relaxation\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_relax_threshold_pressure'))\n\n x_qe_t_md_k_info_ik = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary MD storage for k-point info, k-index\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_k_info_ik'))\n\n x_qe_t_md_k_info_vec_x = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary MD storage for k-point info, x-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_k_info_vec_x'))\n\n x_qe_t_md_k_info_vec_y = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary MD storage for k-point info, y-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_k_info_vec_y'))\n\n x_qe_t_md_k_info_vec_z = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary MD storage for k-point info, z-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_k_info_vec_z'))\n\n x_qe_t_md_k_info_wk = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary MD storage for k-point info, weight\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_md_k_info_wk'))\n\n x_qe_section_bands_diagonalization = SubSection(\n sub_section=SectionProxy('x_qe_section_bands_diagonalization'),\n repeats=True,\n a_legacy=LegacyDefinition(name='x_qe_section_bands_diagonalization'))\n\n\nclass section_run(public.section_run):\n\n m_def = Section(validate=False, extends_base_section=True, a_legacy=LegacyDefinition(name='section_run'))\n\n x_qe_program_name = Quantity(\n type=str,\n shape=[],\n description='''\n Name of program from Quantum Espresso suite\n ''',\n a_legacy=LegacyDefinition(name='x_qe_program_name'))\n\n x_qe_input_filename = Quantity(\n type=str,\n shape=[],\n description='''\n Filename input was read from\n ''',\n a_legacy=LegacyDefinition(name='x_qe_input_filename'))\n\n x_qe_t_warning = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: Warnings from Quantum Espresso\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_warning'))\n\n x_qe_warning = Quantity(\n type=str,\n shape=[],\n description='''\n Warnings from Quantum Espresso\n ''',\n a_legacy=LegacyDefinition(name='x_qe_warning'))\n\n x_qe_profile_caller = Quantity(\n type=str,\n shape=['x_qe_number_of_profiling_entries'],\n description='''\n QE profiling: caller name\n ''',\n a_legacy=LegacyDefinition(name='x_qe_profile_caller'))\n\n x_qe_profile_category = Quantity(\n type=str,\n shape=['x_qe_number_of_profiling_entries'],\n description='''\n QE profiling: category\n ''',\n a_legacy=LegacyDefinition(name='x_qe_profile_category'))\n\n x_qe_profile_function = Quantity(\n type=str,\n shape=['x_qe_number_of_profiling_entries'],\n description='''\n QE profiling: function name\n ''',\n a_legacy=LegacyDefinition(name='x_qe_profile_function'))\n\n x_qe_profile_cputime = Quantity(\n type=np.dtype(np.float64),\n shape=['x_qe_number_of_profiling_entries'],\n description='''\n QE profiling: cputime spent in function\n ''',\n a_legacy=LegacyDefinition(name='x_qe_profile_cputime'))\n\n x_qe_profile_walltime = Quantity(\n type=np.dtype(np.float64),\n shape=['x_qe_number_of_profiling_entries'],\n description='''\n QE profiling: wallclock time spent in function\n ''',\n a_legacy=LegacyDefinition(name='x_qe_profile_walltime'))\n\n x_qe_profile_ncalls = Quantity(\n type=np.dtype(np.int32),\n shape=['x_qe_number_of_profiling_entries'],\n description='''\n QE profiling: how often was function called\n ''',\n a_legacy=LegacyDefinition(name='x_qe_profile_ncalls'))\n\n x_qe_t_profile_function = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: QE profiling: function name\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_profile_function'))\n\n x_qe_t_profile_cputime = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: QE profiling: cputime spent in function\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_profile_cputime'))\n\n x_qe_t_profile_walltime = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: QE profiling: wallclock time spent in function\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_profile_walltime'))\n\n x_qe_t_profile_ncalls = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: QE profiling: how often was function called\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_profile_ncalls'))\n\n x_qe_t_profile_caller = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: QE profiling: who was the caller\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_profile_caller'))\n\n x_qe_t_profile_caller_list = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: QE profiling: who was the caller (list for each function)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_profile_caller_list'))\n\n x_qe_t_profile_category = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: QE profiling: category\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_profile_category'))\n\n x_qe_t_profile_category_list = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: QE profiling: category (list for each function)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_profile_category_list'))\n\n x_qe_input_positions_cell_dirname = Quantity(\n type=str,\n shape=[],\n description='''\n Directory where initial atom_positions and simulation_cell were read from\n ''',\n a_legacy=LegacyDefinition(name='x_qe_input_positions_cell_dirname'))\n\n x_qe_input_potential_recalculated_file = Quantity(\n type=str,\n shape=[],\n description='''\n File that was used to recalculate initial potential\n ''',\n a_legacy=LegacyDefinition(name='x_qe_input_potential_recalculated_file'))\n\n x_qe_section_parallel = SubSection(\n sub_section=SectionProxy('x_qe_section_parallel'),\n repeats=True,\n a_legacy=LegacyDefinition(name='x_qe_section_parallel'))\n\n x_qe_section_compile_options = SubSection(\n sub_section=SectionProxy('x_qe_section_compile_options'),\n repeats=True,\n a_legacy=LegacyDefinition(name='x_qe_section_compile_options'))\n\n\nclass section_method(public.section_method):\n\n m_def = Section(validate=False, extends_base_section=True, a_legacy=LegacyDefinition(name='section_method'))\n\n x_qe_t_species_dispersion_correction_label = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: DFT-D species label\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_species_dispersion_correction_label'))\n\n x_qe_t_species_dispersion_correction_vdw_radius = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: DFT-D species vdW radius\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_species_dispersion_correction_vdw_radius'))\n\n x_qe_t_species_dispersion_correction_C6 = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: DFT-D species C6 coefficient\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_species_dispersion_correction_C6'))\n\n x_qe_dispersion_correction = Quantity(\n type=bool,\n shape=[],\n description='''\n Calculation includes semi-empirical DFT-D dispersion correction\n ''',\n a_legacy=LegacyDefinition(name='x_qe_dispersion_correction'))\n\n x_qe_gamma_algorithms = Quantity(\n type=bool,\n shape=[],\n description='''\n Usage of gamma-only optimized algorithms\n ''',\n a_legacy=LegacyDefinition(name='x_qe_gamma_algorithms'))\n\n x_qe_exx_grid_same_as_k_grid = Quantity(\n type=bool,\n shape=[],\n description='''\n Exact-exchange k+q grid is the same as k grid (flag)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_exx_grid_same_as_k_grid'))\n\n x_qe_diagonalization_algorithm = Quantity(\n type=str,\n shape=[],\n description='''\n Algorithm used in subspace diagonalization\n ''',\n a_legacy=LegacyDefinition(name='x_qe_diagonalization_algorithm'))\n\n x_qe_sticks_sum_dense = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_sticks_sum_dense'))\n\n x_qe_sticks_sum_smooth = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_sticks_sum_smooth'))\n\n x_qe_sticks_sum_PW = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_sticks_sum_PW'))\n\n x_qe_sticks_sum_G_dense = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_sticks_sum_G_dense'))\n\n x_qe_sticks_sum_G_smooth = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_sticks_sum_G_smooth'))\n\n x_qe_sticks_sum_G_PW = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_sticks_sum_G_PW'))\n\n x_qe_sticks_tot_dense = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_sticks_tot_dense'))\n\n x_qe_sticks_tot_smooth = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_sticks_tot_smooth'))\n\n x_qe_sticks_tot_PW = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_sticks_tot_PW'))\n\n x_qe_sticks_old = Quantity(\n type=str,\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_sticks_old'))\n\n x_qe_t_species_integration_radius = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: radius used to integrate charge/magnetization over (per species)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_species_integration_radius'))\n\n x_qe_t_species_integration_radius_idx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: radius used to integrate charge/magnetization over (per species),\n species index\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_species_integration_radius_idx'))\n\n x_qe_fock_operator_cutoff = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Cutoff for defining the direct-space grid used to compute Fock exchange in EXX\n ''',\n a_legacy=LegacyDefinition(name='x_qe_fock_operator_cutoff'))\n\n x_qe_t_xc_functional_shortname_enforced = Quantity(\n type=str,\n shape=[],\n description='''\n Short name of User-enforced XC functional; overrides the setting implied by the\n pseudopotentials\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_xc_functional_shortname_enforced'))\n\n x_qe_potential_convergence_threshold = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Convergence threshold for potentials\n ''',\n a_legacy=LegacyDefinition(name='x_qe_potential_convergence_threshold'))\n\n x_qe_potential_mixing_beta = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Mixing scheme: parameter beta\n ''',\n a_legacy=LegacyDefinition(name='x_qe_potential_mixing_beta'))\n\n x_qe_potential_mixing_iterations = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Mixing scheme: number of previous iterations\n ''',\n a_legacy=LegacyDefinition(name='x_qe_potential_mixing_iterations'))\n\n x_qe_potential_mixing_scheme = Quantity(\n type=str,\n shape=[],\n description='''\n Mixing scheme: type of mixing\n ''',\n a_legacy=LegacyDefinition(name='x_qe_potential_mixing_scheme'))\n\n x_qe_xc_functional_user_enforced = Quantity(\n type=bool,\n shape=[],\n description='''\n True if the user enforced setting the XC functional; overrides the setting implied\n by the pseudopotentials\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_functional_user_enforced'))\n\n x_qe_xc_functional_shortname = Quantity(\n type=str,\n shape=[],\n description='''\n Short name of XC functional used in calculation\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_functional_shortname'))\n\n x_qe_xc_functional_num = Quantity(\n type=str,\n shape=[],\n description='''\n QE Index number representation of XC functional\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_functional_num'))\n\n x_qe_xc_iexch_name = Quantity(\n type=str,\n shape=[],\n description='''\n Name of XC functional (density exchange component) in Quantum Espresso context\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_iexch_name'))\n\n x_qe_xc_icorr_name = Quantity(\n type=str,\n shape=[],\n description='''\n Name of XC functional (density correlation component) in Quantum Espresso context\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_icorr_name'))\n\n x_qe_xc_igcx_name = Quantity(\n type=str,\n shape=[],\n description='''\n Name of XC functional (gradient exchange component) in Quantum Espresso context\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_igcx_name'))\n\n x_qe_xc_igcc_name = Quantity(\n type=str,\n shape=[],\n description='''\n Name of XC functional (gradient correlation component) in Quantum Espresso context\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_igcc_name'))\n\n x_qe_xc_imeta_name = Quantity(\n type=str,\n shape=[],\n description='''\n Name of XC functional (meta-gga component) in Quantum Espresso context\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_imeta_name'))\n\n x_qe_xc_inlc_name = Quantity(\n type=str,\n shape=[],\n description='''\n Name of XC functional (Van-der-Waals non-local component) in Quantum Espresso\n context\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_inlc_name'))\n\n x_qe_xc_iexch_comment = Quantity(\n type=str,\n shape=[],\n description='''\n Quantum Espresso comment about XC functional (density exchange component)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_iexch_comment'))\n\n x_qe_xc_icorr_comment = Quantity(\n type=str,\n shape=[],\n description='''\n Quantum Espresso comment about XC functional (density correlation component)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_icorr_comment'))\n\n x_qe_xc_igcx_comment = Quantity(\n type=str,\n shape=[],\n description='''\n Quantum Espresso comment about XC functional (gradient exchange component)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_igcx_comment'))\n\n x_qe_xc_igcc_comment = Quantity(\n type=str,\n shape=[],\n description='''\n Quantum Espresso comment about XC functional (gradient correlation component)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_igcc_comment'))\n\n x_qe_xc_imeta_comment = Quantity(\n type=str,\n shape=[],\n description='''\n Quantum Espresso comment about XC functional (meta-gga component)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_imeta_comment'))\n\n x_qe_xc_inlc_comment = Quantity(\n type=str,\n shape=[],\n description='''\n Quantum Espresso comment about XC functional (Van-der-Waals non-local component)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_inlc_comment'))\n\n x_qe_xc_iexch = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Quantum Espresso internal code-specific index of XC functional (density exchange\n component)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_iexch'))\n\n x_qe_xc_icorr = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Quantum Espresso internal code-specific index of XC functional (density\n correlation component)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_icorr'))\n\n x_qe_xc_igcx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Quantum Espresso internal code-specific index of XC functional (gradient exchange\n component)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_igcx'))\n\n x_qe_xc_igcc = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Quantum Espresso internal code-specific index of XC functional (gradient\n correlation component)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_igcc'))\n\n x_qe_xc_imeta = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Quantum Espresso internal code-specific index of XC functional (meta-gga\n component)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_imeta'))\n\n x_qe_xc_inlc = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Quantum Espresso internal code-specific index of XC functional (Van-der-Waals non-\n local component)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_inlc'))\n\n x_qe_t_exact_exchange_fraction = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: store fraction of exact-exchange before defining section_xc_functionals\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_exact_exchange_fraction'))\n\n x_qe_exact_exchange_fraction = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Fraction of exact-exchange in EXX-refinement\n ''',\n a_legacy=LegacyDefinition(name='x_qe_exact_exchange_fraction'))\n\n x_qe_md_max_steps = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Maximum number of ionic+electronic steps in dynamics (MD/relax) calculation\n ''',\n a_legacy=LegacyDefinition(name='x_qe_md_max_steps'))\n\n x_qe_berry_efield_direction = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Finite E-field: direction\n ''',\n a_legacy=LegacyDefinition(name='x_qe_berry_efield_direction'))\n\n x_qe_berry_efield_intensity = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Berry phase with E-field: intensity\n ''',\n a_legacy=LegacyDefinition(name='x_qe_berry_efield_intensity'))\n\n x_qe_berry_efield_strings_nk = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Berry phase with E-field: number of k-points in string\n ''',\n a_legacy=LegacyDefinition(name='x_qe_berry_efield_strings_nk'))\n\n x_qe_berry_efield_niter = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Berry phase with E-field: number of iterative cycles\n ''',\n a_legacy=LegacyDefinition(name='x_qe_berry_efield_niter'))\n\n x_qe_berry_efield = Quantity(\n type=bool,\n shape=[],\n description='''\n Berry phase with E-field: flag if berry-efield-calc was done\n ''',\n a_legacy=LegacyDefinition(name='x_qe_berry_efield'))\n\n x_qe_t_spin_orbit_magn = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: spin-orbit msg: magnetic mode (non-)collinear / (non-)magnetic\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_spin_orbit_magn'))\n\n x_qe_t_spin_orbit_mode = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: spin-orbit msg: with/without spin-orbit\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_spin_orbit_mode'))\n\n x_qe_spin_orbit = Quantity(\n type=bool,\n shape=[],\n description='''\n Spin-orbit coupling flag: with/without spin-orbit\n ''',\n a_legacy=LegacyDefinition(name='x_qe_spin_orbit'))\n\n x_qe_spin_noncollinear = Quantity(\n type=bool,\n shape=[],\n description='''\n Noncollinear spin mode\n ''',\n a_legacy=LegacyDefinition(name='x_qe_spin_noncollinear'))\n\n x_qe_t_pp_renormalized_filename = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: renormalized WFCs in pseudopotential: filename\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_renormalized_filename'))\n\n x_qe_t_pp_renormalized_wfc = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: renormalized WFCs in pseudopotential\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_pp_renormalized_wfc'))\n\n x_qe_t_allocated_array_name = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: allocated arrays, name\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_allocated_array_name'))\n\n x_qe_t_allocated_array_size = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: allocated arrays, size\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_allocated_array_size'))\n\n x_qe_t_allocated_array_dimensions = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: allocated arrays, dimensions\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_allocated_array_dimensions'))\n\n x_qe_allocated_array_name = Quantity(\n type=str,\n shape=['x_qe_allocated_arrays'],\n description='''\n Allocated arrays, name\n ''',\n a_legacy=LegacyDefinition(name='x_qe_allocated_array_name'))\n\n x_qe_allocated_array_size = Quantity(\n type=np.dtype(np.float64),\n shape=['x_qe_allocated_arrays'],\n description='''\n Allocated arrays, size\n ''',\n a_legacy=LegacyDefinition(name='x_qe_allocated_array_size'))\n\n x_qe_allocated_array_dimensions = Quantity(\n type=str,\n shape=['x_qe_allocated_arrays'],\n description='''\n Allocated arrays, dimensions\n ''',\n a_legacy=LegacyDefinition(name='x_qe_allocated_array_dimensions'))\n\n x_qe_t_temporary_array_name = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: temporary arrays, name\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_temporary_array_name'))\n\n x_qe_t_temporary_array_size = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: temporary arrays, size\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_temporary_array_size'))\n\n x_qe_t_temporary_array_dimensions = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: temporary arrays, dimensions\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_temporary_array_dimensions'))\n\n x_qe_temporary_array_name = Quantity(\n type=str,\n shape=['x_qe_temporary_arrays'],\n description='''\n Temporary arrays, name\n ''',\n a_legacy=LegacyDefinition(name='x_qe_temporary_array_name'))\n\n x_qe_temporary_array_size = Quantity(\n type=np.dtype(np.float64),\n shape=['x_qe_temporary_arrays'],\n description='''\n Temporary arrays, size\n ''',\n a_legacy=LegacyDefinition(name='x_qe_temporary_array_size'))\n\n x_qe_temporary_array_dimensions = Quantity(\n type=str,\n shape=['x_qe_temporary_arrays'],\n description='''\n Temporary arrays, dimensions\n ''',\n a_legacy=LegacyDefinition(name='x_qe_temporary_array_dimensions'))\n\n x_qe_core_charge_negative = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n QE check: negative core charge\n ''',\n a_legacy=LegacyDefinition(name='x_qe_core_charge_negative'))\n\n x_qe_core_charge_imaginary = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n QE check: imaginary core charge\n ''',\n a_legacy=LegacyDefinition(name='x_qe_core_charge_imaginary'))\n\n x_qe_core_charge_realspace = Quantity(\n type=bool,\n shape=[],\n description='''\n QE flag: core charge treated in real space\n ''',\n a_legacy=LegacyDefinition(name='x_qe_core_charge_realspace'))\n\n x_qe_starting_density_file = Quantity(\n type=str,\n shape=[],\n description='''\n Starting density from file\n ''',\n a_legacy=LegacyDefinition(name='x_qe_starting_density_file'))\n\n x_qe_starting_potential = Quantity(\n type=str,\n shape=[],\n description='''\n Starting potential\n ''',\n a_legacy=LegacyDefinition(name='x_qe_starting_potential'))\n\n x_qe_starting_charge_negative = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Starting charge (warning about negative starting charge)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_starting_charge_negative'))\n\n x_qe_starting_charge_negative_up = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Starting charge up (warning about negative starting charge)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_starting_charge_negative_up'))\n\n x_qe_starting_charge_negative_down = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Starting charge down (warning about negative starting charge)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_starting_charge_negative_down'))\n\n x_qe_starting_charge = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Starting charge\n ''',\n a_legacy=LegacyDefinition(name='x_qe_starting_charge'))\n\n x_qe_starting_charge_renormalized = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Starting charge, renormalized\n ''',\n a_legacy=LegacyDefinition(name='x_qe_starting_charge_renormalized'))\n\n x_qe_starting_wfc = Quantity(\n type=str,\n shape=[],\n description='''\n Starting Wave functions\n ''',\n a_legacy=LegacyDefinition(name='x_qe_starting_wfc'))\n\n x_qe_time_setup_cpu1_end = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n CPU time, setup up until first iteration\n ''',\n a_legacy=LegacyDefinition(name='x_qe_time_setup_cpu1_end'))\n\n x_qe_per_process_mem = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Per-process dynamical memory\n ''',\n a_legacy=LegacyDefinition(name='x_qe_per_process_mem'))\n\n x_qe_isolated_system_method = Quantity(\n type=str,\n shape=[],\n description='''\n Method used if system is assumed to be isolated\n ''',\n a_legacy=LegacyDefinition(name='x_qe_isolated_system_method'))\n\n x_qe_isolated_system_method_martyna_tuckerman_alpha = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Isolated system with Martyna-Tuckerman method, parameter alpha\n ''',\n a_legacy=LegacyDefinition(name='x_qe_isolated_system_method_martyna_tuckerman_alpha'))\n\n x_qe_isolated_system_method_martyna_tuckerman_beta = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Isolated system with Martyna-Tuckerman method, parameter beta\n ''',\n a_legacy=LegacyDefinition(name='x_qe_isolated_system_method_martyna_tuckerman_beta'))\n\n x_qe_input_occupations = Quantity(\n type=np.dtype(np.float64),\n shape=['number_of_spin_channels', 'number_of_k_points', 'number_of_eigen_values'],\n description='''\n User-specified band occupations\n ''',\n a_legacy=LegacyDefinition(name='x_qe_input_occupations'))\n\n x_qe_extrapolation_charge = Quantity(\n type=str,\n shape=[],\n description='''\n Charge extrapolation scheme (MD, (vc-)relax)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_extrapolation_charge'))\n\n x_qe_t_section_pp_report = SubSection(\n sub_section=SectionProxy('x_qe_t_section_pp_report'),\n repeats=True,\n a_legacy=LegacyDefinition(name='x_qe_t_section_pp_report'))\n\n x_qe_t_section_pp_warning = SubSection(\n sub_section=SectionProxy('x_qe_t_section_pp_warning'),\n repeats=True,\n a_legacy=LegacyDefinition(name='x_qe_t_section_pp_warning'))\n\n x_qe_t_section_pseudopotential = SubSection(\n sub_section=SectionProxy('x_qe_t_section_pseudopotential'),\n repeats=True,\n a_legacy=LegacyDefinition(name='x_qe_t_section_pseudopotential'))\n\n x_qe_t_section_input_occupations = SubSection(\n sub_section=SectionProxy('x_qe_t_section_input_occupations'),\n repeats=True,\n a_legacy=LegacyDefinition(name='x_qe_t_section_input_occupations'))\n\n\nclass section_method_atom_kind(public.section_method_atom_kind):\n\n m_def = Section(validate=False, extends_base_section=True, a_legacy=LegacyDefinition(name='section_method_atom_kind'))\n\n x_qe_dispersion_correction_vdw_radius = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n DFT-D species vdW radius\n ''',\n a_legacy=LegacyDefinition(name='x_qe_dispersion_correction_vdw_radius'))\n\n x_qe_dispersion_correction_C6 = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n DFT-D species C6 coefficient\n ''',\n a_legacy=LegacyDefinition(name='x_qe_dispersion_correction_C6'))\n\n x_qe_species_integration_radius = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Radius used to integrate charge/magnetization over (per species)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_species_integration_radius'))\n\n x_qe_pp_renormalized_wfc = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: renormalized WFCs in pseudopotential\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_renormalized_wfc'))\n\n x_qe_pp_idx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Index of Pseudopotential on Espresso side\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_idx'))\n\n x_qe_pp_label = Quantity(\n type=str,\n shape=[],\n description='''\n Label of Pseudopotential on Espresso side\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_label'))\n\n x_qe_pp_filename = Quantity(\n type=str,\n shape=[],\n description='''\n Filename of pseudopotential\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_filename'))\n\n x_qe_pp_type = Quantity(\n type=str,\n shape=[],\n description='''\n Type of pseudopotential, e.g. 'Norm-conserving' or 'Ultrasoft'\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_type'))\n\n x_qe_pp_md5sum = Quantity(\n type=str,\n shape=[],\n description='''\n MD5 checksum of pseudopotential file\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_md5sum'))\n\n x_qe_pp_comment = Quantity(\n type=str,\n shape=[],\n description='''\n Comment about pseudopotential\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_comment'))\n\n x_qe_pp_integral_ndirections = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Number of integration directions (PAW)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_integral_ndirections'))\n\n x_qe_pp_integral_lmax_exact = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Maximum l for which integration is exact (PAW)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_integral_lmax_exact'))\n\n x_qe_pp_augmentation_shape = Quantity(\n type=str,\n shape=[],\n description='''\n Shape of augmentation charge\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_augmentation_shape'))\n\n x_qe_pp_report_version = Quantity(\n type=str,\n shape=[],\n description='''\n Pseudopotential report: version of PP\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_report_version'))\n\n x_qe_pp_report_contents = Quantity(\n type=str,\n shape=[],\n description='''\n Pseudopotential report: contents of PP report\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_report_contents'))\n\n x_qe_pp_valence = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Number of Valence electrons in pseudopotential\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_valence'))\n\n x_qe_pp_weight = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n -\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_weight'))\n\n x_qe_pp_ncoefficients = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Number of coefficients in pseudopotential\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_ncoefficients'))\n\n x_qe_rinner = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: Inner Radii of pseudopotential\n ''',\n a_legacy=LegacyDefinition(name='x_qe_rinner'))\n\n x_qe_kind_mass = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Atomic mass of species\n ''',\n a_legacy=LegacyDefinition(name='x_qe_kind_mass'))\n\n x_qe_pp_ndmx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Radial grid of Pseudopotential on Espresso side\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_ndmx'))\n\n x_qe_pp_nbeta = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Number of beta functions in pseudopotential on Espresso side\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_nbeta'))\n\n x_qe_pp_l_idx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Beta function l index in pseudopotential on Espresso side\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_l_idx'))\n\n x_qe_pp_l = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Beta function l in pseudopotential on Espresso side\n ''',\n a_legacy=LegacyDefinition(name='x_qe_pp_l'))\n\n\nclass section_system(public.section_system):\n\n m_def = Section(validate=False, extends_base_section=True, a_legacy=LegacyDefinition(name='section_system'))\n\n x_qe_ibrav = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Bravais lattice index, constant during a run\n ''',\n a_legacy=LegacyDefinition(name='x_qe_ibrav'))\n\n x_qe_alat = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Lattice Parameter 'a', constant during a run and used as unit in other quantities\n ''',\n a_legacy=LegacyDefinition(name='x_qe_alat'))\n\n x_qe_cell_volume = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Volume of unit cell\n ''',\n a_legacy=LegacyDefinition(name='x_qe_cell_volume'))\n\n x_qe_number_of_species = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Number of Atom species, a.k.a. unique Atom labels; a label may include symmetry-\n breaking suffices, e.g. 'Fe1' and 'Fe2', as some quantities can only prescribed\n per species and not per site\n ''',\n a_legacy=LegacyDefinition(name='x_qe_number_of_species'))\n\n x_qe_t_number_of_electrons = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: Number of electrons in system\n ''',\n categories=[public.configuration_core],\n a_legacy=LegacyDefinition(name='x_qe_t_number_of_electrons'))\n\n x_qe_t_number_of_electrons_up = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: Number of electrons in system (spin up)\n ''',\n categories=[public.configuration_core],\n a_legacy=LegacyDefinition(name='x_qe_t_number_of_electrons_up'))\n\n x_qe_t_number_of_electrons_down = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: Number of electrons in system (spin down)\n ''',\n categories=[public.configuration_core],\n a_legacy=LegacyDefinition(name='x_qe_t_number_of_electrons_down'))\n\n x_qe_number_of_states = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Number of Kohn-Sham states/bands\n ''',\n a_legacy=LegacyDefinition(name='x_qe_number_of_states'))\n\n x_qe_md_cell_mass = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Mass of cell in MD/relax calculation\n ''',\n a_legacy=LegacyDefinition(name='x_qe_md_cell_mass'))\n\n x_qe_t_celldm = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary storage for QE cell dimensions\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_celldm'))\n\n x_qe_celldm = Quantity(\n type=np.dtype(np.float64),\n shape=[6],\n description='''\n QE cell dimensions\n ''',\n a_legacy=LegacyDefinition(name='x_qe_celldm'))\n\n x_qe_t_vec_supercell_x = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for supercell translation vector in fractional coordinates,\n x-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_vec_supercell_x'))\n\n x_qe_t_vec_supercell_y = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for supercell translation vector in fractional coordinates,\n y-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_vec_supercell_y'))\n\n x_qe_t_vec_supercell_z = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for supercell translation vector in fractional coordinates,\n z-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_vec_supercell_z'))\n\n x_qe_vec_supercell = Quantity(\n type=np.dtype(np.float64),\n shape=['x_qe_number_of_supercell_translations', 3],\n description='''\n Supercell translation vector(s) in fractional coordinates\n ''',\n a_legacy=LegacyDefinition(name='x_qe_vec_supercell'))\n\n x_qe_supercell = Quantity(\n type=bool,\n shape=[],\n description='''\n Supercell flag\n ''',\n a_legacy=LegacyDefinition(name='x_qe_supercell'))\n\n x_qe_t_vec_a_units = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary storage for direct lattice vectors, units\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_vec_a_units'))\n\n x_qe_t_vec_a_x = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for direct lattice vectors, x-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_vec_a_x'))\n\n x_qe_t_vec_a_y = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for direct lattice vectors, y-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_vec_a_y'))\n\n x_qe_t_vec_a_z = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for direct lattice vectors, z-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_vec_a_z'))\n\n x_qe_t_vec_b_x = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for reciprocal lattice vectors, x-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_vec_b_x'))\n\n x_qe_t_vec_b_y = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for reciprocal lattice vectors, y-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_vec_b_y'))\n\n x_qe_t_vec_b_z = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for reciprocal lattice vectors, z-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_vec_b_z'))\n\n x_qe_reciprocal_cell = Quantity(\n type=np.dtype(np.float64),\n shape=[3, 3],\n unit='1 / meter',\n description='''\n Reciprocal Lattice vectors (in Cartesian coordinates). The first index runs over\n the $x,y,z$ Cartesian coordinates, and the second index runs over the 3 lattice\n vectors.\n ''',\n categories=[public.configuration_core],\n a_legacy=LegacyDefinition(name='x_qe_reciprocal_cell'))\n\n x_qe_t_starting_magnetization_species = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: Starting magnetic configuration: Species name\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_starting_magnetization_species'))\n\n x_qe_t_starting_magnetization_value = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: Starting magnetic configuration: Species magnetization\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_starting_magnetization_value'))\n\n x_qe_atom_starting_magnetization = Quantity(\n type=np.dtype(np.float64),\n shape=['number_of_atoms'],\n description='''\n Starting magnetic configuration: Atom magnetization\n ''',\n a_legacy=LegacyDefinition(name='x_qe_atom_starting_magnetization'))\n\n x_qe_nsymm = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Number of detected symmetry operations\n ''',\n a_legacy=LegacyDefinition(name='x_qe_nsymm'))\n\n x_qe_nsymm_with_fractional_translation = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Number of detected symmetry operations including fractional translations\n ''',\n a_legacy=LegacyDefinition(name='x_qe_nsymm_with_fractional_translation'))\n\n x_qe_nsymm_ignored = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Number of ignored symmetry operations, due to uncommensurable fractional\n translations\n ''',\n a_legacy=LegacyDefinition(name='x_qe_nsymm_ignored'))\n\n x_qe_t_symm_inversion = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: Inversion symmetry\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_symm_inversion'))\n\n x_qe_symm_inversion = Quantity(\n type=bool,\n shape=[],\n description='''\n Inversion symmetry\n ''',\n a_legacy=LegacyDefinition(name='x_qe_symm_inversion'))\n\n x_qe_atom_idx = Quantity(\n type=np.dtype(np.int32),\n shape=['number_of_atoms'],\n description='''\n Index of atom on Espresso side\n ''',\n a_legacy=LegacyDefinition(name='x_qe_atom_idx'))\n\n x_qe_t_atpos_units = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: Units for atom position\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_atpos_units'))\n\n x_qe_t_atom_idx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: Index of atom on Espresso side\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_atom_idx'))\n\n x_qe_t_atom_labels = Quantity(\n type=str,\n shape=[],\n description='''\n Temporary: Label of atom on Espresso side\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_atom_labels'))\n\n x_qe_t_atpos_x = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for atom position, x-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_atpos_x'))\n\n x_qe_t_atpos_y = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for atom position, y-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_atpos_y'))\n\n x_qe_t_atpos_z = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for atom position, z-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_atpos_z'))\n\n x_qe_nk = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n K-point info, number of k-points\n ''',\n a_legacy=LegacyDefinition(name='x_qe_nk'))\n\n x_qe_smearing_ngauss = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n K-point info, QE number represenation of smearing technique\n ''',\n a_legacy=LegacyDefinition(name='x_qe_smearing_ngauss'))\n\n x_qe_smearing_kind = Quantity(\n type=str,\n shape=[],\n description='''\n K-point info, QE string represenation of smearing technique\n ''',\n a_legacy=LegacyDefinition(name='x_qe_smearing_kind'))\n\n x_qe_t_k_info_ik = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary storage for k-point info, k-index\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_k_info_ik'))\n\n x_qe_t_k_info_vec_x = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for k-point info, x-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_k_info_vec_x'))\n\n x_qe_t_k_info_vec_y = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for k-point info, y-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_k_info_vec_y'))\n\n x_qe_t_k_info_vec_z = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for k-point info, z-component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_k_info_vec_z'))\n\n x_qe_t_k_info_wk = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary storage for k-point info, weight\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_k_info_wk'))\n\n x_qe_k_info_ik = Quantity(\n type=np.dtype(np.int32),\n shape=['x_qe_nk'],\n description='''\n K-point info, k-index\n ''',\n a_legacy=LegacyDefinition(name='x_qe_k_info_ik'))\n\n x_qe_k_info_vec = Quantity(\n type=np.dtype(np.float64),\n shape=['x_qe_nk', 3],\n description='''\n K-point info, cartesian coordinate\n ''',\n a_legacy=LegacyDefinition(name='x_qe_k_info_vec'))\n\n x_qe_k_info_wk = Quantity(\n type=np.dtype(np.float64),\n shape=['x_qe_nk'],\n description='''\n K-point info, weight\n ''',\n a_legacy=LegacyDefinition(name='x_qe_k_info_wk'))\n\n x_qe_dense_g_cutoff = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Dense-grid info, G cutoff\n ''',\n a_legacy=LegacyDefinition(name='x_qe_dense_g_cutoff'))\n\n x_qe_dense_g_vectors = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Dense-grid info, number of G vectors\n ''',\n a_legacy=LegacyDefinition(name='x_qe_dense_g_vectors'))\n\n x_qe_t_dense_FFT_grid_x = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: Dense-grid info, FFT grid x\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_dense_FFT_grid_x'))\n\n x_qe_t_dense_FFT_grid_y = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: Dense-grid info, FFT grid y\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_dense_FFT_grid_y'))\n\n x_qe_t_dense_FFT_grid_z = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: Dense-grid info, FFT grid z\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_dense_FFT_grid_z'))\n\n x_qe_dense_FFT_grid = Quantity(\n type=np.dtype(np.int32),\n shape=[3],\n description='''\n Dense-grid info, FFT grid\n ''',\n a_legacy=LegacyDefinition(name='x_qe_dense_FFT_grid'))\n\n x_qe_smooth_g_cutoff = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Smooth-grid info, G cutoff\n ''',\n a_legacy=LegacyDefinition(name='x_qe_smooth_g_cutoff'))\n\n x_qe_smooth_g_vectors = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Smooth-grid info, number of G vectors\n ''',\n a_legacy=LegacyDefinition(name='x_qe_smooth_g_vectors'))\n\n x_qe_t_smooth_FFT_grid_x = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: Smooth-grid info, FFT grid x\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_smooth_FFT_grid_x'))\n\n x_qe_t_smooth_FFT_grid_y = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: Smooth-grid info, FFT grid y\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_smooth_FFT_grid_y'))\n\n x_qe_t_smooth_FFT_grid_z = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: Smooth-grid info, FFT grid z\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_smooth_FFT_grid_z'))\n\n x_qe_smooth_FFT_grid = Quantity(\n type=np.dtype(np.int32),\n shape=[3],\n description='''\n Smooth-grid info, FFT grid\n ''',\n a_legacy=LegacyDefinition(name='x_qe_smooth_FFT_grid'))\n\n\nclass section_XC_functionals(public.section_XC_functionals):\n\n m_def = Section(validate=False, extends_base_section=True, a_legacy=LegacyDefinition(name='section_XC_functionals'))\n\n x_qe_xc_name = Quantity(\n type=str,\n shape=[],\n description='''\n Name of XC functional component in Quantum Espresso context\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_name'))\n\n x_qe_xc_comment = Quantity(\n type=str,\n shape=[],\n description='''\n Quantum Espresso comment about meaning of XC functional component\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_comment'))\n\n x_qe_xc_index_name = Quantity(\n type=str,\n shape=[],\n description='''\n Name of Index within Quantum Espresso where XC functional component was set from\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_index_name'))\n\n x_qe_xc_index = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Index value within Quantum Espresso where XC functional component was set from\n ''',\n a_legacy=LegacyDefinition(name='x_qe_xc_index'))\n\n\nclass section_scf_iteration(public.section_scf_iteration):\n\n m_def = Section(validate=False, extends_base_section=True, a_legacy=LegacyDefinition(name='section_scf_iteration'))\n\n x_qe_t_iter_mpersite_idx = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Temporary: iteration per-site magnetization data, atom index\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_iter_mpersite_idx'))\n\n x_qe_t_iter_mpersite_charge = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: iteration per-site magnetization data, atom charge\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_iter_mpersite_charge'))\n\n x_qe_t_iter_mpersite_magn = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: iteration per-site magnetization data, atom magnetization\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_iter_mpersite_magn'))\n\n x_qe_t_iter_mpersite_constr = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Temporary: iteration per-site magnetization data, constraints\n ''',\n a_legacy=LegacyDefinition(name='x_qe_t_iter_mpersite_constr'))\n\n x_qe_iter_mpersite_idx = Quantity(\n type=np.dtype(np.int32),\n shape=['number_of_atoms'],\n description='''\n iteration per-site magnetization data, atom index\n ''',\n a_legacy=LegacyDefinition(name='x_qe_iter_mpersite_idx'))\n\n x_qe_iter_mpersite_charge = Quantity(\n type=np.dtype(np.float64),\n shape=['number_of_atoms'],\n description='''\n iteration per-site magnetization data, atom charge\n ''',\n a_legacy=LegacyDefinition(name='x_qe_iter_mpersite_charge'))\n\n x_qe_iter_mpersite_magn = Quantity(\n type=np.dtype(np.float64),\n shape=['number_of_atoms'],\n description='''\n iteration per-site magnetization data, atom magnetization\n ''',\n a_legacy=LegacyDefinition(name='x_qe_iter_mpersite_magn'))\n\n x_qe_iter_mpersite_constr = Quantity(\n type=np.dtype(np.float64),\n shape=['number_of_atoms'],\n description='''\n iteration per-site magnetization data, constraints\n ''',\n a_legacy=LegacyDefinition(name='x_qe_iter_mpersite_constr'))\n\n x_qe_iteration_efield_eeigx_re = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n E-field: expectation value of exp(iGx), real part, in iteration\n ''',\n a_legacy=LegacyDefinition(name='x_qe_iteration_efield_eeigx_re'))\n\n x_qe_iteration_efield_eeigx_im = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n E-field: expectation value of exp(iGx), imaginary part, in iteration\n ''',\n a_legacy=LegacyDefinition(name='x_qe_iteration_efield_eeigx_im'))\n\n x_qe_iteration_efield_dipole_electronic = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n E-field: Electronic dipole, in iteration\n ''',\n a_legacy=LegacyDefinition(name='x_qe_iteration_efield_dipole_electronic'))\n\n x_qe_iteration_efield_dipole_ionic = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n E-field: Ionic dipole, in iteration\n ''',\n a_legacy=LegacyDefinition(name='x_qe_iteration_efield_dipole_ionic'))\n\n x_qe_iteration_number = Quantity(\n type=np.dtype(np.int32),\n shape=[],\n description='''\n Iteration number\n ''',\n a_legacy=LegacyDefinition(name='x_qe_iteration_number'))\n\n x_qe_iteration_ecutwfc = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n PW cutoff used during iteration\n ''',\n a_legacy=LegacyDefinition(name='x_qe_iteration_ecutwfc'))\n\n x_qe_iteration_beta = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Mixing parameter Beta during iteration\n ''',\n a_legacy=LegacyDefinition(name='x_qe_iteration_beta'))\n\n x_qe_iteration_charge_negative_up = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Charge in iteration (up)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_iteration_charge_negative_up'))\n\n x_qe_iteration_charge_negative_down = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Charge in iteration (down)\n ''',\n a_legacy=LegacyDefinition(name='x_qe_iteration_charge_negative_down'))\n\n x_qe_energy_total_harris_foulkes_estimate_iteration = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Harris-Foulkes estimate of total energy\n ''',\n a_legacy=LegacyDefinition(name='x_qe_energy_total_harris_foulkes_estimate_iteration'))\n\n x_qe_energy_total_accuracy_estimate_iteration = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Accuracy estimate of total energy\n ''',\n a_legacy=LegacyDefinition(name='x_qe_energy_total_accuracy_estimate_iteration'))\n\n x_qe_magnetization_total_iteration = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Total per-cell magnetization in iteration\n ''',\n a_legacy=LegacyDefinition(name='x_qe_magnetization_total_iteration'))\n\n x_qe_magnetization_absolute_iteration = Quantity(\n type=np.dtype(np.float64),\n shape=[],\n description='''\n Absolute per-cell magnetization in iteration\n ''',\n a_legacy=LegacyDefinition(name='x_qe_magnetization_absolute_iteration'))\n\n x_qe_section_scf_diagonalization = SubSection(\n sub_section=SectionProxy('x_qe_section_scf_diagonalization'),\n repeats=True,\n a_legacy=LegacyDefinition(name='x_qe_section_scf_diagonalization'))\n\n\nclass section_eigenvalues(public.section_eigenvalues):\n\n m_def = Section(validate=False, extends_base_section=True, a_legacy=LegacyDefinition(name='section_eigenvalues'))\n\n x_qe_eigenvalues_number_of_planewaves = Quantity(\n type=np.dtype(np.int32),\n shape=['number_of_eigenvalues_kpoints'],\n description='''\n Number of plane waves for each k-point\n ''',\n a_legacy=LegacyDefinition(name='x_qe_eigenvalues_number_of_planewaves'))\n\n\nm_package.__init_metainfo__()\n" ]
[ [ "numpy.dtype" ] ]
ThornSun/optimizationLab
[ "5ce49933b23c9f3674bccbc16f12f0955a17de5e" ]
[ "algorithms/GA.py" ]
[ "import numpy\n\n\ndef ga(maxiteration, population, dimension, objf, lb, ub):\n crossRate = 0.8\n mutationRate = 0.1\n x = numpy.random.randint(2, size=(population,dimension))\n" ]
[ [ "numpy.random.randint" ] ]
LilDataScientist/PyTorch-From-Scratch
[ "ae3c0bffc5a36a9a7c123b98f52bdaa32fbedef6", "ae3c0bffc5a36a9a7c123b98f52bdaa32fbedef6" ]
[ "torch/metrics/accuracy_score.py", "torch/nn/ReLU.py" ]
[ "import numpy as np\n\n\ndef accuracy_score(y_true, y_pred):\n a = np.argmax(y_true, axis=1)\n b = np.argmax(y_pred, axis=1)\n return np.count_nonzero(a == b) / y_true.shape[0]\n", "import numpy as np\n\nfrom torch.nn import Module\n\n\nclass ReLU(Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, input):\n self.output = np.maximum(input, 0)\n return self.output\n\n def backward(self, input, grad_output):\n grad_input = np.multiply(grad_output, input > 0)\n return grad_input\n\n\ninput = np.array([\n [1, 1],\n [-1, 5],\n [9, -1],\n [-1, -1],\n [12, 4],\n [16, 2]\n])\n\n\ngrad_output = np.array([\n [0, 0],\n [0, 4],\n [3, 0],\n [0, -5],\n [-9, -1],\n [-1, -1]\n])\n\nactivation = ReLU()\n\nassert np.array_equal(activation.forward(input), np.array([\n [1, 1],\n [0, 5],\n [9, 0],\n [0, 0],\n [12, 4],\n [16, 2]\n]))\n\nassert np.array_equal(activation.backward(input, grad_output), np.array([\n [0, 0],\n [0, 4],\n [3, 0],\n [0, 0],\n [-9, -1],\n [-1, -1]\n]))\n" ]
[ [ "numpy.argmax", "numpy.count_nonzero" ], [ "numpy.array", "numpy.maximum", "numpy.multiply" ] ]
chenying-wang/Fast-HEVC-Intra-Encoder
[ "ffa48c2d4f27882ac1411f415ec93d14fc9a2bde" ]
[ "src/cnn/bp.py" ]
[ "import tensorflow as tf\n\nimport util\n\n_fc_with_dropout = util.fc_with_dropout\n\ndef bp(features, features_size, keep_prob = 1.0):\n\thidden1 = _fc_with_dropout(\n\t\tinput = features,\n\t\tinput_size = features_size,\n\t\toutput_size = 32,\n\t\tkeep_prob = keep_prob,\n\t\tname = \"hidden1\"\n\t)\n\thidden2 = _fc_with_dropout(\n\t\tinput = hidden1,\n\t\tinput_size = 32,\n\t\toutput_size = 32,\n\t\tkeep_prob = keep_prob,\n\t\tname = \"hidden2\"\n\t)\n\toutput = _fc_with_dropout(\n\t\tinput = hidden2,\n\t\tinput_size = 32,\n\t\toutput_size = 1,\n\t\tkeep_prob = keep_prob,\n\t\tname = \"output\"\n\t)\n\n\treturn output\n\nif __name__ == \"__main__\":\n\ttf.app.run()\n" ]
[ [ "tensorflow.app.run" ] ]
turingbirds/howland_vccs
[ "b4d69476f151a05d830396e152d06a93b6bc0e3f" ]
[ "data/spectrum_measurements/wave_generator.py" ]
[ "#!/usr/bin/python \n\nimport wave\nimport struct\nimport numpy as np\nimport scipy\nimport scipy.signal\nimport scipy.io.wavfile\n\n\nfreq = 100. # [Hz]\nvolume = 1.\nduration = 10 * 60. # [s]\nsample_rate = 48000 # [Hz]\n\nprint(\"Generating...\")\ntimevec = np.arange(0., duration, 1/sample_rate)\nn_samples = len(timevec)\naudio = np.empty((n_samples, 2))\naudio[:, 0] = volume * np.sin(2 * np.pi * freq * timevec)\naudio[:, 1] = -volume * np.sin(2 * np.pi * freq * timevec)\n#audio[:, 1] = audio[:, 0]\n\nprint(\"Saving...\")\nfname = \"output.wav\"\n#fname = \"output_cm.wav\"\nscipy.io.wavfile.write(filename=fname, rate=sample_rate, data=audio)\n\n\n" ]
[ [ "numpy.arange", "scipy.io.wavfile.write", "numpy.empty", "numpy.sin" ] ]
sytelus/darts
[ "243b9dff94efaaa07891f9e449b1d0a8f28705cd" ]
[ "cnn/model_search.py" ]
[ "import torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom operations import OPS, FactorizedReduce, ReLUConvBN\nfrom genotypes import PRIMITIVES, Genotype\n\n\nclass MixedLayer(nn.Module):\n \"\"\"\n a mixtures output of 8 type of units. Each MixedLayer is one op (i.e. edge).\n The output of MixedLayer is weighted output of all allowed primitives.\n\n we use weights to aggregate these outputs while training.\n and softmax to select the strongest edges while inference.\n \"\"\"\n def __init__(self, c, stride):\n \"\"\"\n\n :param c: 16\n :param stride: 1\n \"\"\"\n super(MixedLayer, self).__init__()\n\n self.layers = nn.ModuleList()\n \"\"\"\n PRIMITIVES = [\n 'none',\n 'max_pool_3x3',\n 'avg_pool_3x3',\n 'skip_connect',\n 'sep_conv_3x3',\n 'sep_conv_5x5',\n 'dil_conv_3x3',\n 'dil_conv_5x5'\n ]\n \"\"\"\n for primitive in PRIMITIVES:\n # create corresponding layer\n layer = OPS[primitive](c, stride, False)\n # append batchnorm after pool layer\n if 'pool' in primitive:\n # disable affine w/b for batchnorm\n layer = nn.Sequential(layer, nn.BatchNorm2d(c, affine=False))\n\n self.layers.append(layer)\n\n def forward(self, x, weights):\n \"\"\"\n\n :param x: data\n :param weights: alpha,[op_num:8], the output = sum of alpha * op(x)\n :return:\n \"\"\"\n res = [w * layer(x) for w, layer in zip(weights, self.layers)]\n # element-wise add by torch.add\n res = sum(res)\n return res\n\n\n\n\n\n\n\nclass Cell(nn.Module):\n\n def __init__(self, steps, multiplier, cpp, cp, c, reduction, reduction_prev):\n \"\"\"\n Each cell k takes input from last two cells k-2, k-1. The cell consists of `steps` so that on each step i,\n we take output of all previous i steps + 2 cell inputs, apply op on each of these outputs and produce their\n sum as output of i-th step.\n Each op output has c channels. The output of the cell is produced by forward() is concatenation of last\n `multiplier` number of layers. Cell could be a reduction cell or it could be a normal cell. The only\n diference between two is that reduction cell uses stride=2 for the ops that connects to cell inputs.\n\n :param steps: 4, number of layers inside a cell\n :param multiplier: 4, number of last nodes to concatenate as output, this will multiply number of channels in node\n :param cpp: 48, channels from cell k-2\n :param cp: 48, channels from cell k-1\n :param c: 16, output channels for each node\n :param reduction: indicates whether to reduce the output maps width\n :param reduction_prev: when previous cell reduced width, s1_d = s0_d//2\n in order to keep same shape between s1 and s0, we adopt prep0 layer to\n reduce the s0 width by half.\n \"\"\"\n super(Cell, self).__init__()\n\n # indicating current cell is reduction or not\n self.reduction = reduction\n self.reduction_prev = reduction_prev\n\n # preprocess0 deal with output from prev_prev cell\n if reduction_prev:\n # if prev cell has reduced channel/double width,\n # it will reduce width by half\n self.preprocess0 = FactorizedReduce(cpp, c, affine=False)\n else:\n self.preprocess0 = ReLUConvBN(cpp, c, 1, 1, 0, affine=False)\n # preprocess1 deal with output from prev cell\n self.preprocess1 = ReLUConvBN(cp, c, 1, 1, 0, affine=False)\n\n # steps inside a cell\n self.steps = steps # 4\n self.multiplier = multiplier # 4\n\n self.layers = nn.ModuleList()\n\n for i in range(self.steps):\n # for each i inside cell, it connects with all previous output\n # plus previous two cells' output\n for j in range(2 + i):\n # for reduction cell, it will reduce the heading 2 inputs only\n stride = 2 if reduction and j < 2 else 1\n layer = MixedLayer(c, stride)\n self.layers.append(layer)\n\n def forward(self, s0, s1, weights):\n \"\"\"\n\n :param s0: output of cell k-1\n :param s1: output of cell k-2\n :param weights: [14, 8], weights for primitives for each edge\n :return:\n \"\"\"\n # print('s0:', s0.shape,end='=>')\n s0 = self.preprocess0(s0) # [40, 48, 32, 32], [40, 16, 32, 32]\n # print(s0.shape, self.reduction_prev)\n # print('s1:', s1.shape,end='=>')\n s1 = self.preprocess1(s1) # [40, 48, 32, 32], [40, 16, 32, 32]\n # print(s1.shape)\n\n states = [s0, s1]\n offset = 0\n # for each node, receive input from all previous intermediate nodes and s0, s1\n for i in range(self.steps): # 4\n # [40, 16, 32, 32]\n s = sum(self.layers[offset + j](h, weights[offset + j]) for j, h in enumerate(states))\n offset += len(states)\n # append one state since s is the elem-wise addition of all output\n states.append(s)\n # print('node:',i, s.shape, self.reduction)\n\n # concat along dim=channel\n return torch.cat(states[-self.multiplier:], dim=1) # 6 of [40, 16, 32, 32]\n\n\n\n\n\n\nclass Network(nn.Module):\n\n \"\"\"\n stack number:layer of cells and then flatten to fed a linear layer\n \"\"\"\n def __init__(self, c, num_classes, layers, criterion, steps=4, multiplier=4, stem_multiplier=3):\n \"\"\"\n\n :param c: 16, (number of output channels from the first layer) / stem_multiplier\n :param num_classes: 10\n :param layers: number of cells of current network\n :param criterion:\n :param steps: nodes num inside cell\n :param multiplier: output channel of cell = multiplier * ch\n :param stem_multiplier: output channel of stem net = stem_multiplier * ch\n \"\"\"\n super(Network, self).__init__()\n\n self.c = c\n self.num_classes = num_classes\n self.layers = layers\n self.criterion = criterion\n self.steps = steps\n self.multiplier = multiplier\n\n\n # stem_multiplier is for stem network,\n # and multiplier is for general cell\n # TODO: why do we need stem_multiplier?\n c_curr = stem_multiplier * c # 3*16\n # stem network, convert 3 channel to c_curr\n # First layer is 3x3, stride 1 layer and assumes 3 channel input\n self.stem = nn.Sequential( # 3 => 48\n # batchnorm is added after each layer. Bias is turned off due to this in conv layer.\n nn.Conv2d(3, c_curr, 3, padding=1, bias=False),\n nn.BatchNorm2d(c_curr)\n )\n\n # c_curr means a factor of the output channels of current cell\n # output channels = multiplier * c_curr\n # c_curr: current cell output channels\n # cp: previous cell output channels\n # cpp: previous previous cell output channels\n cpp, cp, c_curr = c_curr, c_curr, c # 48, 48, 16\n self.cells = nn.ModuleList()\n reduction_prev = False\n for i in range(layers):\n\n # for layer in the middle [1/3, 2/3], reduce via stride=2\n if i in [layers // 3, 2 * layers // 3]:\n c_curr *= 2\n reduction = True\n else:\n reduction = False\n\n # [cp, h, h] => [multiplier*c_curr, h/h//2, h/h//2]\n # the output channels = multiplier * c_curr\n cell = Cell(steps, multiplier, cpp, cp, c_curr, reduction, reduction_prev)\n # update reduction_prev\n reduction_prev = reduction\n\n self.cells += [cell]\n\n cpp, cp = cp, multiplier * c_curr\n\n # adaptive pooling output size to 1x1\n self.global_pooling = nn.AdaptiveAvgPool2d(1)\n # since cp records last cell's output channels\n # it indicates the input channel number\n self.classifier = nn.Linear(cp, num_classes)\n\n # k is the total number of edges inside single cell, 14\n k = sum(1 for i in range(self.steps) for j in range(2 + i))\n num_ops = len(PRIMITIVES) # 8\n\n # create k*num_ops parameters that we will share between all cells\n # this kind of implementation will add alpha into self.parameters()\n # it has num k of alpha parameters, and each alpha shape: [num_ops]\n # it requires grad and can be converted to cpu/gpu automatically\n self.alpha_normal = nn.Parameter(torch.randn(k, num_ops))\n self.alpha_reduce = nn.Parameter(torch.randn(k, num_ops))\n with torch.no_grad():\n # initialize to smaller value\n self.alpha_normal.mul_(1e-3)\n self.alpha_reduce.mul_(1e-3)\n self._arch_parameters = [\n self.alpha_normal,\n self.alpha_reduce,\n ]\n\n def new(self):\n \"\"\"\n create a new model and initialize it with current alpha parameters.\n However, its weights are left at initial value.\n :return:\n \"\"\"\n model_new = Network(self.c, self.num_classes, self.layers, self.criterion).cuda()\n for x, y in zip(model_new.arch_parameters(), self.arch_parameters()):\n x.data.copy_(y.data)\n return model_new\n\n def forward(self, x):\n \"\"\"\n Runs x through cells, applies final pooling, send through FCs and returns logits.\n This would tech alpha parameters into account.\n\n in: torch.Size([3, 3, 32, 32])\n stem: torch.Size([3, 48, 32, 32])\n cell: 0 torch.Size([3, 64, 32, 32]) False\n cell: 1 torch.Size([3, 64, 32, 32]) False\n cell: 2 torch.Size([3, 128, 16, 16]) True\n cell: 3 torch.Size([3, 128, 16, 16]) False\n cell: 4 torch.Size([3, 128, 16, 16]) False\n cell: 5 torch.Size([3, 256, 8, 8]) True\n cell: 6 torch.Size([3, 256, 8, 8]) False\n cell: 7 torch.Size([3, 256, 8, 8]) False\n pool: torch.Size([16, 256, 1, 1])\n linear: [b, 10]\n :param x:\n :return:\n \"\"\"\n # print('in:', x.shape)\n # s0 & s1 means the last cells' output\n s0 = s1 = self.stem(x) # [b, 3, 32, 32] => [b, 48, 32, 32]\n # print('stem:', s0.shape)\n\n for i, cell in enumerate(self.cells):\n # weights are shared across all reduction cell or normal cell\n # according to current cell's type, it choose which architecture parameters\n # to use\n if cell.reduction: # if current cell is reduction cell\n weights = F.softmax(self.alpha_reduce, dim=-1)\n else:\n weights = F.softmax(self.alpha_normal, dim=-1) # [14, 8]\n # execute cell() firstly and then assign s0=s1, s1=result\n s0, s1 = s1, cell(s0, s1, weights) # [40, 64, 32, 32]\n # print('cell:',i, s1.shape, cell.reduction, cell.reduction_prev)\n # print('\\n')\n\n # s1 is the last cell's output\n out = self.global_pooling(s1)\n # print('pool', out.shape)\n logits = self.classifier(out.view(out.size(0), -1))\n\n return logits\n\n def loss(self, x, target):\n \"\"\"\n\n :param x:\n :param target:\n :return:\n \"\"\"\n logits = self(x)\n return self.criterion(logits, target)\n\n\n\n def arch_parameters(self):\n return self._arch_parameters\n\n\n\n\n def genotype(self):\n \"\"\"\n Returns display description of network from the weights for each ops in cell\n\n :return: \n \"\"\"\n def _parse(weights):\n \"\"\"\n We have 4 steps, each step can have edge with previous steps + 2 inputs.\n So total edges = 2 + 3 + 4 + 5 = 14\n We will have total 8 primitives for each of the 14 edges within each cell.\n So weight shape is [14, 8]. These are the alpha parameters and shared across cells.\n For each of the edges for a node, we want to find out top 2 strongest prmitives\n and make them as \"final\" for that node. As we don't consider none edge,\n this guerentees that each node will exactly end up with 2 edges, one final non-none \n primitive attached to each. \n\n :param weights: [14, 8]\n :return: string array, each member describes edge in the cell\n \"\"\"\n gene = []\n n = 2\n start = 0\n for i in range(self.steps): # for each node\n end = start + n\n W = weights[start:end].copy() # [2, 8], [3, 8], ...\n\n # so far each edge has 8 primitives attached, we will chose top two so that\n # we get two best edges on which best primitives resides\n edges = sorted(range(i + 2), # i+2 is the number of connection for node i\n key=lambda x: -max(W[x][k] # by descending order\n for k in range(len(W[x])) # get strongest ops\n if k != PRIMITIVES.index('none'))\n )[:2] # only has two inputs\n\n # Each node i now we have 2 edges that still has 8 primitives each and \n # we want to select best primitive for each edge\n for j in edges: # for every input nodes j of current node i\n k_best = None\n for k in range(len(W[j])): # get strongest ops for current input j->i\n if k != PRIMITIVES.index('none'):\n if k_best is None or W[j][k] > W[j][k_best]:\n k_best = k\n gene.append((PRIMITIVES[k_best], j)) # save ops and input node\n start = end\n n += 1\n\n # at this point we should have each node, with exactly two edges and associated best primitive\n return gene\n\n gene_normal = _parse(F.softmax(self.alpha_normal, dim=-1).data.cpu().numpy())\n gene_reduce = _parse(F.softmax(self.alpha_reduce, dim=-1).data.cpu().numpy())\n\n concat = range(2 + self.steps - self.multiplier, self.steps + 2)\n genotype = Genotype(\n normal=gene_normal, normal_concat=concat,\n reduce=gene_reduce, reduce_concat=concat\n )\n\n return genotype\n" ]
[ [ "torch.nn.functional.softmax", "torch.cat", "torch.randn", "torch.nn.ModuleList", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.AdaptiveAvgPool2d", "torch.no_grad", "torch.nn.BatchNorm2d" ] ]
choupi/NDHUDLWorkshop
[ "63525f8dffacd3487c10ddb0d5dc389585833045" ]
[ "mnist/xgboost/predict_xg.py" ]
[ "'''Trains a simple convnet on the MNIST dataset.\n\nGets to 99.25% test accuracy after 12 epochs\n(there is still a lot of margin for parameter tuning).\n16 seconds per epoch on a GRID K520 GPU.\n'''\n\nfrom __future__ import print_function\nimport numpy as np\nnp.random.seed(1337) # for reproducibility\n\nfrom keras.datasets import mnist\nimport xgboost as xgb\nfrom sklearn.metrics import *\n\nbatch_size = 128\nnb_classes = 10\nnb_epoch = 12\n\n# input image dimensions\nimg_rows, img_cols = 28, 28\n\n# the data, shuffled and split between train and test sets\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n\n#X_train = X_train.reshape(X_train.shape[0], img_rows*img_cols)\nX_test = X_test.reshape(X_test.shape[0], img_rows*img_cols)\n#X_train = X_train.astype('float32')\n#X_test = X_test.astype('float32')\n#print('X_train shape:', X_train.shape)\n#print(X_train.shape[0], 'train samples')\nprint(X_test.shape[0], 'test samples')\n\n# convert class vectors to binary class matrices\n#Y_train = np_utils.to_categorical(y_train, nb_classes)\n#Y_test = np_utils.to_categorical(y_test, nb_classes)\n#Y_train = [int(y) for y in y_train]\nY_test = [int(y) for y in y_test]\n\nmodel_file='mnist.model'\nxgmat = xgb.DMatrix(X_test)\nbst = xgb.Booster(model_file = model_file)\ny_predict = bst.predict(xgmat)\n#y_predict = bst.predict_proba(xgmat)\nprint(y_predict)\n\nprint(log_loss(Y_test, y_predict))\n#print(y_predict)\n#predict=y_predict\npredict=[]\nfor yy in y_predict: predict.append(np.argmax(yy))\n#print(predict)\nprint(f1_score(Y_test, predict))\nprint(classification_report(Y_test, predict))\nprint(confusion_matrix(Y_test, predict))\n" ]
[ [ "numpy.argmax", "numpy.random.seed" ] ]
waybarrios/Flow-Guided-Feature-Aggregation
[ "beb7f66798f1f7b08d4f8dd54d4a463f9fd049a5" ]
[ "lib/nms/setup_windows.py" ]
[ "# --------------------------------------------------------\n# Flow-Guided Feature Aggregation\n# Copyright (c) 2017 Microsoft\n# Licensed under The MIT License [see LICENSE for details]\n# Modified by Yuwen Xiong\n# --------------------------------------------------------\n# Based on:\n# py-faster-rcnn\n# Copyright (c) 2016 by Contributors\n# Licence under The MIT License\n# https://github.com/rbgirshick/py-faster-rcnn\n# --------------------------------------------------------\n\n\nimport numpy as np\nimport os\nfrom os.path import join as pjoin\n#from distutils.core import setup\nfrom setuptools import setup\nfrom distutils.extension import Extension\nfrom Cython.Distutils import build_ext\nimport subprocess\n\n#change for windows, by MrX\nnvcc_bin = 'nvcc.exe'\nlib_dir = 'lib/x64'\n\nimport distutils.msvc9compiler\ndistutils.msvc9compiler.VERSION = 14.0\n\n\ndef find_in_path(name, path):\n \"Find a file in a search path\"\n # Adapted fom\n # http://code.activestate.com/recipes/52224-find-a-file-given-a-search-path/\n for dir in path.split(os.pathsep):\n binpath = pjoin(dir, name)\n if os.path.exists(binpath):\n return os.path.abspath(binpath)\n return None\n\n\ndef locate_cuda():\n \"\"\"Locate the CUDA environment on the system\n\n Returns a dict with keys 'home', 'nvcc', 'include', and 'lib64'\n and values giving the absolute path to each directory.\n\n Starts by looking for the CUDAHOME env variable. If not found, everything\n is based on finding 'nvcc' in the PATH.\n \"\"\"\n\n # first check if the CUDAHOME env variable is in use\n if 'CUDA_PATH' in os.environ:\n home = os.environ['CUDA_PATH']\n print(\"home = %s\\n\" % home)\n nvcc = pjoin(home, 'bin', nvcc_bin)\n else:\n # otherwise, search the PATH for NVCC\n default_path = pjoin(os.sep, 'usr', 'local', 'cuda', 'bin')\n nvcc = find_in_path(nvcc_bin, os.environ['PATH'] + os.pathsep + default_path)\n if nvcc is None:\n raise EnvironmentError('The nvcc binary could not be '\n 'located in your $PATH. Either add it to your path, or set $CUDA_PATH')\n home = os.path.dirname(os.path.dirname(nvcc))\n print(\"home = %s, nvcc = %s\\n\" % (home, nvcc))\n\n\n cudaconfig = {'home':home, 'nvcc':nvcc,\n 'include': pjoin(home, 'include'),\n 'lib64': pjoin(home, lib_dir)}\n for k, v in cudaconfig.iteritems():\n if not os.path.exists(v):\n raise EnvironmentError('The CUDA %s path could not be located in %s' % (k, v))\n\n return cudaconfig\nCUDA = locate_cuda()\n\n\n# Obtain the numpy include directory. This logic works across numpy versions.\ntry:\n numpy_include = np.get_include()\nexcept AttributeError:\n numpy_include = np.get_numpy_include()\n\n\ndef customize_compiler_for_nvcc(self):\n \"\"\"inject deep into distutils to customize how the dispatch\n to gcc/nvcc works.\n\n If you subclass UnixCCompiler, it's not trivial to get your subclass\n injected in, and still have the right customizations (i.e.\n distutils.sysconfig.customize_compiler) run on it. So instead of going\n the OO route, I have this. Note, it's kindof like a wierd functional\n subclassing going on.\"\"\"\n\n # tell the compiler it can processes .cu\n #self.src_extensions.append('.cu')\n\n\t\n # save references to the default compiler_so and _comple methods\n #default_compiler_so = self.spawn \n #default_compiler_so = self.rc\n super = self.compile\n\n # now redefine the _compile method. This gets executed for each\n # object but distutils doesn't have the ability to change compilers\n # based on source extension: we add it.\n def compile(sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None):\n postfix=os.path.splitext(sources[0])[1]\n \n if postfix == '.cu':\n # use the cuda for .cu files\n #self.set_executable('compiler_so', CUDA['nvcc'])\n # use only a subset of the extra_postargs, which are 1-1 translated\n # from the extra_compile_args in the Extension class\n postargs = extra_postargs['nvcc']\n else:\n postargs = extra_postargs['gcc']\n\n\n return super(sources, output_dir, macros, include_dirs, debug, extra_preargs, postargs, depends)\n # reset the default compiler_so, which we might have changed for cuda\n #self.rc = default_compiler_so\n\n # inject our redefined _compile method into the class\n self.compile = compile\n\n\n# run the customize_compiler\nclass custom_build_ext(build_ext):\n def build_extensions(self):\n customize_compiler_for_nvcc(self.compiler)\n build_ext.build_extensions(self)\n\n\next_modules = [\n # unix _compile: obj, src, ext, cc_args, extra_postargs, pp_opts\n Extension(\n \"cpu_nms\",\n sources=[\"cpu_nms.pyx\"],\n extra_compile_args={'gcc': []},\n include_dirs = [numpy_include],\n ),\n]\n\nsetup(\n name='fast_rcnn',\n ext_modules=ext_modules,\n # inject our custom trigger\n cmdclass={'build_ext': custom_build_ext},\n)\n" ]
[ [ "numpy.get_numpy_include", "numpy.get_include" ] ]
ka40/AE4350-assignment
[ "06e701cfffded6f7e9c34a64616df17c0cbed241" ]
[ "environments/vectorized_environment.py" ]
[ "from environments.worker import Worker\nimport multiprocessing as mp\nimport numpy as np\nimport random\n\nclass VectorizedEnvironment(object):\n \"\"\"\n Creates multiple instances of an environment to run in parallel.\n Each of them contains a separate worker (actor) all of them following\n the same policy\n \"\"\"\n\n def __init__(self, parameters, seed):\n print('cpu count', mp.cpu_count())\n if parameters['num_workers'] < mp.cpu_count():\n self.num_workers = parameters['num_workers']\n else:\n self.num_workers = mp.cpu_count()\n # Random seed needs to be set different for each worker (seed + worker_id). Otherwise multiprocessing takes \n # the current system time, which is the same for all workers!\n self.workers = [Worker(parameters, worker_id, seed + worker_id) for worker_id in range(self.num_workers)]\n self.parameters = parameters\n self.env = parameters['env_type']\n\n def reset(self):\n \"\"\"\n Resets each of the environment instances\n \"\"\"\n for worker in self.workers:\n worker.child.send(('reset', None))\n output = {'obs': [], 'prev_action': []}\n for worker in self.workers:\n obs = worker.child.recv()\n if self.env == 'atari':\n stacked_obs = np.zeros((self.parameters['frame_height'],\n self.parameters['frame_width'],\n self.parameters['num_frames']))\n stacked_obs[:, :, 0] = obs[:, :, 0]\n obs = stacked_obs\n output['obs'].append(obs)\n output['prev_action'].append(-1)\n return output\n\n def step(self, actions, prev_stacked_obs):\n \"\"\"\n Takes an action in each of the enviroment instances\n \"\"\"\n for worker, action in zip(self.workers, actions):\n worker.child.send(('step', action))\n output = {'obs': [], 'reward': [], 'done': [], 'prev_action': [],\n 'info': []}\n i = 0\n for worker in self.workers:\n obs, reward, done, info = worker.child.recv()\n if self.parameters['flicker']:\n p = 0.5\n prob_flicker = random.uniform(0, 1)\n if prob_flicker > p:\n obs = np.zeros_like(obs)\n if self.env == 'atari':\n new_stacked_obs = np.zeros((self.parameters['frame_height'],\n self.parameters['frame_width'],\n self.parameters['num_frames']))\n new_stacked_obs[:, :, 0] = obs[:, :, 0]\n new_stacked_obs[:, :, 1:] = prev_stacked_obs[i][:, :, :-1]\n obs = new_stacked_obs\n output['obs'].append(obs)\n output['reward'].append(reward)\n output['done'].append(done)\n output['info'].append(info)\n i += 1\n output['prev_action'] = actions\n return output\n\n def action_space(self):\n \"\"\"\n Returns the dimensions of the environment's action space\n \"\"\"\n self.workers[0].child.send(('action_space', None))\n action_space = self.workers[0].child.recv()\n return action_space\n\n def close(self):\n \"\"\"\n Closes each of the threads in the multiprocess\n \"\"\"\n for worker in self.workers:\n worker.child.send(('close', None))\n" ]
[ [ "numpy.zeros", "numpy.zeros_like" ] ]
linjieccc/PaddleHub
[ "27ef1d9286bf1682c0906c796260b9e91514b021" ]
[ "modules/image/object_detection/yolov3_darknet53_vehicles/module.py" ]
[ "# coding=utf-8\nfrom __future__ import absolute_import\n\nimport ast\nimport argparse\nimport os\nfrom functools import partial\n\nimport numpy as np\nimport paddle.fluid as fluid\nimport paddlehub as hub\nfrom paddle.fluid.core import PaddleTensor, AnalysisConfig, create_paddle_predictor\nfrom paddlehub.module.module import moduleinfo, runnable, serving\nfrom paddlehub.common.paddle_helper import add_vars_prefix\n\nfrom yolov3_darknet53_vehicles.darknet import DarkNet\nfrom yolov3_darknet53_vehicles.processor import load_label_info, postprocess, base64_to_cv2\nfrom yolov3_darknet53_vehicles.data_feed import reader\nfrom yolov3_darknet53_vehicles.yolo_head import MultiClassNMS, YOLOv3Head\n\n\n@moduleinfo(\n name=\"yolov3_darknet53_vehicles\",\n version=\"1.0.2\",\n type=\"CV/object_detection\",\n summary=\n \"Baidu's YOLOv3 model for vehicles detection, with backbone DarkNet53.\",\n author=\"paddlepaddle\",\n author_email=\"[email protected]\")\nclass YOLOv3DarkNet53Vehicles(hub.Module):\n def _initialize(self):\n self.default_pretrained_model_path = os.path.join(\n self.directory, \"yolov3_darknet53_vehicles_model\")\n self.label_names = load_label_info(\n os.path.join(self.directory, \"label_file.txt\"))\n self._set_config()\n\n def _set_config(self):\n \"\"\"\n predictor config setting.\n \"\"\"\n cpu_config = AnalysisConfig(self.default_pretrained_model_path)\n cpu_config.disable_glog_info()\n cpu_config.disable_gpu()\n cpu_config.switch_ir_optim(False)\n self.cpu_predictor = create_paddle_predictor(cpu_config)\n\n try:\n _places = os.environ[\"CUDA_VISIBLE_DEVICES\"]\n int(_places[0])\n use_gpu = True\n except:\n use_gpu = False\n if use_gpu:\n gpu_config = AnalysisConfig(self.default_pretrained_model_path)\n gpu_config.disable_glog_info()\n gpu_config.enable_use_gpu(memory_pool_init_size_mb=500, device_id=0)\n self.gpu_predictor = create_paddle_predictor(gpu_config)\n\n def context(self, trainable=True, pretrained=True, get_prediction=False):\n \"\"\"\n Distill the Head Features, so as to perform transfer learning.\n\n Args:\n trainable (bool): whether to set parameters trainable.\n pretrained (bool): whether to load default pretrained model.\n get_prediction (bool): whether to get prediction.\n\n Returns:\n inputs(dict): the input variables.\n outputs(dict): the output variables.\n context_prog (Program): the program to execute transfer learning.\n \"\"\"\n context_prog = fluid.Program()\n startup_program = fluid.Program()\n with fluid.program_guard(context_prog, startup_program):\n with fluid.unique_name.guard():\n # image\n image = fluid.layers.data(\n name='image', shape=[3, 608, 608], dtype='float32')\n # backbone\n backbone = DarkNet(norm_type='sync_bn', norm_decay=0., depth=53)\n # body_feats\n body_feats = backbone(image)\n # im_size\n im_size = fluid.layers.data(\n name='im_size', shape=[2], dtype='int32')\n # yolo_head\n yolo_head = YOLOv3Head(\n anchor_masks=[[6, 7, 8], [3, 4, 5], [0, 1, 2]],\n anchors=[[8, 9], [10, 23], [19, 15], [23, 33], [40, 25],\n [54, 50], [101, 80], [139, 145], [253, 224]],\n norm_decay=0.,\n num_classes=6,\n ignore_thresh=0.7,\n label_smooth=False,\n nms=MultiClassNMS(\n background_label=-1,\n keep_top_k=100,\n nms_threshold=0.45,\n nms_top_k=400,\n normalized=False,\n score_threshold=0.005))\n # head_features\n head_features, body_features = yolo_head._get_outputs(\n body_feats, is_train=trainable)\n\n place = fluid.CPUPlace()\n exe = fluid.Executor(place)\n exe.run(fluid.default_startup_program())\n\n # var_prefix\n var_prefix = '@HUB_{}@'.format(self.name)\n # name of inputs\n inputs = {\n 'image': var_prefix + image.name,\n 'im_size': var_prefix + im_size.name\n }\n # name of outputs\n if get_prediction:\n bbox_out = yolo_head.get_prediction(head_features, im_size)\n outputs = {'bbox_out': [var_prefix + bbox_out.name]}\n else:\n outputs = {\n 'head_features':\n [var_prefix + var.name for var in head_features],\n 'body_features':\n [var_prefix + var.name for var in body_features]\n }\n # add_vars_prefix\n add_vars_prefix(context_prog, var_prefix)\n add_vars_prefix(fluid.default_startup_program(), var_prefix)\n # inputs\n inputs = {\n key: context_prog.global_block().vars[value]\n for key, value in inputs.items()\n }\n # outputs\n outputs = {\n key: [\n context_prog.global_block().vars[varname]\n for varname in value\n ]\n for key, value in outputs.items()\n }\n # trainable\n for param in context_prog.global_block().iter_parameters():\n param.trainable = trainable\n # pretrained\n if pretrained:\n\n def _if_exist(var):\n return os.path.exists(\n os.path.join(self.default_pretrained_model_path,\n var.name))\n\n fluid.io.load_vars(\n exe,\n self.default_pretrained_model_path,\n predicate=_if_exist)\n else:\n exe.run(startup_program)\n\n return inputs, outputs, context_prog\n\n def object_detection(self,\n paths=None,\n images=None,\n batch_size=1,\n use_gpu=False,\n output_dir='yolov3_vehicles_detect_output',\n score_thresh=0.2,\n visualization=True):\n \"\"\"API of Object Detection.\n\n Args:\n paths (list[str]): The paths of images.\n images (list(numpy.ndarray)): images data, shape of each is [H, W, C]\n batch_size (int): batch size.\n use_gpu (bool): Whether to use gpu.\n output_dir (str): The path to store output images.\n visualization (bool): Whether to save image or not.\n score_thresh (float): threshold for object detecion.\n\n Returns:\n res (list[dict]): The result of vehicles detecion. keys include 'data', 'save_path', the corresponding value is:\n data (dict): the result of object detection, keys include 'left', 'top', 'right', 'bottom', 'label', 'confidence', the corresponding value is:\n left (float): The X coordinate of the upper left corner of the bounding box;\n top (float): The Y coordinate of the upper left corner of the bounding box;\n right (float): The X coordinate of the lower right corner of the bounding box;\n bottom (float): The Y coordinate of the lower right corner of the bounding box;\n label (str): The label of detection result;\n confidence (float): The confidence of detection result.\n save_path (str, optional): The path to save output images.\n \"\"\"\n if use_gpu:\n try:\n _places = os.environ[\"CUDA_VISIBLE_DEVICES\"]\n int(_places[0])\n except:\n raise RuntimeError(\n \"Attempt to use GPU for prediction, but environment variable CUDA_VISIBLE_DEVICES was not set correctly.\"\n )\n\n paths = paths if paths else list()\n data_reader = partial(reader, paths, images)\n batch_reader = fluid.io.batch(data_reader, batch_size=batch_size)\n res = []\n for iter_id, feed_data in enumerate(batch_reader()):\n feed_data = np.array(feed_data)\n image_tensor = PaddleTensor(np.array(list(feed_data[:, 0])))\n im_size_tensor = PaddleTensor(np.array(list(feed_data[:, 1])))\n if use_gpu:\n data_out = self.gpu_predictor.run(\n [image_tensor, im_size_tensor])\n else:\n data_out = self.cpu_predictor.run(\n [image_tensor, im_size_tensor])\n\n output = postprocess(\n paths=paths,\n images=images,\n data_out=data_out,\n score_thresh=score_thresh,\n label_names=self.label_names,\n output_dir=output_dir,\n handle_id=iter_id * batch_size,\n visualization=visualization)\n res.extend(output)\n return res\n\n def save_inference_model(self,\n dirname,\n model_filename=None,\n params_filename=None,\n combined=True):\n if combined:\n model_filename = \"__model__\" if not model_filename else model_filename\n params_filename = \"__params__\" if not params_filename else params_filename\n place = fluid.CPUPlace()\n exe = fluid.Executor(place)\n\n program, feeded_var_names, target_vars = fluid.io.load_inference_model(\n dirname=self.default_pretrained_model_path, executor=exe)\n\n fluid.io.save_inference_model(\n dirname=dirname,\n main_program=program,\n executor=exe,\n feeded_var_names=feeded_var_names,\n target_vars=target_vars,\n model_filename=model_filename,\n params_filename=params_filename)\n\n @serving\n def serving_method(self, images, **kwargs):\n \"\"\"\n Run as a service.\n \"\"\"\n images_decode = [base64_to_cv2(image) for image in images]\n results = self.object_detection(images=images_decode, **kwargs)\n return results\n\n @runnable\n def run_cmd(self, argvs):\n \"\"\"\n Run as a command.\n \"\"\"\n self.parser = argparse.ArgumentParser(\n description=\"Run the {} module.\".format(self.name),\n prog='hub run {}'.format(self.name),\n usage='%(prog)s',\n add_help=True)\n self.arg_input_group = self.parser.add_argument_group(\n title=\"Input options\", description=\"Input data. Required\")\n self.arg_config_group = self.parser.add_argument_group(\n title=\"Config options\",\n description=\n \"Run configuration for controlling module behavior, not required.\")\n self.add_module_config_arg()\n self.add_module_input_arg()\n args = self.parser.parse_args(argvs)\n results = self.object_detection(\n paths=[args.input_path],\n batch_size=args.batch_size,\n use_gpu=args.use_gpu,\n output_dir=args.output_dir,\n visualization=args.visualization,\n score_thresh=args.score_thresh)\n return results\n\n def add_module_config_arg(self):\n \"\"\"\n Add the command config options.\n \"\"\"\n self.arg_config_group.add_argument(\n '--use_gpu',\n type=ast.literal_eval,\n default=False,\n help=\"whether use GPU or not\")\n self.arg_config_group.add_argument(\n '--output_dir',\n type=str,\n default='yolov3_vehicles_detect_output',\n help=\"The directory to save output images.\")\n self.arg_config_group.add_argument(\n '--visualization',\n type=ast.literal_eval,\n default=False,\n help=\"whether to save output as images.\")\n\n def add_module_input_arg(self):\n \"\"\"\n Add the command input options.\n \"\"\"\n self.arg_input_group.add_argument(\n '--input_path', type=str, help=\"path to image.\")\n self.arg_input_group.add_argument(\n '--batch_size',\n type=ast.literal_eval,\n default=1,\n help=\"batch size.\")\n self.arg_input_group.add_argument(\n '--score_thresh',\n type=ast.literal_eval,\n default=0.2,\n help=\"threshold for object detecion.\")\n" ]
[ [ "numpy.array" ] ]
xaviergonzalez/geotorch
[ "ba4ebe7c86d6678f903525606843f6341d1b7060" ]
[ "test/test_positive_semidefinite.py" ]
[ "from unittest import TestCase\nimport itertools\n\nimport torch\nimport torch.nn as nn\n\nimport geotorch.parametrize as P\n\nfrom geotorch.pssdlowrank import PSSDLowRank\nfrom geotorch.pssdfixedrank import PSSDFixedRank\nfrom geotorch.pssd import PSSD\nfrom geotorch.psd import PSD\n\n\nclass TestPSSDLowRank(TestCase):\n def assertIsSymmetric(self, X):\n self.assertAlmostEqual(\n torch.norm(X - X.transpose(-2, -1), p=float(\"inf\")).item(), 0.0, places=5\n )\n\n def assertIsOrthogonal(self, X):\n if X.size(-2) < X.size(-1):\n X = X.transpose(-2, -1)\n Id = torch.eye(X.size(-1))\n if X.dim() > 2:\n Id = Id.repeat(*(X.size()[:-2] + (1, 1)))\n norm = torch.norm(X.transpose(-2, -1) @ X - Id, dim=(-2, -1))\n self.assertTrue((norm < 4e-3).all())\n\n def vector_error(self, X, Y):\n # Error relative to the size in infinity norm\n X_inf = X.abs().max(dim=-1).values\n abs_error = (Y - X).abs().max(dim=-1).values\n error = abs_error / X_inf\n # Unless X is very small, if so we do absolute error\n small = X_inf < 1e-5\n error[small] = abs_error[small]\n return error\n\n def assertHasEigenvalues(self, X, L_orig):\n L = torch.symeig(X).eigenvalues\n L_orig = torch.sort(L_orig.abs(), descending=False).values\n\n # Add the missign dimensions\n batch_dim = L.size()[:-1]\n pad_dim = batch_dim + (L.size(-1) - L_orig.size(-1),)\n L_orig = torch.cat([torch.zeros(pad_dim), L_orig], dim=-1)\n\n error = self.vector_error(L_orig, L)\n self.assertTrue((error < 1e-3).all())\n\n def test_positive_semidefinite(self):\n sizes = [\n (1, 1),\n (2, 2),\n (3, 3),\n (4, 4),\n (7, 7),\n (8, 8),\n ]\n\n rs = [1, 3, 4]\n\n with torch.random.fork_rng(devices=range(torch.cuda.device_count())):\n torch.random.manual_seed(8888)\n for cls in [PSSDLowRank, PSSDFixedRank, PSSD, PSD]:\n for (n, k), r in itertools.product(sizes, rs):\n for layer in [nn.Linear(n, k), nn.Conv2d(n, 4, k)]:\n needs_rank = cls in [PSSDLowRank, PSSDFixedRank]\n if not needs_rank and r != 1:\n continue\n # Only show r when we have a non-full rank\n print(\n \"{}({}, {}{}) on {}\".format(\n cls.__name__,\n n,\n k,\n \", {}\".format(r) if needs_rank else \"\",\n str(layer),\n )\n )\n r = min(n, k, r)\n if needs_rank:\n M = cls(size=layer.weight.size(), rank=r)\n else:\n M = cls(size=layer.weight.size())\n P.register_parametrization(layer, \"weight\", M)\n self.assertTrue(P.is_parametrized(layer, \"weight\"))\n Q_orig, L_orig = M.original\n L_orig = M.f(L_orig)\n self.assertIsOrthogonal(Q_orig)\n self.assertIsSymmetric(layer.weight)\n self.assertHasEigenvalues(layer.weight, L_orig)\n\n optim = torch.optim.SGD(layer.parameters(), lr=0.1)\n if isinstance(layer, nn.Linear):\n input_ = torch.rand(5, n)\n elif isinstance(layer, nn.Conv2d):\n # batch x in_channel x in_length x in_width\n input_ = torch.rand(6, n, 9, 8)\n\n for i in range(2):\n print(i)\n loss = layer(input_).sum()\n optim.zero_grad()\n loss.backward()\n optim.step()\n\n Q_orig, L_orig, = M.original\n L_orig = M.f(L_orig)\n self.assertIsOrthogonal(Q_orig)\n self.assertIsSymmetric(layer.weight)\n self.assertHasEigenvalues(layer.weight, L_orig)\n\n # Test update_base\n prev_out = layer(input_)\n layer.parametrizations.weight.update_base()\n new_out = layer(input_)\n self.assertAlmostEqual(\n torch.norm(prev_out - new_out).abs().max().item(),\n 0.0,\n places=3,\n )\n\n def test_positive_semidefinite_errors(self):\n for cls in [PSSDLowRank, PSSDFixedRank]:\n # rank always has to be 1 <= rank <= n\n with self.assertRaises(ValueError):\n cls(size=(4, 4), rank=5)\n with self.assertRaises(ValueError):\n cls(size=(3, 3), rank=0)\n # Instantiate it in a non-square matrix\n with self.assertRaises(ValueError):\n cls(size=(3, 6), rank=2)\n # Try to instantiate it in a vector rather than a matrix\n with self.assertRaises(ValueError):\n cls(size=(5,), rank=1)\n\n for cls in [PSSD, PSD]:\n # Try to instantiate it in a vector rather than a matrix\n with self.assertRaises(ValueError):\n cls(size=(5,))\n # Or a non-square\n with self.assertRaises(ValueError):\n cls(size=(5, 3))\n\n # Pass a non-callable object\n with self.assertRaises(ValueError):\n PSSDFixedRank(size=(5, 2), rank=1, f=3)\n # Or the wrong string\n with self.assertRaises(ValueError):\n PSSDFixedRank(size=(5, 3), rank=2, f=\"fail\")\n # Same with PSD\n with self.assertRaises(ValueError):\n PSD(size=(5, 2), f=3)\n with self.assertRaises(ValueError):\n PSD(size=(5, 3), f=\"fail\")\n" ]
[ [ "torch.norm", "torch.zeros", "torch.random.manual_seed", "torch.nn.Conv2d", "torch.nn.Linear", "torch.symeig", "torch.rand", "torch.cuda.device_count" ] ]
ecreager/beta-tcvae
[ "692d336927c0bf393e3b89e9e58ea299d93c660e" ]
[ "plot_latent_vs_true.py" ]
[ "import matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport torch\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nimport brewer2mpl\nbmap = brewer2mpl.get_map('Set1', 'qualitative', 3)\ncolors = bmap.mpl_colors\n\nplt.style.use('ggplot')\n\nVAR_THRESHOLD = 1e-2\n\n\ndef plot_vs_gt_shapes(vae, shapes_dataset, save, z_inds=None):\n dataset_loader = DataLoader(shapes_dataset, batch_size=1000, num_workers=1, shuffle=False)\n\n N = len(dataset_loader.dataset) # number of data samples\n K = vae.z_dim # number of latent variables\n nparams = vae.q_dist.nparams\n vae.eval()\n\n # print('Computing q(z|x) distributions.')\n qz_params = torch.Tensor(N, K, nparams)\n\n n = 0\n for xs in dataset_loader:\n batch_size = xs.size(0)\n xs = Variable(xs.view(batch_size, 1, 64, 64).cuda(), volatile=True)\n qz_params[n:n + batch_size] = vae.encoder.forward(xs).view(batch_size, vae.z_dim, nparams).data\n n += batch_size\n\n qz_params = qz_params.view(3, 6, 40, 32, 32, K, nparams)\n\n # z_j is inactive if Var_x(E[z_j|x]) < eps.\n qz_means = qz_params[:, :, :, :, :, :, 0]\n var = torch.std(qz_means.contiguous().view(N, K), dim=0).pow(2)\n active_units = torch.arange(0, K)[var > VAR_THRESHOLD].long()\n print('Active units: ' + ','.join(map(str, active_units.tolist())))\n n_active = len(active_units)\n print('Number of active units: {}/{}'.format(n_active, vae.z_dim))\n\n if z_inds is None:\n z_inds = active_units\n\n # subplots where subplot[i, j] is gt_i vs. z_j\n mean_scale = qz_means.mean(2).mean(2).mean(2) # (shape, scale, latent)\n mean_rotation = qz_means.mean(1).mean(2).mean(2) # (shape, rotation, latent)\n mean_pos = qz_means.mean(0).mean(0).mean(0) # (pos_x, pos_y, latent)\n\n fig = plt.figure(figsize=(3, len(z_inds))) # default is (8,6)\n gs = gridspec.GridSpec(len(z_inds), 3)\n gs.update(wspace=0, hspace=0) # set the spacing between axes.\n\n vmin_pos = torch.min(mean_pos)\n vmax_pos = torch.max(mean_pos)\n for i, j in enumerate(z_inds):\n ax = fig.add_subplot(gs[i * 3])\n ax.imshow(mean_pos[:, :, j].numpy(), cmap=plt.get_cmap('coolwarm'), vmin=vmin_pos, vmax=vmax_pos)\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_ylabel(r'$z_' + str(j) + r'$')\n if i == len(z_inds) - 1:\n ax.set_xlabel(r'pos')\n\n vmin_scale = torch.min(mean_scale)\n vmax_scale = torch.max(mean_scale)\n for i, j in enumerate(z_inds):\n ax = fig.add_subplot(gs[1 + i * 3])\n ax.plot(mean_scale[0, :, j].numpy(), color=colors[2])\n ax.plot(mean_scale[1, :, j].numpy(), color=colors[0])\n ax.plot(mean_scale[2, :, j].numpy(), color=colors[1])\n ax.set_ylim([vmin_scale, vmax_scale])\n ax.set_xticks([])\n ax.set_yticks([])\n x0, x1 = ax.get_xlim()\n y0, y1 = ax.get_ylim()\n ax.set_aspect(abs(x1 - x0) / abs(y1 - y0))\n if i == len(z_inds) - 1:\n ax.set_xlabel(r'scale')\n\n vmin_rotation = torch.min(mean_rotation)\n vmax_rotation = torch.max(mean_rotation)\n for i, j in enumerate(z_inds):\n ax = fig.add_subplot(gs[2 + i * 3])\n ax.plot(mean_rotation[0, :, j].numpy(), color=colors[2])\n ax.plot(mean_rotation[1, :, j].numpy(), color=colors[0])\n ax.plot(mean_rotation[2, :, j].numpy(), color=colors[1])\n ax.set_ylim([vmin_rotation, vmax_rotation])\n ax.set_xticks([])\n ax.set_yticks([])\n x0, x1 = ax.get_xlim()\n y0, y1 = ax.get_ylim()\n ax.set_aspect(abs(x1 - x0) / abs(y1 - y0))\n if i == len(z_inds) - 1:\n ax.set_xlabel(r'rotation')\n\n fig.text(0.5, 0.03, 'Ground Truth', ha='center')\n fig.text(0.01, 0.5, 'Learned Latent Variables ', va='center', rotation='vertical')\n plt.savefig(save)\n plt.close()\n\n\ndef plot_vs_gt_faces(vae, faces_dataset, save, z_inds=None):\n dataset_loader = DataLoader(faces_dataset, batch_size=1000, num_workers=1, shuffle=False)\n\n N = len(dataset_loader.dataset) # number of data samples\n K = vae.z_dim # number of latent variables\n nparams = vae.q_dist.nparams\n vae.eval()\n\n # print('Computing q(z|x) distributions.')\n qz_params = torch.Tensor(N, K, nparams)\n\n n = 0\n for xs in dataset_loader:\n batch_size = xs.size(0)\n xs = Variable(xs.view(batch_size, 1, 64, 64).cuda(), volatile=True)\n qz_params[n:n + batch_size] = vae.encoder.forward(xs).view(batch_size, vae.z_dim, nparams).data\n n += batch_size\n\n qz_params = qz_params.view(50, 21, 11, 11, K, nparams)\n\n # z_j is inactive if Var_x(E[z_j|x]) < eps.\n qz_means = qz_params[:, :, :, :, :, 0]\n var = torch.std(qz_means.contiguous().view(N, K), dim=0).pow(2)\n active_units = torch.arange(0, K)[var > VAR_THRESHOLD].long()\n print('Active units: ' + ','.join(map(str, active_units.tolist())))\n n_active = len(active_units)\n print('Number of active units: {}/{}'.format(n_active, vae.z_dim))\n\n if z_inds is None:\n z_inds = active_units\n\n # subplots where subplot[i, j] is gt_i vs. z_j\n mean_pose_az = qz_means.mean(3).mean(2).mean(0) # (pose_az, latent)\n mean_pose_el = qz_means.mean(3).mean(1).mean(0) # (pose_el, latent)\n mean_light_az = qz_means.mean(2).mean(1).mean(0) # (light_az, latent)\n\n fig = plt.figure(figsize=(len(z_inds), 3)) # default is (8,6)\n gs = gridspec.GridSpec(3, len(z_inds))\n gs.update(wspace=0, hspace=0) # set the spacing between axes.\n\n vmin_scale = torch.min(mean_pose_az)\n vmax_scale = torch.max(mean_pose_az)\n for i, j in enumerate(z_inds):\n ax = fig.add_subplot(gs[i])\n ax.plot(mean_pose_az[:, j].numpy())\n ax.set_ylim([vmin_scale, vmax_scale])\n ax.set_xticks([])\n ax.set_yticks([])\n x0, x1 = ax.get_xlim()\n y0, y1 = ax.get_ylim()\n ax.set_aspect(abs(x1 - x0) / abs(y1 - y0))\n if i == 0:\n ax.set_ylabel(r'azimuth')\n\n vmin_scale = torch.min(mean_pose_el)\n vmax_scale = torch.max(mean_pose_el)\n for i, j in enumerate(z_inds):\n ax = fig.add_subplot(gs[len(z_inds) + i])\n ax.plot(mean_pose_el[:, j].numpy())\n ax.set_ylim([vmin_scale, vmax_scale])\n ax.set_xticks([])\n ax.set_yticks([])\n x0, x1 = ax.get_xlim()\n y0, y1 = ax.get_ylim()\n ax.set_aspect(abs(x1 - x0) / abs(y1 - y0))\n if i == 0:\n ax.set_ylabel(r'elevation')\n\n vmin_scale = torch.min(mean_light_az)\n vmax_scale = torch.max(mean_light_az)\n for i, j in enumerate(z_inds):\n ax = fig.add_subplot(gs[2 * len(z_inds) + i])\n ax.plot(mean_light_az[:, j].numpy())\n ax.set_ylim([vmin_scale, vmax_scale])\n ax.set_xticks([])\n ax.set_yticks([])\n x0, x1 = ax.get_xlim()\n y0, y1 = ax.get_ylim()\n ax.set_aspect(abs(x1 - x0) / abs(y1 - y0))\n if i == 0:\n ax.set_ylabel(r'lighting')\n\n plt.suptitle('GT Factors vs. Latent Variables')\n plt.savefig(save)\n plt.close()\n\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('-checkpt', required=True)\n parser.add_argument('-zs', type=str, default=None)\n parser.add_argument('-gpu', type=int, default=0)\n parser.add_argument('-save', type=str, default='latent_vs_gt.pdf')\n parser.add_argument('-elbo_decomp', action='store_true')\n args = parser.parse_args()\n\n from elbo_decomposition import elbo_decomposition\n import lib.dist as dist\n import lib.flows as flows\n from vae_quant import VAE, setup_data_loaders\n\n def load_model_and_dataset(checkpt_filename):\n print('Loading model and dataset.')\n checkpt = torch.load(checkpt_filename, map_location=lambda storage, loc: storage)\n args = checkpt['args']\n state_dict = checkpt['state_dict']\n\n # model\n if not hasattr(args, 'dist') or args.dist == 'normal':\n prior_dist = dist.Normal()\n q_dist = dist.Normal()\n elif args.dist == 'laplace':\n prior_dist = dist.Laplace()\n q_dist = dist.Laplace()\n elif args.dist == 'flow':\n prior_dist = flows.FactorialNormalizingFlow(dim=args.latent_dim, nsteps=4)\n q_dist = dist.Normal()\n vae = VAE(z_dim=args.latent_dim, use_cuda=True, prior_dist=prior_dist, q_dist=q_dist, conv=args.conv)\n vae.load_state_dict(state_dict, strict=False)\n\n # dataset loader\n loader = setup_data_loaders(args)\n return vae, loader, args\n\n z_inds = list(map(int, args.zs.split(','))) if args.zs is not None else None\n torch.cuda.set_device(args.gpu)\n vae, dataset_loader, cpargs = load_model_and_dataset(args.checkpt)\n if args.elbo_decomp:\n elbo_decomposition(vae, dataset_loader)\n eval('plot_vs_gt_' + cpargs.dataset)(vae, dataset_loader.dataset, args.save, z_inds)\n\n\ndef plot_vs_gt_celeba(vae, celeba_dataset, save, z_inds=None):\n # no ground truth factors of variation...\n pass\n" ]
[ [ "torch.max", "torch.Tensor", "torch.cuda.set_device", "torch.load", "matplotlib.use", "torch.min", "torch.utils.data.DataLoader", "matplotlib.pyplot.get_cmap", "matplotlib.pyplot.savefig", "matplotlib.pyplot.close", "torch.arange", "matplotlib.pyplot.suptitle", "matplotlib.pyplot.style.use" ] ]
sammympie/scitools
[ "776c5bbfb0752ef20f242a8d0ecaa66d9141282c" ]
[ "examples/streamline_demo3.py" ]
[ "#!/usr/bin/env python\n\n# Example taken from:\n# http://www.mathworks.fr/access/helpdesk/help/techdoc/ref/streamparticles.html\n\nfrom scitools.easyviz import *\nfrom time import sleep\nfrom scipy import io\n\nwind = io.loadmat('wind_matlab_v6.mat')\nx = wind['x']\ny = wind['y']\nz = wind['z']\nu = wind['u']\nv = wind['v']\nw = wind['w']\n\nsetp(show=False)\nsx, sy, sz = ndgrid([80]*36,seq(20,55,1),[5]*36)\nsl = streamline(x,y,z,u,v,w,sx,sy,sz)\naxis('tight')\nview(30,30)\ndaspect([1,1,.125])\ncamproj('perspective')\ncamva(8)\nbox('on')\nsetp(show=True)\nshow()\n\n\nfigure()\n# alternative syntax:\nsl = streamline(x,y,z,u,v,w,sx,sy,sz,\n axis='tight',\n view=(30,30),\n daspect=[1,1,.125],\n camproj='perspective',\n camva=8,\n box='on')\n\nraw_input('Press Return key to quit: ')\n\n" ]
[ [ "scipy.io.loadmat" ] ]
williamsnider/objects
[ "c5dfc68947391e5cb8da19eb9a34a70c5d864a8a" ]
[ "objects/backbone.py" ]
[ "from splipy import Curve, BSplineBasis\nfrom objects.parameters import NUM_SAMPLES_FOR_REPARAMETERIZATION, ORDER, NUM_INTERPOLATION_POINTS, EPSILON\nfrom objects.utilities import open_uniform_knot_vector\nimport numpy as np\nfrom copy import deepcopy\n\n\nclass Backbone:\n def __init__(self, controlpoints, reparameterize=True, name=None):\n\n self.controlpoints = controlpoints\n self.num_controlpoints = self.controlpoints.shape[0]\n self.name = name\n\n # Construct B-Spline\n self.construct_B_spline()\n\n # Arc length parameterization\n if reparameterize is True:\n self.backbone = self.reparameterize()\n\n def construct_B_spline(self):\n \"\"\"Construct the initial B-spline. This is formed by the relatively small number of control points that will give the curve its shape. An open uniform knot vector is used so that the endpoints are the first and last controlpoints. The resulting curved must be reparameterized to be arc length parameterized.\"\"\"\n knot = open_uniform_knot_vector(self.num_controlpoints, ORDER)\n basis = BSplineBasis(order=ORDER, knots=knot, periodic=-1)\n self.backbone = Curve(basis=basis, controlpoints=self.controlpoints, rational=False)\n\n def reparameterize(self):\n \"\"\"Create arc length parameterization of the backbone. This is works by sampling many evenly-spaced points along the original backbone and using these as the controlpoints of a new B-spline curve with a uniform knot-vector. This reparameterization is approximate. However, by choosing a large number of sample points, the curves become very close.\n\n See https://homepage.cs.uiowa.edu/~kearney/pubs/CurvesAndSurfacesArcLength.pdf for the idea.\"\"\"\n\n #### Choose controlpoints that are evenly spaced\n\n # The arc length (that we want) to each control point\n target_arc_lengths = np.linspace(0, self.backbone.length(), NUM_INTERPOLATION_POINTS)\n\n # Sample many points along the backbone and choose the one that results in the arc length that is closest to our target arc length\n # This method seems coarse but is way faster than using a function optimizer (e.g. scipy.optimize.minimize), which is also an approximation.\n\n t = np.linspace(0, 1, NUM_SAMPLES_FOR_REPARAMETERIZATION)\n points = self.backbone(t)\n dists = np.linalg.norm(points[1:] - points[:-1], axis=1)\n cum_dists = np.cumsum(dists) # Approximate distance by summing linear distances\n idx = np.searchsorted(cum_dists, target_arc_lengths, side=\"left\")\n controlpoints = points[idx]\n\n #### Create new backbone that is reparameterized\n\n # Wrap first and last controlpoint so that new backbone goes through these endpoints\n NUM_EXTRA_CP = 2\n controlpoints_wrapped = np.zeros((NUM_INTERPOLATION_POINTS + NUM_EXTRA_CP, 3))\n controlpoints_wrapped[1:-1] = controlpoints\n controlpoints_wrapped[[0, -1]] = controlpoints[[0, -1]] # Duplicate first and last cp\n\n # Construct new backbone\n knot = np.linspace(0, 1, NUM_INTERPOLATION_POINTS + ORDER + NUM_EXTRA_CP) # uniform (not open uniform!)\n basis = BSplineBasis(order=ORDER, knots=knot, periodic=-1)\n backbone = Curve(basis=basis, controlpoints=controlpoints_wrapped, rational=False)\n backbone.reparam() # Reparameterize between 0 and 1\n\n return backbone\n\n def dx(self, t):\n \"\"\"First derivative (velocity) of b-spline backbone.\"\"\"\n\n if type(t) != type(np.array(0)):\n t = np.array(t, dtype=\"float64\")\n\n # Copy t to avoid problems when it gets changed\n t = t.copy() # Changing t was causing a bug\n\n # Handle array that may contain t == 0 or t == 1\n mask_t_0 = t == 0\n mask_t_1 = t == 1\n t[mask_t_0] = EPSILON\n t[mask_t_1] = 1 - EPSILON\n\n dx = self.backbone.derivative(t, 1)\n\n # Negative/positive values close to zero cause inconsistency when taking cross product\n dx = np.round(dx, 8)\n return dx\n\n def r(self, t):\n\n if type(t) != type(np.array(0)):\n t = np.array(t, dtype=\"float64\")\n\n return self.backbone(t)\n\n def T(self, t):\n \"\"\"Tangent vector is unit vector in same direction as velocity vector.\"\"\"\n\n if type(t) != type(np.array(0)):\n t = np.array(t, dtype=\"float64\")\n\n dx = self.dx(t)\n T = dx / np.linalg.norm(dx, axis=1, keepdims=True)\n return T\n\n def N(self, t):\n \"\"\"Normal vector is unit vector that is perpendicular to tangent vector and to [0,0,1].\n\n I chose [0,0,1] arbitrarily, in any case, it will result in the binormal vector that is perpendicular to the tangent and is pointing \"most upward\" (has largest Z-component).\"\"\"\n\n if type(t) != type(np.array(0)):\n t = np.array(t, dtype=\"float64\")\n\n UP_VECTOR = np.array([0, 0, 1])\n T = self.T(t)\n cross = np.cross(UP_VECTOR, T)\n\n # Normalize\n magnitude = np.linalg.norm(cross, axis=1, keepdims=True)\n assert np.all(\n ~np.isclose(magnitude, 0)\n ), \"Normal vectors with 0 magnitude aren't valid. This may be because the tangent vector was colinear with [0,0,1].\"\n N = cross / magnitude\n\n # Check that the two are perpendicular\n assert np.all(np.isclose(np.dot(T, N.T).diagonal(), 0)), \"Tangent and Normal vectors are not perpendicular.\"\n return N\n\n def B(self, t):\n \"\"\"Binormal vector is unit vector that is perpendicular to tangent vector and closest to [0,0,1].\"\"\"\n\n if type(t) != type(np.array(0)):\n t = np.array(t, dtype=\"float64\")\n\n T = self.T(t)\n N = self.N(t)\n cross = np.cross(T, N)\n B = cross / np.linalg.norm(cross, axis=1, keepdims=True)\n\n # Check that the two are perpendicular\n assert np.all(np.isclose(np.dot(T, N.T).diagonal(), 0)), \"Tangent and Normal vectors are not perpendicular.\"\n assert np.all(np.isclose(np.dot(T, B.T).diagonal(), 0)), \"Tangent and Normal vectors are not perpendicular.\"\n assert np.all(np.isclose(np.dot(B, N.T).diagonal(), 0)), \"Tangent and Normal vectors are not perpendicular.\"\n\n return B\n\n def length(self):\n\n return self.backbone.length()\n\n def copy(self):\n\n return deepcopy(self)\n" ]
[ [ "numpy.dot", "numpy.linspace", "numpy.cumsum", "numpy.linalg.norm", "numpy.round", "numpy.searchsorted", "numpy.cross", "numpy.array", "numpy.zeros", "numpy.isclose" ] ]
jhpenas/RodasHackathonCCR
[ "8dc8c2e5dc5f960b1da040347a4b857417564e63" ]
[ "app1/interface.py" ]
[ "from kivy.app import App\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.screenmanager import ScreenManager, Screen\nfrom kivy.core.window import Window\nfrom kivy.uix.label import Label\nfrom kivy.uix.behaviors.button import ButtonBehavior\nfrom kivy.graphics import Color, Ellipse, Rectangle, Triangle\nfrom kivy.properties import ListProperty\nfrom kivy.uix.popup import Popup\nfrom kivy.uix.image import Image\nfrom kivy.animation import Animation\nimport json\nfrom kivy.garden.mapview import MapMarkerPopup\n\n\nclass Gerenciador(ScreenManager):\n pass\n\n\nclass Menu(Screen):\n def on_pre_enter(self):\n Window.bind(on_request_close=self.confirmacao)\n\n def confirmacao(self, *args, **kwargs):\n box = BoxLayout(orientation='vertical', padding=10, spacing=10)\n botoes = BoxLayout(padding=10, spacing=10)\n\n pop = Popup(title='Deseja mesmo sair?', content=box, size_hint=(None, None),\n size=(150, 150))\n\n sim = Botao(text='Sim', on_release=App.get_running_app().stop)\n nao = Botao(text='Não', on_release=pop.dismiss)\n\n botoes.add_widget(sim)\n botoes.add_widget(nao)\n\n atencao = Image(source='atencao.png')\n\n box.add_widget(atencao)\n box.add_widget(botoes)\n\n animText = Animation(color=(0, 0, 0, 1)) + Animation(color=(1, 1, 1, 1))\n animText.repeat = True\n animText.start(sim)\n anim = Animation(size=(300, 180), duration=0.2, t='out_back')\n anim.start(pop)\n pop.open()\n return True\n\n\nclass Botao(ButtonBehavior, Label):\n cor = ListProperty([0.1, 0.5, 0.7, 1])\n cor2 = ListProperty([0.1, 0.1, 0.1, 1])\n\n def __init__(self, **kwargs):\n super(Botao, self).__init__(**kwargs)\n self.atualizar()\n\n def on_pos(self, *args):\n self.atualizar()\n\n def on_size(self, *args):\n self.atualizar()\n\n def on_press(self, *args):\n self.cor, self.cor2 = self.cor2, self.cor\n\n def on_release(self, *args):\n self.cor, self.cor2 = self.cor2, self.cor\n\n def on_cor(self, *args):\n self.atualizar()\n\n def atualizar(self, *args):\n self.canvas.before.clear()\n with self.canvas.before:\n Color(rgba=self.cor)\n Ellipse(size=(self.height, self.height),\n pos=self.pos)\n Ellipse(size=(self.height, self.height),\n pos=(self.x + self.width - self.height, self.y))\n Rectangle(size=(self.width - self.height, self.height),\n pos=(self.x + self.height / 2.0, self.y))\n\n\nclass Tarefas(Screen):\n tarefas = []\n path = ''\n\n def on_pre_enter(self):\n self.path = App.get_running_app().user_data_dir + '/'\n self.loadData()\n Window.bind(on_keyboard=self.voltar)\n for tarefa in self.tarefas:\n self.ids.box.add_widget(Tarefa(text=tarefa))\n\n def voltar(self, window, key, *args):\n if key == 27:\n App.get_running_app().root.current = 'menu'\n return True\n\n def on_pre_leave(self):\n Window.unbind(on_keyboard=self.voltar)\n\n def loadData(self, *args):\n try:\n with open(self.path + 'data.json', 'r') as data:\n self.tarefas = json.load(data)\n except FileNotFoundError:\n pass\n\n def saveData(self, *args):\n with open(self.path + 'data.json', 'w') as data:\n json.dump(self.tarefas, data)\n\n def removeWidget(self, tarefa):\n texto = tarefa.ids.label.text\n self.ids.box.remove_widget(tarefa)\n self.tarefas.remove(texto)\n self.saveData()\n\n def addWidget(self):\n texto = self.ids.texto.text\n self.ids.box.add_widget(Tarefa(text=texto))\n self.ids.texto.text = ''\n self.tarefas.append(texto)\n self.saveData()\n\n\n# Teste DASS 21\nclass Testepsi0(Screen):\n pass\n\n\nclass Testepsi1(Screen):\n pass\n\n\nclass Testepsi2(Screen):\n pass\n\n\nclass Testepsi3(Screen):\n pass\n\n\nclass Testepsi4(Screen):\n pass\n\n\nclass Testepsi5(Screen):\n pass\n\n\nclass Testepsi6(Screen):\n pass\n\n\nclass Testepsi7(Screen):\n pass\n\n\nclass Testepsi8(Screen):\n pass\n\n\nclass Testepsi9(Screen):\n pass\n\n\nclass Testepsi10(Screen):\n pass\n\n\nclass Testepsi11(Screen):\n pass\n\n\nclass Testepsi12(Screen):\n pass\n\n\nclass Testepsi13(Screen):\n pass\n\n\nclass Testepsi14(Screen):\n pass\n\n\nclass Testepsi15(Screen):\n pass\n\n\nclass Testepsi16(Screen):\n pass\n\n\nclass Testepsi17(Screen):\n pass\n\n\nclass Testepsi18(Screen):\n pass\n\n\nclass Testepsi19(Screen):\n pass\n\n\nclass Testepsi20(Screen):\n pass\n\n\nclass Testepsi21(Screen):\n pass\n\n\nclass TestepsiResult(Screen):\n pass\n\n\nclass TroqueseusPontos(Screen):\n pass\n\n\nclass MapaPsi(Screen):\n def lst_pts(self):\n import pandas as pd\n df = pd.read_csv('Tabela Psicologos - Página1.csv')\n self.lista = []\n for i in range(0, len(df)):\n lt = df.latitude[i]\n ln = df.longitude[i]\n self.lista.append((lt, ln))\n\n marker = MapMarkerPopup(lat=10, lon=15)\n self.add_widget(marker)\n\nclass EmpresasParceiras(Screen):\n pass\n\n\nclass Sobre(Screen):\n pass\n\n\nclass TesteSono0(Screen):\n pass\n\n\nclass TesteSono1(Screen):\n pass\n\nclass TesteSono2(Screen):\n pass\n\nclass TesteSono3(Screen):\n pass\n\nclass TesteSono4(Screen):\n pass\n\nclass TesteSono5(Screen):\n pass\n\nclass TesteSono6(Screen):\n pass\n\nclass TesteSono7(Screen):\n pass\n\nclass TesteSono8(Screen):\n pass\n\nclass TesteSonoR(Screen):\n pass\n\nclass Tarefa(BoxLayout):\n def __init__(self, text='', **kwargs):\n super(Tarefa, self).__init__(**kwargs)\n self.ids.label.text = text\n\n\nclass Test(App):\n def build(self):\n self.pontos = {'dep': 0, 'ans': 0, 'str': 0}\n self.sono = 0\n return Gerenciador()\n\n def calc_pontos_sono(self, *args):\n pts = self.sono\n if pts <= 6:\n sit = f'Voce fez {pts} pontos e possui um Sono normal'\n elif pts <= 8:\n sit = f'Voce fez {pts} pontos e esta na Media de sonolencia'\n else:\n sit = f'Voce fez {pts} pontos.\\nATENÇÃO! Sonolência anormal (possivelmente patológica)\\nTome muito cuidado, principalmente quando estiver na estrada e procure por ajuda médica'\n return sit\n\n def calc_pontos_dep(self, *args):\n pts = self.pontos['dep'] * 2\n if pts <= 9:\n sit = 'Normal'\n elif pts <= 13:\n sit = 'Leve'\n elif pts <= 20:\n sit = 'Moderado'\n elif pts <= 27:\n sit = 'Severo'\n else:\n sit = 'Extremamente severo'\n return sit\n\n def calc_pontos_ans(self, *args):\n pts = self.pontos['ans'] * 2\n if pts <= 7:\n sit = 'Normal'\n elif pts <= 9:\n sit = 'Leve'\n elif pts <= 14:\n sit = 'Moderado'\n elif pts <= 19:\n sit = 'Severo'\n else:\n sit = 'Extremamente severo'\n return sit\n\n def calc_pontos_str(self, *args):\n pts = self.pontos['str'] * 2\n if pts <= 14:\n sit = 'Normal'\n elif pts <= 18:\n sit = 'Leve'\n elif pts <= 25:\n sit = 'Moderado'\n elif pts <= 33:\n sit = 'Severo'\n else:\n sit = 'Extremamente severo'\n return sit\n\n def ver_situacao(self):\n if self.calc_pontos_str() == 'Extremamente severo' or self.calc_pontos_dep() == 'Extremamente severo' or self.calc_pontos_ans() == 'Extremamente severo':\n frase = 'ATENÇÃO! Você atingiu um Nível Muito Severo em uma ou mais situações. Você deveria procurar um especialista com urgência'\n elif self.calc_pontos_str() == 'Severo' or self.calc_pontos_dep() == 'Severo' or self.calc_pontos_ans() == 'Severo':\n frase = 'Você atingiu um Nível Severo em uma ou mais situações. Você deveria procurar um especialista'\n elif self.calc_pontos_str() == 'Moderado' or self.calc_pontos_dep() == 'Moderado' or self.calc_pontos_ans() == 'Moderado':\n frase = 'Você atingiu um Nível Moderado em uma ou mais situações. Você deveria procurar um especialista assim que possível'\n else:\n frase = 'Você está saúdavel mentalmente, mas se sentir necessidade, consulte um especialista'\n return frase\n\n def mudar_menu(*args):\n App.get_running_app().root.current = 'menu'\n\n def mudar_mapa(*args):\n App.get_running_app().root.current = 'mapapsi'\n\n def alerta(self, *args, **kwargs):\n box = BoxLayout(orientation='vertical', padding=10, spacing=10)\n botoes = BoxLayout(padding=10, spacing=10)\n\n pop = Popup(title=f'{self.ver_situacao()}', content=box, size_hint=(None, None),\n size=(300, 300))\n a = False\n voltar = Botao(text='Menu', on_release=self.mudar_menu)\n mapa = Botao(text='Mapa', on_release=self.mudar_mapa)\n\n botoes.add_widget(voltar)\n botoes.add_widget(mapa)\n\n atencao = Image(source='atencao.png')\n\n box.add_widget(atencao)\n box.add_widget(botoes)\n\n # animText = Animation(color=(0, 0, 0, 1)) + Animation(color=(1, 1, 1, 1))\n # animText.repeat = True\n # animText.start(mapa)\n # anim = Animation(size=(300, 180), duration=0.2, t='out_back')\n # anim.start(pop)\n pop.open()\n return True\n\n\n\n\nTest().run()\n" ]
[ [ "pandas.read_csv" ] ]
ChristianLin0420/MNE
[ "3655af79d76099ff9cedf80021d549521a80aad7" ]
[ "Preprocessing/ArtifactDetection.py" ]
[ "### Overview of artifact detection ###\n\nimport os\nimport numpy as np\nimport mne\n\nsample_data_folder = mne.datasets.sample.data_path()\nsample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',\n 'sample_audvis_raw.fif')\nraw = mne.io.read_raw_fif(sample_data_raw_file)\nraw.crop(0, 60).load_data() # just use a fraction of data for speed here\n\n\n######## Artifact detection ########\nssp_projectors = raw.info['projs']\nraw.del_proj()\n\nmag_channels = mne.pick_types(raw.info, meg='mag')\nraw.plot(duration=60, order=mag_channels, n_channels=len(mag_channels), remove_dc=False)\n\n\n######## Power line noise ########\nfig = raw.plot_psd(tmax=np.inf, fmax=250, average=True)\n# add some arrows at 60 Hz and its harmonics:\nfor ax in fig.axes[1:]:\n freqs = ax.lines[-1].get_xdata()\n psds = ax.lines[-1].get_ydata()\n for freq in (60, 120, 180, 240):\n idx = np.searchsorted(freqs, freq)\n ax.arrow(x=freqs[idx], y=psds[idx] + 18, dx=0, dy=-12, color='red',\n width=0.1, head_width=3, length_includes_head=True)\n\n\n######## Heartbeat artifacts (ECG) ########\necg_epochs = mne.preprocessing.create_ecg_epochs(raw)\necg_epochs.plot_image(combine='mean')\n\navg_ecg_epochs = ecg_epochs.average().apply_baseline((-0.5, -0.2))\navg_ecg_epochs.plot_topomap(times=np.linspace(-0.05, 0.05, 11))\navg_ecg_epochs.plot_joint(times=[-0.25, -0.025, 0, 0.025, 0.25])\n\n\n######## Ocular artifacts (EOG) ########\neog_epochs = mne.preprocessing.create_eog_epochs(raw, baseline=(-0.5, -0.2))\neog_epochs.plot_image(combine='mean')\neog_epochs.average().plot_joint()\n\n\n" ]
[ [ "numpy.searchsorted", "numpy.linspace" ] ]
VivanVatsa/wave-apps
[ "3bcaa612205cbe9da0691e99e4387d452c6f9e44" ]
[ "explaining-ratings/src/config.py" ]
[ "import pandas as pd\n\n\nclass Configuration:\n \"\"\"\n Configuration file for Explain Ratings\n \"\"\"\n\n def __init__(self):\n self.color = \"#00A8E0\"\n self.image_path = \"static/icon.png\"\n self.title = \"Hotel Reviews\"\n self.subtitle = \"Explains the hotel reviews\"\n self.icon = \"ReviewSolid\"\n self.review_column_list = ['reviews.title', 'reviews.text']\n self.training_path = \"data/Hotel_Reviews.csv\"\n self.default_model = \"explain_rating_model\"\n\n self.dataset = None\n self.filterable_columns = ['categories', 'city', 'country', 'postalCode', 'province',\n 'reviews.rating', 'reviews.userCity', 'reviews.userProvince']\n self.column_mapping = {\n 'reviews.title': 'Review Title',\n 'reviews.text': 'Review Description',\n 'categories': 'Categories',\n 'city': 'City',\n 'country': 'Country',\n 'postalCode': 'Postal Code',\n 'province': 'Province',\n 'reviews.rating': 'Rating',\n 'reviews.userCity': 'Reviewer City',\n 'reviews.userProvince': 'Reviewer Province',\n }\n\n self.boxes = {\n \"banner\": \"1 1 12 1\",\n \"content\": \"1 2 -1 -1\",\n \"left_panel\": \"1 2 3 2\",\n \"new_filter\": \"1 4 3 1\",\n \"filters\": \"1 5 3 -1\",\n \"middle_panel\": \"4 2 4 -1\",\n \"right_panel\": \"8 2 5 -1\",\n }\n\n def init_dataset(self, refresh=False):\n if refresh or self.dataset is None:\n df = pd.read_csv(self.training_path).head(50)\n df.dropna(subset=self.filterable_columns, inplace=True)\n df['reviews.rating'] = df['reviews.rating'].astype(int)\n self.dataset = df\n" ]
[ [ "pandas.read_csv" ] ]
APMonitor/arduino
[ "4d9ea70688427e610228036c44560a11246930e1" ]
[ "2_Regression/Higher_order_MIMO/APM_Python/empirical_id.py" ]
[ "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom apm import *\r\n\r\n######################################################\r\n# Configuration\r\n######################################################\r\n# number of terms\r\nny = 3 # output coefficients\r\nnu = 3 # input coefficients\r\n# number of inputs\r\nni = 2\r\n# number of outputs\r\nno = 2\r\n# load data and parse into columns\r\ndata = np.loadtxt('data_no_headers.csv',delimiter=',')\r\n######################################################\r\n\r\n# generate time-series model\r\nypred = sysid(data,ni,nu,ny)\r\n\r\n# plot results\r\nplt.figure(1)\r\nplt.subplot(2,1,1)\r\nplt.plot(data[:,0],ypred[:,0],'r-',LineWidth=2)\r\nplt.plot(data[:,0],data[:,3],'b--',LineWidth=2)\r\nplt.plot(data[:,0],ypred[:,1],'k-',LineWidth=2)\r\nplt.plot(data[:,0],data[:,4],'g:',LineWidth=2)\r\nplt.legend(['Predicted 1','Measured 1',\\\r\n 'Predicted 2','Measured 2'],loc='best')\r\nplt.ylabel('Temp (degC)')\r\n\r\nplt.subplot(2,1,2)\r\nplt.plot(data[:,0],data[:,1],'r-',LineWidth=2)\r\nplt.plot(data[:,0],data[:,2],'b--',LineWidth=2)\r\nplt.legend(['Heater 1','Heater 2'],loc='best')\r\nplt.ylabel('Heater')\r\nplt.show()\r\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "numpy.loadtxt", "matplotlib.pyplot.figure" ] ]
s0lvang/ideal-pancake
[ "f7a55f622b02b03a987d74cfdff1c51288bfb657" ]
[ "classifier/utils.py" ]
[ "import os\nfrom itertools import chain, combinations\nfrom comet_ml import ExistingExperiment, Experiment\nimport joblib\nfrom tensorflow.io import gfile\nfrom classifier import globals\nimport argparse\n\n\ndef upload_to_gcs(local_path, gcs_path):\n \"\"\"Upload local file to Google Cloud Storage.\n\n Args:\n local_path: (string) Local file\n gcs_path: (string) Google Cloud Storage destination\n\n Returns:\n None\n \"\"\"\n gfile.copy(local_path, gcs_path)\n\n\ndef dump_object(object_to_dump, output_path):\n \"\"\"Pickle the object and save to the output_path.\n\n Args:\n object_to_dump: Python object to be pickled\n output_path: (string) output path which can be Google Cloud Storage\n\n Returns:\n None\n \"\"\"\n path = f\"gs://{output_path}\"\n if not gfile.exists(path):\n gfile.makedirs(os.path.dirname(path))\n with gfile.GFile(path, \"w\") as wf:\n joblib.dump(object_to_dump, wf)\n\n\ndef download_object(path):\n bucket_path = f\"gs://{path}\"\n with gfile.GFile(bucket_path, \"rb\") as wf:\n obj = joblib.load(wf)\n return obj\n\n\ndef log_hyperparameters_to_comet(clf, experiment):\n for i in range(len(clf.cv_results_[\"params\"])):\n exp = Experiment(\n workspace=\"s0lvang\",\n project_name=\"ideal-pancake-hyperparameter\",\n api_key=globals.flags.comet_api_key,\n )\n exp.add_tag(\"hp_tuning\")\n exp.add_tags(globals.comet_logger.get_tags())\n for k, v in clf.cv_results_.items():\n if k == \"params\":\n exp.log_parameters(v[i])\n else:\n exp.log_metric(k, v[i])\n exp.end()\n\n old_experiment = ExistingExperiment(\n api_key=globals.flags.comet_api_key,\n previous_experiment=experiment.get_key(),\n )\n globals.comet_logger = old_experiment\n\n\ndef log_dataframe_to_comet(df, name):\n globals.comet_logger.log_table(f\"{name}.csv\", tabular_data=df)\n\n\ndef str2bool(v):\n if isinstance(v, bool):\n return v\n if v.lower() in (\"yes\", \"true\", \"t\", \"y\", \"1\"):\n return True\n elif v.lower() in (\"no\", \"false\", \"f\", \"n\", \"0\", \"\"):\n return False\n else:\n raise argparse.ArgumentTypeError(\"Boolean value expected.\")\n\n\ndef powerset(iterable):\n \"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)\"\n s = list(iterable)\n powerset = chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))\n return list(filter(len, powerset))\n\n\ndef normalize_series(series):\n return (series - series.min()) / (series.max() - series.min())\n\n\ndef combine_regexes_and_filter_df(df, regexes):\n combined_regex = \"|\".join(regexes)\n regex = f\"^(?:{combined_regex})\"\n df = df.loc[:, df.columns.str.contains(regex)]\n return df\n" ]
[ [ "tensorflow.io.gfile.exists", "tensorflow.io.gfile.GFile", "tensorflow.io.gfile.copy" ] ]
raikonenfnu/iree-samples
[ "4d265d8cddf2ed0124dee4ed67684cbfa9ad8fc5" ]
[ "tflitehub/mobilenet_v1_uint8_test.py" ]
[ "# RUN: %PYTHON %s\n# XFAIL: *\n\nimport absl.testing\nimport numpy\nimport test_util\n\nmodel_path = \"https://storage.googleapis.com/iree-model-artifacts/mobilenet_v1_224_1.0_uint8.tflite\"\n\nclass MobilenetV1Uint8Test(test_util.TFLiteModelTest):\n def __init__(self, *args, **kwargs):\n super(MobilenetV1Uint8Test, self).__init__(model_path, *args, **kwargs)\n\n def compare_results(self, iree_results, tflite_results, details):\n super(MobilenetV1Uint8Test, self).compare_results(iree_results, tflite_results, details)\n self.assertTrue(numpy.isclose(iree_results[0], tflite_results[0], atol=1.0).all())\n\n def test_compile_tflite(self):\n self.compile_and_execute()\n\nif __name__ == '__main__':\n absl.testing.absltest.main()\n\n" ]
[ [ "numpy.isclose" ] ]
drublackberry/prove-it
[ "61db9d2e39c7e75e4d715348245c7212fc02964e" ]
[ "financial/Markowitz.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nScript to show the Markowitz bullet working principle with two assets\r\nand different correlation coefficients\r\n\r\nCreated on Wed Oct 14 13:03:05 2015\r\n\r\n@author: Andreu Mora\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nx = [0.5, 0.5]\r\n\r\nmu = np.array([3./100, 1./100])\r\nsigma = np.array([15./100, 5./100])\r\nlabel = ['Asset A', 'Asset B']\r\nrf = 0.5/100\r\n\r\nf = plt.figure()\r\n\r\nw = np.zeros((100,2))\r\nw[:,0] = np.linspace(-0.5,1.5,w.shape[0])\r\nw[:,1] = 1 - w[:,0]\r\n\r\ncorr_vec = [-1, -0.5, 0, 0.5, 1]\r\nfor corr in corr_vec:\r\n \r\n # Processing\r\n cov = [[sigma[0]**2, corr*sigma[0]*sigma[1]],[corr*sigma[0]*sigma[1], sigma[1]**2]]\r\n \r\n ret_out = np.dot(w, mu)\r\n var = ret_out*0\r\n for i in range(0,w.shape[0]):\r\n var[i] = np.dot(np.dot(w[i], cov), w[i])\r\n std_out = np.sqrt(var)\r\n plt.plot(std_out, ret_out)\r\n \r\n # Compute the minimum variance portfolio\r\n inv_cov = np.linalg.inv(cov)\r\n Sigma_1 = np.dot(inv_cov, [1,1])\r\n m = Sigma_1 / np.dot([1,1], Sigma_1)\r\n ret_m = np.dot(m, mu)\r\n var_m = np.dot(np.dot(m,cov),m)\r\n std_m = np.sqrt(var_m)\r\n plt.plot(std_m, ret_m, '*')\r\n \r\n # Compute the tangency portfolio\r\n Sigma_rf = np.dot(inv_cov, mu-rf)\r\n tan = Sigma_rf / np.dot([1,1], Sigma_rf)\r\n ret_tan = np.dot(tan, mu)\r\n var_tan = np.dot(np.dot(tan,cov),tan)\r\n std_tan = np.sqrt(var_tan)\r\n plt.plot([0, std_tan], [rf, ret_tan], '--k')\r\n\r\nplt.grid()\r\nfor i in [0,1]:\r\n #plt.plot(sigma[i], mu[i],'b*')\r\n plt.text(sigma[i], mu[i], label[i])\r\n plt.hold()\r\nplt.show()\r\n#plt.legend(corr_vec, loc=2)\r\nplt.title('Markowitz bullet for two assets with tangency and minimum variance')" ]
[ [ "numpy.dot", "numpy.sqrt", "numpy.linspace", "matplotlib.pyplot.title", "numpy.linalg.inv", "matplotlib.pyplot.hold", "matplotlib.pyplot.plot", "matplotlib.pyplot.grid", "matplotlib.pyplot.text", "numpy.array", "numpy.zeros", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
fpbattaglia/ophys_io
[ "9fdc1507184a6dc815fe29e767bd8f50b2408933" ]
[ "oio/conversion.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Jun 15, 2014 23:40\n@author: <'Ronny Eichler'> [email protected]\n\nReads Open Ephys .continuous files and converts them to raw 16-bit .dat files\n\"\"\"\n\nimport os\nimport time\nimport logging\nimport os.path as op\nfrom contextlib import ExitStack\n\nimport numpy as np\nimport oio.open_ephys_io as oe\nfrom oio.util import fmt_time\n\nLOG_STR_INPUT = '==> Input: {path}'\nLOG_STR_OUTPUT = '<== Output {path}'\nLOG_STR_CHAN = 'Channels: {channels}, reference: {reference}, Dead: {dead}, ' \\\n 'proc_node: {proc_node}, write mode: {file_mode}'\nLOG_STR_ITEM = ', Header: channel: {header[channel]}, date: {header[date_created]}'\nDEBUG_STR_CHUNK = '~ Reading {count} records (left: {left}, max: {num_records})'\nDEBUG_STR_REREF = '~ Re-referencing by subtracting average of channels {channels}'\nDEBUG_STR_ZEROS = '~ Zeroing (Flag: {flag}) dead channel {channel}'\n\nMODE_STR = {'a': 'Append', 'w': \"Write\"}\nMODE_STR_PAST = {'a': 'Appended', 'w': \"Wrote\"}\n\n\ndef continuous_to_dat(input_path, output_path, channel_group, proc_node=100,\n file_mode='w', chunk_records=10000, duration=False,\n dead_channels=None, zero_dead_channels=True):\n \"\"\"Given an input directory [in_dir] will write or append .continuous files for channels in [channels] iterable\n of an open ephys [proc_node] into single [outfile] .dat file.\n Data is transferred in batches of [chunk_records] 2kiB records per channel.\n \"\"\"\n\n start_t = time.time()\n logger = logging.getLogger(output_path)\n file_handler = logging.FileHandler(output_path + '.log', mode=file_mode)\n formatter = logging.Formatter('%(message)s')\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n logger.setLevel(logging.DEBUG)\n\n logger.info(LOG_STR_INPUT.format(path=input_path))\n logger.info(LOG_STR_OUTPUT.format(path=output_path))\n\n # NOTE: Channel numbers zero-based in configuration, but not in file name space. Grml.\n data_channels = [cid + 1 for cid in channel_group['channels']]\n ref_channels = [rid + 1 for rid in channel_group['reference']] if \"reference\" in channel_group else []\n dead_channels = [did + 1 for did in dead_channels]\n logger.info(\"Dead channels to zero: {}, {}\".format(zero_dead_channels, dead_channels))\n\n dead_channels_indices = [data_channels.index(dc) for dc in dead_channels if dc in data_channels]\n\n data_file_paths = oe.gather_files(input_path, data_channels, proc_node)\n ref_file_paths = oe.gather_files(input_path, ref_channels, proc_node)\n\n logger.info(LOG_STR_CHAN.format(channels=data_channels,\n reference=ref_channels, dead=dead_channels,\n proc_node=proc_node, file_mode=MODE_STR[file_mode]))\n\n try:\n with ExitStack() as stack, open(output_path, file_mode + 'b') as out_fid_dat:\n\n data_files = [stack.enter_context(oe.ContinuousFile(f)) for f in data_file_paths]\n ref_files = [stack.enter_context(oe.ContinuousFile(f)) for f in ref_file_paths]\n for oe_file in data_files:\n logger.info(\"Open data file: {}\".format(op.basename(oe_file.path)) +\n LOG_STR_ITEM.format(header=oe_file.header))\n for oe_file in ref_files:\n logger.info(\"Open reference file: {}\".format(op.basename(oe_file.path)) +\n LOG_STR_ITEM.format(header=oe_file.header))\n\n num_records, sampling_rate, buffer_size, block_size = oe.check_headers(data_files + ref_files)\n\n # If duration limited, find max number of records that should be grabbed\n records_left = num_records if not duration \\\n else min(num_records, int(duration * sampling_rate // block_size))\n if records_left < 1:\n epsilon = 1/sampling_rate*block_size*1000\n logger.warning(\"Remaining duration limit ({:.0f} ms) less than duration of single block ({:.0f} ms).\"\n \" Skipping target.\".format(duration*1000, epsilon))\n return 0\n\n # # preallocate temporary storage\n # buf = oe.make_buffer(len(data_channels), chunk_records)\n\n # loop over all records, in chunk sizes\n bytes_written = 0\n while records_left:\n count = min(records_left, chunk_records)\n\n logger.debug(DEBUG_STR_CHUNK.format(count=count, left=records_left,\n num_records=num_records))\n res = np.vstack([f.read_record(count) for f in data_files])\n\n # reference channels if needed\n if len(ref_channels):\n logger.debug(DEBUG_STR_REREF.format(channels=ref_channels))\n res -= np.vstack([f.read_record(count) for f in ref_files]).mean(axis=0, dtype=np.int16)\n\n # zero dead channels if needed\n if len(dead_channels_indices) and zero_dead_channels:\n zeros = np.zeros_like(res[0])\n for dci in dead_channels_indices:\n logger.debug(DEBUG_STR_ZEROS.format(flag=zero_dead_channels, channel=data_channels[dci]))\n res[dci] = zeros\n\n res.transpose().tofile(out_fid_dat)\n\n # offset = num_records - records_left\n\n # # load chunk of data from all channels\n # for n, fname in enumerate(file_paths):\n # buf[n, 0:count * oe.NUM_SAMPLES] = oe.read_records(fname, record_count=count,\n # record_offset=offset)['samples'].ravel()\n # out_fid_log.write(DEBUG_STR_CHUNK.format(filename=fname, count=count,\n # start=offset, end=offset + count - 1))\n #\n # # write chunk of interleaved data\n # if count == chunk_records:\n # buf.transpose().tofile(out_fid_dat)\n # else:\n # # We don't want to write the trailing zeros on the last chunk\n # buf[:, 0:count * oe.NUM_SAMPLES].transpose().tofile(out_fid_dat)\n # out_fid_log.write('\\n')\n\n records_left -= count\n bytes_written += (count * 2048 * len(data_channels))\n\n data_duration = bytes_written / (2 * sampling_rate * len(data_channels))\n elapsed = time.time() - start_t\n speed = bytes_written / elapsed\n logger.info('{appended} {channels} channels into \"{op:s}\"'.format(\n appended=MODE_STR_PAST[file_mode], channels=len(data_channels),\n op=os.path.abspath(output_path)))\n logger.info('{rec} blocks ({dur:s}, {bw:.2f} MB) in {et:.2f} s ({ts:.2f} MB/s)'.format(\n rec=num_records-records_left, dur=fmt_time(data_duration),\n bw=bytes_written / 1e6, et=elapsed, ts=speed / 1e6))\n\n # returning duration of data written, epsilon=1 sample, allows external loop to make proper judgement if\n # going to next target makes sense via comparison. E.g. if time less than one sample short of\n # duration limit.\n logger.removeHandler(file_handler)\n file_handler.close()\n\n return data_duration\n\n except IOError as e:\n print('Operation failed: {error}'.format(error=e.strerror))\n\n\ndef kwik_to_dat(*args, **kwargs):\n print(args, kwargs)\n raise NotImplementedError\n" ]
[ [ "numpy.zeros_like" ] ]
derangedhk417/SpectrumPlot
[ "b315edf3db8d22812631614f79bc848ec20c1841" ]
[ "src/SpectrumPlot.py" ]
[ "# Author: Adam Robinson\n# Description: This script is designed to plot one or more vdat files \n# containing Raman or PL spectra. It includes cosmic ray removal, peak\n# detection and various other functionality.\n\nfrom datetime import datetime\nfrom glob import glob\nfrom scipy.integrate import trapz\nfrom scipy.signal import find_peaks\nfrom scipy.ndimage import gaussian_filter\nfrom scipy.interpolate import interp1d\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport argparse\nimport code\nimport json\n\nhc = 1.986445e-25\njte = 6.242e18\n\n# Parses a vdat file and extracts the timestamp, header values and\n# data. The data is stored in VDATfile.data, where the columns are\n#\n# 1) Wavelength (nm)\n# 2) Wavenumber (cm^-1)\n# 3) Intensity (counts)\nclass VDATFile:\n\tdef __init__(self, path):\n\t\twith open(path, 'r') as file:\n\t\t\tself.raw_text = file.read()\n\n\t\tself.raw_text.replace('\\r', '')\n\t\tself.lines = self.raw_text.split(\"\\n\")\n\t\tself.lines = [l for l in self.lines if l.strip() != '']\n\n\t\tself.parseHeader()\n\t\tself.parseData()\n\n\tdef parseHeader(self):\n\t\t# First, read the date and time.\n\t\tself.datetime = datetime.strptime(self.lines[0], '%m/%d/%Y %I:%M %p')\n\n\t\t# The second line should be the fields.\n\t\traw_fields = self.lines[1].split(\"\\t\")\n\t\tself.fields = {} \n\n\t\tfor f in raw_fields:\n\t\t\tk, v = f.split(':')\n\t\t\tself.fields[k.strip()] = float(v.strip())\n\n\t\tself.comments = self.lines[2].split(':')[1].strip()\n\n\tdef parseData(self):\n\t\tself.data = [list(map(float, line.split('\\t'))) for line in self.lines[5:]]\n\nclass RRUFFFile:\n\tdef __init__(self, path):\n\t\twith open(path, 'r') as file:\n\t\t\tself.raw_text = file.read()\n\n\t\tself.raw_text.replace('\\r', '')\n\t\tself.lines = self.raw_text.split(\"\\n\")\n\t\tself.lines = [l for l in self.lines if l.strip() != '']\n\n\t\tself.parseData()\n\n\tdef parseData(self):\n\t\tdata = [list(map(float, line.split(','))) for line in self.lines[12:-1]]\n\t\tdata = np.array(data)\n\t\tself.data = np.zeros((len(data), 3))\n\t\tself.data[:, 1] = data[:, 0]\n\t\tself.data[:, 2] = data[:, 1]\n\nclass CSVFile:\n\tdef __init__(self, path):\n\t\twith open(path, 'r') as file:\n\t\t\tself.raw_text = file.read()\n\n\t\tself.raw_text.replace('\\r', '')\n\t\tself.lines = self.raw_text.split(\"\\n\")\n\t\tself.lines = [l for l in self.lines if l.strip() != '']\n\n\t\tself.parseData()\n\n\tdef parseData(self):\n\t\tdata = [list(map(float, line.split(','))) for line in self.lines[1:]]\n\t\tdata = np.array(data)\n\t\tself.data = np.zeros((len(data), 3))\n\t\tself.data[:, 1] = data[:, 1]\n\t\tself.data[:, 2] = data[:, 0]\n\n# Process the command line arguments supplied to the program. These will be \n# in the json file named \"SpectrumPlot.py\"\ndef preprocess(args_specification):\n\tparser = argparse.ArgumentParser(description=args_specification['description'])\n\n\ttypes = {'str': str, 'int': int, 'float': float}\n\n\tfor argument in args_specification['arguments']:\n\t\tspec = argument['spec']\n\t\tif 'type' in spec:\n\t\t\tspec['type'] = types[spec['type']]\n\t\tparser.add_argument(\n\t\t\t*argument['names'], \n\t\t\t**spec\n\t\t)\n\n\targs = parser.parse_args()\n\n\treturn args\n\nif __name__ == '__main__':\n\twith open(\"SpectrumPlot.json\", 'r') as file:\n\t\targs_specification = json.loads(file.read())\n\n\targs = preprocess(args_specification)\n\n\t# Load all of the files specified by the user.\n\tfiles = []\n\tfor path in args.inputs:\n\t\tfiles.extend(glob(path))\n\n\tfiles = sorted(files)\n\n\tbackground = None\n\tif args.background_file != \"\":\n\t\tfile = glob(args.background_file)[0]\n\t\text = file.split('.')[-1].lower()\n\t\tif ext == 'vdat':\n\t\t\tv = VDATFile(file)\n\t\telif ext == 'rruff':\n\t\t\tv = RRUFFFile(file)\n\t\telif ext == 'csv':\n\t\t\tv = CSVFile(file)\n\t\telse:\n\t\t\tprint(\"Unrecognized file extension %s\"%ext)\n\t\t\texit()\n\t\t\n\t\tbackground = np.array(v.data)\n\t\tbackground[:, 2] -= background[:, 2].min()\n\n\t\tn_x = background.shape[0] * 4\n\t\tlaser_line = float(v.fields[\"Laser Wavelength (nm)\"])\n\t\tlaser_cm = 1 / (laser_line * 1e-7)\n\n\t\t# We're going to interpolate the data and quadruple the resolution\n\t\t# in order to make any offsets applied later look right.\n\t\tinterp_nm = interp1d(background[:, 0], background[:, 2], kind=\"cubic\")\n\t\tbackground_nm_new = np.linspace(background[0, 0], background[-1, 0], n_x)\n\t\tbackground_cm_new = laser_cm - (1 / (background_nm_new * 1e-7)) \n\n\t\tbackground = np.stack([\n\t\t\tbackground_nm_new,\n\t\t\tbackground_cm_new,\n\t\t\tinterp_nm(background_nm_new)\n\t\t], axis=1)\n\n\n\tif background is not None:\n\t\tbackground[:, 2] = background[:, 2] / args.background_normalization\n\n\tif args.background_offset != 0:\n\t\t# In order to apply a horizontal offset correctly we'll have to interpolate the data.\n\n\t\tif args.PL or args.NM:\n\t\t\t# Shift by the nanometer\n\t\t\tinput_dim = 0\n\t\telse:\n\t\t\t# Shift by the inverse centimeter\n\t\t\tinput_dim = 1\n\n\t\tinterp = interp1d(background[:, input_dim], background[:, 2], kind=\"linear\")\n\n\t\tx_values = background[:, input_dim]\n\t\tx_shifted = x_values - args.background_offset\n\t\tfor idx, x_val in enumerate(x_shifted):\n\t\t\tif x_val >= x_values[0] and x_val <= x_values[-1]:\n\t\t\t\tbackground[idx, 2] = interp(x_val)\n\t\n\t# Load the files into a vdat data structure.\n\tdataset = []\n\tvdat = []\n\tfor idx, file in enumerate(files):\n\t\t# Figure out the extension and us the appropriate loader.\n\t\text = file.split('.')[-1].lower()\n\t\tif ext == 'vdat':\n\t\t\tv = VDATFile(file)\n\t\t\tvdat.append(v)\n\t\telif ext == 'rruff':\n\t\t\tv = RRUFFFile(file)\n\t\telif ext == 'csv':\n\t\t\tv = CSVFile(file)\n\t\telse:\n\t\t\tprint(\"Unrecognized file extension %s\"%ext)\n\t\t\texit()\n\n\t\td = np.array(v.data)\n\t\td[:, 2] -= d[:, 2].min()\n\n\n\t\tn_x = d.shape[0] * 4\n\t\tlaser_line = float(v.fields[\"Laser Wavelength (nm)\"])\n\t\tlaser_cm = 1 / (laser_line * 1e-7)\n\n\t\t# We're going to interpolate the data and quadruple the resolution\n\t\t# in order to make any offsets applied later look right.\n\t\tinterp_nm = interp1d(d[:, 0], d[:, 2], kind=\"cubic\")\n\t\td_nm_new = np.linspace(d[0, 0], d[-1, 0], n_x)\n\t\td_cm_new = laser_cm - (1 / (d_nm_new * 1e-7)) \n\n\t\td = np.stack([\n\t\t\td_nm_new,\n\t\t\td_cm_new,\n\t\t\tinterp_nm(d_nm_new)\n\t\t], axis=1)\n\n\n\t\t# Apply x-offsets\n\t\tif args.x_offsets != []:\n\t\t\tif args.PL or args.NM:\n\t\t\t\t# Shift by the nanometer\n\t\t\t\tinput_dim = 0\n\t\t\telse:\n\t\t\t\t# Shift by the inverse centimeter\n\t\t\t\tinput_dim = 1\n\n\t\t\tinterp = interp1d(d[:, input_dim], d[:, 2], kind=\"linear\")\n\n\t\t\tx_values = d[:, input_dim]\n\t\t\tx_shifted = x_values - args.x_offsets[idx]\n\t\t\tfor i, x_val in enumerate(x_shifted):\n\t\t\t\tif x_val >= x_values[0] and x_val <= x_values[-1]:\n\t\t\t\t\td[i, 2] = interp(x_val)\n\n\t\t# Apply manual normalization constants\n\t\tif args.manual_normalizations != []:\n\t\t\td[:, 2] = d[:, 2] / args.manual_normalizations[idx]\n\n\t\t\n\t\tif background is not None and not args.normalize:\n\t\t\td[:, 2] -= background[:, 2]\n\t\t\n\t\tdataset.append(d)\n\n\n\t# Calculate the max value across the entire spectrum so we can scale \n\t# label locations appropriately.\n\tmax_values = []\n\tmin_values = []\n\tfor data in dataset:\n\t\tmax_values.append(data[:, 2].max())\n\t\tmin_values.append(data[:, 2].min())\n\n\tmax_value = max(max_values)\n\tmin_value = min(min_values)\n\t_range = max_value - min_value\n\n\t# Remove cosmics if requested.\n\tif args.correct_cosmics:\n\t\tcosmic_centers = []\n\t\tcosmic_lefts = []\n\t\tcosmic_rights = []\n\t\tmin_prominence = _range / args.prominence_divisor\n\t\tfor data in dataset:\n\t\t\tprobable_cosmics = find_peaks(\n\t\t\t\tdata[:, 2], \n\t\t\t\twidth=[1, 6], \n\t\t\t\tprominence=[min_prominence, 100000]\n\t\t\t)\n\n\t\t\tcosmic_centers.append(list(probable_cosmics[0]))\n\t\t\tcosmic_lefts.append(list(probable_cosmics[1]['left_ips']))\n\t\t\tcosmic_rights.append(list(probable_cosmics[1]['right_ips']))\n\n\tif args.manual_cosmics != []:\n\t\tif not args.correct_cosmics:\n\t\t\tcosmic_centers = []\n\t\t\tcosmic_lefts = []\n\t\t\tcosmic_rights = []\n\t\t\tfor data in dataset:\n\t\t\t\tcosmic_centers.append([])\n\t\t\t\tcosmic_lefts.append([])\n\t\t\t\tcosmic_rights.append([])\n\n\t\tif len(args.manual_cosmics) % 3 != 0:\n\t\t\tprint(\"Manual cosmics must be specified in pairs of three (idx, min, max)\")\n\t\t\texit()\n\t\t\n\t\tfor base_idx in range(len(args.manual_cosmics) // 3):\n\t\t\tidx = int(args.manual_cosmics[base_idx])\n\t\t\tlow = args.manual_cosmics[base_idx + 1]\n\t\t\thigh = args.manual_cosmics[base_idx + 2]\n\n\t\t\tdef index_from_wavenumber(idx, k):\n\t\t\t\tclosest_index = 0\n\t\t\t\tclosest = 10000\n\t\t\t\tfor i, k0 in enumerate(dataset[idx][:, 1]):\n\t\t\t\t\tdist = np.abs(k - k0)\n\t\t\t\t\tif dist < closest:\n\t\t\t\t\t\tclosest = dist\n\t\t\t\t\t\tclosest_index = i\n\n\t\t\t\treturn closest_index\n\n\t\t\tcosmic_centers[idx].append(index_from_wavenumber(idx, (high - low) / 2))\n\t\t\tcosmic_lefts[idx].append(index_from_wavenumber(idx, low))\n\t\t\tcosmic_rights[idx].append(index_from_wavenumber(idx, high))\n\n\n\t# Normalize the data if requested.\n\tif args.normalize:\n\t\tif background is not None:\n\t\t\tbg_integral = trapz(background[:, 2], background[:, 1])\n\t\t\tbackground[:, 2] = background[:, 2] / bg_integral\n\t\tfor idx, data in enumerate(dataset):\n\t\t\tintegral = trapz(data[:, 2], data[:, 1])\n\t\t\tdataset[idx][:, 2] = dataset[idx][:, 2] / integral\n\t\t\t\n\t\t\tif background is not None:\n\t\t\t\tdataset[idx][:, 2] -= background[:, 2]\n\n\n\tfig, ax = plt.subplots(1, 1)\n\n\n\t# Offset the data points based on the specified offset.\n\tif args.offset != 0:\n\t\tcumulative_offset = 0\n\t\tfor idx, data in enumerate(dataset):\n\t\t\tdataset[idx][:, 2] = dataset[idx][:, 2] + cumulative_offset\n\t\t\tcumulative_offset += args.offset\n\n\t# Remove the cosmic rays detected in an earlier step (if requested)\n\tif args.correct_cosmics:\n\t\tfor idx in range(len(dataset)):\n\t\t\tds_centers = cosmic_centers[idx]\n\t\t\tds_rights = cosmic_rights[idx]\n\t\t\tds_lefts = cosmic_lefts[idx]\n\n\t\t\tfor c, l, r in zip(ds_centers, ds_lefts, ds_rights):\n\t\t\t\t# Find the datapoint that straddles the peak on the\n\t\t\t\t# left and on the right. We will use these to produce a linear\n\t\t\t\t# interpolation over the range of the cosmic.\n\t\t\t\tleft_idx = int(round(l)) - 1\n\t\t\t\tright_idx = int(round(r)) + 1\n\t\t\t\tleft_x = dataset[idx][left_idx, 1]\n\t\t\t\tright_x = dataset[idx][right_idx, 1]\n\t\t\t\tleft_point = dataset[idx][left_idx, 2]\n\t\t\t\tright_point = dataset[idx][right_idx, 2]\n\t\t\t\tslope = (right_point - left_point) / (right_x - left_x)\n\n\t\t\t\t# Now we take all of the indices that are greater than left_idx\n\t\t\t\t# and less than right_idx and replace the data points with an interpolation.\n\t\t\t\tcorrection_idx = left_idx + 1\n\t\t\t\twhile correction_idx < right_idx:\n\t\t\t\t\tx = dataset[idx][correction_idx, 1]\n\t\t\t\t\tdataset[idx][correction_idx, 2] = left_point + (x - left_x) * slope\n\t\t\t\t\tcorrection_idx += 1\n\n\tif args.gaussian_convolve != 0.0:\n\t\tfor idx, data in enumerate(dataset):\n\t\t\tdataset[idx][:, 2] = gaussian_filter(dataset[idx][:, 2], args.gaussian_convolve)\n\n\tif args.PL:\n\t\tfor data in dataset:\n\t\t\tdata[:, 1] = jte * (hc / data[:, 0]) * 1e9\n\telif args.NM:\n\t\tfor data in dataset:\n\t\t\tdata[:, 1] = data[:, 0]\n\t\t\t\n\tplots = []\n\tfor data in dataset:\n\t\tpl, = ax.plot(data[:, 1], data[:, 2])\n\t\tplots.append(pl)\n\n\t# Label each series based on the specified field in the file header.\n\tif args.manual_labels != []:\n\t\tax.legend(\n\t\t\t\tplots,\n\t\t\t\targs.manual_labels\n\t\t\t)\n\telse:\n\t\tif args.label_fields != []:\n\t\t\tlabels = []\n\t\t\tfor v in vdat:\n\t\t\t\tl = []\n\t\t\t\tfor field in args.label_fields:\n\t\t\t\t\tl.append(str(v.fields[field]))\n\t\t\t\tlabels.append(\" / \".join(l))\n\n\t\t\tax.legend(\n\t\t\t\tplots,\n\t\t\t\tlabels\n\t\t\t)\n\t\telse:\n\t\t\tlabels = [f.split('/')[-1] for f in files]\n\t\t\tax.legend(\n\t\t\t\tplots,\n\t\t\t\tlabels\n\t\t\t)\n\n\t# Draw peak labels as requested.\n\tif args.peaks != []:\n\t\tif args.labels == []:\n\t\t\tlabels = [str(p) for p in args.peaks]\n\t\telse:\n\t\t\tlabels = args.labels\n\n\t\tfor idx, peak in enumerate(args.peaks):\n\t\t\tax.axvline(peak, c='green', linestyle='-.')\n\n\t\t\t# Find the highest value within plus or minus 5 inverse centimeters\n\t\t\t# of this peak and place the label above it.\n\t\t\thighest = 0\n\t\t\tfor data in dataset:\n\t\t\t\tfor k, c in zip(data[:, 1], data[:, 2]):\n\t\t\t\t\tif k > peak - 5 and k < peak + 5:\n\t\t\t\t\t\tif c > highest:\n\t\t\t\t\t\t\thighest = c\n\n\t\t\tax.text(peak + 2, highest + (_range / 50), labels[idx])\n\n\t\n\n\n\n\t# DEBUG CODE\n\t# # Plot locations where there are cosmics identified.\n\t# if args.correct_cosmics:\n\t# \tfor cosmic in cosmics:\n\t# \t\tax.axvline(dataset[0][cosmic, 1], c='red')\n\n\t# \tfor l, r in zip(lb, rb):\n\t# \t\tax.axvline(dataset[0][int(round(l)), 1], c='green')\n\t# \t\tax.axvline(dataset[0][int(round(r)), 1], c='green')\n\n\n\t#code.interact(local=locals())\n\n\n\tif args.PL:\n\t\tax.set_xlabel(r\"Energy [$eV$]\")\n\telif args.NM:\n\t\tax.set_xlabel(r\"Wavelength [$nm$]\")\n\telse:\n\t\tax.set_xlabel(r\"Relative Wavenumber [$cm^{-1}$]\")\n\tif args.normalize:\n\t\tax.set_ylabel(r\"Arbitrary Units\")\n\telse:\n\t\tax.set_ylabel(r\"Intensity [counts]\")\n\tax.set_title(args.title)\n\n\tplt.show()\n\n\t\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" ]
[ [ "scipy.signal.find_peaks", "scipy.ndimage.gaussian_filter", "numpy.linspace", "numpy.abs", "scipy.integrate.trapz", "matplotlib.pyplot.subplots", "scipy.interpolate.interp1d", "numpy.array", "matplotlib.pyplot.show" ] ]
GCA-VH-lab/2019-NAR
[ "c355fc5f2ac414ab8c365397c2595ecd07b50020" ]
[ "scripts/hdf_2_bedgraph.py" ]
[ "#!/usr/bin/env python\n#\n# assumes *.h5 conains all positions in index for each chr\n# it is not practical but works for yeast\n#\nimport sys\nimport argparse\nimport pandas as pd\n#import numpy as np\n\nparser = argparse.ArgumentParser(description='Converts Ribo-Seq coverage to bedgraph format.')\nparser.add_argument('-iN', type=str, help='Sample name')\nparser.add_argument('-i', type=str, help='*.hd5 file name')\nparser.add_argument('-dtype', type=str, help='Data type for oufile', default='raw')\nparser.add_argument('-col', type=str, help='column for values - default is \"sum\"', default='sum')\nparser.add_argument('-v', '--verbose', help=\"increase output verbosity\", action=\"store_true\")\nargs = parser.parse_args()\n\nif args.verbose:\n print(\"verbosity turned on\")\n \nprint(\"\\n-iN prefix: {}\\n-i input table: {}\\n-dtype str for outfile: {}\\n-col column: {}\\n\".format(args.iN, args.i, args.dtype, args.col))\n\nusage = \"./hdf2bedgraph.py -iN WTS1 -i 9-Assigncorr/WTS1_5-End_28-33_idx_assign_rpm.h5 -dtype rpm -col sum\"\n\nif (args.i==None)|(args.iN==None):\n sys.exit(\"\\n usage:\\n\\t{}\\n\".format(usage))\n\niN = args.iN\ninfile_h5 = args.i\ncol = args.col\ndtype = args.dtype\n\nstorage = pd.HDFStore(infile_h5, \"r\")\n\n# open file for Forward BedGraph\nf1 = iN + '_'+ dtype +'_For.bedgraph'\nf2 = iN + '_'+ dtype +'_Rev.bedgraph'\noutfile_forward = open(f1, 'w+')\noutfile_reverse = open(f2, 'w+')\n\n# chr_list=list(set(df_f.Chr))\nchr_list = ['I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII','XIII','XIV',\n 'XV','XVI','Mito']\nchr_length = { 'I':230218, 'II':813184, 'III':316620, 'IV':1531933, 'IX':439888, 'Mito':85779, \n'V':576874, 'VI':270161, 'VII':1090940, 'VIII':562643, 'X':745751, 'XI':666816, 'XII':1078177,\n'XIII':924431, 'XIV':784333, 'XV':1091291, 'XVI':948066 }\n# Generate header\nheader_1 = 'track type=bedGraph name=\"{} F {}\" description=\"SacCer3 BedGraph format\"\\n'.format(iN,dtype)\nheader_2 = 'track type=bedGraph name=\"{} R {}\" description=\"SacCer3 BedGraph format\"\\n'.format(iN,dtype)\n# Write header to file\noutfile_forward.write(header_1)\noutfile_reverse.write(header_2)\n\n\ndef series_2_df(s):\n '''return df with column \"sum\" '''\n s.name='sum'\n return pd.DataFrame(s)\n\n\ndef df_fill_iv(df1, index, columns):\n \"\"\" returns df what contains values for all positions in the given range\n df1 is condensed df containing positions with values > 0\n :param df1: condensed df, i. e. don't contain rows with 0 in index\n :param index: range of genome positions\n :param columns: list of read length + 'sum'\n \"\"\"\n # create df2\n df2 = pd.DataFrame(0, index=index, columns=columns)\n df1 = df1.add(df2, fill_value=0, axis=1)\n return df1[columns]\n \n \nfor ref in chr_list: # take one Chr\n print(\" {} ...\".format(ref))\n \n ######################\n # For Forward strand\n key = \"For_rpm/\" + ref\n df_ref_f = storage[key]\n # convert series to df\n if type(df_ref_f) == pd.core.series.Series:\n df_ref_f = series_2_df(df_ref_f)\n # For collecting data\n rpm_start = 0 # initial_value\n pos_start = 0 # remember start\n len_incr = 0 # append to length #! might be omitted\n rpm_current = 0 # current_value #! might be omitted\n \n # interval -> continious\n index = list(range(chr_length[ref]+1))\n columns = ['sum']\n df_ref_f = df_fill_iv(df_ref_f, index, columns)\n \n # going throug each position for current reference (Chr)\n for i in df_ref_f.index:\n # current value (rpm) in a line \n rpm_current = df_ref_f.loc[i, col] \n pos = i # current position\n\n # Compare with previous \n if rpm_start == rpm_current: # same value in a row as before\n len_incr += 1\n else:\n # generate output\n out_line = \"{}\\t{}\\t{}\\t{}\\n\".format(ref, pos_start, pos, rpm_start)\n outfile_forward.write(out_line)\n # redefine variables for next step\n rpm_start = rpm_current\n pos_start = pos\n len_incr = 0\n\n ######################\n # For Reverse strand\n key = \"Rev_rpm/\" + ref\n df_ref_r = storage[key]\n # convert series to df\n if type(df_ref_r) == pd.core.series.Series:\n df_ref_r = series_2_df(df_ref_r)\n # For collecting data\n rpm_start = 0 # initial_value\n pos_start = 0 # remember start\n len_incr = 0 # append to length #! might be omitted\n rpm_current = 0 # current_value #! might be omitted\n \n # interval -> continious\n index = list(range(chr_length[ref]+1))\n columns = ['sum']\n df_ref_r = df_fill_iv(df_ref_r, index, columns)\n \n # going throug each position for current reference (Chr)\n for i in df_ref_r.index:\n # current value (rpm) in a line \n rpm_current = df_ref_r.loc[i, col] \n pos = i # current position\n\n # Compare with previous \n if rpm_start == rpm_current: # same value in a row as before\n len_incr += 1\n else:\n # generate output\n out_line = \"{}\\t{}\\t{}\\t{}\\n\".format(ref, pos_start, pos, rpm_start)\n outfile_reverse.write(out_line)\n # redefine variables for next step\n rpm_start = rpm_current\n pos_start = pos\n len_incr = 0\n \nprint(\"\\n\\tAll done!\\n\")\noutfile_forward.close()\noutfile_reverse.close()\nprint(\"Output BedGrapf files are:\\n\\t{}\\n\\t{}\\n\\n\".format(f1,f2))" ]
[ [ "pandas.HDFStore", "pandas.DataFrame" ] ]
laurinwagner/grouploss_plus
[ "add9e3e7b4fcfccf0393124aeb6e1f35a442ed88" ]
[ "dataset/Inshop.py" ]
[ "\nimport numpy as np, os, sys, pandas as pd, csv, copy\nimport torch\nimport torchvision\nimport PIL.Image\nfrom .base import *\n\n\nclass Inshop_Dataset(torch.utils.data.Dataset):\n def __init__(self, root, mode, transform = None):\n self.root = root\n self.mode = mode\n self.transform = transform\n self.train_ys, self.train_im_paths = [], []\n self.query_ys, self.query_im_paths = [], []\n self.gallery_ys, self.gallery_im_paths = [], []\n \n data_info = np.array(pd.read_table(self.root +'/Eval/list_eval_partition.txt', header=1, delim_whitespace=True))[:,:]\n #Separate into training dataset and query/gallery dataset for testing.\n train, query, gallery = data_info[data_info[:,2]=='train'][:,:2], data_info[data_info[:,2]=='query'][:,:2], data_info[data_info[:,2]=='gallery'][:,:2]\n\n #Generate conversions\n lab_conv = {x:i for i,x in enumerate(np.unique(np.array([int(x.split('_')[-1]) for x in train[:,1]])))}\n train[:,1] = np.array([lab_conv[int(x.split('_')[-1])] for x in train[:,1]])\n\n lab_conv = {x:i for i,x in enumerate(np.unique(np.array([int(x.split('_')[-1]) for x in np.concatenate([query[:,1], gallery[:,1]])])))}\n query[:,1] = np.array([lab_conv[int(x.split('_')[-1])] for x in query[:,1]])\n gallery[:,1] = np.array([lab_conv[int(x.split('_')[-1])] for x in gallery[:,1]])\n\n #Generate Image-Dicts for training, query and gallery of shape {class_idx:[list of paths to images belong to this class] ...}\n for img_path, key in train:\n self.train_im_paths.append(os.path.join(self.root, 'Img', img_path))\n self.train_ys += [int(key)]\n\n for img_path, key in query:\n self.query_im_paths.append(os.path.join(self.root, 'Img', img_path))\n self.query_ys += [int(key)]\n\n for img_path, key in gallery:\n self.gallery_im_paths.append(os.path.join(self.root, 'Img', img_path))\n self.gallery_ys += [int(key)]\n \n if self.mode == 'train':\n self.im_paths = self.train_im_paths\n self.ys = self.train_ys\n elif self.mode == 'query':\n self.im_paths = self.query_im_paths\n self.ys = self.query_ys\n elif self.mode == 'gallery':\n self.im_paths = self.gallery_im_paths\n self.ys = self.gallery_ys\n\n def nb_classes(self):\n return len(set(self.ys))\n \n def __len__(self):\n return len(self.ys)\n \n def __getitem__(self, index):\n \n def img_load(index):\n im = PIL.Image.open(self.im_paths[index])\n # convert gray to rgb\n if len(list(im.split())) == 1 : im = im.convert('RGB') \n if self.transform is not None:\n im = self.transform(im)\n return im\n \n im = img_load(index)\n target = self.ys[index]\n\n return im, target" ]
[ [ "numpy.concatenate", "pandas.read_table" ] ]
google-research/prompt-tuning
[ "616f486d353fae596466c92d04dc326ed076c109" ]
[ "prompt_tuning/train/train_test.py" ]
[ "# Copyright 2022 Google.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Larger scale tests to make sure core assumptions aren't being broken.\n\nThis modules contains integration-style tests. It tests things that are critical\nfor prompt tuning, but easy to overlook, are being used. Some of these include:\n\n * Testing that only the prompt is being updated based on our default configs.\n In prompt tuning we only make changes to the prompt, the model is frozen,\n this test loads in our model, based on our prompt tuning configs, runs the\n loss function and parameter update, and then checks that only the prompt\n variables have changed.\n * Testing that model parameters are loaded from the checkpoint. The t5x partial\n loading mechanism will fill all parameters not in the checkpoint with ones\n that are initialized from scratch. This means that if there is a problem and\n the weight isn't loaded from the checkpoint training won't fail, it will just\n be running with random weights. This test checks that model parameters are\n actually loaded from the checkpoint.\n * Testing the DecoderOnly inference can run with the right shapes and the like.\n\n\"\"\"\n\nimport os\nimport re\nimport textwrap\nfrom absl import flags\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nfrom flax import traverse_util\nimport gin\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\n# t5.data.tasks has transitive dependencies that are gin configurable (in things\n# like the t5.data.glue_utils). We need to import these now, before we parse the\n# gin configs. If we don't then these files will (most likely) get imported\n# during the `import_modules` call that makes sure that our task is loaded. This\n# would introduce new gin.configurable objects after parsing which isn't\n# allowed.\nimport t5.data.tasks # pylint: disable=unused-import\nfrom t5x import checkpoints\nfrom t5x import partitioning\nfrom t5x import train as train_lib\nfrom t5x import utils\n\n# Work-around for GIN `runs` configs expecting to find\n# the `train` at the root scope of the `__main__`.\ntrain = train_lib.train\n\nFLAGS = flags.FLAGS\nTEST_DATA = os.path.join(\n os.path.dirname(os.path.abspath(__file__)), \"test_data\")\n\n\nclass PromptsTrainTest(parameterized.TestCase):\n\n\n @parameterized.named_parameters([\n dict(\n testcase_name=\"prompt_t5_1_1_tiny\",\n config=\"prompt_tuning/configs/test/train_t5_1_1_tiny_prompt.gin\",\n run_config=\"prompt_tuning/configs/runs/prompt_finetune.gin\",\n change_regex=\".*/prompt/.*\"),\n dict(\n testcase_name=\"multitask_t5_1_1_tiny\",\n config=\"prompt_tuning/configs/extended/test/train_multi_task_t5_1_1_tiny_prompt.gin\",\n run_config=\"prompt_tuning/configs/extended/runs/multitask_prompt_finetune.gin\",\n change_regex=\".*/(shared_prompt|task_prompts)/.*\"),\n ])\n def test_only_prompts_are_updated(self, config, run_config, change_regex):\n gin.clear_config(clear_constants=True)\n # Create references to gin configurable versions of our model and the\n # partition config.\n configured_partitioner = gin.configurable(partitioning.PjitPartitioner)\n # Parse the gin file.\n # Set all the required things that we don't use, but get pulled in through\n # the run configs (which we need because it configures partitioning.\n bindings = textwrap.dedent(\"\"\"\n INITIAL_CHECKPOINT_PATH=''\n MIXTURE_OR_TASK_NAME=''\n TASK_FEATURE_LENGTHS=''\n TRAIN_STEPS=''\n MODEL_DIR=''\n \"\"\")\n gin.parse_config_files_and_bindings([config, run_config], bindings)\n model = gin.query_parameter(\"%MODEL\").scoped_configurable_fn()\n # Our `configured_(model|partition_cfg)` has now been populated by gin, as\n # if its arguments were applied during the parsing. Now we can call it with\n # no arguments.\n partitioner = configured_partitioner()\n\n # Create spec for fake input data.\n input_shapes = {\n \"encoder_input_tokens\": (4, 512),\n \"decoder_input_tokens\": (4, 4),\n \"decoder_target_tokens\": (4, 4)\n }\n input_types = {\n \"encoder_input_tokens\": jnp.int32,\n \"decoder_input_tokens\": jnp.int32,\n \"decoder_target_tokens\": jnp.int32\n }\n\n # This t5x object manages the initialization of the optimizer and model\n # parameters.\n train_state_initializer = utils.TrainStateInitializer(\n init_fn=model.get_initial_variables,\n optimizer_def=model.optimizer_def,\n input_shapes=input_shapes,\n input_types=input_types,\n partitioner=partitioner)\n # Create the optimizer from scratch, we don't care about the weights just\n # how they change so we don't need to load from a checkpoint.\n train_state = train_state_initializer.from_scratch(\n init_rng=jax.random.PRNGKey(42),)\n train_state_axes = train_state_initializer.train_state_axes\n\n def update(train_state, batch):\n # Create a jax grad function based on our models loss.\n grad_fn = jax.value_and_grad(model.loss_fn, has_aux=True)\n\n # Run the forward and backward pass of the model.\n (loss, metrics), grad = grad_fn(train_state.params, batch,\n jax.random.PRNGKey(0))\n del loss, metrics\n\n # Apply the gradients to get an optimizer with updated variables.\n return train_state.apply_gradient(grad, learning_rate=0.3)\n\n p_update = partitioner.partition(\n update,\n in_axis_resources=(train_state_axes,\n partitioning.PartitionSpec(\"data\")),\n out_axis_resources=(train_state_axes))\n\n # Create fake data to feed the model.\n batch = {\n \"encoder_input_tokens\": jnp.ones((4, 512)),\n \"decoder_target_tokens\": jnp.ones((4, 4)),\n \"decoder_input_tokens\": jnp.ones((4, 4)),\n }\n\n new_train_state = p_update(train_state, batch)\n\n # Flatten both optimizers so the parameters are /scopes/of/nested/params.\n # This makes comparing them easier.\n flat_train_state = traverse_util.flatten_dict(train_state.params.unfreeze())\n flat_train_state = {\"/\".join(k): v for k, v in flat_train_state.items()}\n\n flat_new = traverse_util.flatten_dict(new_train_state.params.unfreeze())\n flat_new = {\"/\".join(k): v for k, v in flat_new.items()}\n\n # Make sure that any variable that matches the change regex has been updated\n # and any variable that doesn't has not.\n for var, og_weight in flat_train_state.items():\n new_weight = flat_new[var]\n if re.fullmatch(change_regex, var):\n self.assertFalse(\n np.all(np.allclose(new_weight, og_weight)), f\"'{var}' matches.\")\n else:\n np.testing.assert_allclose(\n new_weight, og_weight, err_msg=f\"non-prompt '{var}' mismatch.\")\n\n @parameterized.named_parameters([\n dict(\n testcase_name=\"prompt_t5_1_1_tiny\",\n config=\"prompt_tuning/configs/test/load_t5_1_1_tiny_prompt.gin\",\n checkpoint=\"test_t5_1_1_tiny/checkpoint_3/checkpoint\"),\n dict(\n testcase_name=\"multitask_t5_1_1_tiny\",\n config=\"prompt_tuning/configs/extended/test/load_multi_task_t5_1_1_tiny_prompt.gin\",\n checkpoint=\"test_t5_1_1_tiny/checkpoint_3/checkpoint\"),\n ])\n def test_prompt_loading(self, config, checkpoint):\n gin.clear_config(clear_constants=True)\n configured_partitioner = gin.configurable(partitioning.PjitPartitioner)\n configured_checkpoint_cfg = gin.configurable(utils.CheckpointConfig)\n checkpoint = os.path.join(FLAGS.test_srcdir, TEST_DATA, checkpoint)\n gin.parse_config_files_and_bindings(\n [config], f\"INITIAL_CHECKPOINT_PATH='{checkpoint}'\")\n\n model = gin.query_parameter(\"%MODEL\").scoped_configurable_fn()\n partitioner = configured_partitioner()\n checkpoint_cfg = configured_checkpoint_cfg()\n\n input_shapes = {\n \"encoder_input_tokens\": (4, 512),\n \"decoder_input_tokens\": (4, 512),\n \"decoder_target_tokens\": (4, 512)\n }\n input_types = {\n \"encoder_input_tokens\": jnp.int32,\n \"decoder_input_tokens\": jnp.int32,\n \"decoder_target_tokens\": jnp.int32\n }\n\n train_state_initializer = utils.TrainStateInitializer(\n init_fn=model.get_initial_variables,\n optimizer_def=model.optimizer_def,\n input_shapes=input_shapes,\n input_types=input_types,\n partitioner=partitioner)\n train_state = train_state_initializer.from_checkpoint(\n ckpt_cfgs=[checkpoint_cfg.restore],\n ds_iter=None,\n init_rng=jax.random.PRNGKey(0),\n )\n\n checkpoint_contents = checkpoints.load_t5x_checkpoint(checkpoint)\n\n flat_train_state = traverse_util.flatten_dict(train_state.params.unfreeze())\n flat_train_state = {\"/\".join(k): v for k, v in flat_train_state.items()}\n\n flat_checkpoint = traverse_util.flatten_dict(checkpoint_contents)\n flat_checkpoint = {\"/\".join(k): v for k, v in flat_checkpoint.items()}\n\n for opt_key, opt_value in flat_train_state.items():\n if opt_value is not None:\n if opt_key in flat_checkpoint:\n np.testing.assert_allclose(\n opt_value,\n flat_checkpoint[opt_key],\n err_msg=f\"'{opt_key}' mismatch.\")\n\n\nif __name__ == \"__main__\":\n absltest.main()\n" ]
[ [ "numpy.allclose", "numpy.testing.assert_allclose" ] ]
tianyu-su/torchfurnace
[ "2f4a9a0655a8d3c3e231c86611085f834e03c2f8" ]
[ "torchfurnace/utils/torch_summary.py" ]
[ "# -*- coding: utf-8 -*-\n# Date: 2020/3/18 11:50\n\n\"\"\"\nhttps://github.com/sksq96/pytorch-summary/blob/master/torchsummary/torchsummary.py\n\"\"\"\n\nfrom collections import OrderedDict\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\n\ndef summary(model, input_size, batch_size=-1, dtypes=None):\n result, params_info = summary_string(\n model, input_size, batch_size, dtypes)\n print(result)\n\n return params_info\n\n\ndef summary_string(model, input_size, batch_size=-1, dtypes=None):\n \"\"\"\n https://github.com/sksq96/pytorch-summary#multiple-inputs\n :param input_size: this is the same as input of model.forward, can receive multi-params as list\n :param batch_size:\n :param dtypes:\n :return:\n \"\"\"\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n if dtypes == None:\n dtypes = [torch.FloatTensor] * len(input_size)\n\n summary_str = ''\n\n def register_hook(module):\n def hook(module, input, output):\n class_name = str(module.__class__).split(\".\")[-1].split(\"'\")[0]\n module_idx = len(summary)\n\n m_key = \"%s-%i\" % (class_name, module_idx + 1)\n summary[m_key] = OrderedDict()\n summary[m_key][\"input_shape\"] = list(input[0].size())\n summary[m_key][\"input_shape\"][0] = batch_size\n if isinstance(output, (list, tuple)):\n summary[m_key][\"output_shape\"] = [\n [-1] + list(o.size())[1:] for o in output\n ]\n else:\n summary[m_key][\"output_shape\"] = list(output.size())\n summary[m_key][\"output_shape\"][0] = batch_size\n\n params = 0\n if hasattr(module, \"weight\") and hasattr(module.weight, \"size\"):\n params += torch.prod(torch.LongTensor(list(module.weight.size())))\n summary[m_key][\"trainable\"] = module.weight.requires_grad\n if hasattr(module, \"bias\") and hasattr(module.bias, \"size\"):\n params += torch.prod(torch.LongTensor(list(module.bias.size())))\n summary[m_key][\"nb_params\"] = params\n\n if (\n not isinstance(module, nn.Sequential)\n and not isinstance(module, nn.ModuleList)\n ):\n hooks.append(module.register_forward_hook(hook))\n\n # multiple inputs to the network\n if isinstance(input_size, tuple):\n input_size = [input_size]\n\n # batch_size of 2 for batchnorm\n x = [torch.rand(2, *in_size).type(dtype).to(device=device)\n for in_size, dtype in zip(input_size, dtypes)]\n\n # create properties\n summary = OrderedDict()\n hooks = []\n\n # register hook\n model.apply(register_hook)\n\n # make a forward pass\n # print(x.shape)\n model(*x)\n\n # remove these hooks\n for h in hooks:\n h.remove()\n\n summary_str += \"----------------------------------------------------------------\" + \"\\n\"\n line_new = \"{:>20} {:>25} {:>15}\".format(\n \"Layer (type)\", \"Output Shape\", \"Param #\")\n summary_str += line_new + \"\\n\"\n summary_str += \"================================================================\" + \"\\n\"\n total_params = 0\n total_output = 0\n trainable_params = 0\n for layer in summary:\n # input_shape, output_shape, trainable, nb_params\n line_new = \"{:>20} {:>25} {:>15}\".format(\n layer,\n str(summary[layer][\"output_shape\"]),\n \"{0:,}\".format(summary[layer][\"nb_params\"]),\n )\n total_params += summary[layer][\"nb_params\"]\n\n total_output += np.prod(summary[layer][\"output_shape\"])\n if \"trainable\" in summary[layer]:\n if summary[layer][\"trainable\"] == True:\n trainable_params += summary[layer][\"nb_params\"]\n summary_str += line_new + \"\\n\"\n\n # assume 4 bytes/number (float on cuda).\n total_input_size = abs(np.prod(sum(input_size, ()))\n * batch_size * 4. / (1024 ** 2.))\n total_output_size = abs(2. * total_output * 4. /\n (1024 ** 2.)) # x2 for gradients\n total_params_size = abs(total_params * 4. / (1024 ** 2.))\n total_size = total_params_size + total_output_size + total_input_size\n\n summary_str += \"================================================================\" + \"\\n\"\n summary_str += \"Total params: {0:,}\".format(total_params) + \"\\n\"\n summary_str += \"Trainable params: {0:,}\".format(trainable_params) + \"\\n\"\n summary_str += \"Non-trainable params: {0:,}\".format(total_params -\n trainable_params) + \"\\n\"\n summary_str += \"----------------------------------------------------------------\" + \"\\n\"\n summary_str += \"Input size (MB): %0.2f\" % total_input_size + \"\\n\"\n summary_str += \"Forward/backward pass size (MB): %0.2f\" % total_output_size + \"\\n\"\n summary_str += \"Params size (MB): %0.2f\" % total_params_size + \"\\n\"\n summary_str += \"Estimated Total Size (MB): %0.2f\" % total_size + \"\\n\"\n summary_str += \"----------------------------------------------------------------\" + \"\\n\"\n # return summary\n return summary_str, (total_params, trainable_params)\n\n\nif __name__=='__main__':\n from torchvision import models\n\n vgg = models.vgg16()\n summary(vgg, (3, 224, 224))\n # summary(vgg, [(1, 16, 16), (1, 28, 28)])\n pass" ]
[ [ "numpy.prod", "torch.rand", "torch.cuda.is_available" ] ]