repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
longhongc/mobile-industrial-manipulator
|
[
"f1004e4c996005c3231e4ec7d2b998102f7575a8"
] |
[
"scripts/mim_kinematic.py"
] |
[
"import signal\nimport sys\nimport numpy as np\nfrom math import pi, sin, cos, atan2, asin, acos, sqrt\n\n# gravity constant\ng = 9.8\n\nclass MIM_Arm: \n\n l1 = 0.0867\n l2 = 0.6127\n l3 = 0.5722\n l4 = 0.1157\n k1 = 0.1639\n k2 = 0.0912\n\n def __init__(self, init_config):\n # initial config\n self.arm_base_link_pose = [-0.2, 0, 0.321]\n\n self.joints_config = init_config \n self.T = self.forward_kinematic(self.joints_config)\n self.pos = self.T[:,3][:3] \n\n self.joints_traj = []\n self.way_points = self.pos \n\n def forward_kinematic(self, joints_config, link=6): \n if(link == 0):\n return np.matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])\n \n t1, t2, t3, t4, t5, t6 = joints_config\n \n # DH table construction\n def Ttheta(t):\n return np.matrix([[cos(t), -sin(t), 0, 0], [sin(t), cos(t), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])\n \n def Td(d):\n return np.matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, d], [0, 0, 0, 1]])\n\n def Ta(a):\n return np.matrix([[1, 0, 0, a], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])\n \n def Talfa(alfa):\n return np.matrix([[1, 0, 0, 0], [0, cos(alfa), -sin(alfa), 0], [0, sin(alfa), cos(alfa), 0], [0, 0, 0, 1]])\n\n # arm_base to origin\n x, y, z = self.arm_base_link_pose\n Tbase = np.matrix([[1, 0, 0, x], [0, 1, 0, y], [0, 0, 1, z], [0, 0, 0, 1]])\n\n T0 = np.matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])\n if(link == 0):\n return Tbase*T0\n \n T1 = Ttheta(t1 - pi/2) * Td(MIM_Arm.l1) * Talfa(-pi/2)\n if(link == 1):\n return Tbase*T0*T1\n \n T2 = Ttheta(t2 - pi/2) * Ta(MIM_Arm.l2)\n if(link == 2):\n return Tbase*T0*T1*T2\n \n T3 = Ttheta(t3)*Ta(MIM_Arm.l3)\n if(link == 3):\n return Tbase*T0*T1*T2*T3\n \n T4 = Ttheta(t4 + pi/2) * Td(MIM_Arm.k1) * Talfa(pi/2)\n if(link == 4):\n return Tbase*T0*T1*T2*T3*T4\n \n T5 = Ttheta(t5)*Td(MIM_Arm.l4) * Talfa(-pi/2)\n if(link == 5):\n return Tbase*T0*T1*T2*T3*T4*T5\n \n T6 = Ttheta(t6) * Td(MIM_Arm.k2)\n T = Tbase * T0 * T1 * T2 * T3 * T4 * T5 * T6\n return T\n\n def cal_jacobian(self, joints):\n T = self.forward_kinematic(joints); \n\n on = T[:,3][:3] # end point origin\n\n def cal_jacobian_column(link): \n T_matrix = self.forward_kinematic(joints, link)\n o = T_matrix[:,3][:3] # origin\n z = T_matrix[:,2][:3] # z axis\n j_linear = np.cross(z, on-o, axisa=0, axisb=0, axisc=0)\n j_angular = z\n j = np.vstack([j_linear, j_angular])\n\n return j\n \n j1 = cal_jacobian_column(0) \n j2 = cal_jacobian_column(1) \n j3 = cal_jacobian_column(2) \n j4 = cal_jacobian_column(3) \n j5 = cal_jacobian_column(4) \n j6 = cal_jacobian_column(5) \n\n j = np.hstack((j1, j2, j3, j4, j5, j6))\n return j\n\n def inverse_velocity(self, joints, velocity):\n j = self.cal_jacobian(joints) # jacobian\n inv_j = j.getI() # inverse jacobian\n joints_velocity = inv_j * velocity \n return joints_velocity\n\n def clip_angle(self, joints):\n clipped_joints = []\n for joint in joints:\n joint = joint % (2 * pi)\n if(joint > pi):\n joint = -(2 * pi - joint)\n clipped_joints.append(joint)\n return clipped_joints\n \n def grasp_motion(self, init_joints, length, velocity, simulated_points):\n self.joints_traj = []\n self.joints_config = init_joints\n q = self.joints_config\n v = velocity\n v_vector_T= np.array([[0, 0, v, 0, 0, 0]]) # end point (vx, vy, vz, ax, ay, az) related to base\n v_vector = np.transpose(v_vector_T)\n motion_length = length\n total_time = motion_length / abs(v)\n \n\n delta_t = total_time / simulated_points\n print(delta_t)\n sim_time = 0\n\n count = 0\n while(True): \n # calculate joints velocity\n q_dot = self.inverse_velocity(q, v_vector)\n q = np.array([q]).T + q_dot * delta_t \n sim_time = sim_time + delta_t\n q = self.clip_angle(q.T.tolist()[0])\n self.joints_traj.append(q)\n self.joints_config = q\n\n T = self.forward_kinematic(q); \n self.pos = T[:,3][:3] # origin\n self.way_points = np.hstack((self.way_points, self.pos))\n print(\"pos: \", self.pos.T.tolist()[0])\n \n count+=1\n if(sim_time > total_time):\n print(\"finish\")\n return self.joints_traj\n\n \n def _fk_test(self):\n # joints config \n config_1 = [0, 0, 0, 0, 0, 0] \n config_2 = [pi/2, 0, 0, 0, 0, 0] \n config_3 = [0, 0, 0, pi/2, 0, 0] \n config_4 = [0, 0, pi/2, 0, 0, 0] \n config_5 = [0, 0, pi/2, -pi/2, pi/2, 0] \n diffdrive_pick_config = [1.4, 0.4, 0.8, 0.15, -1.57, 0]\n \n print(\"config_1: \", config_1)\n print(self.forward_kinematic(config_1))\n print(\"config_2: \", config_2)\n print(self.forward_kinematic(config_2))\n print(\"config_3: \", config_3)\n print(self.forward_kinematic(config_3))\n print(\"config_4: \", config_4)\n print(self.forward_kinematic(config_4))\n print(\"config_5: \", config_5)\n print(self.forward_kinematic(config_5))\n print(\"config_6: \", diffdrive_pick_config)\n print(self.forward_kinematic(diffdrive_pick_config))\n\n def _iv_test(self):\n joints_config = [1.4, 0.4, 0.8, 0.15, -1.57, 0]\n v = 0.3\n v_vector_T= np.array([[0, 0, -v, 0, 0, 0]]) # end point (vx, vy, vz, ax, ay, az) related to base\n v_vector = np.transpose(v_vector_T)\n print(v_vector)\n joints_vel = self.inverse_velocity(joints_config, v_vector)\n print(joints_vel)\n \n\n\ndef main():\n init_config = [1.4, 0.42, 0.8, 0.15, -1.57, 0]\n mim_arm = MIM_Arm(init_config)\n #mim_arm._fk_test()\n #mim_arm._iv_test()\n joints_traj = mim_arm.grasp_motion()\n print(joints_traj)\n\ndef signal_handler(sig, frame):\n print(\"\")\n print(\"bye bye!\")\n sys.exit(0)\n\nif __name__ == \"__main__\":\n signal.signal(signal.SIGINT, signal_handler)\n\n main()\n"
] |
[
[
"numpy.matrix",
"numpy.hstack",
"numpy.transpose",
"numpy.cross",
"numpy.array",
"numpy.vstack"
]
] |
paulwong16/TrafficMapForecasting
|
[
"793b55b203c4cbb89cce62b77a3e43b4df05b638",
"793b55b203c4cbb89cce62b77a3e43b4df05b638"
] |
[
"utils/earlystopping.py",
"models/deep_resunet_fusion.py"
] |
[
"import numpy as np\nimport torch\n\n\nclass EarlyStopping:\n \"\"\"Early stops the training if validation loss doesn't improve after a given patience.\"\"\"\n\n def __init__(self, logdir, patience=7, verbose=False, delta=0):\n \"\"\"\n Args:\n patience (int): How long to wait after last time validation loss improved.\n Default: 7\n verbose (bool): If True, prints a message for each validation loss improvement. \n Default: False\n delta (float): Minimum change in the monitored quantity to qualify as an improvement.\n Default: 0\n \"\"\"\n self.log_dir = logdir\n self.patience = patience\n self.verbose = verbose\n self.counter = 0\n self.best_score = None\n self.early_stop = False\n self.val_loss_min = np.Inf\n self.delta = delta\n\n def __call__(self, val_loss, model, epoch, globaliter):\n\n score = -val_loss\n\n if self.best_score is None:\n self.best_score = score\n self.save_checkpoint(val_loss, model, epoch, globaliter)\n elif score < self.best_score - self.delta:\n self.counter += 1\n print(f'EarlyStopping counter: {self.counter} out of {self.patience}')\n if self.counter >= self.patience:\n self.early_stop = True\n else:\n self.best_score = score\n self.save_checkpoint(val_loss, model, epoch, globaliter)\n self.counter = 0\n\n def save_checkpoint(self, val_loss, model, epoch, globaliter):\n \"\"\"Saves model when validation loss decrease.\"\"\"\n if self.verbose:\n print(f'Validation loss decreased ({self.val_loss_min:.6f} --> {val_loss:.6f}). Saving model ...')\n checkpoint = {\n \"net\": model.state_dict(),\n \"epoch\": epoch,\n \"globaliter\": globaliter\n }\n torch.save(checkpoint, self.log_dir + '/checkpoint.pt')\n self.val_loss_min = val_loss\n",
"import torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom models.deep_resunet import DeepResUNet\n\n\nclass CNN(nn.Module):\n def __init__(self, in_channels=1, out=2):\n super(CNN, self).__init__()\n self.conv1 = nn.Conv2d(in_channels, 64, 3, 1, 1)\n self.conv2 = nn.Conv2d(64, 64, 3, 1, 1)\n self.conv3 = nn.Conv2d(64, out, 3, 1, 1)\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = F.relu(self.conv2(x))\n x = F.relu(self.conv3(x))\n return x\n\n\nclass Deep_Res_UNet_fusion(nn.Module):\n def __init__(self, in_channels=1, out_classes=2, static_in=1, static_out=2):\n super(Deep_Res_UNet_fusion, self).__init__()\n self.unet = DeepResUNet(in_channels, out_classes)\n self.cnn = CNN(static_in, static_out)\n self.conv = nn.Conv2d(out_classes+static_out, out_classes, 3, 1, 1)\n self.in_ch = in_channels\n self.out_ch = out_classes\n self.s_in_ch = static_in\n self.s_out_ch = static_out\n\n def forward(self, x):\n x1 = self.unet(x[:, :self.in_ch, :, :])\n x2 = self.cnn(x[:, self.in_ch:, :, :])\n x = torch.cat([x1, x2], dim=1)\n x = F.relu(self.conv(x))\n return x\n"
] |
[
[
"torch.save"
],
[
"torch.nn.Conv2d",
"torch.cat"
]
] |
ClazyCoder/YSGStereoVision
|
[
"e238af72ed0929b620b44a2ff8328658f3600efc"
] |
[
"captureChArUco.py"
] |
[
"import cv2 as cv\nimport numpy as np\nfrom cv2 import aruco\nimport cameramodule.cameramodule as cm\nimport os\nimport datetime\nimport json\n\nIMGSIZE = (640,480)\ncriteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 100, 0.00001)\n\ndef main():\n if not os.path.isdir('./ChAruco_captures'):\n os.mkdir('./ChAruco_captures')\n if not os.path.isdir('./ChAruco_datas'):\n os.mkdir('./ChAruco_datas')\n aruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250)\n board = aruco.CharucoBoard_create(7, 5, 1, .8, aruco_dict)\n imboard = board.draw((2000, 2000))\n if not os.path.exists('./chessboard.tiff'):\n print('Chessboard has created.')\n cv.imwrite(\"./chessboard.tiff\", imboard)\n stereo_cam = cm.StereoCamera(IMGSIZE)\n all_corners_left = []\n all_corners_right = []\n all_ids_left = []\n all_ids_right = []\n obj_points= []\n is_calibrating = False\n while True:\n leftFrame, rightFrame = stereo_cam.get_frame()\n grayLeft = cv.cvtColor(leftFrame, cv.COLOR_BGR2GRAY)\n grayRight = cv.cvtColor(rightFrame, cv.COLOR_BGR2GRAY)\n img_left = leftFrame.copy()\n img_right = rightFrame.copy()\n if is_calibrating:\n corners_left, ids_left, rejectedImgPointsLeft = cv.aruco.detectMarkers(grayLeft, aruco_dict)\n corners_right, ids_right, rejectedImgPointsRight = cv.aruco.detectMarkers(grayRight, aruco_dict)\n if(len(corners_left) > 0 and len(corners_right) > 0):\n for corner in corners_left:\n cv.cornerSubPix(grayLeft, corner, (3,3), (-1,-1),criteria)\n ret, charucoCorners, charucoIds = cv.aruco.interpolateCornersCharuco(corners_left,ids_left,grayLeft,board)\n if ret:\n all_corners_left.append(charucoCorners)\n all_ids_left.append(charucoIds)\n cv.aruco.drawDetectedCornersCharuco(img_left, charucoCorners, charucoIds)\n for corner in corners_right:\n cv.cornerSubPix(grayRight,corner, (3,3),(-1,-1),criteria)\n ret, charucoCorners, charucoIds = cv.aruco.interpolateCornersCharuco(corners_right,ids_right,grayRight,board)\n if ret:\n all_corners_right.append(charucoCorners)\n all_ids_right.append(charucoIds)\n cv.aruco.drawDetectedCornersCharuco(img_right, charucoCorners, charucoIds)\n newChessboardCorners = board.chessboardCorners\n newChessboardCorners[:,1] = (7*1) - newChessboardCorners[:,1]\n for idx in ids_left:\n obj_points.append(newChessboardCorners[idx])\n obj_points = np.asarray(obj_points)\n \n today = datetime.datetime.today()\n filename_left = './ChAruco_captures/capture_left' + str(today.year)+str(today.month)+str(today.day)+'-'+str(today.hour)+\"h\"+str(today.minute)+\"m\"+str(today.second)+\"s\"+\".jpg\"\n jsonfilename_left = './ChAruco_datas/data_left' + str(today.year)+str(today.month)+str(today.day)+'-'+str(today.hour)+\"h\"+str(today.minute)+\"m\"+str(today.second)+\"s\"+\".json\"\n jsonfile_left = json.dumps(\n {\n \"imgp\" : all_corners_left.tolist(),\n \"ids\" : all_ids_left.tolist()\n }\n )\n with open(jsonfilename_left, 'w') as f:\n f.write(jsonfile_left)\n filename_right = './ChAruco_captures/capture_right' + str(today.year)+str(today.month)+str(today.day)+'-'+str(today.hour)+\"h\"+str(today.minute)+\"m\"+str(today.second)+\"s\"+\".jpg\"\n jsonfilename_right = './ChAruco_datas/data_right' + str(today.year)+str(today.month)+str(today.day)+'-'+str(today.hour)+\"h\"+str(today.minute)+\"m\"+str(today.second)+\"s\"+\".json\"\n jsonfile_right = json.dumps(\n {\n \"imgp\" : all_corners_right.tolist(),\n \"ids\" : all_ids_right.tolist()\n }\n )\n with open(jsonfilename_right, 'w') as f:\n f.write(jsonfile_right)\n cv.imwrite(filename_left, img_left)\n cv.imwrite(filename_right, img_right)\n cv.imshow('left', img_left)\n cv.imshow('right', img_right)\n cv.waitKey(3000)\n is_calibrating = False\n k = cv.waitKey(1)\n if k == 27:\n break\n elif k == 99: # C\n is_calibrating = not is_calibrating\n\nif __name__ == \"__main__\":\n main()"
] |
[
[
"numpy.asarray"
]
] |
beaulima/thelper
|
[
"c389352c3541d18bb9d8255d6d3efe295ff1d71b"
] |
[
"thelper/train/segm.py"
] |
[
"\"\"\"Segmentation trainer/evaluator implementation module.\"\"\"\nimport logging\nfrom typing import AnyStr, Optional # noqa: F401\n\nimport torch\nimport torch.optim\n\nimport thelper.concepts\nimport thelper.typedefs as typ # noqa: F401\nimport thelper.utils\nfrom thelper.train.base import Trainer\n\nlogger = logging.getLogger(__name__)\n\n\n@thelper.concepts.segmentation\nclass ImageSegmTrainer(Trainer):\n \"\"\"Trainer interface specialized for image segmentation.\n\n This class implements the abstract functions of :class:`thelper.train.base.Trainer` required to train/evaluate\n a model for image segmentation (i.e. pixel-level classification/labeling). It also provides a utility function\n for fetching i/o packets (images, class labels) from a sample, and that converts those into tensors for forwarding\n and loss estimation.\n\n .. seealso::\n | :class:`thelper.train.base.Trainer`\n \"\"\"\n\n def __init__(self,\n session_name, # type: AnyStr\n session_dir, # type: AnyStr\n model, # type: thelper.typedefs.ModelType\n task, # type: thelper.tasks.Task\n loaders, # type: thelper.typedefs.MultiLoaderType\n config, # type: thelper.typedefs.ConfigDict\n ckptdata=None # type: Optional[thelper.typedefs.CheckpointContentType]\n ):\n \"\"\"Receives session parameters, parses image/label keys from task object, and sets up metrics.\"\"\"\n super().__init__(session_name, session_dir, model, task, loaders, config, ckptdata=ckptdata)\n assert isinstance(self.task, thelper.tasks.Segmentation), \"expected task to be segmentation\"\n trainer_config = thelper.utils.get_key_def(\"params\", config[\"trainer\"], config[\"trainer\"])\n self.scale_preds = thelper.utils.get_key_def(\"scale_preds\", trainer_config, default=False)\n self.warned_no_shuffling_augments = False\n self.output_pred_key = thelper.utils.get_key_def(\"output_pred\", trainer_config, default=\"out\")\n\n def _to_tensor(self, sample):\n \"\"\"Fetches and returns tensors of input images and label maps from a batched sample dictionary.\"\"\"\n assert isinstance(sample, dict), \"trainer expects samples to come in dicts for key-based usage\"\n assert self.task.input_key in sample, f\"could not find input key '{self.task.input_key}' in sample dict\"\n input_val, label_map = sample[self.task.input_key], None\n if isinstance(input_val, list):\n if self.task.gt_key in sample and sample[self.task.gt_key] is not None:\n label_map = sample[self.task.gt_key]\n assert isinstance(label_map, list) and len(label_map) == len(input_val), \\\n \"label_map should also be a list of the same length as input\"\n for idx in range(len(input_val)):\n input_val[idx], label_map[idx] = self._to_tensor({self.task.input_key: input_val[idx],\n self.task.gt_key: label_map[idx]})\n else:\n for idx in range(len(input_val)):\n input_val[idx] = torch.FloatTensor(input_val[idx])\n else:\n input_val = torch.FloatTensor(input_val)\n if self.task.gt_key in sample and sample[self.task.gt_key] is not None:\n label_map = sample[self.task.gt_key]\n assert not isinstance(label_map, list), \"unexpected label map type\"\n label_map = label_map.long() # long instead of bytes to support large/negative values for dontcare\n return input_val, label_map\n\n def train_epoch(self, model, epoch, dev, loss, optimizer, loader, metrics, output_path):\n \"\"\"Trains the model for a single epoch using the provided objects.\n\n Args:\n model: the model to train that is already uploaded to the target device(s).\n epoch: the epoch index we are training for (0-based).\n dev: the target device that tensors should be uploaded to.\n loss: the loss function used to evaluate model fidelity.\n optimizer: the optimizer used for back propagation.\n loader: the data loader used to get transformed training samples.\n metrics: the dictionary of metrics/consumers to update every iteration.\n output_path: directory where output files should be written, if necessary.\n \"\"\"\n assert loss is not None, \"missing loss function\"\n assert optimizer is not None, \"missing optimizer\"\n assert loader, \"no available data to load\"\n assert isinstance(metrics, dict), \"expect metrics as dict object\"\n epoch_loss = 0\n epoch_size = len(loader)\n self.logger.debug(\"fetching data loader samples...\")\n for idx, sample in enumerate(loader):\n input_val, label_map = self._to_tensor(sample)\n assert label_map is not None, \"groundtruth required when training a model\"\n optimizer.zero_grad()\n if isinstance(input_val, list):\n # training samples got augmented, we need to backprop in multiple steps\n assert input_val, \"cannot train with empty post-augment sample lists\"\n assert isinstance(label_map, list) and len(label_map) == len(input_val), \\\n \"label maps should also be provided via a list of the same length as the input_val\"\n if not self.warned_no_shuffling_augments:\n self.logger.warning(\"using training augmentation without global shuffling, gradient steps might be affected\")\n # see the docstring of thelper.transforms.operations.Duplicator for more information\n self.warned_no_shuffling_augments = True\n iter_loss = None\n iter_pred = None\n augs_count = len(input_val)\n for aug_idx in range(augs_count):\n aug_pred = model(self._move_tensor(input_val[aug_idx], dev))\n if isinstance(aug_pred, dict):\n aug_pred = aug_pred[self.output_pred_key]\n if self.scale_preds:\n aug_pred = torch.nn.functional.interpolate(aug_pred, size=input_val[aug_idx].shape[-2:], mode=\"bilinear\")\n aug_loss = loss(aug_pred, label_map[aug_idx].long())\n aug_loss.backward() # test backprop all at once? might not fit in memory...\n if iter_pred is None:\n iter_loss = aug_loss.clone().detach()\n iter_pred = aug_pred.clone().detach()\n else:\n iter_loss += aug_loss.detach()\n iter_pred = torch.cat((aug_pred.detach(), iter_pred), dim=0)\n iter_loss /= augs_count\n label_map = torch.cat(label_map, dim=0)\n else: # this is the default (simple) case where we generate predictions without augmentations\n iter_pred = model(self._move_tensor(input_val, dev))\n if isinstance(iter_pred, dict):\n iter_pred = iter_pred[self.output_pred_key]\n if self.scale_preds:\n iter_pred = torch.nn.functional.interpolate(iter_pred, size=input_val.shape[-2:], mode=\"bilinear\")\n iter_loss = loss(iter_pred, self._move_tensor(label_map, dev).long())\n iter_loss.backward()\n optimizer.step()\n iter_pred_cpu = self._move_tensor(iter_pred, dev=\"cpu\", detach=True)\n label_map_cpu = self._move_tensor(label_map, dev=\"cpu\", detach=True)\n iter_loss = iter_loss.item()\n for metric in metrics.values():\n metric.update(task=self.task, input=input_val, pred=iter_pred_cpu,\n target=label_map_cpu, sample=sample, loss=iter_loss,\n iter_idx=idx, max_iters=epoch_size, epoch_idx=epoch,\n max_epochs=self.epochs, output_path=output_path)\n epoch_loss += iter_loss\n epoch_loss /= epoch_size\n return epoch_loss\n\n def eval_epoch(self, model, epoch, dev, loader, metrics, output_path):\n \"\"\"Evaluates the model using the provided objects.\n\n Args:\n model: the model to evaluate that is already uploaded to the target device(s).\n epoch: the epoch index we are training for (0-based).\n dev: the target device that tensors should be uploaded to.\n loader: the data loader used to get transformed valid/test samples.\n metrics: the dictionary of metrics/consumers to update every iteration.\n output_path: directory where output files should be written, if necessary.\n \"\"\"\n assert loader, \"no available data to load\"\n assert isinstance(metrics, dict), \"expect metrics as dict object\"\n with torch.no_grad():\n epoch_size = len(loader)\n self.logger.debug(\"fetching data loader samples...\")\n for idx, sample in enumerate(loader):\n if idx < self.skip_eval_iter:\n continue # skip until previous iter count (if set externally; no effect otherwise)\n input_val, label_map = self._to_tensor(sample)\n if isinstance(input_val, list):\n # evaluation samples got augmented, we need to get the mean prediction\n assert input_val, \"cannot eval with empty post-augment sample lists\"\n assert isinstance(label_map, list) and len(label_map) == len(input_val), \\\n \"label maps should also be provided via a list of the same length as the input_val\"\n # this might be costly for nothing, we could remove the check and assume user is not dumb\n assert not any([not torch.eq(lbl, label_map[0]).all() for lbl in label_map]), \\\n \"all label maps should be identical! (why do eval-time augment otherwise?)\"\n label_map = label_map[0] # since all identical, just pick the first one and pretend its the only one\n preds = None\n for input_idx in range(len(input_val)):\n pred = model(self._move_tensor(input_val[input_idx], dev))\n if isinstance(pred, dict):\n pred = pred[self.output_pred_key]\n if preds is None:\n preds = torch.unsqueeze(pred.clone(), 0)\n else:\n preds = torch.cat((preds, torch.unsqueeze(pred, 0)), 0)\n pred = torch.mean(preds, dim=0)\n else: # this is the default (simple) case where we generate predictions without augmentations\n pred = model(self._move_tensor(input_val, dev))\n if isinstance(pred, dict):\n pred = pred[self.output_pred_key]\n if self.scale_preds:\n pred = torch.nn.functional.interpolate(pred, size=input_val.shape[-2:], mode=\"bilinear\")\n pred_cpu = self._move_tensor(pred, dev=\"cpu\", detach=True)\n label_map_cpu = self._move_tensor(label_map, dev=\"cpu\", detach=True)\n for metric in metrics.values():\n metric.update(task=self.task, input=input_val, pred=pred_cpu,\n target=label_map_cpu, sample=sample, loss=None, iter_idx=idx,\n max_iters=epoch_size, epoch_idx=epoch, max_epochs=self.epochs,\n output_path=output_path)\n"
] |
[
[
"torch.mean",
"torch.cat",
"torch.eq",
"torch.unsqueeze",
"torch.no_grad",
"torch.FloatTensor",
"torch.nn.functional.interpolate"
]
] |
kerengaiger/ai2v
|
[
"55a71e1d5a91841b84356a9806889b37ec9c66e6"
] |
[
"models/ai2v_model.py"
] |
[
"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport torch as t\nimport torch.nn as nn\nfrom tqdm import tqdm\nimport datetime\n\nfrom torch import FloatTensor as FT\n\n\nclass MultiHeadAttention(nn.Module):\n def __init__(self, embedding_size, window_size, device, num_h, d_k=50, d_v=50):\n super(MultiHeadAttention, self).__init__()\n self.emb_size = embedding_size\n self.window_size = window_size\n self.device = device\n self.d_k = d_k\n self.d_v = d_v\n self.num_h = num_h\n self.Ac = nn.Linear(self.emb_size, self.num_h * self.d_k)\n self.At = nn.Linear(self.emb_size, self.num_h * self.d_k)\n self.cos = nn.CosineSimilarity(dim=-1, eps=1e-6)\n self.Bc = nn.Linear(self.emb_size, self.num_h * self.d_v)\n self.pos_bias = nn.Parameter(FT(self.window_size).uniform_(-0.5 / self.window_size,\n 0.5 / self.window_size))\n self.pos_bias.requires_grad = True\n self.R = nn.Linear(self.num_h * self.d_v, self.emb_size)\n\n def forward(self, queries, keys, values, attention_mask=None, add_pos_bias=False):\n b_s, n_t_items = queries.shape[:2]\n n_c_items = keys.shape[1]\n q = self.At(queries).view(b_s, n_t_items, self.num_h, self.d_k).permute(0, 2, 1, 3) # (b_s, num_h, n_t_items, d_k)\n k = self.Ac(keys).view(b_s, n_c_items, self.num_h, self.d_k).permute(0, 2, 1, 3) # (b_s, num_h, d_k, n_c_items)\n v = self.Bc(values).view(b_s, n_c_items, self.num_h, self.d_v).permute(0, 2, 1, 3) # (b_s, num_h, n_c_items, d_v)\n\n att = self.cos(q.unsqueeze(3), k.unsqueeze(2))\n if add_pos_bias:\n batch_pos_bias = self.pos_bias.repeat(b_s, self.num_h, n_t_items, 1)\n att = att + batch_pos_bias\n\n if attention_mask is not None:\n attention_mask = attention_mask.repeat_interleave(t.tensor([n_t_items * self.num_h],\n device=self.device).repeat(b_s),\n dim=0).view(b_s, self.num_h, n_t_items, n_c_items)\n att = att.masked_fill(attention_mask, -np.inf)\n\n att = t.softmax(att, -1)\n out = t.matmul(att, v).permute(0, 2, 1, 3).contiguous().view(b_s, n_t_items, self.num_h * self.d_v) # (b_s, n_t_items, num_h*d_num_h)\n out = self.R(out) # (b_s, n_t_items, emb_size)\n return out, att\n\n\nclass AttentiveItemToVec(nn.Module):\n def __init__(self, padding_idx, vocab_size, emb_size, window_size, device, n_b, n_h, add_pos_bias):\n super(AttentiveItemToVec, self).__init__()\n self.name = 'ai2v'\n self.vocab_size = vocab_size\n self.emb_size = emb_size\n self.pad_idx = padding_idx\n self.window_size = window_size\n self.n_b = n_b\n self.device = device\n self.tvectors = nn.Embedding(self.vocab_size, self.emb_size, padding_idx=padding_idx)\n self.cvectors = nn.Embedding(self.vocab_size, self.emb_size, padding_idx=padding_idx)\n self.tvectors.weight = nn.Parameter(t.cat([FT(self.vocab_size - 1,\n self.emb_size).uniform_(-0.5 / self.emb_size,\n 0.5 / self.emb_size),\n t.zeros(1, self.emb_size)]))\n self.cvectors.weight = nn.Parameter(t.cat([FT(self.vocab_size - 1,\n self.emb_size).uniform_(-0.5 / self.emb_size,\n 0.5 / self.emb_size),\n t.zeros(1, self.emb_size)]))\n self.tvectors.weight.requires_grad = True\n self.cvectors.weight.requires_grad = True\n self.W0 = nn.Linear(4 * self.emb_size, self.emb_size)\n self.W1 = nn.Linear(self.emb_size, 1)\n self.relu = nn.ReLU()\n self.b_l_j = nn.Parameter(FT(self.vocab_size).uniform_(-0.5 / self.emb_size, 0.5 / self.emb_size))\n self.b_l_j.requires_grad = True\n self.mha_layers = nn.ModuleList([MultiHeadAttention(embedding_size=self.emb_size, window_size=window_size,\n device=device, num_h=n_h)\n for _ in range(self.n_b)])\n self.Bt = nn.Linear(self.emb_size, self.emb_size)\n self.add_pos_bias = add_pos_bias\n\n def forward(self, batch_titems, batch_citems, mask_pad_ids=None):\n v_l_j = self.forward_t(batch_titems)\n u_l_m = self.forward_c(batch_citems)\n\n sub_users_l = v_l_j\n for l in self.mha_layers:\n sub_users_l, att_scores_l = l(sub_users_l, u_l_m, u_l_m, attention_mask=mask_pad_ids, add_pos_bias=self.add_pos_bias)\n\n return sub_users_l, att_scores_l\n\n def forward_t(self, data):\n v = data.long()\n return self.tvectors(v)\n\n def forward_c(self, data):\n v = data.long()\n return self.cvectors(v)\n\n\nclass SGNS(nn.Module):\n def __init__(self, base_model, vocab_size, n_negs, weights, loss_method, device):\n super(SGNS, self).__init__()\n self.ai2v = base_model\n self.vocab_size = vocab_size\n self.n_negs = n_negs\n self.device = device\n self.weights=None\n if weights is not None:\n wf = np.power(weights, 0.75)\n wf = wf / wf.sum()\n self.weights = FT(wf)\n self.loss_method = loss_method\n\n def similarity(self, batch_sub_users, batch_tvecs, batch_titem_ids):\n return self.ai2v.W1(self.ai2v.relu(self.ai2v.W0(t.cat([batch_sub_users, batch_tvecs,\n t.mul(batch_sub_users, batch_tvecs),\n (batch_sub_users - batch_tvecs).abs()], 2)))) + \\\n self.ai2v.b_l_j[batch_titem_ids].unsqueeze(2)\n\n def inference(self, user_items):\n if len(user_items) < self.ai2v.window_size:\n pad_times = self.ai2v.window_size - len(user_items)\n user_items = [self.ai2v.pad_idx] * pad_times + user_items\n else:\n user_items = user_items[-self.ai2v.window_size:]\n num_items = self.ai2v.tvectors.weight.size()[0]\n citems = t.tensor([user_items])\n citems = citems.to(self.device)\n all_titems = t.tensor(range(num_items)).unsqueeze(0)\n all_titems = all_titems.to(self.device)\n mask_pad_ids = citems == self.ai2v.pad_idx\n sub_users, _ = self.ai2v(all_titems, citems, mask_pad_ids=mask_pad_ids)\n all_tvecs = self.ai2v.Bt(self.ai2v.forward_t(all_titems))\n sim = self.similarity(sub_users, all_tvecs, all_titems)\n return sim.squeeze(-1).squeeze(0).detach().cpu().numpy()\n\n def forward(self, batch_titems, batch_citems):\n if self.weights is not None:\n batch_nitems = t.multinomial(self.weights, batch_titems.size()[0] * self.n_negs, replacement=True).view(batch_titems.size()[0], -1)\n else:\n batch_nitems = FT(batch_titems.size()[0], self.n_negs).uniform_(0, self.vocab_size - 1).long()\n if next(self.parameters()).is_cuda:\n batch_nitems = batch_nitems.to(self.device)\n\n batch_titems = t.cat([batch_titems.reshape(-1, 1), batch_nitems], 1)\n mask_pad_ids = (batch_citems == self.ai2v.pad_idx)\n batch_sub_users, _ = self.ai2v(batch_titems, batch_citems, mask_pad_ids)\n batch_tvecs = self.ai2v.Bt(self.ai2v.forward_t(batch_titems))\n\n sim = self.similarity(batch_sub_users, batch_tvecs, batch_titems)\n\n if self.loss_method == 'CCE': # This option is the default option.\n soft = sim.softmax(dim=1) + 1e-6\n return -soft[:, 0].log().sum()\n\n if self.loss_method == 'BCE':\n soft_pos = sim[:, 0].sigmoid() + 1e-6\n soft_neg = sim[:, 1:].neg().sigmoid() + 1e-6\n return (-soft_pos.log().sum()) + (-soft_neg.log().sum())\n\n if self.loss_method == 'Hinge':\n soft_pos = t.maximum((t.ones_like(sim[:, 0]) - sim[:, 0]), t.zeros_like(sim[:, 0])) + 1e-6\n soft_neg = t.maximum((t.ones_like(sim[:, 1:]) - (-sim[:, 1:])), t.zeros_like(sim[:, 1:])) + 1e-6\n return soft_pos.sum() + soft_neg.sum()\n\n def run_epoch(self, train_dl, epoch, sgns, optim):\n pbar = tqdm(train_dl)\n pbar.set_description(\"[Epoch {}]\".format(epoch))\n train_loss = 0\n\n srt = datetime.datetime.now().replace(microsecond=0)\n for batch_titems, batch_citems in pbar:\n batch_titems, batch_citems = batch_titems.to(self.device), batch_citems.to(self.device)\n loss = sgns(batch_titems, batch_citems)\n train_loss += loss.item()\n optim.zero_grad()\n loss.backward()\n optim.step()\n pbar.set_postfix(train_loss=loss.item())\n\n train_loss = train_loss / len(pbar)\n print(f'train_loss: {train_loss}')\n end = datetime.datetime.now().replace(microsecond=0)\n print('epoch time: ', end - srt)\n return train_loss, sgns\n"
] |
[
[
"torch.softmax",
"numpy.power",
"torch.zeros",
"torch.zeros_like",
"torch.nn.CosineSimilarity",
"torch.nn.Embedding",
"torch.tensor",
"torch.nn.Linear",
"torch.matmul",
"torch.mul",
"torch.FloatTensor",
"torch.nn.ReLU",
"torch.ones_like"
]
] |
LeonardoAlchieri/Top-Of-Youtube
|
[
"ec2fc3f2a40afd5ffe831136c75b2951b4b74341"
] |
[
"testQuerying/testEnrichScrapingWithKaggle.py"
] |
[
"import pandas as pd\nimport pymongo\nimport json\nimport re\nimport base64\nfrom sqlalchemy import create_engine\nimport pymysql\nfrom pymongo import UpdateOne\nfrom pymongo import UpdateMany\nfrom mpi4py import MPI\nimport sys\nimport logging\nimport bcolors\nimport os\nimport shutil\nfrom apiclient.discovery import build\nfrom datetime import datetime\nimport yaml\nimport time\n\n\n\ndef main():\n START = time.time()\n comm = MPI.COMM_WORLD\n\n ID = comm.Get_rank()\n\n logging.basicConfig(filename='./logs/log_enrichScraperWithkaggle'+str(ID)+'.log', level=logging.INFO)\n logging.info(\"\\n\")\n logging.info(\"Log file created. Program started.\")\n logging.info(\"Reading config files.\")\n\n\n\n\n with open(\"configMongo.yml\", \"r\") as file:\n cfgMongo = yaml.safe_load(file)\n\n LOADING_PERC = cfgMongo[\"percentage\"]\n\n logging.info(\"Config files succesfully read.\")\n logging.info(\"Loading Mongo collections.\")\n MONGO_HOST = cfgMongo[\"host\"]\n MONGO_DATABASE = cfgMongo[\"database\"]\n\n clientMongo = pymongo.MongoClient(MONGO_HOST)\n databaseMongo = clientMongo[MONGO_DATABASE]\n\n collectionName = \"scrape\"+str(LOADING_PERC)\n scraperCollection = databaseMongo[collectionName]\n\n collectionName = \"kaggleNation\"+str(LOADING_PERC)\n kaggleCollection = databaseMongo[collectionName]\n\n logging.info(\"Mongo collections loaded.\")\n\n BATCH_SIZE = round(kaggleCollection.count_documents({})/comm.Get_size() + 0.5)\n cursorKaggle = kaggleCollection.find().skip(BATCH_SIZE*ID).limit(BATCH_SIZE)\n\n logging.info(\"Preparing to update.\")\n # This Updated enriches scraper documents with data from kaggle\n upserts = [ UpdateMany(\n {'id': kaggleDoc[\"id\"]},\n {\n '$set': {\"date\": kaggleDoc[\"date\"]}\n }) for kaggleDoc in cursorKaggle]\n logging.info(\"Updating documents.\")\n scraperCollection.bulk_write(upserts)\n logging.info(\"Data saved succesfully to Mongo.\")\n\n logging.info(\"[\"+str(ID)+\"] Program completed.\")\n END = time.time()\n time_result = {\n \"collection\": collectionName,\n \"percentage\": LOADING_PERC,\n \"time\": (END - START),\n \"number of cores\": 1\n }\n df = pd.DataFrame()\n df = df.append(time_result, ignore_index=True)\n with open(\"results/resultTogether.csv\", \"a\") as file:\n df.to_csv(file, header=False)\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"pandas.DataFrame"
]
] |
sbam13/open_lth
|
[
"d8c8d450cc8229afed54b26f77b91c3fe0c3f339"
] |
[
"datasets/test/test_imagedataset_and_dataloader.py"
] |
[
"# Copyright (c) Facebook, Inc. and its affiliates.\r\n\r\n# This source code is licensed under the MIT license found in the\r\n# LICENSE file in the root directory of this source tree.\r\n\r\nimport numpy as np\r\n\r\nfrom datasets import base, cifar10\r\nfrom testing import test_case\r\n\r\n\r\nclass TestImageDatasetAndDataLoader(test_case.TestCase):\r\n def test_is_image_dataset(self):\r\n train_set = cifar10.Dataset.get_train_set(use_augmentation=True)\r\n self.assertIsInstance(train_set, base.ImageDataset)\r\n\r\n def get_labels_from_loader(self, loader, minibatches=10):\r\n i = 0\r\n actual_labels = []\r\n for examples, labels in loader:\r\n self.assertEqual(list(examples.shape), [4, 3, 32, 32])\r\n self.assertEqual(list(labels.shape), [4])\r\n actual_labels += labels.tolist()\r\n\r\n i += 1\r\n if i > minibatches: break\r\n\r\n return actual_labels\r\n\r\n def data_loading_helper(self, dataset, shuffle_seed=None):\r\n loader = base.DataLoader(dataset, batch_size=4, num_workers=0, pin_memory=True)\r\n self.assertIsNotNone(loader)\r\n self.assertEqual(len(loader), 12500)\r\n\r\n if shuffle_seed is not None: loader.shuffle(shuffle_seed)\r\n return self.get_labels_from_loader(loader)\r\n\r\n def test_data_loading(self):\r\n train_set = cifar10.Dataset.get_train_set(use_augmentation=False)\r\n actual_labels = self.data_loading_helper(train_set)\r\n self.assertEqual(actual_labels, train_set._labels[np.arange(len(actual_labels))].tolist())\r\n\r\n train_set = cifar10.Dataset.get_train_set(use_augmentation=True)\r\n self.data_loading_helper(train_set)\r\n\r\n train_set = cifar10.Dataset.get_train_set(use_augmentation=True)\r\n train_set.unsupervised_rotation(2)\r\n self.data_loading_helper(train_set)\r\n\r\n train_set = cifar10.Dataset.get_train_set(use_augmentation=True)\r\n train_set.blur(4)\r\n self.data_loading_helper(train_set)\r\n\r\n def test_shuffling_dataloader(self):\r\n train_set = cifar10.Dataset.get_train_set(use_augmentation=False)\r\n\r\n # The first ten labels that occur in the dataset after shuffling with seed 1.\r\n expected_labels = [0, 1, 6, 3, 6, 0, 0, 4, 3, 8]\r\n\r\n # The first ten labels seen by the data loader.\r\n actual_labels = self.data_loading_helper(train_set, shuffle_seed=1)[:10]\r\n\r\n # They should be equal.\r\n self.assertEqual(actual_labels, expected_labels)\r\n\r\n # Again for seed 0.\r\n expected_labels = [6, 8, 7, 5, 5, 3, 2, 2, 0, 9]\r\n actual_labels = self.data_loading_helper(train_set, shuffle_seed=0)[:10]\r\n self.assertEqual(actual_labels, expected_labels)\r\n\r\n def test_shuffling_dataloader_twice(self):\r\n train_set = cifar10.Dataset.get_train_set(use_augmentation=False)\r\n loader = base.DataLoader(train_set, batch_size=4, num_workers=0, pin_memory=True)\r\n\r\n loader.shuffle(0)\r\n actual_seed0 = self.get_labels_from_loader(loader)\r\n expected_seed0 = [6, 8, 7, 5, 5, 3, 2, 2, 0, 9]\r\n self.assertEqual(actual_seed0[:10], expected_seed0)\r\n\r\n loader.shuffle(1)\r\n actual_seed1 = self.get_labels_from_loader(loader)\r\n expected_seed1 = [0, 1, 6, 3, 6, 0, 0, 4, 3, 8]\r\n self.assertEqual(actual_seed1[:10], expected_seed1)\r\n\r\n def test_blur(self):\r\n train_set = cifar10.Dataset.get_train_set(use_augmentation=True)\r\n train_set.blur(4)\r\n\r\n # Nothing should change about the labels.\r\n self.assertEqual(len(train_set), 50000)\r\n self.assertEqual(np.max(train_set._labels), 9)\r\n self.assertEqual(train_set._labels[:10].tolist(), [6, 9, 9, 4, 1, 1, 2, 7, 8, 3])\r\n\r\n def test_unsupervised_rotation(self):\r\n train_set = cifar10.Dataset.get_train_set(use_augmentation=True)\r\n train_set.unsupervised_rotation(0)\r\n self.assertEqual(len(train_set), 50000)\r\n self.assertEqual(np.max(train_set._labels), 3)\r\n self.assertEqual(np.sum(train_set._labels == 0), 12539)\r\n self.assertEqual(np.sum(train_set._labels == 1), 12629)\r\n self.assertEqual(np.sum(train_set._labels == 2), 12411)\r\n self.assertEqual(np.sum(train_set._labels == 3), 12421)\r\n self.assertEqual(train_set._labels[:20].tolist(),\r\n [0, 3, 1, 0, 3, 3, 3, 3, 1, 3, 1, 2, 0, 3, 2, 0, 0, 0, 2, 1])\r\n\r\n train_set = cifar10.Dataset.get_train_set(use_augmentation=True)\r\n train_set.unsupervised_rotation(1)\r\n self.assertEqual(len(train_set), 50000)\r\n self.assertEqual(np.max(train_set._labels), 3)\r\n self.assertEqual(np.sum(train_set._labels == 0), 12379)\r\n self.assertEqual(np.sum(train_set._labels == 1), 12568)\r\n self.assertEqual(np.sum(train_set._labels == 2), 12433)\r\n self.assertEqual(np.sum(train_set._labels == 3), 12620)\r\n self.assertEqual(train_set._labels[:20].tolist(),\r\n [1, 3, 0, 0, 3, 1, 3, 1, 3, 0, 0, 1, 0, 3, 1, 0, 2, 1, 2, 0])\r\n\r\n\r\ntest_case.main()\r\n"
] |
[
[
"numpy.max",
"numpy.sum"
]
] |
Haftom2323/USGSg_3DEP_Interface
|
[
"22ab16be411541853d4ecdc551a639d3003e48af"
] |
[
"visualize.py"
] |
[
"from get_data import get_raster_terrain\n\nimport geopandas as gpd\nimport imageio\nimport pandas as pd\nimport pathlib\nimport matplotlib.pyplot as plt\nimport mapclassify as mc\nimport numpy as np\nimport laspy\nimport rasterio\nfrom rasterio import mask\nimport folium\n\n## Plot raster/tif image\n# --------------------\ndef plot_raster(rast_data, title=''):\n \"\"\"\n Plots raster tif image both in log scale(+1) and original verion\n \"\"\"\n fig, (axlog, axorg) = plt.subplots(1, 2, figsize=(14,7))\n im1 = axlog.imshow(np.log1p(rast_data)) # vmin=0, vmax=2.1)\n# im2 = axorg.imshow(rast_data)\n\n plt.title(\"{}\".format(title), fontdict = {'fontsize': 15}) \n plt.axis('off')\n plt.colorbar(im1, fraction=0.03)\n\ndef visualize(bounds, region):\n get_raster_terrain(bounds=bounds,region=region)\n iowa_tif = './data/tif/'+region+'.tif'\n raster_iowa = rasterio.open(iowa_tif)\n iowa_data = raster_iowa.read(1)\n count = iowa_data[iowa_data > 0].sum()\n title = 'Log scaled (+1) and No Scale Raster plots'.format(count)\n plot_raster(iowa_data, title)\n\n"
] |
[
[
"matplotlib.pyplot.colorbar",
"numpy.log1p",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.axis"
]
] |
mdylan2/single-cell-explorer
|
[
"775e59fcf5c105bbe70edd17dbf1d2153c4f662c"
] |
[
"server/tests/unit/common/fbs/test_matrix.py"
] |
[
"import unittest\nimport pandas as pd\nimport numpy as np\nfrom scipy import sparse\nfrom parameterized import parameterized_class\nimport json\n\nfrom server.tests import decode_fbs\nfrom server.common.fbs.matrix import encode_matrix_fbs, decode_matrix_fbs\nfrom server.common.utils.type_conversion_utils import get_dtypes_and_schemas_of_dataframe\nimport server.common.fbs as fbs\n\n\nclass FbsTests(unittest.TestCase):\n \"\"\"Test Case for Matrix FBS data encode/decode\"\"\"\n\n def test_encode_boundary(self):\n \"\"\"test various boundary checks\"\"\"\n\n # row indexing is unsupported\n with self.assertRaises(ValueError):\n encode_matrix_fbs(matrix=pd.DataFrame(), row_idx=[])\n\n # matrix must be 2D\n with self.assertRaises(ValueError):\n encode_matrix_fbs(matrix=np.zeros((3, 2, 1)))\n with self.assertRaises(ValueError):\n encode_matrix_fbs(matrix=np.ones((10,)))\n\n def fbs_checks(self, fbs, dims, expected_types, expected_column_idx):\n d = decode_fbs.decode_matrix_FBS(fbs)\n self.assertEqual(d[\"n_rows\"], dims[0])\n self.assertEqual(d[\"n_cols\"], dims[1])\n self.assertIsNone(d[\"row_idx\"])\n self.assertEqual(len(d[\"columns\"]), dims[1])\n for i in range(0, len(d[\"columns\"])):\n self.assertEqual(len(d[\"columns\"][i]), dims[0])\n self.assertIsInstance(d[\"columns\"][i], expected_types[i][0])\n if expected_types[i][1] is not None:\n self.assertEqual(d[\"columns\"][i].dtype, expected_types[i][1])\n if expected_column_idx is not None:\n self.assertSetEqual(set(expected_column_idx), set(d[\"col_idx\"]))\n\n def test_encode_DataFrame(self):\n df = pd.DataFrame(\n data={\n \"a\": np.zeros((10,), dtype=np.float32),\n \"b\": np.ones((10,), dtype=np.int64),\n \"c\": np.array([i for i in range(0, 10)], dtype=np.uint16),\n \"d\": pd.Series([\"x\", \"y\", \"z\", \"x\", \"y\", \"z\", \"a\", \"x\", \"y\", \"z\"], dtype=\"category\"),\n }\n )\n expected_types = ((np.ndarray, np.float32), (np.ndarray, np.int32), (np.ndarray, np.int32), (list, None))\n fbs = encode_matrix_fbs(matrix=df, row_idx=None, col_idx=df.columns)\n self.fbs_checks(fbs, (10, 4), expected_types, [\"a\", \"b\", \"c\", \"d\"])\n\n def test_encode_ndarray(self):\n arr = np.zeros((3, 2), dtype=np.float32)\n expected_types = ((np.ndarray, np.float32), (np.ndarray, np.float32), (np.ndarray, np.float32))\n fbs = encode_matrix_fbs(matrix=arr, row_idx=None, col_idx=None)\n self.fbs_checks(fbs, (3, 2), expected_types, None)\n\n def test_encode_sparse(self):\n csc = sparse.csc_matrix(np.array([[0, 1, 2], [3, 0, 4]]))\n expected_types = ((np.ndarray, np.int32), (np.ndarray, np.int32), (np.ndarray, np.int32))\n fbs = encode_matrix_fbs(matrix=csc, row_idx=None, col_idx=None)\n self.fbs_checks(fbs, (2, 3), expected_types, None)\n\n def test_roundtrip(self):\n dfSrc = pd.DataFrame(\n data={\n \"a\": np.zeros((10,), dtype=np.float32),\n \"b\": np.ones((10,), dtype=np.int64),\n \"c\": np.array([i for i in range(0, 10)], dtype=np.uint16),\n \"d\": pd.Series([\"x\", \"y\", \"z\", \"x\", \"y\", \"z\", \"a\", \"x\", \"y\", \"z\"], dtype=\"category\"),\n }\n )\n dfDst = decode_matrix_fbs(encode_matrix_fbs(matrix=dfSrc, col_idx=dfSrc.columns))\n self.assertEqual(dfSrc.shape, dfDst.shape)\n self.assertEqual(set(dfSrc.columns), set(dfDst.columns))\n for c in dfSrc.columns:\n self.assertTrue(c in dfDst.columns)\n if isinstance(dfSrc[c], pd.Series):\n self.assertTrue(np.all(dfSrc[c] == dfDst[c]))\n else:\n self.assertEqual(dfSrc[c], dfDst[c])\n\n\n\"\"\"\nTest type consistency between FBS encoding and the underlying schema hint.\n\nBasic assertion: the FBS type returned by encode_matrix_fbs() will be consistent\nwith the schema hint returned by type_conversion_utils (which is in turn used\nto create the client schema).\n\nThe following test cases are all dicts which contain the following keys:\n - dataframe - the dataframe used as input for encode_matrix_fbs\n - expected_fbs_types - upon success, dict of FBS column types expected (eg, Float32Array)\n - expected_schema_hints - upon success, dict of schema hint\nAll are keyed by column name.\n\"\"\"\n\n# simple tests that we convert all ints to int32\nint_dtypes = [np.dtype(d) for d in [np.int8, np.uint8, np.int16, np.uint16, np.int32, np.uint32, np.int64, np.uint64]]\nint_test_cases = [\n {\n \"dataframe\": pd.DataFrame({dtype.name: np.zeros((10,), dtype=dtype) for dtype in int_dtypes}),\n \"expected_fbs_types\": dict(\n [(dtype.name, fbs.NetEncoding.TypedArray.TypedArray.Int32Array) for dtype in int_dtypes]\n ),\n \"expected_schema_hints\": dict([(dtype.name, {\"type\": \"int32\"}) for dtype in int_dtypes]),\n }\n]\n\n# simple tests that we convert all floats to float32\nfloat_dtypes = [np.dtype(d) for d in [np.float16, np.float32, np.float64]]\nfloat_test_cases = [\n {\n \"dataframe\": pd.DataFrame({dtype.name: np.zeros((10,), dtype=dtype) for dtype in float_dtypes}),\n \"expected_fbs_types\": dict(\n [(dtype.name, fbs.NetEncoding.TypedArray.TypedArray.Float32Array) for dtype in float_dtypes]\n ),\n \"expected_schema_hints\": dict([(dtype.name, {\"type\": \"float32\"}) for dtype in float_dtypes]),\n }\n]\n\n# boolean - should be encoded as an uint32\nbool_dtypes = [np.dtype(d) for d in [np.bool_, bool]]\nbool_test_cases = [\n {\n \"dataframe\": pd.DataFrame({dtype.name: np.ones((10,), dtype=dtype) for dtype in bool_dtypes}),\n \"expected_fbs_types\": dict(\n [(dtype.name, fbs.NetEncoding.TypedArray.TypedArray.Uint32Array) for dtype in bool_dtypes]\n ),\n \"expected_schema_hints\": dict([(dtype.name, {\"type\": \"boolean\"}) for dtype in bool_dtypes]),\n }\n]\n\ncat_test_cases = [\n {\n \"dataframe\": pd.DataFrame({\"a\": pd.Series([\"a\", \"b\", \"c\", \"a\", \"b\", \"c\"], dtype=\"category\")}),\n \"expected_fbs_types\": {\"a\": fbs.NetEncoding.TypedArray.TypedArray.JSONEncodedArray},\n \"expected_schema_hints\": {\"a\": {\"type\": \"categorical\", \"categories\": [\"a\", \"b\", \"c\"]}},\n },\n {\n \"dataframe\": pd.DataFrame(\n {\"a\": pd.Series([\"a\", \"b\", \"c\", \"a\", \"b\", \"c\"], dtype=\"category\").cat.remove_categories(\"b\")}\n ),\n \"expected_fbs_types\": {\"a\": fbs.NetEncoding.TypedArray.TypedArray.JSONEncodedArray},\n \"expected_schema_hints\": {\"a\": {\"type\": \"categorical\", \"categories\": [\"a\", \"c\"]}},\n },\n {\n \"dataframe\": pd.DataFrame({\"a\": pd.Series(np.arange(0, 10, dtype=np.int64), dtype=\"category\")}),\n \"expected_fbs_types\": {\"a\": fbs.NetEncoding.TypedArray.TypedArray.Int32Array},\n \"expected_schema_hints\": {\"a\": {\"type\": \"categorical\"}},\n },\n {\n \"dataframe\": pd.DataFrame(\n {\"a\": pd.Series(np.arange(0, 10, dtype=np.int64), dtype=\"category\").cat.remove_categories(2)}\n ),\n \"expected_fbs_types\": {\"a\": fbs.NetEncoding.TypedArray.TypedArray.Float32Array},\n \"expected_schema_hints\": {\"a\": {\"type\": \"categorical\"}},\n },\n {\n \"dataframe\": pd.DataFrame({\"a\": pd.Series(np.arange(0, 10, dtype=np.float64), dtype=\"category\")}),\n \"expected_fbs_types\": {\"a\": fbs.NetEncoding.TypedArray.TypedArray.Float32Array},\n \"expected_schema_hints\": {\"a\": {\"type\": \"categorical\"}},\n },\n {\n \"dataframe\": pd.DataFrame(\n {\"a\": pd.Series(np.arange(0, 10, dtype=np.float64), dtype=\"category\").cat.remove_categories(2)}\n ),\n \"expected_fbs_types\": {\"a\": fbs.NetEncoding.TypedArray.TypedArray.Float32Array},\n \"expected_schema_hints\": {\"a\": {\"type\": \"categorical\"}},\n },\n]\n\n\ntest_cases = [\n *int_test_cases,\n *float_test_cases,\n *bool_test_cases,\n *cat_test_cases,\n]\n\n\n@parameterized_class(test_cases)\nclass TestTypeConversionConsistency(unittest.TestCase):\n def test_type_conversion_consistency(self):\n self.assertEqual(self.dataframe.shape[1], len(self.expected_fbs_types))\n self.assertEqual(self.dataframe.shape[1], len(self.expected_schema_hints))\n\n buf = encode_matrix_fbs(matrix=self.dataframe, col_idx=self.dataframe.columns)\n encoding_dtypes, schema_hints = get_dtypes_and_schemas_of_dataframe(self.dataframe)\n\n # check schema hints\n # print(schema_hints)\n # print(self.expected_schema_hints)\n self.assertEqual(schema_hints, self.expected_schema_hints)\n\n # inspect the FBS types\n matrix = fbs.NetEncoding.Matrix.Matrix.GetRootAsMatrix(buf, 0)\n columns_length = matrix.ColumnsLength()\n self.assertEqual(columns_length, self.dataframe.shape[1])\n\n self.assertEqual(matrix.ColIndexType(), fbs.NetEncoding.TypedArray.TypedArray.JSONEncodedArray)\n col_labels_arr = fbs.NetEncoding.JSONEncodedArray.JSONEncodedArray()\n col_labels_arr.Init(matrix.ColIndex().Bytes, matrix.ColIndex().Pos)\n col_index_labels = json.loads(col_labels_arr.DataAsNumpy().tobytes().decode(\"utf-8\"))\n self.assertEqual(len(col_index_labels), self.dataframe.shape[1])\n\n for col_idx in range(0, columns_length):\n col_label = col_index_labels[col_idx]\n col = matrix.Columns(col_idx)\n col_type = col.UType()\n self.assertEqual(self.expected_fbs_types[col_label], col_type)\n"
] |
[
[
"pandas.Series",
"numpy.arange",
"numpy.dtype",
"numpy.ones",
"pandas.DataFrame",
"numpy.all",
"numpy.array",
"numpy.zeros"
]
] |
JuliaTagBot/BenchFourierFlows.jl
|
[
"5b36232ad6f0ac5b3be9c2ed2e59622e17566b94"
] |
[
"dedalus/dedalus_decaying2Dturbulence.py"
] |
[
"import numpy as np\nimport time, logging\n\nfrom mpi4py import MPI\nfrom dedalus import public as de\nfrom dedalus.extras import plot_tools\n\nfrom numpy import pi\n\n# Parameters\nLx = Ly = 2 * pi\nnx = ny = 256\ndealias = 1\nnu = 0.\ndt = 0.001\nstop_iteration = 5000\nstartup_iterations = 10\n\nlogger = logging.getLogger(__name__)\nminute = 60.0\nhour = 60*minute\n\nxbasis = de.Fourier('x', nx, interval=(-Lx/2, Lx/2), dealias=dealias)\nybasis = de.Fourier('y', ny, interval=(-Ly/2, Ly/2), dealias=dealias)\ndomain = de.Domain([xbasis, ybasis], grid_dtype=np.float64)\n\nx, y = domain.grid(0), domain.grid(1)\n\nvariables = ['psi']\nproblem = de.IVP(domain, variables=variables, time='t')\nproblem.parameters['nu'] = nu\nproblem.substitutions['J(a, b)'] = \"dy(dx(a)*b) - dx(dy(a)*b)\" # Laplacian in conservative form\nproblem.substitutions['lap(a)'] = \"d(a, x=2) + d(a, y=2)\"\nproblem.substitutions['q'] = \"lap(psi)\"\nproblem.add_equation(\"dt(q) + nu*lap(lap(q)) = - J(psi, q)\", condition=\"(nx != 0) or (ny != 0)\")\nproblem.add_equation(\"psi = 0\", condition=\"(nx == 0) and (ny == 0)\")\n\nstart_build_time = time.time()\nsolver = problem.build_solver(de.timesteppers.SBDF3)\nlogger.info('Solver built. (t = %f) ' %(time.time()-start_build_time))\n\npsi = solver.state['psi']\n\ndef constructfilter(domain):\n kx = domain.elements(0)\n ky = domain.elements(1)\n cphi = 0.65 * np.pi\n filterfac = 23.6\n wv = np.sqrt((kx*Lx/nx)**2+(ky*Ly/ny)**2)\n filter = np.exp(-filterfac*(wv-cphi)**4)\n filter[wv<=cphi] = 1.\n return filter\n\nfilter = constructfilter(domain)\n\n# Initialize state variables\ndef peakedisotropicspectrum(domain, k0=6, energy0=0.5, seed=1234):\n # Wavenumbers\n kx = domain.elements(0)\n ky = domain.elements(1)\n modk = np.sqrt(kx**2+ky**2)\n # Isotropic spectrum\n psi = domain.new_field()\n psi['c'] = (modk**2 * (1 + (modk/k0)**4) + 1e-14)**(-0.5)\n psi['c'][modk == 0] = 0\n # Add random phases, globally initialized for parallel reproducibility\n rand = np.random.RandomState(seed=seed)\n cshape = domain.dist.coeff_layout.global_shape(scales=1)\n slices = domain.dist.coeff_layout.slices(scales=1)\n phases = rand.standard_normal(cshape)[slices] + 1j*rand.standard_normal(cshape)[slices]\n psi['c'] *= phases\n # Impose Hermitian symmetry\n psi['g']\n # Normalize energy\n u = psi.differentiate('x')\n v = psi.differentiate('y')\n Ein = (0.5 * (u*u + v*v)).evaluate().integrate()\n psi['g'] *= (energy0 / Ein['g'])**0.5\n return psi\n\npsi.set_scales(domain.dealias)\npsi['g'] = peakedisotropicspectrum(domain, k0=6, energy0=0.5)['g']\npsi['c'] *= filter\nq = problem.namespace['q'].evaluate()\nq.set_scales(domain.dealias)\nqi = q['g'].copy()\n\n# Integration parameters\nsolver.stop_sim_time = np.inf\nsolver.stop_wall_time = np.inf\nsolver.stop_iteration = stop_iteration\nlog_cadence = stop_iteration\n\ndef time_to_log(log_cadence):\n (solver.iteration-1) % log_cadence == 0\n\n# Main loop\ntry:\n logger.info('Starting loop')\n while solver.ok:\n if solver.iteration == startup_iterations:\n start_run_time = time.time()\n solver.step(dt)\n psi['c'] *= filter\n if time_to_log(log_cadence):\n log(logger, dt)\nexcept:\n logger.error('Exception raised, triggering end of main loop.')\n raise\nfinally:\n end_run_time = time.time()\n logger.info('Iterations: %i' %solver.iteration)\n logger.info('Sim end time: %f' %solver.sim_time)\n logger.info('Run time: %.2f sec' %(end_run_time-start_run_time))\n logger.info('Time per time-step: %.3f ms' %((end_run_time-start_run_time)/(solver.iteration - startup_iterations)*1000))\n # logger.info(\n # 'Run time: %f cpu-hr' %((end_run_time-start_run_time)/hour * domain.dist.comm_cart.size))\n\n# # Gather distributed snapshots\n# q = problem.namespace['q'].evaluate()\n# qf = q['g'].copy()\n# qi = domain.dist.comm.gather(qi, root=0)\n# qf = domain.dist.comm.gather(qf, root=0)\n# \n# # Plot from root\n# if domain.dist.comm.rank == 0:\n# import matplotlib.pyplot as plt\n# qi = np.concatenate(qi, axis=1)\n# qf = np.concatenate(qf, axis=1)\n# X, Y = plot_tools.quad_mesh(xbasis.grid(dealias), ybasis.grid(dealias))\n# plt.figure(figsize=(10, 4))\n# plt.subplot(121)\n# plt.pcolormesh(X, Y, qi.T)\n# plt.xlabel(\"x\")\n# plt.ylabel(\"y\")\n# plt.title(\"vorticity @ t=0\")\n# plt.axis(\"square\")\n# plt.subplot(122)\n# plt.pcolormesh(X, Y, qf.T)\n# plt.axis(\"square\")\n# plt.xlabel(\"x\")\n# plt.ylabel(\"y\")\n# plt.title(\"vorticity @ t= %.2f\" %solver.sim_time)\n# plt.savefig(\"dedalus_n\"+str(nx)+\".png\", dpi=400)\n"
] |
[
[
"numpy.exp",
"numpy.sqrt",
"numpy.random.RandomState"
]
] |
buxiangzhiren/VQ-Diffusion_office
|
[
"a431c5e5622971b50e7fdd43ac7d8e4432001863"
] |
[
"image_synthesis/data/utils/comm.py"
] |
[
"\"\"\"\nThis file contains primitives for multi-gpu communication.\nThis is useful when doing distributed training.\n\"\"\"\n\nimport pickle\n\nimport torch\nimport torch.distributed as dist\n# from diffdist.functional import all_gather as better_all_gather\n\n\nclass Comm(object):\n def __init__(self, local_rank=0):\n self.local_rank = 0\n\n @property\n def world_size(self):\n if not dist.is_available():\n return 1\n if not dist.is_initialized():\n return 1\n return dist.get_world_size()\n\n @property\n def rank(self):\n if not dist.is_available():\n return 0\n if not dist.is_initialized():\n return 0\n return dist.get_rank()\n\n @property\n def local_rank(self):\n if not dist.is_available():\n print(\"****************** yes1\")\n return 0\n if not dist.is_initialized():\n print(\"****************** yes2\")\n return 0\n print(\"****************** yes3\", self._local_rank)\n return self._local_rank\n\n @local_rank.setter\n def local_rank(self, value):\n if not dist.is_available():\n self._local_rank = 0\n if not dist.is_initialized():\n self._local_rank = 0\n self._local_rank = value\n\n @property\n def head(self):\n return 'Rank[{}/{}]'.format(self.rank, self.world_size)\n \n def is_main_process(self):\n return self.rank == 0\n\n def synchronize(self):\n \"\"\"\n Helper function to synchronize (barrier) among all processes when\n using distributed training\n \"\"\"\n if self.world_size == 1:\n return\n dist.barrier()\n\n\ncomm = Comm()\n\n\ndef all_gather(data):\n \"\"\"\n Run all_gather on arbitrary picklable data (not necessarily tensors)\n Args:\n data: any picklable object\n Returns:\n list[data]: list of data gathered from each rank\n \"\"\"\n world_size = comm.world_size\n if world_size == 1:\n return [data]\n\n # serialized to a Tensor\n buffer = pickle.dumps(data)\n storage = torch.ByteStorage.from_buffer(buffer)\n tensor = torch.ByteTensor(storage).to(\"cuda\")\n\n # obtain Tensor size of each rank\n local_size = torch.LongTensor([tensor.numel()]).to(\"cuda\")\n size_list = [torch.LongTensor([0]).to(\"cuda\") for _ in range(world_size)]\n dist.all_gather(size_list, local_size)\n size_list = [int(size.item()) for size in size_list]\n max_size = max(size_list)\n\n # receiving Tensor from all ranks\n # we pad the tensor because torch all_gather does not support\n # gathering tensors of different shapes\n tensor_list = []\n for _ in size_list:\n tensor_list.append(torch.ByteTensor(size=(max_size,)).to(\"cuda\"))\n if local_size != max_size:\n padding = torch.ByteTensor(size=(max_size - local_size,)).to(\"cuda\")\n tensor = torch.cat((tensor, padding), dim=0)\n dist.all_gather(tensor_list, tensor)\n\n data_list = []\n for size, tensor in zip(size_list, tensor_list):\n buffer = tensor.cpu().numpy().tobytes()[:size]\n data_list.append(pickle.loads(buffer))\n\n return data_list\n\n\ndef reduce_dict(input_dict, average=True):\n \"\"\"\n Args:\n input_dict (dict): all the values will be reduced\n average (bool): whether to do average or sum\n Reduce the values in the dictionary from all processes so that process with rank\n 0 has the averaged results. Returns a dict with the same fields as\n input_dict, after reduction.\n \"\"\"\n world_size = comm.world_size\n if world_size < 2:\n return input_dict\n with torch.no_grad():\n names = []\n values = []\n # sort the keys so that they are consistent across processes\n for k in sorted(input_dict.keys()):\n names.append(k)\n values.append(input_dict[k])\n values = torch.stack(values, dim=0)\n dist.reduce(values, dst=0)\n if dist.get_rank() == 0 and average:\n # only main process gets accumulated, so only divide by\n # world_size in this case\n values /= world_size\n reduced_dict = {k: v for k, v in zip(names, values)}\n return reduced_dict\n\n\ndef gather_tensors(tensor):\n \"\"\"\n Performs all_gather operation on the provided tensors.\n *** Warning ***: torch.distributed.all_gather has no gradient.\n \"\"\"\n tensors_gather = [\n torch.ones_like(tensor)\n for _ in range(comm.world_size)\n ]\n\n dist.all_gather(tensors_gather, tensor, async_op=False)\n # need to do this to restore propagation of the gradients\n tensors_gather[comm.rank] = tensor\n output = torch.cat(tensors_gather, dim=0)\n return output\n\ndef gather_tensors_fake(tensor):\n \"\"\"\n Performs all_gather operation on the provided tensors.\n *** Warning ***: torch.distributed.all_gather has no gradient.\n \"\"\"\n tensors_gather = [\n torch.ones_like(tensor)\n for _ in range(comm.world_size)\n ]\n\n dist.all_gather(tensors_gather, tensor, async_op=False)\n # need to do this to restore propagation of the gradients\n tensors_gather[comm.rank] = tensor\n output = torch.cat(tensors_gather, dim=0)\n output = torch.cat([output,output.detach()],0)\n return output\n\ndef gather_nearby_tensors(tensor):\n \"\"\"\n Performs all_gather operation on the provided tensors.\n *** Warning ***: torch.distributed.all_gather has no gradient.\n \"\"\"\n step=comm.rank//2\n if comm.rank%2==0:\n nearby_rank=step*2+1\n else:\n nearby_rank=step*2\n cpu_tensor=tensor\n tensors_gather = [\n torch.ones_like(cpu_tensor)\n for _ in range(comm.world_size)\n ]\n dist.all_gather(tensors_gather, cpu_tensor, async_op=False)\n # need to do this to restore propagation of the gradients\n tensors_gather=[tensors_gather[nearby_rank].to(tensor.device),tensor]\n output = torch.cat(tensors_gather, dim=0)\n return output\n\n\ndef gather_tensors_with_gradient(x):\n \"\"\" collect all tensor from all GPUs\n args:\n x: shape (mini_batch, ...)\n returns:\n shape (mini_batch * num_gpu, ...)\n \"\"\"\n x = x.contiguous()\n out_list = [torch.zeros_like(x, device=x.device, dtype=x.dtype) for _ in range(comm.world_size)]\n out_list = better_all_gather(out_list, x)\n return torch.cat(out_list, dim=0)\n\ngather_funcs={\n \"ALL\":gather_tensors,\n \"NEAR\":gather_nearby_tensors,\n \"GRAD\":gather_tensors_with_gradient,\n \"FAKE\":gather_tensors_fake\n}\n\nfrom contextlib import contextmanager\n\n@contextmanager\ndef torch_distributed_zero_first():\n \"\"\"\n Decorator to make all processes in distributed training wait for each local_master to do something.\n \"\"\"\n local_rank=comm.local_rank\n if local_rank not in [-1, 0]:\n dist.barrier(device_ids=[local_rank])\n yield\n if local_rank == 0:\n dist.barrier(device_ids=[0])\n"
] |
[
[
"torch.ByteTensor",
"torch.LongTensor",
"torch.cat",
"torch.distributed.all_gather",
"torch.zeros_like",
"torch.distributed.is_initialized",
"torch.distributed.barrier",
"torch.distributed.reduce",
"torch.distributed.is_available",
"torch.no_grad",
"torch.stack",
"torch.distributed.get_rank",
"torch.distributed.get_world_size",
"torch.ones_like",
"torch.ByteStorage.from_buffer"
]
] |
anupamme/CheXpert-Federated
|
[
"afef9d4b477716c289a23b80d7e59b6f36da72a1"
] |
[
"transfer.py"
] |
[
"'''This script goes along the blog post\n\"Building powerful image classification models using very little data\"\nfrom blog.keras.io.\nIt uses data that can be downloaded at:\nhttps://www.kaggle.com/c/dogs-vs-cats/data\nIn our setup, we:\n- created a data/ folder\n- created train/ and validation/ subfolders inside data/\n- created cats/ and dogs/ subfolders inside train/ and validation/\n- put the cat pictures index 0-999 in data/train/cats\n- put the cat pictures index 1000-1400 in data/validation/cats\n- put the dogs pictures index 12500-13499 in data/train/dogs\n- put the dog pictures index 13500-13900 in data/validation/dogs\nSo that we have 1000 training examples for each class, and 400 validation examples for each class.\nIn summary, this is our directory structure:\n```\ndata/\n train/\n dogs/\n dog001.jpg\n dog002.jpg\n ...\n cats/\n cat001.jpg\n cat002.jpg\n ...\n validation/\n dogs/\n dog001.jpg\n dog002.jpg\n ...\n cats/\n cat001.jpg\n cat002.jpg\n ...\n```\n'''\nimport numpy as np\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Dropout, Flatten, Dense\nfrom keras import applications\n\n# dimensions of our images.\nimg_width, img_height = 150, 150\n\ntop_model_weights_path = 'bottleneck_fc_model.h5'\ntrain_data_dir = 'data/train'\nvalidation_data_dir = 'data/validation'\nnb_train_samples = 2000\nnb_validation_samples = 800\nepochs = 50\nbatch_size = 16\n\n\ndef save_bottlebeck_features():\n datagen = ImageDataGenerator(rescale=1. / 255)\n\n # build the VGG16 network\n model = applications.VGG16(include_top=False, weights='imagenet')\n\n generator = datagen.flow_from_directory(\n train_data_dir,\n target_size=(img_width, img_height),\n batch_size=batch_size,\n class_mode=None,\n shuffle=False)\n bottleneck_features_train = model.predict_generator(\n generator, nb_train_samples // batch_size)\n np.save(open('bottleneck_features_train.npy', 'w'),\n bottleneck_features_train)\n\n generator = datagen.flow_from_directory(\n validation_data_dir,\n target_size=(img_width, img_height),\n batch_size=batch_size,\n class_mode=None,\n shuffle=False)\n bottleneck_features_validation = model.predict_generator(\n generator, nb_validation_samples // batch_size)\n np.save(open('bottleneck_features_validation.npy', 'w'),\n bottleneck_features_validation)\n\n\ndef train_top_model():\n train_data = np.load(open('bottleneck_features_train.npy'))\n train_labels = np.array(\n [0] * (nb_train_samples / 2) + [1] * (nb_train_samples / 2))\n\n validation_data = np.load(open('bottleneck_features_validation.npy'))\n validation_labels = np.array(\n [0] * (nb_validation_samples / 2) + [1] * (nb_validation_samples / 2))\n\n model = Sequential()\n model.add(Flatten(input_shape=train_data.shape[1:]))\n model.add(Dense(256, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(1, activation='sigmoid'))\n\n model.compile(optimizer='rmsprop',\n loss='binary_crossentropy', metrics=['accuracy'])\n\n model.fit(train_data, train_labels,\n epochs=epochs,\n batch_size=batch_size,\n validation_data=(validation_data, validation_labels))\n model.save_weights(top_model_weights_path)\n\n\nsave_bottlebeck_features()\ntrain_top_model()"
] |
[
[
"numpy.array"
]
] |
vbsteja/code
|
[
"0c8f4dc579f5de21b6c55fe6e65c3c8eb5473687"
] |
[
"Python/ML_DL/ML/tensorflow_examples.py"
] |
[
"#first program in tensorflow\n\nimport numpy as np\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\n\n# Model parameters\nW = tf.Variable([.3], tf.float32)\nb = tf.Variable([-.3], tf.float32)\n\n# Model input and output\nx = tf.placeholder(tf.float32)\nlinear_model = W * x + b\ny = tf.placeholder(tf.float32)\n\n# loss\nloss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares\n\n# optimizer\noptimizer = tf.train.GradientDescentOptimizer(0.01)\ntrain = optimizer.minimize(loss)\n\n# training data\nx_train = [1,2,3,4]\ny_train = [0,-1,-2,-3]\n\n# training loop\ninit = tf.global_variables_initializer()\nsess = tf.Session()\nsess.run(init) # reset values to wrong\n\nfor i in range(1000):\n sess.run(train, {x:x_train, y:y_train})\n\n# evaluate training accuracy\ncurr_W, curr_b, curr_loss = sess.run([W, b, loss], {x:x_train, y:y_train})\nprint(\"W: %s b: %s loss: %s\"%(curr_W, curr_b, curr_loss))\n"
] |
[
[
"tensorflow.Variable",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.Session",
"tensorflow.square"
]
] |
EtienneDavid/FROST
|
[
"1cea124d69f07e3ac7e3ad074059d29c0849254c"
] |
[
"TF-FROST/boss.py"
] |
[
"# Copyright 2019 Google LLC\n# Modified 2020 by authors of BOSS paper\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.\nimport functools\nimport os\nimport math\nimport sys\n\nimport numpy as np\nimport tensorflow as tf\nfrom absl import app\nfrom absl import flags\nfrom tqdm import trange\n\nfrom cta_boss.cta_remixmatch import CTAReMixMatch\nfrom libml import data, utils, augment, ctaugment\n\nFLAGS = flags.FLAGS\n\n\nclass AugmentPoolCTACutOut(augment.AugmentPoolCTA):\n @staticmethod\n def numpy_apply_policies(arglist):\n x, cta, probe = arglist\n if x.ndim == 3:\n assert probe\n policy = cta.policy(probe=True)\n return dict(policy=policy,\n probe=ctaugment.apply(x, policy),\n image=x)\n assert not probe\n cutout_policy = lambda: cta.policy(probe=False) + [ctaugment.OP('cutout', (1,))]\n return dict(image=np.stack([x[0]] + [ctaugment.apply(y, cutout_policy()) for y in x[1:]]).astype('f'))\n\n\nclass Boss(CTAReMixMatch):\n AUGMENT_POOL_CLASS = AugmentPoolCTACutOut\n\n def train(self, train_nimg, report_nimg):\n if FLAGS.eval_ckpt:\n self.eval_checkpoint(FLAGS.eval_ckpt)\n return\n batch = FLAGS.batch\n train_labeled = self.dataset.train_labeled.repeat().shuffle(FLAGS.shuffle).parse().augment()\n train_labeled = train_labeled.batch(batch).prefetch(16).make_one_shot_iterator().get_next()\n train_unlabeled = self.dataset.train_unlabeled.repeat().shuffle(FLAGS.shuffle).parse().augment()\n train_unlabeled = train_unlabeled.batch(batch * self.params['uratio']).prefetch(16)\n train_unlabeled = train_unlabeled.make_one_shot_iterator().get_next()\n train_original = self.dataset.train_original.repeat().shuffle(False).parse().augment()\n train_original = train_original.batch(50000).prefetch(16).make_one_shot_iterator().get_next()\n scaffold = tf.train.Scaffold(saver=tf.train.Saver(max_to_keep=FLAGS.keep_ckpt,\n pad_step_number=10))\n\n with tf.Session(config=utils.get_config()) as sess:\n self.session = sess\n self.cache_eval()\n\n with tf.train.MonitoredTrainingSession(\n scaffold=scaffold,\n checkpoint_dir=self.checkpoint_dir,\n config=utils.get_config(),\n save_checkpoint_steps=FLAGS.save_kimg << 10,\n save_summaries_steps=report_nimg - batch) as train_session:\n self.session = train_session._tf_sess()\n gen_labeled = self.gen_labeled_fn(train_labeled)\n gen_unlabeled = self.gen_unlabeled_fn(train_unlabeled)\n self.tmp.step = self.session.run(self.step)\n while self.tmp.step < train_nimg:\n loop = trange(self.tmp.step % report_nimg, report_nimg, batch,\n leave=False, unit='img', unit_scale=batch,\n desc='Epoch %d/%d' % (1 + (self.tmp.step // report_nimg), train_nimg // report_nimg))\n for _ in loop:\n self.train_step(train_session, gen_labeled, gen_unlabeled)\n while self.tmp.print_queue:\n loop.write(self.tmp.print_queue.pop(0))\n while self.tmp.print_queue:\n print(self.tmp.print_queue.pop(0))\n\n def model(self, batch, lr, wd, wu, mom, delT, confidence, balance, uratio, ema=0.999, **kwargs):\n hwc = [self.dataset.height, self.dataset.width, self.dataset.colors]\n\n xt_in = tf.placeholder(tf.float32, [batch] + hwc, 'xt') # Training labeled\n x_in = tf.placeholder(tf.float32, [None] + hwc, 'x') # Eval images\n y_in = tf.placeholder(tf.float32, [batch * uratio, 2] + hwc, 'y') # Training unlabeled (weak, strong)\n l_in = tf.placeholder(tf.int32, [batch], 'labels') # Labels\n\n lrate = tf.clip_by_value(tf.to_float(self.step) / (FLAGS.train_kimg << 10), 0, 1)\n lr *= tf.cos(lrate * (7 * np.pi) / (2 * 8))\n tf.summary.scalar('monitors/lr', lr)\n\n # Compute logits for xt_in and y_in\n classifier = lambda x, **kw: self.classifier(x, **kw, **kwargs).logits\n skip_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n x = utils.interleave(tf.concat([xt_in, y_in[:, 0], y_in[:, 1]], 0), 2 * uratio + 1)\n logits = utils.para_cat(lambda x: classifier(x, training=True), x)\n logits = utils.de_interleave(logits, 2 * uratio+1)\n post_ops = [v for v in tf.get_collection(tf.GraphKeys.UPDATE_OPS) if v not in skip_ops]\n logits_x = logits[:batch]\n logits_weak, logits_strong = tf.split(logits[batch:], 2)\n del logits, skip_ops\n\n # Labeled cross-entropy\n loss_xe = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=l_in, logits=logits_x)\n loss_xe = tf.reduce_mean(loss_xe)\n tf.summary.scalar('losses/xe', loss_xe)\n\n # Pseudo-label cross entropy for unlabeled data\n pseudo_labels = tf.stop_gradient(tf.nn.softmax(logits_weak))\n pLabels = tf.math.argmax(pseudo_labels, axis=1)\n loss_xeu = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=pLabels, logits=logits_strong)\n####################### Modification\n pLabels = tf.cast(pLabels,dtype=tf.float32)\n classes, idx, counts = tf.unique_with_counts(pLabels)\n shape = tf.constant([self.dataset.nclass])\n classes = tf.cast(classes,dtype=tf.int32)\n class_count = tf.scatter_nd(tf.reshape(classes,[tf.size(classes),1]),counts, shape)\n print_cc = tf.print(\"class_count \", class_count, output_stream=sys.stdout)\n class_count = tf.cast(class_count,dtype=tf.float32)\n mxCount = tf.reduce_max(class_count, axis=0)\n\n if balance > 0:\n pLabels = tf.cast(pLabels,dtype=tf.int32)\n if balance == 1 or balance == 4:\n confidences = tf.zeros_like(pLabels,dtype=tf.float32)\n ratios = 1.0 - tf.math.divide_no_nan(class_count, mxCount)\n ratios = confidence - delT*ratios\n confidences = tf.gather_nd(ratios, tf.reshape(pLabels,[tf.size(pLabels),1]) )\n pseudo_mask = tf.reduce_max(pseudo_labels, axis=1) >= confidences\n else:\n pseudo_mask = tf.reduce_max(pseudo_labels, axis=1) >= confidence\n\n if balance == 3 or balance == 4:\n classes, idx, counts = tf.unique_with_counts(tf.boolean_mask(pLabels,pseudo_mask))\n shape = tf.constant([self.dataset.nclass])\n classes = tf.cast(classes,dtype=tf.int32)\n class_count = tf.scatter_nd(tf.reshape(classes,[tf.size(classes),1]),counts, shape)\n class_count = tf.cast(class_count,dtype=tf.float32)\n pseudo_mask = tf.cast(pseudo_mask,dtype=tf.float32)\n\n if balance > 1:\n ratios = tf.math.divide_no_nan(tf.ones_like(class_count,dtype=tf.float32),class_count)\n ratio = tf.gather_nd(ratios, tf.reshape(pLabels,[tf.size(pLabels),1]) )\n # ratio = sum(pseudo_mask) * ratio / sum(ratio)\n Z = tf.reduce_sum(pseudo_mask)\n pseudo_mask = tf.math.multiply(pseudo_mask, tf.cast(ratio,dtype=tf.float32))\n pseudo_mask = tf.math.divide_no_nan(tf.scalar_mul(Z, pseudo_mask), tf.reduce_sum(pseudo_mask))\n else:\n pseudo_mask = tf.cast(tf.reduce_max(pseudo_labels, axis=1) >= confidence,dtype=tf.float32)\n###################### End\n\n \n# tf.print(\" class_count= \",class_count)\n tf.summary.scalar('monitors/mask', tf.reduce_mean(pseudo_mask))\n loss_xeu = tf.reduce_mean(loss_xeu * pseudo_mask)\n tf.summary.scalar('losses/xeu', loss_xeu)\n\n # L2 regularization\n loss_wd = sum(tf.nn.l2_loss(v) for v in utils.model_vars('classify') if 'kernel' in v.name)\n tf.summary.scalar('losses/wd', loss_wd)\n\n ema = tf.train.ExponentialMovingAverage(decay=ema)\n ema_op = ema.apply(utils.model_vars())\n ema_getter = functools.partial(utils.getter_ema, ema)\n post_ops.append(ema_op)\n\n# train_op = tf.train.MomentumOptimizer(lr, 0.9, use_nesterov=True).minimize(\n train_op = tf.train.MomentumOptimizer(lr, mom, use_nesterov=True).minimize(\n loss_xe + wu * loss_xeu + wd * loss_wd, colocate_gradients_with_ops=True)\n with tf.control_dependencies([train_op]):\n train_op = tf.group(*post_ops)\n\n return utils.EasyDict(\n xt=xt_in, x=x_in, y=y_in, label=l_in, train_op=train_op,\n classify_raw=tf.nn.softmax(classifier(x_in, training=False)), # No EMA, for debugging.\n classify_op=tf.nn.softmax(classifier(x_in, getter=ema_getter, training=False)))\n\n\ndef main(argv):\n utils.setup_main()\n del argv # Unused.\n dataset = data.PAIR_DATASETS()[FLAGS.dataset]()\n log_width = utils.ilog2(dataset.width)\n model = Boss(\n os.path.join(FLAGS.train_dir, dataset.name, FixMatch.cta_name()),\n dataset,\n lr=FLAGS.lr,\n wd=FLAGS.wd,\n arch=FLAGS.arch,\n batch=FLAGS.batch,\n nclass=dataset.nclass,\n wu=FLAGS.wu,\n mom=FLAGS.mom,\n delT=FLAGS.delT,\n confidence=FLAGS.confidence,\n balance=FLAGS.balance,\n uratio=FLAGS.uratio,\n scales=FLAGS.scales or (log_width - 2),\n filters=FLAGS.filters,\n repeat=FLAGS.repeat)\n model.train(FLAGS.train_kimg << 10, FLAGS.report_kimg << 10)\n\n\nif __name__ == '__main__':\n utils.setup_tf()\n flags.DEFINE_float('confidence', 0.95, 'Confidence threshold.')\n flags.DEFINE_float('wd', 0.0005, 'Weight decay.')\n flags.DEFINE_float('wu', 1, 'Pseudo label loss weight.')\n flags.DEFINE_float('mom', 0.9, 'Momentum coefficient.')\n flags.DEFINE_float('delT', 0.2, 'The amount balance=1 can reduce the confidence threshold.')\n flags.DEFINE_integer('filters', 32, 'Filter size of convolutions.')\n flags.DEFINE_integer('repeat', 4, 'Number of residual layers per stage.')\n flags.DEFINE_integer('scales', 0, 'Number of 2x2 downscalings in the classifier.')\n flags.DEFINE_integer('uratio', 7, 'Unlabeled batch size ratio.')\n flags.DEFINE_integer('balance', 0, 'Method to help balance classes')\n FLAGS.set_default('augment', 'd.d.d')\n FLAGS.set_default('dataset', 'cifar10.3@250-1')\n FLAGS.set_default('batch', 64)\n FLAGS.set_default('lr', 0.03)\n FLAGS.set_default('train_kimg', 1 << 16)\n app.run(main)\n"
] |
[
[
"tensorflow.concat",
"tensorflow.control_dependencies",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.train.ExponentialMovingAverage",
"tensorflow.nn.l2_loss",
"tensorflow.group",
"tensorflow.summary.scalar",
"tensorflow.math.argmax",
"tensorflow.boolean_mask",
"tensorflow.get_collection",
"tensorflow.train.MomentumOptimizer",
"tensorflow.unique_with_counts",
"tensorflow.to_float",
"tensorflow.train.Saver",
"tensorflow.math.divide_no_nan",
"tensorflow.scalar_mul",
"tensorflow.placeholder",
"tensorflow.zeros_like",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"tensorflow.print",
"tensorflow.split",
"tensorflow.size",
"tensorflow.reduce_max",
"tensorflow.nn.softmax",
"tensorflow.cos",
"tensorflow.constant",
"tensorflow.reduce_mean",
"tensorflow.ones_like"
]
] |
omri123/rotational-unit-of-memory
|
[
"e796c841e1e837df09497ba77c3bc285db47d02d",
"e796c841e1e837df09497ba77c3bc285db47d02d"
] |
[
"tasks/LM/ptb_iterator.py",
"tasks/summarization/decode.py"
] |
[
"# Copyright 2015 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\n\n\"\"\"Utilities for parsing PTB text files.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport os\n\nimport numpy as np\nimport tensorflow as tf\n\n\ndef _read_words(filename):\n with tf.gfile.GFile(filename, \"r\") as f:\n return f.read().replace(\"\\n\", \"<eos>\").split()\n\n\ndef _build_vocab(filename):\n data = _read_words(filename)\n\n counter = collections.Counter(data)\n count_pairs = sorted(counter.items(), key=lambda x: (-x[1], x[0]))\n\n words, _ = list(zip(*count_pairs))\n word_to_id = dict(zip(words, range(len(words))))\n\n return word_to_id\n\n\ndef _file_to_word_ids(filename, word_to_id):\n data = _read_words(filename)\n return [word_to_id[word] for word in data]\n\n\ndef ptb_raw_data(data_path=None):\n \"\"\"Load PTB raw data from data directory \"data_path\".\n Reads PTB text files, converts strings to integer ids,\n and performs mini-batching of the inputs.\n The PTB dataset comes from Tomas Mikolov's webpage:\n http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz\n Args:\n data_path: string path to the directory where simple-examples.tgz has\n been extracted.\n Returns:\n tuple (train_data, valid_data, test_data, vocabulary)\n where each of the data objects can be passed to PTBIterator.\n \"\"\"\n\n train_path = os.path.join(data_path, \"ptb.train.txt\")\n valid_path = os.path.join(data_path, \"ptb.valid.txt\")\n test_path = os.path.join(data_path, \"ptb.test.txt\")\n\n word_to_id = _build_vocab(train_path)\n train_data = _file_to_word_ids(train_path, word_to_id)\n valid_data = _file_to_word_ids(valid_path, word_to_id)\n test_data = _file_to_word_ids(test_path, word_to_id)\n vocabulary = len(word_to_id)\n return train_data, valid_data, test_data, vocabulary\n\n\ndef ptb_iterator(raw_data, batch_size, num_steps):\n \"\"\"Iterate on the raw PTB data.\n This generates batch_size pointers into the raw PTB data, and allows\n minibatch iteration along these pointers.\n Args:\n raw_data: one of the raw data outputs from ptb_raw_data.\n batch_size: int, the batch size.\n num_steps: int, the number of unrolls.\n Yields:\n Pairs of the batched data, each a matrix of shape [batch_size, num_steps].\n The second element of the tuple is the same data time-shifted to the\n right by one.\n Raises:\n ValueError: if batch_size or num_steps are too high.\n \"\"\"\n raw_data = np.array(raw_data, dtype=np.int32)\n\n data_len = len(raw_data)\n batch_len = data_len // batch_size\n data = np.zeros([batch_size, batch_len], dtype=np.int32)\n for i in range(batch_size):\n data[i] = raw_data[batch_len * i:batch_len * (i + 1)]\n\n epoch_size = (batch_len - 1) // num_steps\n\n if epoch_size == 0:\n raise ValueError(\"epoch_size == 0, decrease batch_size or num_steps\")\n\n for i in range(epoch_size):\n x = data[:, i * num_steps:(i + 1) * num_steps]\n y = data[:, i * num_steps + 1:(i + 1) * num_steps + 1]\n yield (x, y)\n",
"\n\"\"\"This file contains code to run beam search decoding, including running ROUGE evaluation and producing JSON datafiles for the in-browser attention visualizer, which can be found here https://github.com/abisee/attn_vis\"\"\"\n\nimport os\nimport time\nimport tensorflow as tf\nimport beam_search\nimport data\nimport json\nimport pyrouge\nimport util\nimport logging\nimport time\nfrom utils import *\n\nFLAGS = tf.flags.FLAGS\n\nSECS_UNTIL_NEW_CKPT = 60 # max number of seconds before loading new checkpoint\n\n\nclass BeamSearchDecoder(object):\n \"\"\"Beam search decoder.\"\"\"\n\n def __init__(self, model, batcher, vocab, is_sd):\n \"\"\"Initialize decoder.\n\n Args:\n model: a Seq2SeqAttentionModel object.\n batcher: a Batcher object.\n vocab: Vocabulary object\n \"\"\"\n self._model = model\n self._model.build_graph()\n self._batcher = batcher\n self._vocab = vocab\n self._saver = tf.train.Saver() # we use this to load checkpoints for decoding\n self._sess = tf.Session(config=util.get_config())\n self._is_sd = is_sd\n\n # Load an initial checkpoint to use for decoding\n ckpt_path = util.load_ckpt(self._saver, self._sess)\n\n if FLAGS.single_pass:\n # Make a descriptive decode directory name\n # this is something of the form \"ckpt-123456\"\n ckpt_name = \"ckpt-\" + ckpt_path.split('-')[-1]\n if FLAGS.coverage:\n self._decode_dir = os.path.join(\n FLAGS.log_root, \"coverage_v4_\" + get_decode_dir_name(ckpt_name))\n else:\n self._decode_dir = os.path.join(\n FLAGS.log_root, get_decode_dir_name(ckpt_name))\n # if os.path.exists(self._decode_dir):\n # raise Exception(\"single_pass decode directory %s should not already exist\" % self._decode_dir)\n\n else: # Generic decode dir name\n self._decode_dir = os.path.join(FLAGS.log_root, \"decode\")\n\n # Make the decode dir if necessary\n if not os.path.exists(self._decode_dir):\n os.mkdir(self._decode_dir)\n\n if FLAGS.single_pass:\n # Make the dirs to contain output written in the correct format for\n # pyrouge\n self._rouge_ref_dir = os.path.join(self._decode_dir, \"reference\")\n if not os.path.exists(self._rouge_ref_dir):\n os.mkdir(self._rouge_ref_dir)\n self._rouge_dec_dir = os.path.join(self._decode_dir, \"decoded\")\n if not os.path.exists(self._rouge_dec_dir):\n os.mkdir(self._rouge_dec_dir)\n\n def decode(self):\n \"\"\"Decode examples until data is exhausted (if FLAGS.single_pass) and return, or decode indefinitely, loading latest checkpoint at regular intervals\"\"\"\n t0 = time.time()\n counter = 0\n while True:\n batch = self._batcher.next_batch() # 1 example repeated across batch\n if batch is None: # finished decoding dataset in single_pass mode\n assert FLAGS.single_pass, \"Dataset exhausted, but we are not in single_pass mode\"\n tf.logging.info(\n \"Decoder has finished reading dataset for single_pass.\")\n tf.logging.info(\"Output has been saved in %s and %s. Now starting ROUGE eval...\",\n self._rouge_ref_dir, self._rouge_dec_dir)\n results_dict = rouge_eval(\n self._rouge_ref_dir, self._rouge_dec_dir)\n rouge_log(results_dict, self._decode_dir)\n return\n\n original_article = batch.original_articles[0] # string\n original_abstract = batch.original_abstracts[0] # string\n original_abstract_sents = batch.original_abstracts_sents[\n 0] # list of strings\n\n article_withunks = data.Vocab.show_art_oovs(\n original_article, self._vocab) # string\n abstract_withunks = data.Vocab.show_abs_oovs(original_abstract, self._vocab, (batch.art_oovs[\n 0] if FLAGS.pointer_gen else None)) # string\n\n # Run beam search to get best Hypothesis\n best_hyp = beam_search.run_beam_search(\n self._sess, self._model, self._vocab, batch)\n\n # Extract the output ids from the hypothesis and convert back to\n # words\n output_ids = [int(t) for t in best_hyp.tokens[1:]]\n decoded_words = data.Vocab.outputids2words(\n output_ids, self._vocab, (batch.art_oovs[0] if FLAGS.pointer_gen else None))\n\n # Remove the [STOP] token from decoded_words, if necessary\n try:\n # index of the (first) [STOP] symbol\n fst_stop_idx = decoded_words.index(data.STOP_DECODING)\n decoded_words = decoded_words[:fst_stop_idx]\n except ValueError:\n decoded_words = decoded_words\n decoded_output = ' '.join(decoded_words) # single string\n\n if FLAGS.single_pass:\n # print_results(article_withunks, abstract_withunks, decoded_output, counter)\n # write ref summary and decoded summary to file, to eval with\n # pyrouge later\n self.write_for_rouge(\n original_abstract_sents, decoded_words, counter)\n counter += 1 # this is how many examples we've decoded\n else:\n print_results(article_withunks, abstract_withunks,\n decoded_output, counter) # log output to screen\n # write info to .json file for visualization tool\n self.write_for_attnvis(\n article_withunks, abstract_withunks, decoded_words, best_hyp.attn_dists, best_hyp.p_gens)\n\n # Check if SECS_UNTIL_NEW_CKPT has elapsed; if so return so we\n # can load a new checkpoint\n t1 = time.time()\n if t1 - t0 > SECS_UNTIL_NEW_CKPT:\n tf.logging.info(\n 'We\\'ve been decoding with same checkpoint for %i seconds. Time to load new checkpoint', t1 - t0)\n _ = util.load_ckpt(self._saver, self._sess)\n t0 = time.time()\n\n def write_for_rouge(self, reference_sents, decoded_words, ex_index):\n \"\"\"Write output to file in correct format for eval with pyrouge. This is called in single_pass mode.\n\n Args:\n reference_sents: list of strings\n decoded_words: list of strings\n ex_index: int, the index with which to label the files\n \"\"\"\n # First, divide decoded output into sentences\n decoded_sents = []\n while len(decoded_words) > 0:\n try:\n fst_period_idx = decoded_words.index(\".\")\n except ValueError: # there is text remaining that doesn't end in \".\"\n fst_period_idx = len(decoded_words)\n # sentence up to and including the period\n sent = decoded_words[:fst_period_idx + 1]\n decoded_words = decoded_words[\n fst_period_idx + 1:] # everything else\n decoded_sents.append(' '.join(sent))\n\n # pyrouge calls a perl script that puts the data into HTML files.\n # Therefore we need to make our output HTML safe.\n decoded_sents = [make_html_safe(w) for w in decoded_sents]\n reference_sents = [make_html_safe(w) for w in reference_sents]\n\n # Write to file\n ref_file = os.path.join(self._rouge_ref_dir,\n \"%06d_reference.txt\" % ex_index)\n decoded_file = os.path.join(\n self._rouge_dec_dir, \"%06d_decoded.txt\" % ex_index)\n\n if self._is_sd:\n with open(ref_file, \"w\") as f:\n f.write(''.join(reference_sents))\n else:\n with open(ref_file, \"w\") as f:\n for idx, sent in enumerate(reference_sents):\n f.write(sent) if idx == len(reference_sents) - \\\n 1 else f.write(sent + \"\\n\")\n\n with open(decoded_file, \"w\") as f:\n for idx, sent in enumerate(decoded_sents):\n f.write(sent) if idx == len(decoded_sents) - \\\n 1 else f.write(sent + \"\\n\")\n\n tf.logging.info(\"Wrote example %i to file\" % ex_index)\n\n def write_for_attnvis(self, article, abstract, decoded_words, attn_dists, p_gens):\n \"\"\"Write some data to json file, which can be read into the in-browser attention visualizer tool:\n https://github.com/abisee/attn_vis\n\n Args:\n article: The original article string.\n abstract: The human (correct) abstract string.\n attn_dists: List of arrays; the attention distributions.\n decoded_words: List of strings; the words of the generated summary.\n p_gens: List of scalars; the p_gen values. If not running in pointer-generator mode, list of None.\n \"\"\"\n article_lst = article.split() # list of words\n decoded_lst = decoded_words # list of decoded words\n to_write = {\n 'article_lst': [make_html_safe(t) for t in article_lst],\n 'decoded_lst': [make_html_safe(t) for t in decoded_lst],\n 'abstract_str': make_html_safe(abstract),\n 'attn_dists': attn_dists\n }\n if FLAGS.pointer_gen:\n to_write['p_gens'] = p_gens\n output_fname = os.path.join(self._decode_dir, 'attn_vis_data.json')\n with open(output_fname, 'w') as output_file:\n json.dump(to_write, output_file)\n tf.logging.info('Wrote visualization data to %s', output_fname)\n\n\ndef print_results(article, abstract, decoded_output, counter):\n \"\"\"Prints the article, the reference summmary and the decoded summary to screen\"\"\"\n print(\"---------------------------------------------------------------------------\")\n #tf.logging.info('ARTICLE: %s', article)\n #tf.logging.info('REFERENCE SUMMARY: %s', abstract)\n #tf.logging.info('GENERATED SUMMARY: %s', decoded_output)\n print(col(\"#: \" + str(counter) + \"\\t BEAM SIZE: \" +\n str(FLAGS.beam_size) + \"\\t MAX. LENGTH: \" + str(FLAGS.max_dec_steps), 'b'))\n print(col(\"ARTICLE: \" + article, 'r'))\n print(col(\"REFERENCE SUMMARY: \" + abstract, 'g'))\n print(col(\"GENERATED SUMMARY: \" + decoded_output, 'y'))\n time.sleep(1)\n print(\"---------------------------------------------------------------------------\")\n\n\ndef make_html_safe(s):\n \"\"\"Replace any angled brackets in string s to avoid interfering with HTML attention visualizer.\"\"\"\n s.replace(\"<\", \"<\")\n s.replace(\">\", \">\")\n return s\n\n\ndef rouge_eval(ref_dir, dec_dir):\n \"\"\"Evaluate the files in ref_dir and dec_dir with pyrouge, returning results_dict\"\"\"\n r = pyrouge.Rouge155()\n r.model_filename_pattern = '#ID#_reference.txt'\n r.system_filename_pattern = '(\\d+)_decoded.txt'\n r.model_dir = ref_dir\n r.system_dir = dec_dir\n logging.getLogger('global').setLevel(\n logging.WARNING) # silence pyrouge logging\n rouge_results = r.convert_and_evaluate()\n return r.output_to_dict(rouge_results)\n\n\ndef rouge_log(results_dict, dir_to_write):\n \"\"\"Log ROUGE results to screen and write to file.\n\n Args:\n results_dict: the dictionary returned by pyrouge\n dir_to_write: the directory where we will write the results to\"\"\"\n log_str = \"\"\n for x in [\"1\", \"2\", \"l\"]:\n log_str += \"\\nROUGE-%s:\\n\" % x\n for y in [\"f_score\", \"recall\", \"precision\"]:\n key = \"rouge_%s_%s\" % (x, y)\n key_cb = key + \"_cb\"\n key_ce = key + \"_ce\"\n val = results_dict[key]\n val_cb = results_dict[key_cb]\n val_ce = results_dict[key_ce]\n log_str += \"%s: %.4f with confidence interval (%.4f, %.4f)\\n\" % (\n key, val, val_cb, val_ce)\n tf.logging.info(log_str) # log to screen\n results_file = os.path.join(dir_to_write, \"ROUGE_results.txt\")\n tf.logging.info(\"Writing final ROUGE results to %s...\", results_file)\n with open(results_file, \"w\") as f:\n f.write(log_str)\n\n\ndef get_decode_dir_name(ckpt_name):\n \"\"\"Make a descriptive name for the decode dir, including the name of the checkpoint we use to decode. This is called in single_pass mode.\"\"\"\n\n if \"train\" in FLAGS.data_path:\n dataset = \"train\"\n elif \"val\" in FLAGS.data_path:\n dataset = \"val\"\n elif \"test\" in FLAGS.data_path:\n dataset = \"test\"\n else:\n raise ValueError(\n \"FLAGS.data_path %s should contain one of train, val or test\" % (FLAGS.data_path))\n dirname = \"decode_%s_%imaxenc_%ibeam_%imindec_%imaxdec\" % (\n dataset, FLAGS.max_enc_steps, FLAGS.beam_size, FLAGS.min_dec_steps, FLAGS.max_dec_steps)\n if ckpt_name is not None:\n dirname += \"_%s\" % ckpt_name\n return dirname\n"
] |
[
[
"tensorflow.gfile.GFile",
"numpy.array",
"numpy.zeros"
],
[
"tensorflow.train.Saver",
"tensorflow.logging.info"
]
] |
astrojose9/fulmar
|
[
"62a79fb9b7ab01e5b7b3acadaca8e4f0db0e0e2f"
] |
[
"fulmar/estimators.py"
] |
[
"import astropy.units as u\nimport numpy as np\n\nimport warnings\nfrom fulmar.utils import (\n FulmarWarning\n)\n\n\ndef estimate_planet_mass(\n R_p,\n rho_p):\n \"\"\"\n Estimates the mass of an exoplanet from its radius and density.\n\n Parameters\n ----------\n R_p : `~astropy.units.Quantity` or float\n Radius of the exolanet. (defaults to units of Earth radii)\n rho_p : `~astropy.units.Quantity`, float or str\n Density of the exoplanet in kg * m^-3. Can be \"Earth\" or \"Neptune\".\n\n Returns\n -------\n M_planet : `~astropy.units.Quantity`\n Estimated mass of the exoplanet.\n \"\"\"\n dens_dic = {'earth': 5514 * (u.kg / u.m**3),\n 'neptune': 1638 * (u.kg / u.m**3)}\n\n if isinstance(R_p, (int, float)):\n R_p = R_p * u.earthRad\n\n elif isinstance(R_p, u.Quantity):\n R_p = R_p.to(u.earthRad)\n\n else:\n raise TypeError('R_p should be `astropy.units.Quantity` or float')\n\n if isinstance(rho_p, (int, float)):\n rho_p = rho_p * (u.kg / u.m**3)\n\n elif isinstance(rho_p, str):\n if rho_p.lower() in dens_dic.keys():\n rho_p = dens_dic[rho_p.lower()]\n else:\n raise ValueError(\n 'Accepted str values for rho_p are \"Earth\" and \"Neptune\".')\n else:\n raise TypeError(\n 'rho_p should be `astropy.units.Quantity`, float or str.')\n\n M_planet = (R_p.value ** 3 * rho_p / dens_dic['earth']) * u.earthMass\n return M_planet\n\n\ndef estimate_semi_amplitude(\n period,\n M_star,\n M_planet=None,\n R_planet=None,\n rho_planet=None,\n inc=90 * u.deg,\n ecc=0):\n \"\"\"\n Estimates the radial velocity semi-amplitude corresponding to a planet of\n given parameters.\n\n Parameters\n ----------\n period : `~astropy.units.Quantity` or float\n The period to use for folding. (defaults to units of days)\n M_star : `~astropy.units.Quantity` or float\n Stellar mass (defaults to units of solar masses)\n M_planet : `~astropy.units.Quantity` or float\n Mass of the exolanet. (defaults to units of Earth masses)\n R_planet : `~astropy.units.Quantity` or float\n Radius of the exolanet. (defaults to units of Earth radii)\n rho_planet : `~astropy.units.Quantity`, float or str\n Density of the exoplanet in kg * m^-3. Can be \"Earth\" or \"Neptune\".\n inc : `~astropy.units.Quantity` or float\n Orbital inclination (in degrees). Default: 90.\n ecc : float\n Orbital eccentricity. Default: 0.\n\n Returns\n -------\n K : `~astropy.units.Quantity`\n Estimated semi-amplitude of the RV.\n \"\"\"\n if isinstance(period, (int, float)):\n period = period * u.d\n elif not isinstance(period, u.Quantity):\n raise TypeError(\n 'period shoud be `astropy.units.Quantity` or float')\n\n if isinstance(M_star, (int, float)):\n M_star = M_star * u.solMass\n elif not isinstance(M_star, u.Quantity):\n raise TypeError(\n 'M_star shoud be `astropy.units.Quantity` or float')\n\n if isinstance(inc, (int, float)):\n inc = inc * u.deg\n elif not isinstance(inc, u.Quantity):\n raise TypeError(\n 'inc shoud be `astropy.units.Quantity` or float')\n\n if M_planet is None:\n\n if R_planet is None or rho_planet is None:\n raise ValueError('R_planet and rho_planet are both required '\n 'when M_planet is not given')\n else:\n M_planet = estimate_planet_mass(R_planet, rho_planet)\n else:\n if R_planet is not None or rho_planet is not None:\n warnings.warn(\n 'M_planet overrides R_planet and rho_planet', FulmarWarning)\n\n if isinstance(M_planet, (int, float)):\n M_planet = M_planet * u.earthMass\n\n elif not isinstance(M_planet, u.Quantity):\n raise TypeError(\n 'M_planet should be `astropy.units.Quantity` or float')\n\n inc = inc.to(u.deg)\n\n M_p_jovian = M_planet.to(u.jupiterMass).value\n M_tot_solar = (M_star + M_planet).to(u.solMass).value\n\n # Equation (14) from Lovis & Fischer 2010\n K = 28.4329 * (u.m / u.s) * \\\n M_p_jovian * \\\n np.sin(inc) * np.power(M_tot_solar, -2 / 3) * \\\n np.power(period.to(u.year).value, -1 / 3) / np.sqrt(1 - ecc)\n\n return K\n"
] |
[
[
"numpy.sin",
"numpy.sqrt",
"numpy.power"
]
] |
Nuri-benbarka/PCDet
|
[
"8da66ead3bb1120db2fa919187948c8c134e85ae"
] |
[
"pcdet/utils/calibration.py"
] |
[
"import numpy as np\n\n\ndef get_calib_from_file(calib_file):\n with open(calib_file) as f:\n lines = f.readlines()\n\n obj = lines[2].strip().split(' ')[1:]\n P2 = np.array(obj, dtype=np.float32)\n obj = lines[3].strip().split(' ')[1:]\n P3 = np.array(obj, dtype=np.float32)\n obj = lines[4].strip().split(' ')[1:]\n R0 = np.array(obj, dtype=np.float32)\n obj = lines[5].strip().split(' ')[1:]\n Tr_velo_to_cam = np.array(obj, dtype=np.float32)\n\n return {'P2': P2.reshape(3, 4),\n 'P3': P3.reshape(3, 4),\n 'R0': R0.reshape(3, 3),\n 'Tr_velo2cam': Tr_velo_to_cam.reshape(3, 4)}\n\n\nclass Calibration(object):\n def __init__(self, calib_file):\n if isinstance(calib_file, str):\n calib = get_calib_from_file(calib_file)\n else:\n calib = calib_file\n\n self.P2 = calib['P2'] # 3 x 4\n self.R0 = calib['R0'] # 3 x 3\n self.V2C = calib['Tr_velo2cam'] # 3 x 4\n\n # Camera intrinsics and extrinsics\n self.cu = self.P2[0, 2]\n self.cv = self.P2[1, 2]\n self.fu = self.P2[0, 0]\n self.fv = self.P2[1, 1]\n self.tx = self.P2[0, 3] / (-self.fu)\n self.ty = self.P2[1, 3] / (-self.fv)\n\n def cart_to_hom(self, pts):\n \"\"\"\n :param pts: (N, 3 or 2)\n :return pts_hom: (N, 4 or 3)\n \"\"\"\n pts_hom = np.hstack((pts, np.ones((pts.shape[0], 1), dtype=np.float32)))\n return pts_hom\n\n def rect_to_lidar(self, pts_rect):\n \"\"\"\n :param pts_lidar: (N, 3)\n :return pts_rect: (N, 3)\n \"\"\"\n pts_rect_hom = self.cart_to_hom(pts_rect) # (N, 4)\n R0_ext = np.hstack((self.R0, np.zeros((3, 1), dtype=np.float32))) # (3, 4)\n R0_ext = np.vstack((R0_ext, np.zeros((1, 4), dtype=np.float32))) # (4, 4)\n R0_ext[3, 3] = 1\n V2C_ext = np.vstack((self.V2C, np.zeros((1, 4), dtype=np.float32))) # (4, 4)\n V2C_ext[3, 3] = 1\n\n pts_lidar = np.dot(pts_rect_hom, np.linalg.inv(np.dot(R0_ext, V2C_ext).T))\n return pts_lidar[:, 0:3]\n\n def lidar_to_rect(self, pts_lidar):\n \"\"\"\n :param pts_lidar: (N, 3)\n :return pts_rect: (N, 3)\n \"\"\"\n pts_lidar_hom = self.cart_to_hom(pts_lidar)\n pts_rect = np.dot(pts_lidar_hom, np.dot(self.V2C.T, self.R0.T))\n # pts_rect = reduce(np.dot, (pts_lidar_hom, self.V2C.T, self.R0.T))\n return pts_rect\n\n def rect_to_img(self, pts_rect):\n \"\"\"\n :param pts_rect: (N, 3)\n :return pts_img: (N, 2)\n \"\"\"\n pts_rect_hom = self.cart_to_hom(pts_rect)\n pts_2d_hom = np.dot(pts_rect_hom, self.P2.T)\n pts_img = (pts_2d_hom[:, 0:2].T / pts_rect_hom[:, 2]).T # (N, 2)\n pts_rect_depth = pts_2d_hom[:, 2] - self.P2.T[3, 2] # depth in rect camera coord\n return pts_img, pts_rect_depth\n\n def lidar_to_img(self, pts_lidar):\n \"\"\"\n :param pts_lidar: (N, 3)\n :return pts_img: (N, 2)\n \"\"\"\n pts_rect = self.lidar_to_rect(pts_lidar)\n pts_img, pts_depth = self.rect_to_img(pts_rect)\n return pts_img, pts_depth\n\n def img_to_rect(self, u, v, depth_rect):\n \"\"\"\n :param u: (N)\n :param v: (N)\n :param depth_rect: (N)\n :return:\n \"\"\"\n x = ((u - self.cu) * depth_rect) / self.fu + self.tx\n y = ((v - self.cv) * depth_rect) / self.fv + self.ty\n pts_rect = np.concatenate((x.reshape(-1, 1), y.reshape(-1, 1), depth_rect.reshape(-1, 1)), axis=1)\n return pts_rect\n\n def corners3d_to_img_boxes(self, corners3d):\n \"\"\"\n :param corners3d: (N, 8, 3) corners in rect coordinate\n :return: boxes: (None, 4) [x1, y1, x2, y2] in rgb coordinate\n :return: boxes_corner: (None, 8) [xi, yi] in rgb coordinate\n \"\"\"\n sample_num = corners3d.shape[0]\n corners3d_hom = np.concatenate((corners3d, np.ones((sample_num, 8, 1))), axis=2) # (N, 8, 4)\n\n img_pts = np.matmul(corners3d_hom, self.P2.T) # (N, 8, 3)\n\n x, y = img_pts[:, :, 0] / img_pts[:, :, 2], img_pts[:, :, 1] / img_pts[:, :, 2]\n x1, y1 = np.min(x, axis=1), np.min(y, axis=1)\n x2, y2 = np.max(x, axis=1), np.max(y, axis=1)\n\n boxes = np.concatenate((x1.reshape(-1, 1), y1.reshape(-1, 1), x2.reshape(-1, 1), y2.reshape(-1, 1)), axis=1)\n boxes_corner = np.concatenate((x.reshape(-1, 8, 1), y.reshape(-1, 8, 1)), axis=2)\n\n return boxes, boxes_corner\n"
] |
[
[
"numpy.dot",
"numpy.min",
"numpy.matmul",
"numpy.ones",
"numpy.max",
"numpy.array",
"numpy.zeros"
]
] |
tobinsouth/covid19-forecasting-aus
|
[
"c42f2cfe423eddc7ddeb95a85a3ccf189269b6b2"
] |
[
"model/EpyReff/run_estimator.py"
] |
[
"###\n# Run EpyReff on NNDSS data\n###\n\nprint('Running EpyReff on NNDSS data')\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nfrom epyreff import *\n\nfrom sys import argv\nfrom scipy.stats import gamma\n\n## parameters\ntau = 4\nprior_a=1\nprior_b=2\ntrunc_days = 21\n\nshape_inc = 5.807 #taken from Lauer et al. 2020 #1.62/0.418\nscale_inc= 0.948 #0.418\noffset_inc = 0\n\nshape_rd=1.82\nscale_rd=2.88\noffset_rd=0\n\nshape_gen=3.64/3.07\nscale_gen=3.07\noffset=0\nshift=0\n\ndate = argv[1]\ndt_date = pd.to_datetime(date, format=\"%Y-%m-%d\")\nfile_date = dt_date.strftime(\"%Y-%m-%d\")\ntry:\n plot_time = argv[2]\nexcept:\n plot_time = False\n# Read in the data\n\n##read in case file data\nprint(dt_date.strftime(\"%d%b%Y\"))\ndf_interim = read_cases_lambda(dt_date.strftime(\"%d%b%Y\"))\n\n##generate dataframe with id_vars date and state, variable SOURCE and number of cases\ndf_linel = tidy_cases_lambda(df_interim)\n\n##infer extra cases in last 10 days by the reporting delay distribution\n\n \n##generate possible infection dates from the notification data\ndf_inf = draw_inf_dates(df_linel, nreplicates=1000,\n shape_rd=shape_rd, scale_rd=scale_rd, offset_rd=offset_rd,\n shape_inc=shape_inc, scale_inc=scale_inc, offset_inc=offset_inc,\n )\n\n##reindex dataframe to include all dates, \n## return df with index (STATE, INFECTION_DATE, SOURCE), columns are samples\ndf_inc_zeros = index_by_infection_date(df_inf)\n\n\n#get all lambdas\nlambda_dict = lambda_all_states(df_inc_zeros,\n shape_gen=shape_gen,scale_gen=scale_gen,offset=offset, \n trunc_days=trunc_days)\n\n\n\nstates = [*df_inc_zeros.index.get_level_values('STATE').unique()]\nR_summary_states={}\ndates = {}\ndf= pd.DataFrame()\nfor state in states:\n lambda_state = lambda_dict[state]\n df_state_I = df_inc_zeros.xs((state,'local'),level=('STATE','SOURCE'))\n #get Reproduciton numbers\n a,b,R = Reff_from_case(df_state_I.values,lambda_state,prior_a=prior_a, prior_b=prior_b, tau=tau)\n\n #summarise for plots and file printing\n R_summary_states[state] = generate_summary(R)\n dates[state] = df_state_I.index.values[trunc_days-1+tau:]\n \n temp =pd.DataFrame.from_dict(R_summary_states[state])\n temp['INFECTION_DATES'] = dates[state]\n temp['STATE'] = state\n #temp.index =pd.MultiIndex.from_product(([state], dates[state]))\n df = df.append(temp, ignore_index=True)\n\n#make folder to record files\nos.makedirs(\"results/EpyReff/\", exist_ok=True)\n\n\n\nif plot_time:\n #plot assumed distributions\n inc_period = offset_inc+np.random.gamma(shape_inc, scale_inc, size = 1000)\n rep_delay = offset_rd+np.random.gamma(shape_rd, scale_rd, size = 1000)\n\n #generation interval discretised\n xmids = [x+shift for x in range(trunc_days+1)] #Find midpoints for discretisation\n gamma_vals = gamma.pdf(xmids, a=shape_gen, scale=scale_gen) #double check parameterisation of scipy\n #renormalise the pdf\n disc_gamma = gamma_vals/sum(gamma_vals)\n ws = disc_gamma[:trunc_days]\n #offset\n ws[offset:] = disc_gamma[:trunc_days-offset]\n ws[:offset] = 0\n\n fig, ax = plt.subplots(figsize=(12,18),nrows=3,sharex=True)\n\n ax[0].hist(rep_delay, bins=50,density=True)\n ax[0].set_title(\"Reporting Delay\")\n ax[1].hist(inc_period, bins=50,density=True)\n ax[1].set_title(\"Incubation Period\")\n ax[2].bar(xmids[:-1], height=ws, width=1)\n ax[2].set_title(\"Generation Interval\")\n\n plt.savefig('figs/Time_distributions'+file_date+\"tau_\"+str(tau)+\".png\",dpi=400)\n\n\n\ndf.to_csv('results/EpyReff/Reff'+file_date+\"tau_\"+str(tau)+\".csv\",index=False)\n\n#plot all the estimates\nfig,ax = plot_all_states(R_summary_states,df_interim, dates, \n start='2020-03-01',end=file_date,save=True,\n tau=tau, date=date\n )\nplt.close()\n"
] |
[
[
"pandas.to_datetime",
"numpy.random.gamma",
"matplotlib.use",
"scipy.stats.gamma.pdf",
"matplotlib.pyplot.subplots",
"pandas.DataFrame",
"matplotlib.pyplot.close",
"pandas.DataFrame.from_dict"
]
] |
AfonsoSeguro/IDS_Comportamental
|
[
"83145f815b67b2d501eb3744367aaea9b5d11cba"
] |
[
"Algoritmo_genetico/Agente.py"
] |
[
"import numpy as np\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom random import random\n\n\nclass Agente:\n def __init__(self, createModel, mutation_rate = 0.2, model = None):\n self.createModel = createModel\n if(model == None): self.model = createModel()\n else: self.model = model\n self.mutation_rate = mutation_rate\n self.fitness = 0\n\n def getFitness(self):\n return self.fitness\n\n def setFitness(self, fitness):\n self.fitness = fitness\n\n def calculateFitness(self, y_true, y_pred):\n losses = keras.losses.sparse_categorical_crossentropy(y_true, y_pred).numpy()\n total = 0\n for loss in losses: total += loss\n self.fitness = total / len(losses)\n return self.fitness\n\n def resetFitness(self):\n self.fitness = 0\n\n def predict(self, inp):\n return self.model.predict(inp)\n\n def mutate(self):\n for i in range(len(self.model.layers)):\n pesos = self.model.layers[i].get_weights()\n for j in range(len(pesos)):\n for k in range(len(pesos[j])):\n if(random() < self.mutation_rate):\n pesos[j][k] *= (random() + 1) * 0.5\n self.model.layers[i].set_weights(pesos)\n\n def save(self, name):\n self.model.save(name + \".h5\")\n\n def load(self, name):\n self.model = keras.models.load_model(name + \".h5\")\n\n def copy(self):\n copy = self.createModel()\n copy.set_weights(self.model.get_weights())\n return Agente(self.createModel, self.mutation_rate, self.model)"
] |
[
[
"tensorflow.keras.models.load_model",
"tensorflow.keras.losses.sparse_categorical_crossentropy"
]
] |
Jsevillamol/ctlearn
|
[
"80461412c8d6bd124a7d8abf65af372e69ab0ed1"
] |
[
"ctalearn/build_model.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 27 10:22:03 2018\n\n@author: jsevillamol\n\"\"\"\n\nimport yaml, argparse\nfrom contextlib import redirect_stdout\n\nfrom tensorflow.keras.models import Model\nimport tensorflow.keras.layers as ll\nfrom tensorflow.keras.regularizers import l2\n\ndef build_model(\n input_shape, \n num_classes,\n activation_function, \n dropout_rate,\n use_batchnorm,\n l2_regularization,\n cnn_layers,\n lstm_units,\n combine_mode,\n fcn_layers):\n ''' Builds a CNN-RNN-FCN classification model\n \n # Parameters\n input_shape (tuple) -- expected input shape\n num_classes (int) -- number of classes\n activation_function (str) -- non linearity to apply between layers\n dropout_rate (float) -- must be between 0 and 1\n use_batchnorm (bool) -- if True, batchnorm layers are added between convolutions\n l2_regularization (float)\n cnn_layers (list) -- list specifying CNN layers. \n Each element must be of the form \n {filters: 32, kernel_size: 3, use_maxpool: true}\n lstm_units (int) -- number of hidden units of the lstm\n if lstm_units is None or 0 the LSTM layer is skipped\n combine_mode (str) -- specifies how the encoding of each image in the sequence \n is to be combined. Supports:\n concat : outputs are stacked on top of one another\n last : only last hidden state is returned\n attention : an attention mechanism is used to combine the hidden states\n \n fcn_layers (list) -- list specifying Dense layers\n example element: {units: 1024}\n # Returns\n model -- an uncompiled Keras model\n '''\n # Regularizer\n l2_reg = l2(l2_regularization)\n \n # Build a model with the functional API\n inputs = ll.Input(input_shape)\n x = inputs\n \n # Reshape entry if needed\n if len(input_shape) == 3:\n x = ll.Reshape([1] + input_shape)(x)\n elif len(input_shape) < 3:\n raise ValueError(f\"Input shape {input_shape} not supported\")\n\n # CNN feature extractor \n for i, cnn_layer in enumerate(cnn_layers):\n # Extract layer params\n filters = cnn_layer['filters']\n kernel_size = cnn_layer['kernel_size']\n use_maxpool = cnn_layer['use_maxpool']\n\n # build cnn_layer\n x = ll.TimeDistributed(ll.Conv2D(\n filters, \n kernel_size, \n strides=(1, 1), \n padding='same', \n data_format=None, \n dilation_rate=(1, 1), \n activation=activation_function, \n use_bias=True, \n kernel_initializer='glorot_uniform', \n bias_initializer='zeros', \n kernel_regularizer=l2_reg, \n bias_regularizer=l2_reg, \n activity_regularizer=None, \n kernel_constraint=None, \n bias_constraint=None\n ), name=f'conv2D_{i}')(x)\n \n # add maxpool if needed\n if use_maxpool:\n x = ll.TimeDistributed(ll.MaxPooling2D(\n pool_size=(2, 2), \n strides=None, \n padding='valid', \n data_format=None\n ), name=f'maxpool_{i}')(x)\n \n if use_batchnorm:\n x = ll.TimeDistributed(ll.BatchNormalization(\n axis=-1, \n momentum=0.99, \n epsilon=0.001, \n center=True, \n scale=True, \n beta_initializer='zeros', \n gamma_initializer='ones', \n moving_mean_initializer='zeros', \n moving_variance_initializer='ones', \n beta_regularizer=None, \n gamma_regularizer=None, \n beta_constraint=None, \n gamma_constraint=None\n ), name=f'batchnorm_{i}')(x)\n\n \n x = ll.TimeDistributed(ll.Flatten(), name='flatten')(x)\n x = ll.TimeDistributed(ll.Dropout(dropout_rate), name='dropout')(x)\n\n # LSTM feature combinator\n if lstm_units is not None and lstm_units > 0:\n x = ll.CuDNNLSTM(\n lstm_units,\n kernel_initializer='glorot_uniform',\n recurrent_initializer='orthogonal',\n bias_initializer='zeros',\n unit_forget_bias=True,\n kernel_regularizer=l2_reg,\n recurrent_regularizer=l2_reg,\n bias_regularizer=l2_reg,\n activity_regularizer=None,\n kernel_constraint=None,\n recurrent_constraint=None,\n bias_constraint=None,\n return_sequences=(combine_mode!='last'),\n return_state=False,\n go_backwards=False,\n stateful=False\n )(x)\n \n # Combine output of each sequence\n if combine_mode == 'concat':\n x = ll.Flatten()(x)\n elif combine_mode == 'last':\n if lstm_units is None or lstm_units == 0: # if no LSTM was used\n x = ll.Lambda(lambda x : x[:,-1,...])(x) # we extract the last element\n elif combine_mode == 'attention':\n attention = ll.TimeDistributed(ll.Dense(1), name='attention_score')(x)\n attention = ll.Flatten()(attention)\n attention = ll.Softmax()(attention)\n x = ll.dot([x, attention], axes=[-2, -1])\n else: raise ValueError(f\"Combine mode {combine_mode} not supported\")\n \n # FCN classifier \n for fcn_layer in fcn_layers:\n # extract layer params\n units = fcn_layer['units']\n \n # build layer\n x = ll.Dense(\n units, \n activation=activation_function, \n use_bias=True, \n kernel_initializer='glorot_uniform', \n bias_initializer='zeros', \n kernel_regularizer=l2_reg, \n bias_regularizer=l2_reg, \n activity_regularizer=None, \n kernel_constraint=None, \n bias_constraint=None\n )(x)\n \n x = ll.Dropout(dropout_rate)(x)\n\n \n prediction = ll.Dense(num_classes, activation='softmax')(x)\n \n # Build model\n model = Model(inputs=inputs, outputs=prediction)\n \n return model\n\nif __name__==\"__main__\":\n # parser options\n parser = argparse.ArgumentParser(\n description=(\"Build a customized cnn-rnn keras model with ctalearn.\"))\n \n parser.add_argument(\n 'config_file',\n help=\"path to YAML file containing a training configuration\")\n\n args = parser.parse_args()\n \n # load config file\n with open(args.config_file, 'r') as config_file:\n config = yaml.load(config_file)\n \n model = build_model(**config['model_config'])\n \n # Show model summary through console and then save it to file\n model.summary()\n\n with open('model_summary.txt', 'w') as f:\n with redirect_stdout(f):\n model.summary()\n \n # save model architecture to disk in .h5 format\n model.save('untrained_model.h5', include_optimizer=False)\n"
] |
[
[
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.CuDNNLSTM",
"tensorflow.keras.layers.Lambda",
"tensorflow.keras.models.Model",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.regularizers.l2",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.layers.dot",
"tensorflow.keras.layers.Reshape",
"tensorflow.keras.layers.MaxPooling2D",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.layers.Softmax",
"tensorflow.keras.layers.Input"
]
] |
Liang-ZX/maskrcnn-benchmark
|
[
"84562b5b1dda871a76d793e5d74297d6fbfe429b"
] |
[
"maskrcnn_benchmark_mine/modeling/roi_heads/keypoint_head/loss.py"
] |
[
"import torch\nfrom torch.nn import functional as F\n\nfrom maskrcnn_benchmark.modeling.matcher import Matcher\n\nfrom maskrcnn_benchmark.modeling.balanced_positive_negative_sampler import (\n BalancedPositiveNegativeSampler,\n)\nfrom maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou\nfrom maskrcnn_benchmark.modeling.utils import cat\nfrom maskrcnn_benchmark.layers import smooth_l1_loss\nfrom maskrcnn_benchmark.structures.boxlist_ops import cat_boxlist\n\nfrom maskrcnn_benchmark.structures.keypoint import keypoints_to_heat_map\n\n\ndef project_keypoints_to_heatmap(keypoints, proposals, discretization_size):\n proposals = proposals.convert(\"xyxy\")\n return keypoints_to_heat_map(\n keypoints.keypoints, proposals.bbox, discretization_size\n )\n\n\ndef cat_boxlist_with_keypoints(boxlists):\n assert all(boxlist.has_field(\"keypoints\") for boxlist in boxlists)\n\n kp = [boxlist.get_field(\"keypoints\").keypoints for boxlist in boxlists]\n kp = cat(kp, 0)\n\n fields = boxlists[0].get_fields()\n fields = [field for field in fields if field != \"keypoints\"]\n\n boxlists = [boxlist.copy_with_fields(fields) for boxlist in boxlists]\n boxlists = cat_boxlist(boxlists)\n boxlists.add_field(\"keypoints\", kp)\n return boxlists\n\n\ndef _within_box(points, boxes):\n \"\"\"Validate which keypoints are contained inside a given box.\n points: NxKx2\n boxes: Nx4\n output: NxK\n \"\"\"\n x_within = (points[..., 0] >= boxes[:, 0, None]) & (\n points[..., 0] <= boxes[:, 2, None]\n )\n y_within = (points[..., 1] >= boxes[:, 1, None]) & (\n points[..., 1] <= boxes[:, 3, None]\n )\n return x_within & y_within\n\n\nclass KeypointRCNNLossComputation(object):\n def __init__(self, proposal_matcher, fg_bg_sampler, discretization_size):\n \"\"\"\n Arguments:\n proposal_matcher (Matcher)\n fg_bg_sampler (BalancedPositiveNegativeSampler)\n discretization_size (int)\n \"\"\"\n self.proposal_matcher = proposal_matcher\n self.fg_bg_sampler = fg_bg_sampler\n self.discretization_size = discretization_size\n\n def match_targets_to_proposals(self, proposal, target):\n match_quality_matrix = boxlist_iou(target, proposal)\n matched_idxs = self.proposal_matcher(match_quality_matrix)\n # Keypoint RCNN needs \"labels\" and \"keypoints \"fields for creating the targets\n target = target.copy_with_fields([\"labels\", \"keypoints\"])\n # get the targets corresponding GT for each proposal\n # NB: need to clamp the indices because we can have a single\n # GT in the image, and matched_idxs can be -2, which goes\n # out of bounds\n matched_targets = target[matched_idxs.clamp(min=0)]\n matched_targets.add_field(\"matched_idxs\", matched_idxs)\n return matched_targets\n\n def prepare_targets(self, proposals, targets):\n labels = []\n keypoints = []\n for proposals_per_image, targets_per_image in zip(proposals, targets):\n matched_targets = self.match_targets_to_proposals(\n proposals_per_image, targets_per_image\n )\n matched_idxs = matched_targets.get_field(\"matched_idxs\")\n\n labels_per_image = matched_targets.get_field(\"labels\")\n labels_per_image = labels_per_image.to(dtype=torch.int64)\n\n # this can probably be removed, but is left here for clarity\n # and completeness\n # TODO check if this is the right one, as BELOW_THRESHOLD\n neg_inds = matched_idxs == Matcher.BELOW_LOW_THRESHOLD\n labels_per_image[neg_inds] = 0\n\n keypoints_per_image = matched_targets.get_field(\"keypoints\")\n within_box = _within_box(\n keypoints_per_image.keypoints, matched_targets.bbox\n )\n vis_kp = keypoints_per_image.keypoints[..., 2] > 0\n is_visible = (within_box & vis_kp).sum(1) > 0\n\n labels_per_image[~is_visible] = -1\n\n labels.append(labels_per_image)\n keypoints.append(keypoints_per_image)\n\n return labels, keypoints\n\n def subsample(self, proposals, targets, sampled=None):\n \"\"\"\n This method performs the positive/negative sampling, and return\n the sampled proposals.\n Note: this function keeps a state.\n\n Arguments:\n proposals (list[BoxList])\n targets (list[BoxList])\n \"\"\"\n\n labels, keypoints = self.prepare_targets(proposals, targets)\n if sampled == None:\n sampled_pos_inds, sampled_neg_inds = self.fg_bg_sampler(labels)\n sampled = (sampled_pos_inds, sampled_neg_inds)\n else:\n sampled_pos_inds, sampled_neg_inds = sampled\n\n proposals = list(proposals)\n # add corresponding label and regression_targets information to the bounding boxes\n for labels_per_image, keypoints_per_image, proposals_per_image in zip(\n labels, keypoints, proposals\n ):\n proposals_per_image.add_field(\"labels\", labels_per_image)\n proposals_per_image.add_field(\"keypoints\", keypoints_per_image)\n\n # distributed sampled proposals, that were obtained on all feature maps\n # concatenated via the fg_bg_sampler, into individual feature map levels\n for img_idx, (pos_inds_img, neg_inds_img) in enumerate(\n zip(sampled_pos_inds, sampled_neg_inds)\n ):\n img_sampled_inds = torch.nonzero(pos_inds_img).squeeze(1)\n proposals_per_image = proposals[img_idx][img_sampled_inds]\n proposals[img_idx] = proposals_per_image\n\n self._proposals = proposals\n return proposals, sampled\n\n def __call__(self, proposals, keypoint_logits):\n heatmaps = []\n valid = []\n for proposals_per_image in proposals:\n kp = proposals_per_image.get_field(\"keypoints\")\n heatmaps_per_image, valid_per_image = project_keypoints_to_heatmap(\n kp, proposals_per_image, self.discretization_size\n )\n heatmaps.append(heatmaps_per_image.view(-1))\n valid.append(valid_per_image.view(-1))\n\n keypoint_targets = cat(heatmaps, dim=0)\n valid = cat(valid, dim=0).to(dtype=torch.bool)\n valid = torch.nonzero(valid).squeeze(1)\n\n # torch.mean (in binary_cross_entropy_with_logits) does'nt\n # accept empty tensors, so handle it sepaartely\n if keypoint_targets.numel() == 0 or len(valid) == 0:\n return keypoint_logits.sum() * 0\n\n N, K, H, W = keypoint_logits.shape\n keypoint_logits = keypoint_logits.view(N * K, H * W)\n\n keypoint_loss = F.cross_entropy(keypoint_logits[valid], keypoint_targets[valid])\n return keypoint_loss\n\n\ndef make_roi_keypoint_loss_evaluator(cfg):\n matcher = Matcher(\n cfg.MODEL.ROI_HEADS.FG_IOU_THRESHOLD,\n cfg.MODEL.ROI_HEADS.BG_IOU_THRESHOLD,\n allow_low_quality_matches=False,\n )\n fg_bg_sampler = BalancedPositiveNegativeSampler(\n cfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE, cfg.MODEL.ROI_HEADS.POSITIVE_FRACTION\n )\n resolution = cfg.MODEL.ROI_KEYPOINT_HEAD.RESOLUTION\n loss_evaluator = KeypointRCNNLossComputation(matcher, fg_bg_sampler, resolution)\n return loss_evaluator\n"
] |
[
[
"torch.nn.functional.cross_entropy",
"torch.nonzero"
]
] |
GuoqingZhou-LANL/hippynn
|
[
"e3c31b3dc77369bd24ed575005b6385796ba04b0",
"e3c31b3dc77369bd24ed575005b6385796ba04b0"
] |
[
"hippynn/layers/physics.py",
"hippynn/databases/SNAPJson.py"
] |
[
"\"\"\"\nLayers for physical operations\n\"\"\"\nimport warnings\n\nimport torch\n\nfrom . import pairs\nfrom . import indexers\n\n\nclass Gradient(torch.nn.Module):\n def __init__(self,sign):\n super().__init__()\n assert sign in (-1,1), \"Sign of gradient must be +1 (gradient) or -1 (force)\"\n self.sign = sign\n def forward(self,molecular_energies, positions):\n return self.sign * torch.autograd.grad(\n molecular_energies.sum(),\n positions,\n create_graph=True)[0]\n\n\nclass StressForce(torch.nn.Module):\n def __init__(self,*args,**kwargs):\n super().__init__(*args,**kwargs)\n self.pbc = False\n\n def forward(self,energy,strain,coordinates,cell):\n total_energy = energy.sum()\n straingrad, grad = torch.autograd.grad(total_energy,[strain,coordinates],create_graph=self.training)\n if self.pbc:\n stress = straingrad/torch.det(cell)\n else:\n stress = straingrad\n return -grad,stress\n\nclass Dipole(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.summer = indexers.MolSummer()\n\n def forward(self, charges, positions, mol_index,n_molecules):\n dipole_elements = charges * positions\n dipoles = self.summer(dipole_elements, mol_index, n_molecules)\n return dipoles\n\n\nclass Quadrupole(torch.nn.Module):\n \"\"\"Computes quadrupoles as a flattened (n_molecules,9) array.\n NOTE: Uses normalization sum_a q_a (r_a,i*r_a,j - 1/3 delta_ij r_a^2)\"\"\"\n def __init__(self,**kwargs):\n super().__init__(**kwargs)\n self.summer = indexers.MolSummer()\n\n def forward(self, charges, positions, mol_index, n_molecules):\n # positions shape: (atoms, xyz)\n # charge shape: (atoms,1)\n ri_rj = positions.unsqueeze(1)*positions.unsqueeze(2)\n ri_rj_flat = ri_rj.reshape(-1,9) #Flatten to component\n rsq = (positions**2).sum(dim=1).unsqueeze(1) #unsqueeze over component index\n delta_ij = torch.eye(3,device=rsq.device).flatten().unsqueeze(0) #unsqueeze over atom index\n quad_elements = charges * (ri_rj_flat - (1/3)*(rsq*delta_ij))\n quadrupoles = self.summer(quad_elements, mol_index, n_molecules)\n return quadrupoles\n\n\nclass CoulombEnergy(torch.nn.Module):\n def __init__(self,energy_conversion_factor):\n super().__init__()\n self.register_buffer(\"energy_conversion_factor\", torch.tensor(energy_conversion_factor))\n self.summer = indexers.MolSummer()\n def forward(self, charges, pair_dist,pair_first,pair_second,mol_index,n_molecules):\n voltage_pairs = self.energy_conversion_factor*(charges[pair_second] / pair_dist.unsqueeze(1))\n n_atoms,_ = charges.shape\n voltage_atom = torch.zeros((n_atoms,1),device=charges.device,dtype=charges.dtype)\n voltage_atom.index_add_(0,pair_first,voltage_pairs)\n coulomb_atom = voltage_atom * charges\n coulomb_molecules = 0.5*self.summer(coulomb_atom,mol_index,n_molecules)\n return coulomb_molecules,voltage_atom\n\n\nclass ScreenedCoulombEnergy(CoulombEnergy):\n def __init__(self,energy_conversion_factor,screening,radius=None):\n super().__init__(energy_conversion_factor)\n if screening is None:\n raise ValueError(\"Screened Coulomb requires specification of a screening type.\")\n if radius is None:\n raise ValueError(\"Screened Coulomb requires specification of a radius\")\n\n if isinstance(screening,type):\n screening = screening()\n\n self.radius = radius\n\n self.screening = screening\n self.bond_summer=pairs.MolPairSummer()\n\n def forward(self, charges, pair_dist,pair_first,pair_second,mol_index,n_molecules):\n\n # Calculation of pair terms\n base_coulomb = (charges[pair_first]*charges[pair_second] / pair_dist.unsqueeze(1))\n screening = self.screening(pair_dist,self.radius).unsqueeze(1)\n screening = torch.where((pair_dist<self.radius).unsqueeze(1),screening,torch.zeros_like(screening))\n coulomb_pairs = base_coulomb * screening\n\n # Add pair contributions to system\n coulomb_molecule = self.bond_summer(coulomb_pairs,mol_index,n_molecules,pair_first)\n\n # Finally, account for symmetry pairs and energy conversion factor.\n coulomb_molecule = 0.5*self.energy_conversion_factor*coulomb_molecule\n\n return coulomb_molecule\n\n\nclass AlphaScreening(torch.nn.Module):\n def __init__(self,alpha):\n super().__init__()\n self.alpha = alpha\n\n\n# Note: This is somewhat incomplete as it does not include a k-space contribution -- more is needed\nclass EwaldRealSpaceScreening(AlphaScreening):\n def __init__(self,alpha):\n warnings.warn(\"Ewald implementation incomplete, does not include k-space contributions.\")\n super.__init__(alpha)\n def forward(self,pair_dist,radius):\n q = pair_dist / radius\n eta = self.alpha * radius\n return torch.erfc(eta*q)\n\n\n# Note: typically\nclass WolfScreening(AlphaScreening):\n def __init__(self,alpha):\n warnings.warn(\"Wolf implemnetation uses exact derivative of the potential.\")\n super.__init__(alpha)\n\n def forward(self,pair_dist,radius):\n q = pair_dist / radius\n eta = self.alpha * radius\n return torch.erfc(eta*q) - q * torch.erfc(eta)\n\n\nclass QScreening(torch.nn.Module):\n def __init__(self,p_value):\n super().__init__()\n self.p_value = p_value\n\n @property\n def p_value(self):\n return self._p_value\n\n @p_value.setter\n def p_value(self,value):\n value = int(value)\n self._p_value = value\n powers = torch.arange(1, value + 1,dtype=torch.long).unsqueeze(0)\n self.register_buffer('powers', powers)\n\n def forward(self,pair_dist,radius):\n q = pair_dist / radius\n q_factors = 1-torch.pow(q.unsqueeze(1),self.powers)\n product = q_factors.prod(dim=1)\n return product\n\n\nclass PerAtom(torch.nn.Module):\n def forward(self,features,species):\n n_atoms = (species!=0).type(features.dtype).sum(dim=1)\n return features/n_atoms.unsqueeze(1)\n\n\nclass VecMag(torch.nn.Module):\n def forward(self, vector_feature):\n return torch.norm(vector_feature, dim=1).unsqueeze(1)\n",
"\"\"\"\nLoad database from SNAP format.\n\"\"\"\nimport json, glob, os\nimport torch\nimport numpy as np\n\nfrom .database import Database\nfrom .restarter import Restartable\nfrom ..tools import pad_np_array_to_length_with_zeros as padax\nfrom ..tools import progress_bar, np_of_torchdefaultdtype\n\nfrom ase.data import chemical_symbols\n\n\nclass SNAPDirectoryDatabase(Database, Restartable):\n def __init__(self,directory,inputs,targets,*args,\n files=None,depth=1,transpose_cell=True,allow_unfound=False,quiet=False,**kwargs):\n\n self.directory = directory\n self.files = files\n self.inputs = inputs\n self.targets = targets\n self.transpose_cell = transpose_cell\n self.depth = depth\n arr_dict = self.load_arrays(quiet=quiet,allow_unfound=allow_unfound)\n\n super().__init__(arr_dict,inputs,targets,*args,**kwargs,allow_unfound=allow_unfound,quiet=quiet)\n\n self.restarter = self.make_restarter(directory,inputs,targets,*args,\n transpose_cell=transpose_cell,files=files,\n allow_unfound=allow_unfound,**kwargs,quiet=quiet)\n\n def load_arrays(self,allow_unfound=False,quiet=False):\n\n if not self.files:\n if not quiet:\n print(\"Acquiring file list\")\n glob_str = f\"{self.directory}\"+('/*'*self.depth)+'/*.json'\n files = glob.glob(glob_str)\n if len(files) == 0:\n raise FileNotFoundError(f\"No '.json' files found in directory {self.directory}\")\n else:\n files = [os.path.join(self.directory,f) for f in self.files]\n\n files.sort()\n\n config_unprocessed = []\n for f in progress_bar(files,desc=\"Data Files\",unit=\"file\"):\n config_unprocessed.append(self.extract_snap_file(f))\n\n config_unprocessed = [c for batch in config_unprocessed for c in batch] # Flattening groups\n\n n_atoms_max = max(d['NumAtoms'] for d in config_unprocessed)\n\n arr_dict = self.process_configs(config_unprocessed, n_atoms_max)\n arr_dict = self.filter_arrays(arr_dict,allow_unfound=allow_unfound,quiet=quiet)\n return arr_dict\n\n def filter_arrays(self,arr_dict,allow_unfound=False,quiet=False):\n if not quiet:\n print(\"Arrays found: \", list(arr_dict.keys()))\n\n floatX = np_of_torchdefaultdtype()\n for k,v in arr_dict.copy().items():\n if not allow_unfound:\n if k not in self.inputs and k not in self.targets:\n del arr_dict[k]\n if v.dtype == 'float64':\n arr_dict[k] = v.astype(floatX)\n\n if not quiet:\n print(\"Data types:\")\n print({k:v.dtype for k,v in arr_dict.items()})\n\n return arr_dict\n\n def extract_snap_file(self,file):\n with open(file, 'rt') as jf:\n comment = jf.readline()\n content = jf.read()\n parsed = json.loads(content)\n dataset = parsed['Dataset']\n data_items = dataset['Data']\n\n for i,d in enumerate(data_items):\n group_path, config_name = os.path.split(file)\n base_path, group_name = os.path.split(file)\n data_items[i]['FileName'] = config_name\n data_items[i]['Group'] = group_name\n data_items[i]['SubConfig'] = i\n\n return data_items\n\n def process_configs(self,configs,n_atoms_max):\n\n arr_dict = {}\n all_keys = 'AtomTypes','Energy',\"Forces\",\"Lattice\",\"Positions\",\"Group\",\"FileName\",\"SubConfig\"\n pad_keys = 'AtomTypes',\"Forces\",\"Positions\"\n for key in all_keys:\n value_list = [c[key] for c in configs]\n if key in pad_keys:\n value_list = [padax(np.asarray(v), n_atoms_max) for v in value_list]\n arr_dict[key] = np.stack(value_list)\n arr_dict[\"AtomTypes\"][arr_dict[\"AtomTypes\"]=='0'] = 'X' # ASE calls blank atoms 'X'\n z_array = [[chemical_symbols.index(s) for s in sym] for sym in arr_dict[\"AtomTypes\"]]\n arr_dict[\"Species\"] = np.asarray(z_array).astype(int)\n arr_dict[\"AtomCount\"] = arr_dict[\"Species\"].astype(bool).sum(axis=1)\n arr_dict[\"EnergyPerAtom\"] = arr_dict[\"Energy\"]/arr_dict[\"AtomCount\"]\n\n if self.transpose_cell:\n arr_dict[\"Lattice\"] = arr_dict[\"Lattice\"].transpose((0,2,1))\n\n\n return arr_dict\n"
] |
[
[
"torch.norm",
"torch.erfc",
"torch.zeros",
"torch.det",
"torch.zeros_like",
"torch.eye",
"torch.tensor",
"torch.arange",
"torch.autograd.grad"
],
[
"numpy.asarray",
"numpy.stack"
]
] |
covernal/mask-rcnn-tensorflow
|
[
"8d5e6c8adcf1ea5208f361ec29287696ff80cc98",
"8d5e6c8adcf1ea5208f361ec29287696ff80cc98"
] |
[
"MaskRCNN/utils/box_ops.py",
"tensorpack/tfutils/collection.py"
] |
[
"# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n# -*- coding: utf-8 -*-\n# File: box_ops.py\n\nimport tensorflow as tf\n\nfrom tensorpack.tfutils.scope_utils import under_name_scope\n\n\n\"\"\"\nThis file is modified from\nhttps://github.com/tensorflow/models/blob/master/object_detection/core/box_list_ops.py\n\"\"\"\n\n\n@under_name_scope()\ndef area(boxes):\n \"\"\"\n Args:\n boxes: nx4 floatbox\n\n Returns:\n n\n \"\"\"\n x_min, y_min, x_max, y_max = tf.split(boxes, 4, axis=1)\n return tf.squeeze((y_max - y_min) * (x_max - x_min), [1])\n\n\n@under_name_scope()\ndef pairwise_intersection(boxlist1, boxlist2):\n \"\"\"Compute pairwise intersection areas between boxes.\n\n Args:\n boxlist1: Nx4 floatbox\n boxlist2: Mx4\n\n Returns:\n a tensor with shape [N, M] representing pairwise intersections\n \"\"\"\n x_min1, y_min1, x_max1, y_max1 = tf.split(boxlist1, 4, axis=1)\n x_min2, y_min2, x_max2, y_max2 = tf.split(boxlist2, 4, axis=1)\n all_pairs_min_ymax = tf.minimum(y_max1, tf.transpose(y_max2))\n all_pairs_max_ymin = tf.maximum(y_min1, tf.transpose(y_min2))\n intersect_heights = tf.maximum(0.0, all_pairs_min_ymax - all_pairs_max_ymin)\n all_pairs_min_xmax = tf.minimum(x_max1, tf.transpose(x_max2))\n all_pairs_max_xmin = tf.maximum(x_min1, tf.transpose(x_min2))\n intersect_widths = tf.maximum(0.0, all_pairs_min_xmax - all_pairs_max_xmin)\n return intersect_heights * intersect_widths\n\n\n@under_name_scope()\ndef pairwise_iou(boxlist1, boxlist2):\n \"\"\"Computes pairwise intersection-over-union between box collections.\n\n Args:\n boxlist1: Nx4 floatbox\n boxlist2: Mx4\n\n Returns:\n a tensor with shape [N, M] representing pairwise iou scores.\n \"\"\"\n intersections = pairwise_intersection(boxlist1, boxlist2)\n areas1 = area(boxlist1)\n areas2 = area(boxlist2)\n unions = (\n tf.expand_dims(areas1, 1) + tf.expand_dims(areas2, 0) - intersections)\n return tf.where(\n tf.equal(intersections, 0.0),\n tf.zeros_like(intersections), tf.truediv(intersections, unions))\n\n\n\n@under_name_scope()\ndef pairwise_iou_batch(proposal_boxes, gt_boxes, orig_gt_counts, batch_size):\n \"\"\"Computes pairwise intersection-over-union between box collections.\n Args:\n proposal_boxes: K x 5 (batch_index, x1, y1, x2, y2)\n gt_boxes: BS x MaxNumGTs x 4\n orig_gt_counts: BS\n Returns:\n list of length BS, each element is output of pairwise_iou: N x M\n (where N is number of boxes for image and M is number of GTs for image)\n \"\"\"\n\n prefix = \"pairwise_iou_batch\"\n\n # For each image index, extract a ?x4 boxlist and gt_boxlist\n\n per_images_iou = []\n for batch_idx in range(batch_size):\n\n box_mask_for_image = tf.equal(proposal_boxes[:, 0], batch_idx)\n\n single_image_boxes = tf.boolean_mask(proposal_boxes, box_mask_for_image)\n single_image_boxes = single_image_boxes[:, 1:]\n single_image_gt_boxes = gt_boxes[batch_idx, 0:orig_gt_counts[batch_idx], :]\n single_image_iou = pairwise_iou(single_image_boxes, single_image_gt_boxes)\n\n per_images_iou.append(single_image_iou)\n\n return per_images_iou\n",
"# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n# -*- coding: utf-8 -*-\n# File: collection.py\n\n\nfrom contextlib import contextmanager\nfrom copy import copy\nimport six\nimport tensorflow as tf\n\nfrom ..utils import logger\nfrom ..utils.argtools import memoized\n\n__all__ = ['backup_collection',\n 'restore_collection',\n 'freeze_collection']\n\n\ndef backup_collection(keys=None):\n \"\"\"\n Args:\n keys (list): list of collection keys to backup.\n Defaults to all keys in the graph.\n\n Returns:\n dict: the backup\n \"\"\"\n if keys is None:\n keys = tf.get_default_graph().get_all_collection_keys()\n ret = {}\n assert isinstance(keys, (list, tuple, set))\n for k in keys:\n ret[k] = copy(tf.get_collection(k))\n return ret\n\n\ndef restore_collection(backup):\n \"\"\"\n Restore from a collection backup.\n\n Args:\n backup (dict):\n \"\"\"\n for k, v in six.iteritems(backup):\n del tf.get_collection_ref(k)[:]\n tf.get_collection_ref(k).extend(v)\n\n\n@contextmanager\ndef freeze_collection(keys):\n \"\"\"\n Args:\n keys(list): list of collection keys to freeze.\n\n Returns:\n a context where the collections are in the end restored to its initial state.\n \"\"\"\n backup = backup_collection(keys)\n yield\n restore_collection(backup)\n\n\n@memoized\ndef get_inverse_graphkeys():\n ret = {}\n for name in dir(tf.GraphKeys):\n if name.startswith('_'):\n continue\n if name in ['VARIABLES']: # will produce deprecated warning\n continue\n ret[getattr(tf.GraphKeys, name)] = \"tf.GraphKeys.{}\".format(name)\n return ret\n\n\nclass CollectionGuard(object):\n \"\"\"\n A context to maintain collection change in a tower.\n \"\"\"\n\n original = None\n\n def __init__(self, name, check_diff,\n freeze_keys=[],\n diff_whitelist=None):\n \"\"\"\n Args:\n name (str): name of the tower\n check_diff (bool): whether to check and print about collection change\n when leaving this guard.\n freeze_keys (list): list of keys to backup when entering and restore when leaving this guard.\n diff_whitelist (list): list of keys to ignore, when check_diff is True.\n Defaults to some collections that are normally changed,\n including variables, losses, contexts, queue runners.\n \"\"\"\n self._name = name\n self._check_diff = check_diff\n if diff_whitelist is None:\n diff_whitelist = CollectionGuard._default_diff_whitelist()\n self._whitelist = set(diff_whitelist)\n self._freeze_keys = freeze_keys\n self._inverse_graphkeys = get_inverse_graphkeys()\n\n @staticmethod\n def _default_diff_whitelist():\n ret = [tf.GraphKeys.TRAINABLE_VARIABLES,\n tf.GraphKeys.GLOBAL_VARIABLES,\n tf.GraphKeys.QUEUE_RUNNERS,\n tf.GraphKeys.LOCAL_VARIABLES]\n for newkey in ['COND_CONTEXT', 'WHILE_CONTEXT', 'LOSSES']:\n if hasattr(tf.GraphKeys, newkey):\n ret.append(getattr(tf.GraphKeys, newkey))\n return ret\n\n def _key_name(self, name):\n return self._inverse_graphkeys.get(name, name)\n\n def __enter__(self):\n self.original = backup_collection()\n self._freeze_backup = backup_collection(self._freeze_keys)\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_type is not None:\n return False\n new_coll = backup_collection()\n\n if self._check_diff:\n self._print_diff(new_coll)\n self._restore_freeze(new_coll)\n return False\n\n def _print_diff(self, new):\n newly_created = []\n size_change = []\n for k, v in six.iteritems(new):\n if k in self._whitelist or k in self._freeze_keys:\n continue\n if k not in self.original:\n newly_created.append(self._key_name(k))\n else:\n old_v = self.original[k]\n if len(old_v) != len(v):\n size_change.append((self._key_name(k), len(old_v), len(v)))\n if newly_created:\n logger.info(\n \"New collections created in tower {}: {}\".format(\n self._name, ', '.join(newly_created)))\n if size_change:\n logger.info(\n \"Size of these collections were changed in {}: {}\".format(\n self._name, ', '.join(\n map(lambda t: \"({}: {}->{})\".format(*t),\n size_change))))\n\n def _restore_freeze(self, new):\n size_change = []\n for k, v in six.iteritems(self._freeze_backup):\n newv = new.get(k, [])\n if len(v) != len(newv):\n size_change.append((self._key_name(k), len(v), len(newv)))\n if size_change:\n logger.info(\n \"These collections were modified but restored in {}: {}\".format(\n self._name, ', '.join(\n map(lambda t: \"({}: {}->{})\".format(*t),\n size_change))))\n restore_collection(self._freeze_backup)\n\n def get_collection_in_tower(self, key):\n \"\"\"\n Get items from this collection that are added in the current tower.\n \"\"\"\n new = tf.get_collection(key)\n old = set(self.original.get(key, []))\n # persist the order in new\n return [x for x in new if x not in old]\n"
] |
[
[
"tensorflow.boolean_mask",
"tensorflow.truediv",
"tensorflow.transpose",
"tensorflow.maximum",
"tensorflow.equal",
"tensorflow.squeeze",
"tensorflow.expand_dims",
"tensorflow.zeros_like",
"tensorflow.split"
],
[
"tensorflow.get_collection",
"tensorflow.get_default_graph",
"tensorflow.get_collection_ref"
]
] |
katwinkl3/locomotion
|
[
"b9c93552608cdaf41a2c0bc9c9e14e8286abc3ea"
] |
[
"locomotion/animal.py"
] |
[
"import os\nimport sys\nimport csv\nimport re\nimport math\nimport numpy as np\nimport json\nfrom math import ceil, exp, log, sin, asin, pi, acosh, cosh, sinh, cos, acos, atanh, tanh\nfrom numpy import min, mean, std, array, linalg, dot, cross\nfrom scipy.optimize import minimize_scalar\n\n\nSMOOTH_RANGE = 5 #technically (range-1)/2\n\n################################################################################\n#### Animal class ####\n################################################################################\n\nclass Animal(object):\n\n def __init__(self, json_item):\n #.encode() all here because python 2's unicode handling drives me crazy\n self.name = json_item[\"name\"].encode()\n self.data_file = os.path.abspath(json_item[\"data_file_location\"].encode())\n self.filename = os.path.basename(self.data_file)\n self.animal_type = json_item[\"animal_attributes\"][\"species\"].encode()\n self.exp_type = json_item[\"animal_attributes\"][\"exp_type\"].encode()\n self.ID = json_item[\"animal_attributes\"][\"ID\"].encode()\n self.isControl = eval(json_item[\"animal_attributes\"][\"control_group\"])\n self.dim_x = json_item[\"capture_attributes\"][\"dim_x\"]\n self.dim_y = json_item[\"capture_attributes\"][\"dim_y\"]\n self.pix = json_item[\"capture_attributes\"][\"pixels_per_mm\"]\n self.frame_rate = json_item[\"capture_attributes\"][\"frames_per_sec\"]\n self.start = json_item[\"capture_attributes\"][\"start_time\"]\n self.end = json_item[\"capture_attributes\"][\"end_time\"]\n self.baseline_start = json_item[\"capture_attributes\"][\"baseline_start_time\"]\n self.baseline_end = json_item[\"capture_attributes\"][\"baseline_end_time\"]\n self.rawvals = {}\n #self.vals = {}\n self.means = {}\n self.stds = {}\n\n def getName(self):\n return self.name\n\n def getDataFileLocation(self):\n return self.data_file\n\n def getDataFileName(self):\n return self.filename\n\n def getAnimalType(self):\n return self.animal_type\n\n def getExpType(self):\n return self.exp_type\n\n def getID(self):\n return self.ID\n\n def getExpTimes(self):\n return (self.start, self.end)\n\n def getExpStartTime(self):\n return self.start\n\n def getExpEndTime(self):\n return self.end\n\n def getBaselineTimes(self):\n return (self.baseline_start, self.baseline_end)\n\n def getBaselineStartTime(self):\n return self.baseline_start\n\n def getBaselineEndTime(self):\n return self.baseline_end\n\n def inControlGroup(self):\n return self.isControl\n\n def getDims(self):\n return self.dim_x, self.dim_y\n\n def getPixelDensity(self):\n return self.pix\n\n def getFrameRate(self):\n return self.frame_rate\n\n #def addVals(self, varname, valList):\n # self.vals.update({varname:valList})\n\n #def getVals(self, varname):\n # return self.vals[varname]\n\n #def getMultVals(self, varnames):\n # return [self.vals[v] for v in varnames]\n\n def addRawVals(self, varname, valList):\n self.rawvals.update({varname:valList})\n\n def getRawVals(self, varname, start=None, end=None):\n #Note that start and end are in frames\n if start == None:\n start =self.start*60*self.frame_rate\n if end == None:\n end = self.end*60*self.frame_rate\n return self.rawvals[varname][start:end]\n\n def getMultRawVals(self, varnames, start=None, end=None):\n return [self.getRawVals(v,start,end) for v in varnames]\n\n def initStats(self, varname):\n self.means.update({varname:{}})\n self.stds.update({varname:{}})\n\n def addStats(self, varname, scope, start_frame, end_frame):\n if varname not in self.means:\n self.initStats(varname)\n m, s = norm(self.rawvals[varname][start_frame:end_frame])\n self.means[varname].update({scope:m})\n self.stds[varname].update({scope:s})\n\n def getStats(self, varname, scope):\n return self.means[varname][scope], self.stds[varname][scope]\n\n def setGridSize(self, grid_size):\n self.grid_size = grid_size\n num_x_grid = int(ceil(self.dim_x/grid_size))\n num_y_grid = int(ceil(self.dim_y/grid_size))\n self.setNumGrids(num_x_grid,num_y_grid)\n\n def getGridSize(self):\n return self.grid_size\n\n def setNumGrids(self, num_x_grid, num_y_grid):\n self.num_x_grid = num_x_grid\n self.num_y_grid = num_y_grid\n\n def getNumGrids(self):\n return self.num_x_grid, self.num_y_grid\n\n def setPerturbation(self, perturbation):\n self.perturbation = perturbation\n\n def getPerturbation(self):\n return self.perturbation\n\n def setConformalFactor(self, conformal_factor):\n self.conformal_factor = conformal_factor\n\n def getConformalFactor(self):\n return self.conformal_factor\n\n def setTolerance(self, tolerance):\n self.tolerance = tolerance\n\n def getTolerance(self):\n return self.tolerance\n\n def setNumVerts(self, n):\n self.numVerts = n\n\n def getNumVerts(self):\n return self.numVerts\n\n def setColors(self, colors):\n self.colors=colors\n\n def getColors(self):\n return self.colors\n\n def setRegularCoordinates(self, coordinates):\n self.regCoords = coordinates\n\n def getRegularCoordinates(self):\n return self.regCoords\n\n def setFlattenedCoordinates(self, coordinates):\n self.flatCoords = coordinates\n\n def getFlattenedCoordinates(self):\n return self.flatCoords\n\n def setTriangulation(self, triangles):\n self.triangulation = triangles\n\n def getTriangulation(self):\n return self.triangulation\n \n################################################################################\n### Basic Functions\n################################################################################\n\n\n# Sure, I suppose I could use the actual error handling, but...\ndef throwError(errmsg):\n print(\"ERROR: %s\" % errmsg)\n exit(1)\n\n\ndef getFrameNum(animal, t):\n#t is in minutes\n return int(animal.getFrameRate() * t * 60)\n\n\ndef findColIndex(header, colName):\n# Finds the column index of the given variable in the data\n# TO-DO: make this case insensitive\n pat = re.compile('^(\")*%s(\")*$' % colName)\n for i in range(len(header)):\n if re.match(pat, header[i]): return i\n # if we didn't find the index, the column name input is incorrect\n throwError(\"invalid column name: %s\" % colName)\n\n\n\ndef norm(data):\n dArr = np.array(data, dtype=np.float)\n m = np.mean(dArr)\n sd = np.std(dArr)\n return m, sd\n\n\ndef normalize(data, m, s):\n if s != 0: return map(lambda x: 1/(1 + math.exp(-(x-m)/s)), data)\n else: return [0 for d in data]\n\n \n \n################################################################################\n### Meat & Potatoes\n################################################################################\n\ndef readInfo(infile):\n with open(infile, 'r') as infofile:\n info = json.load(infofile)\n return info\n\n\ndef getRawData(animal, varnames = ['X','Y']):\n #read in X and Y values from the data file\n with open(animal.getDataFileLocation(), 'r') as infile:\n print(\"LOG: Extracting coordinates for Animal %s...\" % animal.getName())\n header = infile.readline()#.replace('\\r','').replace('\\n','')\n if '\\t' in header: delim = '\\t'\n elif ',' in header: delim = ','\n else: throwError(\"invalid data format\")\n\n header = map(lambda x: x.strip(), header.split(delim))\n try: # verify the file can be parsed\n reader = csv.reader(infile, delimiter = delim)\n except:\n throwError(\"invalid data format\")\n\n XInd = findColIndex(header, 'X')\n YInd = findColIndex(header, 'Y')\n X, Y = [], []\n start, end = animal.getExpTimes()\n start_frame = getFrameNum(animal, start)\n end_frame = getFrameNum(animal, end)\n\n for line, row in enumerate(reader):\n if line < start_frame: continue\n if line == end_frame: break \n x = row[XInd]\n y = row[YInd]\n if len(x)==0 or x==' ' or len(y)==0 or y ==' ':\n print(row)\n throwError(\"possible truncated data\")\n X.append(float(x)/animal.getPixelDensity()) #scaling for pixel density while we are at it\n Y.append(float(y)/animal.getPixelDensity()) \n\n #DEFN: baseline norm is where we take the stats from the first two minutes of the exp to get the \"baseline normal\" numbers\n #DEFN: exp norm is where we take the stats from the whole exp duration and take all 'local data' into consideration\n\n animal.addRawVals('X', X)\n animal.addRawVals('Y', Y)\n\n baseline_start, baseline_end = animal.getBaselineTimes()\n baseline_start_frame = getFrameNum(animal, baseline_start)\n baseline_end_frame = getFrameNum(animal, baseline_end)\n\n animal.addStats('X', 'baseline', baseline_start_frame, baseline_end_frame)\n animal.addStats('Y', 'baseline', baseline_start_frame, baseline_end_frame)\n\n\ndef getAnimalObjs(infofile, name_list = None):\n\n info = readInfo(infofile)\n if name_list != None:\n objs = [initAnimal(item) for item in info if item[\"name\"] in name_list]\n return objs\n else:\n return [initAnimal(item) for item in info]\n\n\ndef initAnimal(json_item):\n# Given a json entry, extracts the relevant information and returns an initialized animal object\n a = Animal(json_item)\n getRawData(a, ['X','Y'])\n return a\n"
] |
[
[
"numpy.std",
"numpy.array",
"numpy.mean"
]
] |
glmcdona/stable-baselines3-contrib
|
[
"91f9b1ed34fbaa9243a044ea67aa4c677663bfc2"
] |
[
"sb3_contrib/tqc/policies.py"
] |
[
"import warnings\nfrom typing import Any, Dict, List, Optional, Tuple, Type, Union\n\nimport gym\nimport torch as th\nfrom stable_baselines3.common.distributions import SquashedDiagGaussianDistribution, StateDependentNoiseDistribution\nfrom stable_baselines3.common.policies import BaseModel, BasePolicy, register_policy\nfrom stable_baselines3.common.preprocessing import get_action_dim\nfrom stable_baselines3.common.torch_layers import (\n BaseFeaturesExtractor,\n CombinedExtractor,\n FlattenExtractor,\n NatureCNN,\n create_mlp,\n get_actor_critic_arch,\n)\nfrom stable_baselines3.common.type_aliases import Schedule\nfrom torch import nn as nn\n\n# CAP the standard deviation of the actor\nLOG_STD_MAX = 2\nLOG_STD_MIN = -20\n\n\nclass Actor(BasePolicy):\n \"\"\"\n Actor network (policy) for TQC.\n\n :param observation_space: Obervation space\n :param action_space: Action space\n :param net_arch: Network architecture\n :param features_extractor: Network to extract features\n (a CNN when using images, a nn.Flatten() layer otherwise)\n :param features_dim: Number of features\n :param activation_fn: Activation function\n :param use_sde: Whether to use State Dependent Exploration or not\n :param log_std_init: Initial value for the log standard deviation\n :param full_std: Whether to use (n_features x n_actions) parameters\n for the std instead of only (n_features,) when using gSDE.\n :param sde_net_arch: Network architecture for extracting features\n when using gSDE. If None, the latent features from the policy will be used.\n Pass an empty list to use the states as features.\n :param use_expln: Use ``expln()`` function instead of ``exp()`` when using gSDE to ensure\n a positive standard deviation (cf paper). It allows to keep variance\n above zero and prevent it from growing too fast. In practice, ``exp()`` is usually enough.\n :param clip_mean: Clip the mean output when using gSDE to avoid numerical instability.\n :param normalize_images: Whether to normalize images or not,\n dividing by 255.0 (True by default)\n \"\"\"\n\n def __init__(\n self,\n observation_space: gym.spaces.Space,\n action_space: gym.spaces.Space,\n net_arch: List[int],\n features_extractor: nn.Module,\n features_dim: int,\n activation_fn: Type[nn.Module] = nn.ReLU,\n use_sde: bool = False,\n log_std_init: float = -3,\n full_std: bool = True,\n sde_net_arch: Optional[List[int]] = None,\n use_expln: bool = False,\n clip_mean: float = 2.0,\n normalize_images: bool = True,\n ):\n super(Actor, self).__init__(\n observation_space,\n action_space,\n features_extractor=features_extractor,\n normalize_images=normalize_images,\n squash_output=True,\n )\n\n # Save arguments to re-create object at loading\n self.use_sde = use_sde\n self.sde_features_extractor = None\n self.net_arch = net_arch\n self.features_dim = features_dim\n self.activation_fn = activation_fn\n self.log_std_init = log_std_init\n self.sde_net_arch = sde_net_arch\n self.use_expln = use_expln\n self.full_std = full_std\n self.clip_mean = clip_mean\n\n action_dim = get_action_dim(self.action_space)\n latent_pi_net = create_mlp(features_dim, -1, net_arch, activation_fn)\n self.latent_pi = nn.Sequential(*latent_pi_net)\n last_layer_dim = net_arch[-1] if len(net_arch) > 0 else features_dim\n\n if sde_net_arch is not None:\n warnings.warn(\"sde_net_arch is deprecated and will be removed in SB3 v2.4.0.\", DeprecationWarning)\n\n if self.use_sde:\n self.action_dist = StateDependentNoiseDistribution(\n action_dim, full_std=full_std, use_expln=use_expln, learn_features=True, squash_output=True\n )\n self.mu, self.log_std = self.action_dist.proba_distribution_net(\n latent_dim=last_layer_dim, latent_sde_dim=last_layer_dim, log_std_init=log_std_init\n )\n # Avoid numerical issues by limiting the mean of the Gaussian\n # to be in [-clip_mean, clip_mean]\n if clip_mean > 0.0:\n self.mu = nn.Sequential(self.mu, nn.Hardtanh(min_val=-clip_mean, max_val=clip_mean))\n else:\n self.action_dist = SquashedDiagGaussianDistribution(action_dim)\n self.mu = nn.Linear(last_layer_dim, action_dim)\n self.log_std = nn.Linear(last_layer_dim, action_dim)\n\n def _get_constructor_parameters(self) -> Dict[str, Any]:\n data = super()._get_constructor_parameters()\n\n data.update(\n dict(\n net_arch=self.net_arch,\n features_dim=self.features_dim,\n activation_fn=self.activation_fn,\n use_sde=self.use_sde,\n log_std_init=self.log_std_init,\n full_std=self.full_std,\n use_expln=self.use_expln,\n features_extractor=self.features_extractor,\n clip_mean=self.clip_mean,\n )\n )\n return data\n\n def get_std(self) -> th.Tensor:\n \"\"\"\n Retrieve the standard deviation of the action distribution.\n Only useful when using gSDE.\n It corresponds to ``th.exp(log_std)`` in the normal case,\n but is slightly different when using ``expln`` function\n (cf StateDependentNoiseDistribution doc).\n\n :return:\n \"\"\"\n msg = \"get_std() is only available when using gSDE\"\n assert isinstance(self.action_dist, StateDependentNoiseDistribution), msg\n return self.action_dist.get_std(self.log_std)\n\n def reset_noise(self, batch_size: int = 1) -> None:\n \"\"\"\n Sample new weights for the exploration matrix, when using gSDE.\n\n :param batch_size:\n \"\"\"\n msg = \"reset_noise() is only available when using gSDE\"\n assert isinstance(self.action_dist, StateDependentNoiseDistribution), msg\n self.action_dist.sample_weights(self.log_std, batch_size=batch_size)\n\n def get_action_dist_params(self, obs: th.Tensor) -> Tuple[th.Tensor, th.Tensor, Dict[str, th.Tensor]]:\n \"\"\"\n Get the parameters for the action distribution.\n\n :param obs:\n :return:\n Mean, standard deviation and optional keyword arguments.\n \"\"\"\n features = self.extract_features(obs)\n latent_pi = self.latent_pi(features)\n mean_actions = self.mu(latent_pi)\n\n if self.use_sde:\n return mean_actions, self.log_std, dict(latent_sde=latent_pi)\n # Unstructured exploration (Original implementation)\n log_std = self.log_std(latent_pi)\n # Original Implementation to cap the standard deviation\n log_std = th.clamp(log_std, LOG_STD_MIN, LOG_STD_MAX)\n return mean_actions, log_std, {}\n\n def forward(self, obs: th.Tensor, deterministic: bool = False) -> th.Tensor:\n mean_actions, log_std, kwargs = self.get_action_dist_params(obs)\n # Note: the action is squashed\n return self.action_dist.actions_from_params(mean_actions, log_std, deterministic=deterministic, **kwargs)\n\n def action_log_prob(self, obs: th.Tensor) -> Tuple[th.Tensor, th.Tensor]:\n mean_actions, log_std, kwargs = self.get_action_dist_params(obs)\n # return action and associated log prob\n return self.action_dist.log_prob_from_params(mean_actions, log_std, **kwargs)\n\n def _predict(self, observation: th.Tensor, deterministic: bool = False) -> th.Tensor:\n return self.forward(observation, deterministic)\n\n\nclass Critic(BaseModel):\n \"\"\"\n Critic network (q-value function) for TQC.\n\n :param observation_space: Obervation space\n :param action_space: Action space\n :param net_arch: Network architecture\n :param features_extractor: Network to extract features\n (a CNN when using images, a nn.Flatten() layer otherwise)\n :param features_dim: Number of features\n :param activation_fn: Activation function\n :param normalize_images: Whether to normalize images or not,\n dividing by 255.0 (True by default)\n :param share_features_extractor: Whether the features extractor is shared or not\n between the actor and the critic (this saves computation time)\n \"\"\"\n\n def __init__(\n self,\n observation_space: gym.spaces.Space,\n action_space: gym.spaces.Space,\n net_arch: List[int],\n features_extractor: nn.Module,\n features_dim: int,\n activation_fn: Type[nn.Module] = nn.ReLU,\n normalize_images: bool = True,\n n_quantiles: int = 25,\n n_critics: int = 2,\n share_features_extractor: bool = True,\n ):\n super().__init__(\n observation_space,\n action_space,\n features_extractor=features_extractor,\n normalize_images=normalize_images,\n )\n\n action_dim = get_action_dim(self.action_space)\n\n self.share_features_extractor = share_features_extractor\n self.q_networks = []\n self.n_quantiles = n_quantiles\n self.n_critics = n_critics\n self.quantiles_total = n_quantiles * n_critics\n\n for i in range(n_critics):\n qf_net = create_mlp(features_dim + action_dim, n_quantiles, net_arch, activation_fn)\n qf_net = nn.Sequential(*qf_net)\n self.add_module(f\"qf{i}\", qf_net)\n self.q_networks.append(qf_net)\n\n def forward(self, obs: th.Tensor, action: th.Tensor) -> List[th.Tensor]:\n # Learn the features extractor using the policy loss only\n # when the features_extractor is shared with the actor\n with th.set_grad_enabled(not self.share_features_extractor):\n features = self.extract_features(obs)\n qvalue_input = th.cat([features, action], dim=1)\n quantiles = th.stack(tuple(qf(qvalue_input) for qf in self.q_networks), dim=1)\n return quantiles\n\n\nclass TQCPolicy(BasePolicy):\n \"\"\"\n Policy class (with both actor and critic) for TQC.\n\n :param observation_space: Observation space\n :param action_space: Action space\n :param lr_schedule: Learning rate schedule (could be constant)\n :param net_arch: The specification of the policy and value networks.\n :param activation_fn: Activation function\n :param use_sde: Whether to use State Dependent Exploration or not\n :param log_std_init: Initial value for the log standard deviation\n :param sde_net_arch: Network architecture for extracting features\n when using gSDE. If None, the latent features from the policy will be used.\n Pass an empty list to use the states as features.\n :param use_expln: Use ``expln()`` function instead of ``exp()`` when using gSDE to ensure\n a positive standard deviation (cf paper). It allows to keep variance\n above zero and prevent it from growing too fast. In practice, ``exp()`` is usually enough.\n :param clip_mean: Clip the mean output when using gSDE to avoid numerical instability.\n :param features_extractor_class: Features extractor to use.\n :param features_extractor_kwargs: Keyword arguments\n to pass to the feature extractor.\n :param normalize_images: Whether to normalize images or not,\n dividing by 255.0 (True by default)\n :param optimizer_class: The optimizer to use,\n ``th.optim.Adam`` by default\n :param optimizer_kwargs: Additional keyword arguments,\n excluding the learning rate, to pass to the optimizer\n :param n_quantiles: Number of quantiles for the critic.\n :param n_critics: Number of critic networks to create.\n :param share_features_extractor: Whether to share or not the features extractor\n between the actor and the critic (this saves computation time)\n \"\"\"\n\n def __init__(\n self,\n observation_space: gym.spaces.Space,\n action_space: gym.spaces.Space,\n lr_schedule: Schedule,\n net_arch: Optional[Union[List[int], Dict[str, List[int]]]] = None,\n activation_fn: Type[nn.Module] = nn.ReLU,\n use_sde: bool = False,\n log_std_init: float = -3,\n sde_net_arch: Optional[List[int]] = None,\n use_expln: bool = False,\n clip_mean: float = 2.0,\n features_extractor_class: Type[BaseFeaturesExtractor] = FlattenExtractor,\n features_extractor_kwargs: Optional[Dict[str, Any]] = None,\n normalize_images: bool = True,\n optimizer_class: Type[th.optim.Optimizer] = th.optim.Adam,\n optimizer_kwargs: Optional[Dict[str, Any]] = None,\n n_quantiles: int = 25,\n n_critics: int = 2,\n share_features_extractor: bool = True,\n ):\n super(TQCPolicy, self).__init__(\n observation_space,\n action_space,\n features_extractor_class,\n features_extractor_kwargs,\n optimizer_class=optimizer_class,\n optimizer_kwargs=optimizer_kwargs,\n squash_output=True,\n )\n\n if net_arch is None:\n if features_extractor_class == NatureCNN:\n net_arch = []\n else:\n net_arch = [256, 256]\n\n actor_arch, critic_arch = get_actor_critic_arch(net_arch)\n\n self.net_arch = net_arch\n self.activation_fn = activation_fn\n self.net_args = {\n \"observation_space\": self.observation_space,\n \"action_space\": self.action_space,\n \"net_arch\": actor_arch,\n \"activation_fn\": self.activation_fn,\n \"normalize_images\": normalize_images,\n }\n self.actor_kwargs = self.net_args.copy()\n\n if sde_net_arch is not None:\n warnings.warn(\"sde_net_arch is deprecated and will be removed in SB3 v2.4.0.\", DeprecationWarning)\n\n sde_kwargs = {\n \"use_sde\": use_sde,\n \"log_std_init\": log_std_init,\n \"use_expln\": use_expln,\n \"clip_mean\": clip_mean,\n }\n self.actor_kwargs.update(sde_kwargs)\n self.critic_kwargs = self.net_args.copy()\n tqc_kwargs = {\n \"n_quantiles\": n_quantiles,\n \"n_critics\": n_critics,\n \"net_arch\": critic_arch,\n \"share_features_extractor\": share_features_extractor,\n }\n self.critic_kwargs.update(tqc_kwargs)\n self.actor, self.actor_target = None, None\n self.critic, self.critic_target = None, None\n self.share_features_extractor = share_features_extractor\n\n self._build(lr_schedule)\n\n def _build(self, lr_schedule: Schedule) -> None:\n self.actor = self.make_actor()\n self.actor.optimizer = self.optimizer_class(self.actor.parameters(), lr=lr_schedule(1), **self.optimizer_kwargs)\n\n if self.share_features_extractor:\n self.critic = self.make_critic(features_extractor=self.actor.features_extractor)\n # Do not optimize the shared features extractor with the critic loss\n # otherwise, there are gradient computation issues\n critic_parameters = [param for name, param in self.critic.named_parameters() if \"features_extractor\" not in name]\n else:\n # Create a separate features extractor for the critic\n # this requires more memory and computation\n self.critic = self.make_critic(features_extractor=None)\n critic_parameters = self.critic.parameters()\n\n # Critic target should not share the feature extactor with critic\n self.critic_target = self.make_critic(features_extractor=None)\n self.critic_target.load_state_dict(self.critic.state_dict())\n\n # Target networks should always be in eval mode\n self.critic_target.set_training_mode(False)\n\n self.critic.optimizer = self.optimizer_class(critic_parameters, lr=lr_schedule(1), **self.optimizer_kwargs)\n\n def _get_constructor_parameters(self) -> Dict[str, Any]:\n data = super()._get_constructor_parameters()\n\n data.update(\n dict(\n net_arch=self.net_arch,\n activation_fn=self.net_args[\"activation_fn\"],\n use_sde=self.actor_kwargs[\"use_sde\"],\n log_std_init=self.actor_kwargs[\"log_std_init\"],\n use_expln=self.actor_kwargs[\"use_expln\"],\n clip_mean=self.actor_kwargs[\"clip_mean\"],\n lr_schedule=self._dummy_schedule, # dummy lr schedule, not needed for loading policy alone\n optimizer_class=self.optimizer_class,\n optimizer_kwargs=self.optimizer_kwargs,\n features_extractor_class=self.features_extractor_class,\n features_extractor_kwargs=self.features_extractor_kwargs,\n n_quantiles=self.critic_kwargs[\"n_quantiles\"],\n n_critics=self.critic_kwargs[\"n_critics\"],\n )\n )\n return data\n\n def reset_noise(self, batch_size: int = 1) -> None:\n \"\"\"\n Sample new weights for the exploration matrix, when using gSDE.\n\n :param batch_size:\n \"\"\"\n self.actor.reset_noise(batch_size=batch_size)\n\n def make_actor(self, features_extractor: Optional[BaseFeaturesExtractor] = None) -> Actor:\n actor_kwargs = self._update_features_extractor(self.actor_kwargs, features_extractor)\n return Actor(**actor_kwargs).to(self.device)\n\n def make_critic(self, features_extractor: Optional[BaseFeaturesExtractor] = None) -> Critic:\n critic_kwargs = self._update_features_extractor(self.critic_kwargs, features_extractor)\n return Critic(**critic_kwargs).to(self.device)\n\n def forward(self, obs: th.Tensor, deterministic: bool = False) -> th.Tensor:\n return self._predict(obs, deterministic=deterministic)\n\n def _predict(self, observation: th.Tensor, deterministic: bool = False) -> th.Tensor:\n return self.actor(observation, deterministic)\n\n def set_training_mode(self, mode: bool) -> None:\n \"\"\"\n Put the policy in either training or evaluation mode.\n This affects certain modules, such as batch normalisation and dropout.\n :param mode: if true, set to training mode, else set to evaluation mode\n \"\"\"\n self.actor.set_training_mode(mode)\n self.critic.set_training_mode(mode)\n self.training = mode\n\n\nMlpPolicy = TQCPolicy\n\n\nclass CnnPolicy(TQCPolicy):\n \"\"\"\n Policy class (with both actor and critic) for TQC.\n\n :param observation_space: Observation space\n :param action_space: Action space\n :param lr_schedule: Learning rate schedule (could be constant)\n :param net_arch: The specification of the policy and value networks.\n :param activation_fn: Activation function\n :param use_sde: Whether to use State Dependent Exploration or not\n :param log_std_init: Initial value for the log standard deviation\n :param sde_net_arch: Network architecture for extracting features\n when using gSDE. If None, the latent features from the policy will be used.\n Pass an empty list to use the states as features.\n :param use_expln: Use ``expln()`` function instead of ``exp()`` when using gSDE to ensure\n a positive standard deviation (cf paper). It allows to keep variance\n above zero and prevent it from growing too fast. In practice, ``exp()`` is usually enough.\n :param clip_mean: Clip the mean output when using gSDE to avoid numerical instability.\n :param features_extractor_class: Features extractor to use.\n :param normalize_images: Whether to normalize images or not,\n dividing by 255.0 (True by default)\n :param optimizer_class: The optimizer to use,\n ``th.optim.Adam`` by default\n :param optimizer_kwargs: Additional keyword arguments,\n excluding the learning rate, to pass to the optimizer\n :param n_quantiles: Number of quantiles for the critic.\n :param n_critics: Number of critic networks to create.\n :param share_features_extractor: Whether to share or not the features extractor\n between the actor and the critic (this saves computation time)\n \"\"\"\n\n def __init__(\n self,\n observation_space: gym.spaces.Space,\n action_space: gym.spaces.Space,\n lr_schedule: Schedule,\n net_arch: Optional[Union[List[int], Dict[str, List[int]]]] = None,\n activation_fn: Type[nn.Module] = nn.ReLU,\n use_sde: bool = False,\n log_std_init: float = -3,\n sde_net_arch: Optional[List[int]] = None,\n use_expln: bool = False,\n clip_mean: float = 2.0,\n features_extractor_class: Type[BaseFeaturesExtractor] = NatureCNN,\n features_extractor_kwargs: Optional[Dict[str, Any]] = None,\n normalize_images: bool = True,\n optimizer_class: Type[th.optim.Optimizer] = th.optim.Adam,\n optimizer_kwargs: Optional[Dict[str, Any]] = None,\n n_quantiles: int = 25,\n n_critics: int = 2,\n share_features_extractor: bool = True,\n ):\n super(CnnPolicy, self).__init__(\n observation_space,\n action_space,\n lr_schedule,\n net_arch,\n activation_fn,\n use_sde,\n log_std_init,\n sde_net_arch,\n use_expln,\n clip_mean,\n features_extractor_class,\n features_extractor_kwargs,\n normalize_images,\n optimizer_class,\n optimizer_kwargs,\n n_quantiles,\n n_critics,\n share_features_extractor,\n )\n\n\nclass MultiInputPolicy(TQCPolicy):\n \"\"\"\n Policy class (with both actor and critic) for TQC.\n\n :param observation_space: Observation space\n :param action_space: Action space\n :param lr_schedule: Learning rate schedule (could be constant)\n :param net_arch: The specification of the policy and value networks.\n :param activation_fn: Activation function\n :param use_sde: Whether to use State Dependent Exploration or not\n :param log_std_init: Initial value for the log standard deviation\n :param sde_net_arch: Network architecture for extracting features\n when using gSDE. If None, the latent features from the policy will be used.\n Pass an empty list to use the states as features.\n :param use_expln: Use ``expln()`` function instead of ``exp()`` when using gSDE to ensure\n a positive standard deviation (cf paper). It allows to keep variance\n above zero and prevent it from growing too fast. In practice, ``exp()`` is usually enough.\n :param clip_mean: Clip the mean output when using gSDE to avoid numerical instability.\n :param features_extractor_class: Features extractor to use.\n :param normalize_images: Whether to normalize images or not,\n dividing by 255.0 (True by default)\n :param optimizer_class: The optimizer to use,\n ``th.optim.Adam`` by default\n :param optimizer_kwargs: Additional keyword arguments,\n excluding the learning rate, to pass to the optimizer\n :param n_quantiles: Number of quantiles for the critic.\n :param n_critics: Number of critic networks to create.\n :param share_features_extractor: Whether to share or not the features extractor\n between the actor and the critic (this saves computation time)\n \"\"\"\n\n def __init__(\n self,\n observation_space: gym.spaces.Space,\n action_space: gym.spaces.Space,\n lr_schedule: Schedule,\n net_arch: Optional[Union[List[int], Dict[str, List[int]]]] = None,\n activation_fn: Type[nn.Module] = nn.ReLU,\n use_sde: bool = False,\n log_std_init: float = -3,\n sde_net_arch: Optional[List[int]] = None,\n use_expln: bool = False,\n clip_mean: float = 2.0,\n features_extractor_class: Type[BaseFeaturesExtractor] = CombinedExtractor,\n features_extractor_kwargs: Optional[Dict[str, Any]] = None,\n normalize_images: bool = True,\n optimizer_class: Type[th.optim.Optimizer] = th.optim.Adam,\n optimizer_kwargs: Optional[Dict[str, Any]] = None,\n n_quantiles: int = 25,\n n_critics: int = 2,\n share_features_extractor: bool = True,\n ):\n super(MultiInputPolicy, self).__init__(\n observation_space,\n action_space,\n lr_schedule,\n net_arch,\n activation_fn,\n use_sde,\n log_std_init,\n sde_net_arch,\n use_expln,\n clip_mean,\n features_extractor_class,\n features_extractor_kwargs,\n normalize_images,\n optimizer_class,\n optimizer_kwargs,\n n_quantiles,\n n_critics,\n share_features_extractor,\n )\n\n\nregister_policy(\"MlpPolicy\", MlpPolicy)\nregister_policy(\"CnnPolicy\", CnnPolicy)\nregister_policy(\"MultiInputPolicy\", MultiInputPolicy)\n"
] |
[
[
"torch.nn.Sequential",
"torch.cat",
"torch.nn.Linear",
"torch.set_grad_enabled",
"torch.clamp",
"torch.nn.Hardtanh"
]
] |
liuruoze/Thought-SC2
|
[
"b3cfbeffbfa09b952c596805d2006af24613db2d",
"b3cfbeffbfa09b952c596805d2006af24613db2d"
] |
[
"TG-zerg and TG-Terran/Terran/lib/utils.py",
"TG-zerg and TG-Terran/Zerg/data_reduce/sample_data.py"
] |
[
"import os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.ndimage as ndimage\nfrom pysc2.lib import actions as sc2_actions\nfrom pysc2.lib import features\nimport lib.transform_pos as T\nfrom lib import config as C\n\n_MINIMAP_SELECTED = features.MINIMAP_FEATURES.selected.index\n_UNIT_TYPE = features.SCREEN_FEATURES.unit_type.index\n_HEIGHT_MAP = features.SCREEN_FEATURES.height_map.index\n_VISIABLE_MAP = features.SCREEN_FEATURES.visibility_map.index\n_RELATIVE = features.SCREEN_FEATURES.player_relative.index\n\n_ENEMY_INDEX = 4\n_PROBE_TYPE_INDEX = 84\n_PYLON_TYPE_INDEX = 60\n_FORGE_TYPE_INDEX = 63\n_CANNON_TYPE_INDEX = 66\n\n_MOVE_SCREEN = sc2_actions.FUNCTIONS.Move_screen.id\n_BUILD_PYLON = sc2_actions.FUNCTIONS.Build_Pylon_screen.id\n_BUILD_FORGE = sc2_actions.FUNCTIONS.Build_Forge_screen.id\n_BUILD_CANNON = sc2_actions.FUNCTIONS.Build_PhotonCannon_screen.id\n\n_ACTION_ARRAY = [_MOVE_SCREEN, _BUILD_PYLON, _BUILD_FORGE, _BUILD_CANNON]\n_ACTION_TYPE_NAME = [\"move\", \"build_pylon\", \"build_forge\", \"build_cannon\"]\n\n\ndef calculate_reward(obs):\n unit_type_map = obs.observation[\"screen\"][_UNIT_TYPE]\n\n pylon_mul = 1\n forge_mul = 5\n cannon_mul = 10\n\n reward = 0\n # reward += np.sum(unit_type_map == _PYLON_TYPE_INDEX) * pylon_mul\n reward += np.sum(unit_type_map == _FORGE_TYPE_INDEX) * forge_mul\n reward += np.sum(unit_type_map == _CANNON_TYPE_INDEX) * cannon_mul\n\n return reward\n\n\ndef get_reward(last_obs, now_obs):\n # reward rule: ( guess, still need to be done)\n # 1. pylon = 1\n # 2. forge = 5\n # 3. cannon = 10\n\n if now_obs.last():\n return 0\n\n last_obs_point = calculate_reward(last_obs)\n now_obs_point = calculate_reward(now_obs)\n reward = now_obs_point - last_obs_point - 1\n\n return reward\n\n\ndef pool_screen_power(power_map):\n pool_size = 4\n map_size = power_map.shape[0]\n\n out_size = map_size // pool_size\n out = np.zeros((out_size, out_size))\n\n for row_index in range(out_size):\n row_num = row_index * pool_size\n for col_index in range(out_size):\n col_num = col_index * pool_size\n out[row_index, col_index] = int(np.all(power_map[row_num:row_num + pool_size, col_num:col_num + 4]))\n\n return out\n\n\ndef get_power_mask_minimap(obs):\n minimap_camera = obs.observation[\"minimap\"][3]\n screen_power = obs.observation[\"screen\"][3]\n\n screen_unit_type = obs.observation[\"screen\"][_UNIT_TYPE]\n screen_unit = (screen_unit_type == 0).astype(\"int\")\n\n reduce_screen_power = np.logical_and(screen_power, screen_unit).astype(\"int\")\n trans_power = pool_screen_power(reduce_screen_power).reshape(-1)\n\n minimap_camera = minimap_camera.reshape(-1)\n minimap_camera[minimap_camera == 1] = trans_power\n\n return (minimap_camera == 1).astype(\"int\")\n\n\ndef dialted_unit(screen_unit, size=1):\n struct = ndimage.generate_binary_structure(2, 1)\n dialted_screen_unit = ndimage.binary_dilation(screen_unit,\n structure=struct, iterations=size).astype(screen_unit.dtype)\n return dialted_screen_unit\n\n\ndef dialted_area(area, size=1):\n struct = ndimage.generate_binary_structure(2, 1)\n dialted_area = ndimage.binary_dilation(area,\n structure=struct, iterations=size).astype(area.dtype)\n return dialted_area\n\n\ndef get_power_mask_screen(obs, size=None, show=False):\n screen_power = obs.observation[\"screen\"][3]\n screen_unit_type = obs.observation[\"screen\"][_UNIT_TYPE]\n screen_unit = (screen_unit_type != 0).astype(\"int\")\n area_1 = dialted_area(1 - get_available_area(obs), size=size)\n area_2 = dialted_area(screen_unit, size=size)\n area_3 = dialted_area(1 - screen_power, size=size)\n\n reduce_area = np.logical_and(1 - area_1, 1 - area_2).astype(\"int\")\n reduce_area = np.logical_and(reduce_area, 1 - area_3).astype(\"int\")\n\n if show:\n imgplot = plt.imshow(reduce_area)\n plt.show()\n return reduce_area.reshape(-1)\n\n\ndef get_pos(pos_prob_array):\n if pos_prob_array.sum() != 0:\n pos = np.random.choice(64 * 64, size=1, p=(pos_prob_array / pos_prob_array.sum()))\n else:\n pos = 0\n\n x = pos % 64\n y = pos // 64\n return [x, y]\n\n\ndef get_available_area(obs, show=False):\n height_type = obs.observation[\"screen\"][_HEIGHT_MAP].astype(\"int\")\n area_1 = (height_type == np.amax(height_type)).astype(\"int\")\n visiable_type = obs.observation[\"screen\"][_VISIABLE_MAP].astype(\"int\")\n area_2 = (visiable_type == np.amax(visiable_type)).astype(\"int\")\n available_area = np.logical_and(area_1, area_2).astype(\"int\")\n if show:\n imgplot = plt.imshow(available_area)\n plt.show()\n return available_area\n\n\ndef get_unit_mask_screen(obs, size=None, show=False):\n screen_unit_type = obs.observation[\"screen\"][_UNIT_TYPE]\n screen_unit = (screen_unit_type != 0).astype(\"int\")\n not_available_area = np.logical_or(1 - get_available_area(obs), screen_unit).astype(\"int\")\n if size:\n not_available_area = dialted_area(not_available_area, size=size)\n reduce_area = 1 - not_available_area\n if show:\n imgplot = plt.imshow(reduce_area)\n plt.show()\n return reduce_area.reshape(-1)\n\n\ndef check_unit(obs, index):\n val = False\n unit_set = obs.raw_observation.observation.raw_data.units\n for unit in unit_set:\n if unit.unit_type == index and unit.build_progress == 1:\n val = True\n break\n return val\n\n\ndef find_unit(obs, index):\n unit_set = obs.raw_observation.observation.raw_data.units\n for unit in unit_set:\n if unit.unit_type == index and unit.build_progress == 1:\n return unit\n\n return None\n\n\ndef find_unit_on_screen(obs, index):\n unit_set = obs.raw_observation.observation.raw_data.units\n for unit in unit_set:\n if unit.unit_type == index and unit.build_progress == 1 and unit.is_on_screen:\n return unit\n\n return None\n\n\ndef find_unit_by_tag(obs, tag):\n unit_set = obs.raw_observation.observation.raw_data.units\n for unit in unit_set:\n if unit.tag == tag:\n return unit\n\n return None\n\n\ndef check_base_camera(game_info, obs):\n camera_world_pos = obs.raw_observation.observation.raw_data.player.camera\n camera_minimap_pos = T.world_to_minimap_pos(game_info, camera_world_pos)\n # print(camera_minimap_pos)\n if camera_minimap_pos == C.base_camera_pos:\n return True\n return False\n\n\ndef get_minimap_data(timestep, verbose=False):\n obs = timestep\n map_width = 64\n relative_type_map = obs.observation[\"minimap\"][C._M_RELATIVE_TYPE].reshape(-1, map_width, map_width) / 255\n if verbose:\n imgplot = plt.imshow(relative_type_map[0])\n plt.show()\n visiable_type_map = obs.observation[\"minimap\"][C._M_VISIABLE_TYPE].reshape(-1, map_width, map_width) / 255\n player_id_map = obs.observation[\"minimap\"][C._M_PLAYID_TYPE].reshape(-1, map_width, map_width) / 255\n if verbose:\n imgplot = plt.imshow(visiable_type_map[0])\n plt.show()\n if verbose:\n imgplot = plt.imshow(player_id_map[0])\n plt.show()\n map_data = np.concatenate([relative_type_map, visiable_type_map, player_id_map], axis=0)\n return map_data\n\n\ndef find_gas(obs, index):\n # index == 1 or 2\n unit_set = obs.raw_observation.observation.raw_data.units\n for unit in unit_set:\n if unit.unit_type == C._ASSIMILATOR_TYPE_INDEX:\n if index == 1 and unit.pos.x == 21.5:\n return unit\n if index == 2 and unit.pos.x == 31.5:\n return unit\n return None\n\n\ndef find_gas_pos(obs, index):\n # index == 1 or 2\n unit_set = obs.raw_observation.observation.raw_data.units\n for unit in unit_set:\n if unit.unit_type == C._GAS_TYPE_INDEX:\n if index == 1 and unit.pos.x == 21.5:\n return unit\n if index == 2 and unit.pos.x == 31.5:\n return unit\n return None\n\n\ndef get_unit_num(obs, unit_type):\n num = 0\n unit_set = obs.raw_observation.observation.raw_data.units\n for unit in unit_set:\n if unit.unit_type == unit_type:\n num += 1\n\n return num\n\n\ndef get_unit_num_array(obs, unit_type_list):\n num_array = np.zeros(len(unit_type_list))\n\n unit_set = obs.raw_observation.observation.raw_data.units\n for unit in unit_set:\n if unit.unit_type in unit_type_list:\n num_array[unit_type_list.index(unit.unit_type)] += 1\n\n return np.array(num_array)\n\n\ndef get_units(obs, unit_type):\n unit_list = []\n unit_set = obs.raw_observation.observation.raw_data.units\n for unit in unit_set:\n if unit.unit_type == unit_type:\n unit_list.append(unit)\n\n return unit_list\n\n\ndef check_action_array_avail(obs, action_array):\n val = []\n avail_actions = obs.observation[\"available_actions\"]\n for action in action_array:\n if action in avail_actions:\n val.append(1)\n else:\n val.append(0)\n return val\n\n\ndef check_tech_action(obs, action_id):\n unit_set = obs.raw_observation.observation.raw_data.units\n for unit in unit_set:\n if unit.orders:\n if unit.orders[0].ability_id == action_id:\n return True\n\n return False\n\n\ndef get_tech_action_num(obs, action_id):\n num = 0\n unit_set = obs.raw_observation.observation.raw_data.units\n for unit in unit_set:\n if unit.orders:\n if unit.orders[0].ability_id == action_id:\n num += 1\n\n return num\n\n\ndef get_unseen_enemy(obs):\n unit_set = obs.raw_observation.observation.raw_data.units\n for unit in unit_set:\n if unit.alliance == _ENEMY_INDEX and unit.is_on_screen == False:\n return unit\n return None\n\n\ndef get_enemy_num(obs):\n num = 0\n unit_set = obs.raw_observation.observation.raw_data.units\n for unit in unit_set:\n if unit.alliance == _ENEMY_INDEX:\n num += 1\n return num\n\n\ndef judge_gas_worker_too_many(obs):\n gas_1 = find_gas(obs, 1)\n gas_2 = find_gas(obs, 2)\n have_gas_1, have_gas_2 = 0, 0\n if gas_1:\n if gas_1.assigned_harvesters > gas_1.ideal_harvesters:\n have_gas_1 = 1\n if gas_2:\n if gas_2.assigned_harvesters > gas_2.ideal_harvesters:\n have_gas_2 = 1\n if have_gas_1 + have_gas_2 > 0:\n return True\n else:\n return False\n\n\ndef judge_gas_worker(obs, game_info):\n gas_1 = find_gas(obs, 1)\n gas_2 = find_gas(obs, 2)\n if gas_1:\n a = gas_1.assigned_harvesters\n i = gas_1.ideal_harvesters\n if a < i:\n return T.world_to_screen_pos(game_info, gas_1.pos, obs)\n # return C.gas1_pos\n if gas_2:\n a = gas_2.assigned_harvesters\n i = gas_2.ideal_harvesters\n if a < i:\n return T.world_to_screen_pos(game_info, gas_2.pos, obs)\n # return C.gas2_pos\n\n return None\n\n\ndef get_gas_probe(obs):\n # if have resources, back to base\n buff = None\n unit_set = obs.raw_observation.observation.raw_data.units\n\n for unit in unit_set:\n if unit.unit_type == C._PROBE_TYPE_INDEX and unit.is_on_screen == True:\n buff = unit.buff_ids\n # [274] gas \n # [271] mineal\n if buff and buff[0] == 274:\n return unit\n\n\ndef get_mineral_probe(obs):\n # if have resources, back to base\n buff = None\n unit_set = obs.raw_observation.observation.raw_data.units\n\n for unit in unit_set:\n if unit.unit_type == C._PROBE_TYPE_INDEX and unit.is_on_screen == True:\n buff = unit.buff_ids\n # [274] gas\n # [271] mineral\n if buff and buff[0] == 271:\n return unit\n\n\ndef get_gas_probe(obs):\n # if have resources, back to base\n buff = None\n unit_set = obs.raw_observation.observation.raw_data.units\n\n for unit in unit_set:\n if unit.unit_type == C._PROBE_TYPE_INDEX and unit.is_on_screen == True:\n buff = unit.buff_ids\n # [274] gas\n # [271] mineal\n if buff and buff[0] == 274:\n return unit\n\n\ndef get_back_pos(obs, game_info):\n # if have resources, back to base\n buff = None\n unit_set = obs.raw_observation.observation.raw_data.units\n for unit in unit_set:\n if unit.unit_type == C._PROBE_TYPE_INDEX and unit.is_selected == True:\n buff = unit.buff_ids\n # print('buff:', buff)\n\n if buff and buff[0] > 0:\n # return C.base_pos\n base = find_unit_on_screen(obs, C._NEXUS_TYPE_INDEX)\n base_pos = T.world_to_screen_pos(game_info, base.pos, obs) if base else None\n return base_pos\n\n base = find_unit_on_screen(obs, C._NEXUS_TYPE_INDEX)\n # number of probe for mineral and the ideal num\n if base:\n a = base.assigned_harvesters\n i = base.ideal_harvesters\n if a < i:\n mineral = find_unit_on_screen(obs, C._MINERAL_TYPE_INDEX)\n mineral_pos = T.world_to_screen_pos(game_info, mineral.pos, obs) if mineral else None\n return mineral_pos\n # return C.mineral_pos\n\n gas_1 = find_gas(obs, 1)\n gas_2 = find_gas(obs, 2)\n if gas_1:\n a = gas_1.assigned_harvesters\n i = gas_1.ideal_harvesters\n if a < i:\n return T.world_to_screen_pos(game_info, gas_1.pos, obs)\n # return C.gas1_pos\n if gas_2:\n a = gas_2.assigned_harvesters\n i = gas_2.ideal_harvesters\n if a < i:\n return T.world_to_screen_pos(game_info, gas_2.pos, obs)\n # return C.gas2_pos\n return T.world_to_screen_pos(game_info, base.pos, obs) if base else None\n # return C.mineral_pos\n\n\ndef get_production_num(obs, train_order_list):\n num_list = np.zeros(len(train_order_list))\n\n unit_set = obs.raw_observation.observation.raw_data.units\n for unit in unit_set:\n if unit.alliance == 1 and unit.orders:\n for order in unit.orders:\n if order.ability_id in train_order_list:\n index = train_order_list.index(order.ability_id)\n num_list[index] += 1\n\n return num_list\n\n\ndef get_best_gateway(obs):\n unit_set = obs.raw_observation.observation.raw_data.units\n best_unit = None\n\n for unit in unit_set:\n if unit.unit_type == C._GATEWAY_TYPE_INDEX and unit.build_progress == 1:\n if (not best_unit) or (not unit.orders) or len(best_unit.orders) > len(unit.orders):\n best_unit = unit\n if not best_unit.orders:\n return best_unit\n\n return best_unit\n\n\ndef get_attack_num(obs, army_index_list):\n unit_set = obs.raw_observation.observation.raw_data.units\n num = 0\n\n for unit in unit_set:\n if unit.unit_type in army_index_list:\n if unit.orders:\n for order in unit.orders:\n if order.ability_id == C._A_ATTACK_ATTACK_MINIMAP_S:\n num += 1\n\n return num\n\n\ndef get_map_data(obs):\n map_width = 64\n m_height = obs.observation[\"minimap\"][C._M_HEIGHT].reshape(-1, map_width, map_width) / 255\n m_visible = obs.observation[\"minimap\"][C._M_VISIBILITY].reshape(-1, map_width, map_width) / 2\n m_camera = obs.observation[\"minimap\"][C._M_CAMERA].reshape(-1, map_width, map_width)\n m_relative = obs.observation[\"minimap\"][C._M_RELATIVE].reshape(-1, map_width, map_width) / 4\n m_selected = obs.observation[\"minimap\"][C._M_SELECTED].reshape(-1, map_width, map_width)\n\n s_relative = obs.observation[\"screen\"][C._S_RELATIVE].reshape(-1, map_width, map_width) / 4\n s_selected = obs.observation[\"screen\"][C._S_SELECTED].reshape(-1, map_width, map_width)\n s_hitpoint = obs.observation[\"screen\"][C._S_HITPOINT_R].reshape(-1, map_width, map_width) / 255\n s_shield = obs.observation[\"screen\"][C._S_SHIELD_R].reshape(-1, map_width, map_width) / 255\n s_density = obs.observation[\"screen\"][C._S_DENSITY_A].reshape(-1, map_width, map_width) / 255\n\n map_data = np.concatenate([m_height, m_visible, m_camera, m_relative, m_selected,\n s_relative, s_selected, s_hitpoint, s_shield, s_density], axis=0)\n return map_data\n\n\ndef get_input(obs):\n high_input = np.zeros([C._SIZE_HIGH_NET_INPUT])\n tech_cost = np.zeros([C._SIZE_TECH_NET_INPUT])\n pop_num = np.zeros([C._SIZE_POP_NET_INPUT])\n\n # ################################### high input ##########################################\n high_input[0] = C.difficulty\n # time\n high_input[1] = int(obs.raw_observation.observation.game_loop)\n # minerals\n high_input[2] = obs.raw_observation.observation.player_common.minerals\n # gas\n high_input[3] = obs.raw_observation.observation.player_common.vespene\n # mineral cost\n high_input[4] = obs.raw_observation.observation.score.score_details.spent_minerals\n # gas cost\n high_input[5] = obs.raw_observation.observation.score.score_details.spent_vespene\n # others\n player_common = obs.raw_observation.observation.player_common\n high_input[6] = player_common.food_cap\n high_input[7] = player_common.food_used\n high_input[8] = player_common.food_army\n high_input[9] = player_common.food_workers\n high_input[10] = player_common.army_count\n # num of probe, zealot, stalker, pylon, assimilator, gateway, cyber\n index_list = [C._PROBE_TYPE_INDEX, C._ZEALOT_TYPE_INDEX, C._STALKER_TYPE_INDEX,\n C._PYLON_TYPE_INDEX, C._ASSIMILATOR_TYPE_INDEX, C._GATEWAY_TYPE_INDEX, C._CYBER_TYPE_INDEX]\n high_input[11:18] = get_unit_num_array(obs, index_list)\n\n high_input[18] = get_attack_num(obs, [C._ZEALOT_TYPE_INDEX, C._STALKER_TYPE_INDEX])\n\n # print('high_input:', high_input)\n\n # ################################## tech cost ###############################################\n # cost of pylon vespene gateway cyber\n tech_cost[:4] = [100, 75, 150, 150]\n tech_cost[4] = player_common.food_cap - player_common.food_used\n tech_cost[5] = get_tech_action_num(obs, C._A_BUILD_PYLON_S)\n tech_cost[6] = get_tech_action_num(obs, C._A_BUILD_ASSIMILATOR_S)\n tech_cost[7] = get_tech_action_num(obs, C._A_BUILD_GATEWAY_S)\n tech_cost[8] = get_tech_action_num(obs, C._A_BUILD_CYBER_S)\n\n # ################################# pop num #################################################\n base = find_unit(obs, C._NEXUS_TYPE_INDEX)\n # number of probe for mineral and the ideal num\n if base:\n pop_num[0] = base.assigned_harvesters\n pop_num[1] = base.ideal_harvesters\n\n gas_1 = find_gas(obs, 1)\n gas_2 = find_gas(obs, 2)\n have_gas_1, have_gas_2 = 0, 0\n if gas_1:\n pop_num[2] = gas_1.assigned_harvesters\n pop_num[3] = gas_1.ideal_harvesters\n have_gas_1 = 1\n if gas_2:\n pop_num[4] = gas_2.assigned_harvesters\n pop_num[5] = gas_2.ideal_harvesters\n have_gas_2 = 1\n\n # all the num of workers\n pop_num[6] = player_common.food_army / max(player_common.food_workers, 1)\n\n pop_num[7] = have_gas_1\n pop_num[8] = have_gas_2\n\n # num of the training probe, zealot, stalker\n production_list = get_production_num(obs, [C._A_TRAIN_PROBE, C._A_TRAIN_ZEALOT, C._A_TRAIN_STALKER])\n pop_num[9] = production_list[0]\n pop_num[10] = production_list[1]\n pop_num[11] = production_list[2]\n\n # pop_num[[12, 13, 14]] = [50, 100, 125]\n\n return high_input, tech_cost, pop_num\n\n\ndef get_production_num_and_progress(obs, train_order_list):\n num_list = np.zeros(len(train_order_list))\n progress_list = np.zeros(len(train_order_list))\n\n unit_set = obs.raw_observation.observation.raw_data.units\n for unit in unit_set:\n if unit.alliance == 1 and unit.orders:\n for order in unit.orders:\n if order.ability_id in train_order_list:\n index = train_order_list.index(order.ability_id)\n num_list[index] += 1\n if order.progress > progress_list[index]:\n progress_list[index] = int(order.progress * 100)\n\n return num_list, progress_list\n\n\ndef get_unit_num_and_progress(obs, unit_type_list):\n num_array = np.zeros(len(unit_type_list))\n progress_list = np.zeros(len(unit_type_list))\n\n unit_set = obs.raw_observation.observation.raw_data.units\n for unit in unit_set:\n if unit.unit_type in unit_type_list:\n index = unit_type_list.index(unit.unit_type)\n if unit.build_progress == 1.0:\n num_array[index] += 1\n elif unit.build_progress > progress_list[index]:\n progress_list[index] = int(unit.build_progress * 100)\n\n return num_array, progress_list\n\n\ndef predict_state_diff_by_rule(state, action):\n simple_input = state\n\n # always add 2 seconds\n time = simple_input[0]\n\n minerals = simple_input[1]\n food_workers = simple_input[2]\n on_build_probe_num = simple_input[3]\n first_probe_progress = simple_input[4]\n\n pylon_build_order = simple_input[5]\n pylon_num = simple_input[6]\n first_pylon_progress = simple_input[7]\n\n food_cap = simple_input[8]\n food_used = simple_input[9]\n\n # now rule the diff of state\n diff_state = np.zeros([C._SIZE_SIMPLE_INPUT])\n\n # every two seconds probe progress add 15 percent\n probe_move = 15\n # every two seconds pylon progress add 11 percent\n pylon_move = 11\n probe_price = 50\n pylon_price = 100\n\n diff_time = +2\n diff_mineral = 0\n diff_food_workers = 0\n if first_probe_progress + probe_move >= 100:\n diff_food_workers += 1\n\n diff_on_build_probe_num = 0\n if action == 1 and minerals > probe_price and on_build_probe_num < 5 and food_used < food_cap:\n diff_on_build_probe_num += 1\n diff_mineral -= probe_price\n if first_probe_progress + probe_move >= 100:\n diff_on_build_probe_num -= 1\n\n diff_first_probe_progress = 0\n if on_build_probe_num >= 1:\n new_probe_progress = first_probe_progress + probe_move\n if new_probe_progress >= 100:\n new_probe_progress -= 100\n diff_first_probe_progress = new_probe_progress - first_probe_progress\n\n diff_pylon_num = 0\n if first_pylon_progress + pylon_move >= 100:\n diff_pylon_num += 1\n\n diff_pylon_build_order = 0\n if action == 2 and minerals > pylon_price:\n diff_pylon_build_order += 1\n diff_mineral -= pylon_price\n elif pylon_build_order > 0:\n diff_pylon_build_order -= 1\n\n diff_first_pylon_progress = 0\n if diff_pylon_build_order < 0 or first_pylon_progress > 0:\n new_pylon_progress = first_pylon_progress + pylon_move\n if new_pylon_progress >= 100:\n new_pylon_progress = 0\n diff_first_pylon_progress = new_pylon_progress - first_pylon_progress\n\n diff_food_cup = 0\n if first_pylon_progress + pylon_move >= 100:\n diff_food_cup += 8\n\n diff_food_used = 0\n # if action == 1 and food_used < food_cap and minerals > probe_price and on_build_probe_num < 5:\n if on_build_probe_num > 1 and first_probe_progress + probe_move > 100:\n diff_food_used += 1\n\n diff_state[0] = diff_time\n diff_state[1] = diff_mineral # use model to predict minerals\n diff_state[2] = diff_food_workers\n diff_state[3] = diff_on_build_probe_num\n diff_state[4] = diff_first_probe_progress\n diff_state[5] = diff_pylon_build_order\n diff_state[6] = diff_pylon_num\n diff_state[7] = diff_first_pylon_progress\n diff_state[8] = diff_food_cup\n diff_state[9] = diff_food_used\n return diff_state\n\n\nGAME_INITIAL_SIMPLE_STATE = np.array([0, 50, 12, 0, 0, 0, 0, 0, 15, 12])\n\n\ndef get_simple_state(obs):\n simple_input = np.zeros([C._SIZE_SIMPLE_INPUT])\n\n # minerals and object\n simple_input[0] = int(obs.raw_observation.observation.game_loop // 22.4)\n simple_input[1] = obs.raw_observation.observation.player_common.minerals\n simple_input[2] = obs.raw_observation.observation.player_common.food_workers\n\n # hidden information 1, probe building and progress\n production_list, progress_list = get_production_num_and_progress(obs, [C._A_TRAIN_PROBE, C._A_BUILD_PYLON_S])\n simple_input[3] = production_list[0]\n simple_input[4] = progress_list[0]\n\n # hidden information 2, probe order to build a pylon\n simple_input[5] = production_list[1]\n\n # hidden information 3, pylon building (100%) and the first one progress\n unit_production_list, unit_progress_list = get_unit_num_and_progress(obs, [C._PYLON_TYPE_INDEX])\n simple_input[6] = unit_production_list[0]\n simple_input[7] = unit_progress_list[0]\n\n player_common = obs.raw_observation.observation.player_common\n simple_input[8] = player_common.food_cap\n simple_input[9] = player_common.food_used\n\n return simple_input\n",
"import numpy as np\nfrom pysc2.lib import point\nfrom pysc2.lib import transform\n\n\ndef func3(name, type_num, train_ratio):\n orders = np.loadtxt(\"../data/new_data/\" + name + \".txt\")\n for i in range(10):\n np.random.shuffle(orders)\n\n seperate_index = int(len(orders) * train_ratio)\n orders_train = orders[:seperate_index, :]\n orders_val = orders[seperate_index:, :]\n func4(orders_train, name, type_num, 'train')\n func4(orders_val, name, type_num, 'val')\n\n\ndef func4(orders, name, type_num, save_name):\n label = orders[:, -3:]\n\n # high_goal: 0, 1, 2\n label_index, label_count = [], []\n for i in range(type_num):\n label_index.append(np.where(label[:, i])[0])\n label_count.append(len(label_index[i]))\n\n sample_num = max(label_count)\n print(\"sample_num:\", sample_num)\n label_index_sample = np.array([])\n for i in range(type_num):\n label_index_sample = np.append(label_index_sample, label_index[i])\n add_data = np.random.choice(label_index[i], sample_num - len(label_index[i]))\n label_index_sample = np.append(label_index_sample, add_data)\n\n for i in range(10):\n np.random.shuffle(label_index_sample)\n\n order_sample = orders[label_index_sample.astype('int'), :]\n np.savetxt('../data/new_data/' + name + '_' + save_name + '.txt', order_sample)\n\n\ndef func1(name, type_num):\n orders = np.loadtxt(\"../data/new_data/\" + name + \".txt\")\n label = orders[:, -3:]\n\n # high_goal: 0, 1, 2\n label_index, label_count = [], []\n for i in range(type_num):\n label_index.append(np.where(label[:, i])[0])\n label_count.append(len(label_index[i]))\n\n sample_num = max(label_count)\n print(\"sample_num:\", sample_num)\n label_index_sample = np.array([])\n for i in range(type_num):\n label_index_sample = np.append(label_index_sample, label_index[i])\n add_data = np.random.choice(label_index[i], sample_num - len(label_index[i]))\n label_index_sample = np.append(label_index_sample, add_data)\n\n for i in range(10):\n np.random.shuffle(label_index_sample)\n\n order_sample = orders[label_index_sample.astype('int'), :]\n np.savetxt('../data/new_data/' + name + '_sample.txt', order_sample)\n\n\ndef func2(name, type_num):\n orders = np.loadtxt(\"../data/new_data/\" + name + \".txt\")\n label = orders[:, -1]\n\n label_index, label_count = [], []\n for i in range(type_num):\n label_index.append(np.where(label == i)[0])\n label_count.append(len(label_index[i]))\n print(i, \":\", len(label_index[i]))\n\n sample_num = 20000\n print(\"sample_num:\", sample_num)\n label_index_sample = np.array([])\n for i in range(type_num):\n label_index_sample = np.append(label_index_sample, label_index[i])\n add_data = np.random.choice(label_index[i], sample_num - len(label_index[i]))\n label_index_sample = np.append(label_index_sample, add_data)\n\n for i in range(10):\n np.random.shuffle(label_index_sample)\n\n order_sample = orders[label_index_sample.astype('int'), :]\n np.savetxt('../data/new_data/' + name + '_sample.txt', order_sample)\n\n\nif __name__ == \"__main__\":\n # func3('high', 3, 0.7)\n # func2('tech', 4)\n func2('pop', 5)\n"
] |
[
[
"matplotlib.pyplot.imshow",
"numpy.amax",
"numpy.logical_and",
"scipy.ndimage.generate_binary_structure",
"numpy.concatenate",
"numpy.all",
"scipy.ndimage.binary_dilation",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"matplotlib.pyplot.show"
],
[
"numpy.random.shuffle",
"numpy.append",
"numpy.savetxt",
"numpy.array",
"numpy.where",
"numpy.loadtxt"
]
] |
balaz94/FRI-RL-SC2
|
[
"eaf2103265a999a16e786da134810681bf0266a0"
] |
[
"utils/init.py"
] |
[
"import torch.nn.init as init\n\ndef weights_init_xavier(layer):\n classname = layer.__class__.__name__\n if classname.find('Conv') != -1 or classname.find('Linear') != -1:\n init.xavier_uniform_(layer.weight)\n init.zeros_(layer.bias)\n\ndef weights_init_orthogonal_head(layer):\n classname = layer.__class__.__name__\n if classname.find('Conv') != -1 or classname.find('Linear') != -1:\n init.orthogonal_(layer.weight, 0.01)\n init.zeros_(layer.bias)\n\ndef weights_init_orthogonal_features(layer):\n classname = layer.__class__.__name__\n if classname.find('Conv') != -1 or classname.find('Linear') != -1:\n init.orthogonal_(layer.weight, 2**0.5)\n init.zeros_(layer.bias)\n"
] |
[
[
"torch.nn.init.zeros_",
"torch.nn.init.orthogonal_",
"torch.nn.init.xavier_uniform_"
]
] |
clwatkins/sec_edgar_parser
|
[
"6ccf74eae14407e64ad033bb74d422d7f1c91495"
] |
[
"secparse/sec_parse.py"
] |
[
"import sys\nimport platform\nimport time\nimport os\nimport multiprocessing\nfrom typing import List, Union, Optional\n\nfrom numpy import ndarray\nfrom sqlalchemy import distinct, func, and_\nimport feedparser\nimport requests as rq\nfrom ssl import SSLError\nfrom urllib3.exceptions import MaxRetryError\nfrom xlrd.biffh import XLRDError\nimport bs4\nimport pandas as pd\nimport click\n\nfrom .apis import api_name_to_ticker, api_cik_to_info\nfrom .db import EdgarDatabase, FilingInfo, CompanyInfo, SicInfo\nfrom .utilities import *\n\n\n# Click helper function for command line interface\n@click.group()\ndef cli():\n \"\"\"Basic command line tool for parsing accounting terms pulled from filings on the SEC's Edgar website.\\n\"\"\"\n if sys.version_info[0] + sys.version_info[1]/10 < 3.6:\n raise Exception(\"Python 3.6 or a more recent version is required.\")\n\n make_folders()\n _build_sic_table()\n print(\"\\n\")\n\n\n@cli.command()\n@click.option('--manual', default=False, is_flag=True, help='Download filing data for a specific month.')\n@click.option('--get_company_info', default=True, is_flag=True, help='Attempt to find additional information '\n 'about companies that have filed.')\ndef update_filings(manual, get_company_info, print_data=True, bisection_search=True,\n db_write=True, update_timeframe=10):\n \"\"\"\n Pulls filing information from Edgar, storing metadata locally, as well as pointers to\n Excel files containing filing financials.\n \"\"\"\n\n # Allows user to specify month to get data from\n if manual:\n print('\\nEnter 4-digit year and 2-digit month:')\n year = click.prompt('Year', type=int)\n month = click.prompt('Month', type=int)\n bisection_search = False\n\n else:\n print(f\"\\nFinding new filings in the SEC's Edgar database over the past {update_timeframe} days.\")\n\n year = dt.datetime.now().year\n month = dt.datetime.now().month\n\n # use bisection search to cut down the number of entries passed to the database for writing\n if bisection_search:\n\n # suppress printing results until we've cut the number of filings to display\n rss_data = _download_filings(year, month, print_data=False)\n\n if not rss_data:\n print('\\nNo filings found for this month. Please use the manual download feature.')\n sys.exit(0)\n\n # set acceptable margin of error for our search algorithm\n margin_error = dt.timedelta(hours=12)\n min_i = 0\n\n max_i = len(rss_data)\n\n date_to_find = dt.datetime.now() - dt.timedelta(days=update_timeframe)\n guess_i = (min_i + max_i) // 2\n guess_date = dt.datetime.strptime(rss_data[guess_i]['edgar_acceptancedatetime'], '%Y%m%d%H%M%S')\n loop_num = 0\n\n while abs(date_to_find - guess_date) >= margin_error and loop_num <= 20:\n guess_date = dt.datetime.strptime(rss_data[guess_i]['edgar_acceptancedatetime'], '%Y%m%d%H%M%S')\n\n if guess_date < date_to_find:\n max_i = guess_i\n else:\n min_i = guess_i\n\n guess_i = (min_i + max_i) // 2\n loop_num += 1\n\n # cuts rss_data list to include only those filings that are more recent than date_to_find\n rss_data = rss_data[:guess_i]\n\n if print_data:\n print(f'\\n{len(rss_data)} filings submitted since '\n f'{dt.datetime.strftime(date_to_find, \"%Y-%m-%d %H:%M:%S\")}:')\n print('')\n print('Company Name'.ljust(30), 'CIK'.ljust(10), 'Period'.ljust(10), 'Form Type'.ljust(10), sep=' | ')\n print('-' * 80)\n\n for item in rss_data:\n name = re.sub(\"[^a-zA-Z ]+\", \"\", item['edgar_companyname']).replace(\" \", \" \").title()\n cik = item['edgar_ciknumber']\n form = item['edgar_formtype']\n try:\n period = dt.datetime.strftime(dt.datetime.strptime(item['edgar_period'], '%Y%m%d'), '%m/%d/%Y')\n except KeyError:\n period = ''\n\n print(name[:30].ljust(30), cik.ljust(10), period.ljust(10), form.ljust(10), sep=' | ')\n\n # if we're not using bisection search (aka not just refreshing the database for the first time in a couple of days),\n # simply call dl_filings respecting print_data state\n else:\n rss_data = _download_filings(year, month, print_data)\n\n if db_write:\n _update_filings(rss_data, get_company_info)\n else:\n return rss_data\n\n\n@cli.command()\n@click.option('--search_type', type=click.Choice(['ticker', 'cik', 'all', 'sic', 'state', 'name']),\n default='all', help='Category of search term(s). List of possible SIC codes based on industry '\n 'classification can be found at:\\nhttps://www.sec.gov/info/edgar/siccodes.htm')\ndef search_filings(search_type, print_results=True):\n \"\"\"Displays filing information stored for any companies matching the search criteria.\"\"\"\n\n edgar_db = EdgarDatabase()\n edgar_db.make_session()\n\n _searcher(search_type, edgar_db, print_results)\n\n edgar_db.close_session()\n\n\n@cli.command()\n@click.option('--search_type', type=click.Choice(['ticker', 'all', 'cik', 'sic', 'state', 'name']),\n default='all', help='Category of search term(s). List of possible SIC codes based on industry '\n 'classification can be found at:\\nhttps://www.sec.gov/info/edgar/siccodes.htm')\n@click.option('--csv/--no-csv', default=False, help='Save all parsed data to CSV file.')\ndef parse_filings(search_type, csv=False):\n \"\"\"\n Attempts to download, extract and store accounting data (P&L / BS) from filings for given companies / categories of\n companies within search parameters. Optionally writes all parsed data to a CSV file.\n \"\"\"\n\n edgar_db = EdgarDatabase()\n edgar_db.make_session()\n\n search_results = _searcher(search_type, edgar_db, print_results=False)\n print('\\n')\n\n filings_to_download = []\n filings_to_parse = []\n parsing_successes = 0\n valid_results = 0\n\n print(f\"Prepping filings. Looking for forms of type {', '.join(VALID_FORMS)} for parsing...\")\n for filing in search_results:\n if filing.FilingInfo.form not in VALID_FORMS:\n continue\n\n valid_results += 1\n\n if filing.FilingInfo.parsing_attempted:\n continue\n\n filings_to_parse.append(filing)\n\n if filing.FilingInfo.excel_path:\n continue\n\n filings_to_download.append(filing)\n\n if filings_to_download:\n print('\\n')\n print('Downloading {} filings...'.format(len(filings_to_download)))\n\n if len(filings_to_download) > 20: # multiprocess this if there are a significant number of filings to dl\n filing_download_pool = multiprocessing.Pool(processes=MULTIPROCESSING_NUMBER)\n filings_to_record = filing_download_pool.map(_download_xlsxs, filings_to_download)\n filing_download_pool.close()\n filings_to_record = flatten(filings_to_record)\n else:\n filings_to_record = _download_xlsxs(filings_to_download)\n\n for f in filings_to_record:\n for r in edgar_db.session.query(FilingInfo).filter(FilingInfo.excel_url == f[1]).all():\n r.excel_path = f[0]\n\n edgar_db.session.commit()\n\n print('\\n')\n print('Download complete.')\n print('\\n')\n\n # reload filing objects from database as Excel write paths have been updated\n filings_to_parse = edgar_db.select_filings_by_accessions([f.FilingInfo.filing_accession for f in filings_to_parse])\n\n parsing_errors = []\n with click.progressbar(label=f'Parsing {len(filings_to_parse)} filings...', length=len(filings_to_parse)) as bar:\n\n for filing in filings_to_parse:\n\n if not filing.FilingInfo.excel_path:\n continue\n\n new_filing_bs_dfs = _build_filing_dfs(\n filing.FilingInfo.excel_path,\n re_search_terms=r'\\bcond.*?\\bconsol.*?\\bbalance|\\bbalance.*?\\bsheet'\n )\n\n new_filing_pl_dfs = _build_filing_dfs(\n filing.FilingInfo.excel_path,\n re_search_terms=r'\\boper|\\bcond.*?\\bconso'\n )\n\n if not new_filing_bs_dfs:\n pass\n else:\n for filing_bs_df in new_filing_bs_dfs:\n clean_filing_bs_data = _clean_data_file(filing_bs_df, r'\\bbalance.*?\\bsheet', r'.?')\n\n # write filing data to db if parsing returns something\n if clean_filing_bs_data is None:\n parsing_errors.append('BS: ' + str(filing.FilingInfo.excel_path))\n else:\n edgar_db.set_filing_data(filing, clean_filing_bs_data, filing_type='BS')\n parsing_successes += 1\n\n if not new_filing_pl_dfs:\n pass\n else:\n for filing_pl_df in new_filing_pl_dfs:\n clean_filing_pl_data = _clean_data_file(filing_pl_df, r'\\boperatio|\\brevenue', '12 months')\n\n # write filing data to db if parsing returns something\n if clean_filing_pl_data is None:\n parsing_errors.append('PL: ' + str(filing.FilingInfo.excel_path))\n continue\n\n if edgar_db.set_filing_data(filing, clean_filing_pl_data, filing_type='PL') is not False:\n parsing_successes += 1\n else:\n parsing_errors.append('PL: ' + str(filing.FilingInfo.excel_path))\n\n bar.update(1)\n\n print('\\n')\n print('Parsing complete.')\n print('Total valid filings:', valid_results)\n print('Successful sheet parses:', parsing_successes)\n print('Unsuccessful sheet parses:', len(parsing_errors))\n\n for c in edgar_db.select_filings_by_url([f.FilingInfo.filing_url for f in filings_to_parse]):\n c.FilingInfo.parsing_attempted = True\n\n error_log_loc = normalize_file_path('unsuccessful_parses.txt')\n\n with open(error_log_loc, 'w') as f:\n f.write('\\n'.join(parsing_errors))\n\n print('Unsuccessful parse log written to:', error_log_loc)\n\n if csv:\n # generate a DataFrame via SQL query for all parsed values in the data table\n sic_df = pd.read_sql_table(DB_SIC_TABLE, edgar_db.db_eng)\n company_df = pd.read_sql_table(DB_COMPANY_TABLE, edgar_db.db_eng)\n filing_info_df = pd.read_sql_table(DB_FILING_TABLE, edgar_db.db_eng,\n parse_dates={'period': '%Y%m%d', 'filed': '%Y%m%d'})\n filing_data_df = pd.read_sql_table(DB_FILING_DATA_TABLE, edgar_db.db_eng,\n parse_dates={'value_period': '%Y%m%d'})\n\n little_data_df = pd.merge(filing_data_df, filing_info_df, how='left')\n some_data_df = pd.merge(little_data_df, company_df, how='left')\n all_data_df = pd.merge(some_data_df, sic_df, how='left', left_on='company_sic', right_on='sic_code')\n\n print('\\n')\n print(all_data_df.head())\n print('\\n')\n print(all_data_df.shape)\n\n # save to file, named for current time\n csv_write_path = normalize_file_path('parsed_data_{}.csv'.format(dt.datetime.now().strftime('%Y%m%d%H%M%S')))\n all_data_df.to_csv(csv_write_path)\n print('\\nParsed data CSV written to:')\n print(csv_write_path)\n\n edgar_db.close_session()\n return search_results\n\n\n@cli.command()\ndef update_company_info():\n \"\"\"Attempts to download information for all company CIKs without an associated ticker.\"\"\"\n\n edgar_db = EdgarDatabase()\n edgar_db.make_session()\n\n to_update_ciks = edgar_db.session.query(\n distinct(CompanyInfo.company_cik)).filter(and_(\n CompanyInfo.company_name.is_(None),\n CompanyInfo.company_info_attempted.is_(False))).all()\n\n _update_company_info(to_update_ciks, edgar_db)\n edgar_db.close_session()\n\n\n@cli.command()\ndef clear_parsed_files():\n \"\"\"Deletes any downloaded Excel files that have been successfully parsed.\"\"\"\n edgar_db = EdgarDatabase()\n edgar_db.make_session()\n\n parsed_excel_paths = edgar_db.session.query(\n distinct(FilingInfo)).filter(FilingInfo.parsed_data.is_(True)).all()\n\n for parsed_excel in parsed_excel_paths:\n try:\n os.remove(parsed_excel.excel_path)\n except FileNotFoundError:\n pass\n\n for c in edgar_db.session.query(FilingInfo).filter(\n FilingInfo.excel_path.is_(parsed_excel.excel_path)).all():\n c.excel_path = None\n\n edgar_db.close_session()\n\n print(f'{len(parsed_excel_paths)} files deleted.')\n\n\ndef _searcher(search_type, edgar_db, print_results=True):\n \"\"\"Prints any downloaded filing information associated with companies within search scope.\"\"\"\n\n if search_type == 'all':\n search_results = edgar_db.select_all_filings()\n else:\n search_term = click.prompt('Please enter search term')\n\n # each of these generates a set of cik numbers for companies that meet search criteria\n if search_type == 'sic':\n ciks_to_parse = edgar_db.select_ciks_by_sic(search_term)\n elif search_type == 'state':\n ciks_to_parse = edgar_db.select_ciks_by_state(search_term)\n elif search_type == 'name':\n ciks_to_parse = edgar_db.select_ciks_by_name(search_term)\n elif search_type == 'cik':\n ciks_to_parse = edgar_db._select_distinct_ciks(CompanyInfo.company_cik, search_term)\n else:\n ciks_to_parse = edgar_db.select_ciks_by_ticker(search_term)\n\n # for cik number matches get list of company-filing objects\n search_results = edgar_db.select_filings_by_ciks(ciks_to_parse)\n\n if print_results:\n print('\\nResults:\\n')\n print('Company name'.ljust(30), 'Form type'.ljust(10), 'Period'.ljust(10), 'Filing URL', sep=' | ')\n print('-' * 100)\n\n for result in search_results:\n try:\n period = dt.datetime.strftime(dt.datetime.strptime(str(result.FilingInfo.period), '%Y%m%d'), '%m/%d/%Y')\n except ValueError:\n period = ''\n company_name = result.CompanyInfo.company_name\n if company_name is None:\n company_name = ''\n\n print(str(company_name[:30]).title().ljust(30),\n str(result.FilingInfo.form).ljust(10),\n str(period).ljust(10),\n str(result.FilingInfo.filing_url), sep=' | ')\n print('\\n')\n print('Filings:', len(search_results))\n\n return search_results\n\n\ndef _download_filings(year, month, print_data=True):\n \"\"\"Downloads list of filings from SEC's Edgar database for given time period.\"\"\"\n print('\\nDownloading filings XML...\\n')\n\n edgar_url = ('http://www.sec.gov/Archives/edgar/monthly/xbrlrss-' + str(year).zfill(4) +\n '-' + str(month).zfill(2) + '.xml')\n\n try:\n # use feedparser rss xml parser to enable selection by tag\n rss_data = feedparser.parse(edgar_url)\n except (ConnectionError, TimeoutError, SSLError, MaxRetryError):\n print(\"Can't connect.\")\n return None\n\n if print_data:\n print(rss_data['feed']['title'] + ':', '\\n')\n print('Company Name'.ljust(30), 'CIK'.ljust(10), 'Period'.ljust(10), 'Form Type'.ljust(10), sep=' | ')\n print('-'*80)\n\n for item in rss_data.entries:\n # do our normal company name formatting\n name = re.sub(\"[^a-zA-Z ]+\", \"\", item['edgar_companyname']).replace(\" \", \" \").title()\n cik = item['edgar_ciknumber']\n form = item['edgar_formtype']\n try:\n # try to pretty-print filing period date\n period = dt.datetime.strftime(dt.datetime.strptime(item['edgar_period'], '%Y%m%d'), '%m/%d/%Y')\n except KeyError:\n period = ''\n\n print(name[:30].ljust(30), cik.ljust(10), period.ljust(10), form.ljust(10), sep=' | ')\n\n return rss_data.entries\n\n\ndef _download_xlsxs(filings) -> list((str, FilingInfo.excel_url)):\n \"\"\"\n Download XLSX files for a list of urls.\n \"\"\"\n\n path_update_list = []\n\n if type(filings) != list:\n filings = [filings]\n\n for f in filings:\n time.sleep(.2)\n try:\n\n # file name will be the cik plus accession numbers\n write_path = normalize_file_path('xlsx_data/' + f.FilingInfo.company_cik + '_' +\n f.FilingInfo.filing_accession +\n '.xlsx')\n\n if not write_path.exists():\n filing_excel = rq.get(f.FilingInfo.excel_url)\n write_path.write_bytes(filing_excel.content)\n\n path_update_list.append((str(write_path), f.FilingInfo.excel_url))\n\n except (FileNotFoundError, rq.Timeout, rq.ConnectionError, rq.ConnectTimeout, SSLError, MaxRetryError):\n print('Unsuccessful:', f.FilingInfo.excel_url)\n continue\n\n return path_update_list\n\n\ndef _build_filing_dfs(file_path: str, re_search_terms: str) -> Union[None, List[pd.DataFrame]]:\n\n if not file_path:\n return None\n\n return_dfs = []\n\n if file_path.split(\".\")[-1] == 'xls' or 'xlsx':\n try:\n excel = pd.ExcelFile(file_path)\n except (FileNotFoundError, XLRDError):\n return None\n\n for sheet_name in excel.sheet_names:\n if re.search(re_search_terms, sheet_name, flags=re.IGNORECASE):\n return_dfs.append(excel.parse(sheet_name, header=None).dropna(how='all'))\n\n excel.close()\n\n elif file_path.split(\".\")[-1] == 'csv':\n\n try:\n df_csv = pd.read_csv(file_path, header=None).dropna(how='all')\n except (FileNotFoundError, XLRDError):\n return None\n\n header_vals_list = [str(item) for item in flatten(df_csv.iloc[:5, :].values.tolist())]\n header_vals_string = ' '.join([str(val) for val in header_vals_list])\n\n if not re.search(re_search_terms, header_vals_string):\n return_dfs.append(None)\n else:\n return return_dfs.append(df_csv)\n\n return return_dfs\n\n\ndef _clean_data_file(df: pd.DataFrame, re_search_filing_type: str, re_search_period: str) -> Optional[ndarray]:\n if type(df) is None:\n return None\n\n header_vals_list = [str(item) for item in flatten(df.iloc[:5, :].values.tolist())]\n header_vals_string = ' '.join([str(val) for val in header_vals_list])\n\n # unit correction to 1 USD\n if re.search('thousands|Thousands', header_vals_string):\n unit_multiplier = 1000\n elif re.search('millions|Millions', header_vals_string):\n unit_multiplier = 1000000\n elif re.search('billions|Billions', header_vals_string):\n unit_multiplier = 1000000000\n else:\n unit_multiplier = 1\n\n # confirm sheet type by looking at header values for relevant string pattern\n if re.search(re_search_filing_type, header_vals_string, flags=re.IGNORECASE) is None:\n return None\n\n if re.search(re_search_period, header_vals_string, flags=re.IGNORECASE) is None:\n return None\n\n dropped_df = df.dropna(how='any', subset=df.columns[1:])\n\n cleaned_df = dropped_df.applymap(lambda x: str(x).replace('\\n', ' ').replace(\"'\", \"\").replace(\":\", \"\")\n .replace('-', '').replace('*', '').replace(' ', ' ')\n .replace('$', '').strip().title())\n\n for col in cleaned_df.columns[1:]:\n cleaned_df.loc[1:, col] = cleaned_df.loc[1:, col].apply(scale_array_val, args=(unit_multiplier,))\n\n final_df = cleaned_df.dropna()\n final_df = final_df.drop_duplicates(subset=[0], keep=False, inplace=False)\n\n return final_df.values\n\n\ndef _get_single_company_info(company_cik):\n time.sleep(.2) # pause for crude rate limiting when hitting in parallel\n\n company_info = CompanyInfo()\n\n company_info.company_cik = company_cik\n\n company_info = api_cik_to_info(company_info)\n\n if company_info.company_name:\n company_info = api_name_to_ticker(company_info)\n\n return company_info\n\n\ndef _update_filings(rss_data, get_company_info):\n \"\"\"\n Parse and store filing data defined by Edgar's filing feed (via a parsed XML file)\n \"\"\"\n print('\\nUpdating filings...')\n\n edgar_db = EdgarDatabase()\n edgar_db.make_session()\n\n duplicates = 0\n company_ciks_to_download = []\n\n with click.progressbar(length=len(rss_data), label=f'Adding {len(rss_data)} new items to database...') as bar:\n for i, item in enumerate(rss_data):\n bar.update(1)\n\n cik = str(item['edgar_ciknumber']).strip()\n filing_url = str(item['link']).strip()\n accession = str(item['edgar_accessionnumber']).strip()\n\n # handle key errors for the filing period as some form types don't have a period associated with them\n try:\n period = str(item['edgar_period']).strip()\n except KeyError:\n period = None\n\n if edgar_db.check_cik_exists(cik) is False:\n company_ciks_to_download.append(cik)\n\n # if db search for filing returns a hit, skip writing that filing\n if edgar_db.check_accession_exists(accession) is True:\n duplicates += 1\n else:\n edgar_db.insert_objects(FilingInfo(\n company_cik=cik,\n filing_accession=accession,\n form=str(item['edgar_formtype']).strip(),\n period=period,\n filed=str(item['edgar_acceptancedatetime']).strip(),\n filing_url=filing_url,\n excel_url='http://www.sec.gov/Archives/edgar/data/' + cik.lstrip(\"0\") + '/' +\n accession.replace(\"-\", \"\") + '/Financial_Report.xlsx',\n excel_path=None,\n parsed_data=False))\n\n # show user if we skipped writing any entries because they were already in database\n if duplicates > 0:\n print(f'{duplicates} duplicate entries skipped...')\n\n if len(company_ciks_to_download) > 0 and get_company_info:\n _update_company_info(company_ciks_to_download, edgar_db)\n\n edgar_db.close_session()\n\n\ndef _update_company_info(company_ciks_to_download, edgar_db):\n \"\"\"Attempt to download info about a given company's CIK\"\"\"\n print('\\n')\n print('Updating company info...')\n\n print(f'Collecting info for {len(company_ciks_to_download)} companies...')\n company_download_pool = multiprocessing.Pool(processes=MULTIPROCESSING_NUMBER)\n info_to_insert = company_download_pool.map(_get_single_company_info, list(set(company_ciks_to_download)))\n company_download_pool.close()\n\n edgar_db.insert_objects(info_to_insert)\n\n for c in edgar_db.select_filings_by_ciks(company_ciks_to_download):\n c.CompanyInfo.company_info_attempted = True\n\n print('Done.')\n print(\"\\n\")\n\n\ndef _build_sic_table():\n\n edgar_db = EdgarDatabase()\n edgar_db.make_session()\n\n if edgar_db.session.query(func.count(SicInfo.sic_code)).first()[0] != 0:\n return True\n\n try:\n sic_tables = bs4.BeautifulSoup(rq.get('https://www.sec.gov/info/edgar/siccodes.htm').content, 'html.parser')\n except (ConnectionError, TimeoutError, SSLError, MaxRetryError):\n edgar_db.close_session()\n print(\"Can't connect.\")\n sys.exit(0)\n\n sic_table_found = sic_tables.findAll('p')[1].findAll('table')[0]\n\n sic_df = pd.read_html(sic_table_found.encode(), header=0)[0]\n sic_df.columns = ['sic_code', 'ad_office', 'drop', 'industry_title']\n sic_df = sic_df.drop('drop', axis='columns')\n\n sic_df.to_sql(DB_SIC_TABLE, edgar_db.db_eng, if_exists='replace', index=False)\n\n edgar_db.close_session() # need to use session logic to commit changes\n\n\nif __name__ == '__main__':\n # activate click command line commands when running module directly\n cli()\n # if using Windows pause at the end of the script so cmd doesn't automatically close\n if platform.system == 'Windows':\n click.pause()\n\n print(\"\\n\")\n"
] |
[
[
"pandas.read_sql_table",
"pandas.merge",
"pandas.read_csv",
"pandas.ExcelFile"
]
] |
Maarten-vd-Sande/gimmemotifs
|
[
"eab24de5a6835f71a957417d879ec5d6c8caebb7"
] |
[
"gimmemotifs/report.py"
] |
[
"# Copyright (c) 2009-2019 Simon van Heeringen <simon.vanheeringen@gmail.com>\n#\n# This module is free software. You can redistribute it and/or modify it under\n# the terms of the MIT License, see the file COPYING included with this\n# distribution.\n\"\"\"Reports (graphical and text) for motifs statistics.\"\"\"\nimport os\nimport sys\nfrom datetime import datetime\nfrom multiprocessing import Pool\nimport re\nimport shutil\nimport logging\n\nimport jinja2\nimport numpy as np\nimport pandas as pd\nfrom statsmodels.stats.multitest import multipletests\n\ntry:\n from pandas.core.indexing import non_reducing_slice\nexcept ImportError:\n from pandas.core.indexing import _non_reducing_slice as non_reducing_slice\n\nfrom pandas.io.formats.style import Styler\nimport seaborn as sns\n\ntry:\n import emoji\nexcept ImportError:\n pass\n\nfrom gimmemotifs.comparison import MotifComparer\nfrom gimmemotifs.fasta import Fasta\nfrom gimmemotifs.motif import read_motifs\nfrom gimmemotifs.config import MotifConfig\nfrom gimmemotifs.plot import roc_plot\nfrom gimmemotifs.stats import calc_stats, add_star, write_stats\nfrom gimmemotifs import __version__\nfrom gimmemotifs.utils import motif_localization\n\nlogger = logging.getLogger(\"gimme.report\")\n\nFACTOR_TOOLTIP = \"<div title='\\\"Direct\\\" means that there is direct evidence of binding or that this assignment is based on curated information. \\\"Predicted\\\" means that the motif comes from a non-curated ChIP-seq experiment or that the factor was computationally predicted to bind this motif based on its DNA binding domain.'>factors<br/>(<span style='color:black'>direct</span> or <span style='color:#666666'>predicted</span>)</div>\"\n\n\ndef _wrap_html_str(x):\n if \" \" not in x:\n return x\n\n min_pos, max_pos = 0, len(x)\n if \">\" in x and \"</\" in x:\n m = re.compile(r\">[^<>]*<\").search(x)\n min_pos, max_pos = m.start(), m.end()\n\n positions = [m.start() for m in re.compile(\" \").finditer(x)]\n\n positions = [p for p in positions if min_pos < p < max_pos]\n\n if len(positions) == 0:\n return x\n\n pos = sorted(positions, key=lambda p: abs(p - len(x) / 2))[0]\n x = x[:pos] + \"<br/>\" + x[pos + 1 :]\n return x\n\n\nclass ExtraStyler(Styler):\n \"\"\"\n Extra styles for a DataFrame or Series based on pandas.styler using HTML and CSS.\n \"\"\"\n\n loader = jinja2.ChoiceLoader(\n [jinja2.FileSystemLoader(MotifConfig().get_template_dir()), Styler.loader]\n )\n env = jinja2.Environment(loader=loader)\n template = env.get_template(\"table.tpl\")\n\n def __init__(self, *args, **kwargs):\n self._data_todo = []\n self.circle_styles = None\n self.palette_styles = None\n self.col_heading_style = {\n \"name\": \"col_heading\",\n \"props\": [(\"border-bottom\", \"1px solid #e0e0e0\")],\n }\n super(ExtraStyler, self).__init__(*args, **kwargs)\n self.display_data = self.data.copy()\n\n # self.template =\n\n self._font = \"Nunito Sans\"\n\n @property\n def font(self):\n return self._font\n\n @font.setter\n def font(self, font_name):\n self._font = font_name\n\n def set_font(self, font_name):\n \"\"\"\n Set the font that will be used.\n\n Parameters\n ----------\n font_name : str\n Should be a font name available though the Google Font API.\n\n Returns\n -------\n self : ExtraStyler\n\n Notes\n -----\n ``font_name`` can contain spaces, eg. \"Nunito Sans\".\n\n Examples\n --------\n >>> df = pd.DataFrame(np.random.randn(4, 2), columns=['a', 'b'])\n >>> ExtraStyler(df).font(\"Roboto)\n \"\"\"\n self.font = font_name\n return self\n\n def _current_index(self, subset):\n subset = pd.IndexSlice[:, :] if subset is None else subset\n subset = non_reducing_slice(subset)\n selected = self.data.loc[subset]\n idx_slice = pd.IndexSlice[\n self.data.index.get_indexer(selected.index),\n self.data.columns.get_indexer(selected.columns),\n ]\n return idx_slice\n\n def _translate(self):\n self._compute_data()\n d = super()._translate()\n circle_styles = self.circle_styles or []\n palette_styles = self.palette_styles or []\n col_heading_style = self.col_heading_style or []\n d.update(\n {\n \"font\": self.font,\n \"circle_styles\": circle_styles,\n \"palette_styles\": palette_styles,\n \"col_heading_style\": col_heading_style,\n }\n )\n return d\n\n def _compute_data(self):\n r = self\n for func, args, kwargs in self._data_todo:\n r = func(self)(*args, **kwargs)\n r.data = r.display_data\n return r\n\n def _tooltip(self, tip, subset=None, part=None):\n subset = pd.IndexSlice[:, :] if subset is None else subset\n subset = non_reducing_slice(subset)\n\n if part is None:\n part = \"data\"\n\n if part == \"data\":\n self.display_data.loc[subset] = (\n \"<div title='\"\n + tip\n + \"'>\"\n + self.display_data.loc[subset].astype(str)\n + \"</div>\"\n )\n elif part == \"columns\":\n idx = self._current_index(subset)[1]\n rename = dict(\n zip(\n self.display_data.columns[idx],\n \"<div title='\"\n + tip\n + \"'>\"\n + self.display_data.columns[idx].astype(str)\n + \"</div>\",\n )\n )\n self.display_data.rename(columns=rename, inplace=True)\n elif part == \"index\":\n idx = self._current_index(subset)[0]\n rename = dict(\n zip(\n self.display_data.index[idx],\n \"<div title='\"\n + tip\n + \"'>\"\n + self.display_data.index[idx].astype(str)\n + \"</div>\",\n )\n )\n self.display_data.rename(index=rename, inplace=True)\n else:\n raise ValueError(f\"unknown value for part: {part}\")\n return self\n\n def _wrap_iterable(self, it):\n return [_wrap_html_str(val) for val in it]\n\n def _wrap(self, subset=None, axis=0):\n subset = pd.IndexSlice[:, :] if subset is None else subset\n subset = non_reducing_slice(subset)\n\n if axis in [0, \"columns\"]:\n idx = self._current_index(subset)[1]\n rename = dict(\n zip(\n self.display_data.columns[idx],\n self._wrap_iterable(self.display_data.columns[idx]),\n )\n )\n self.display_data.rename(columns=rename, inplace=True)\n elif axis in [1, \"index\"]:\n idx = self._current_index(subset)[0]\n rename = dict(\n zip(\n self.display_data.index[idx],\n self._wrap_iterable(self.display_data.index[idx]),\n )\n )\n self.display_data.rename(index=rename, inplace=True)\n else:\n raise ValueError(f\"unknown value for axis: {axis}\")\n return self\n\n def _convert_to_image(self, subset=None, height=30):\n subset = pd.IndexSlice[:, :] if subset is None else subset\n subset = non_reducing_slice(subset)\n\n self.display_data.loc[subset] = (\n f'<div style=\"height:{height}px;object-fit:contain;\"><img src=\"'\n + self.data.loc[subset].astype(str)\n + '\" style=\"height:100%;width:100%;object-fit:contain;\"/></div>'\n )\n return self\n\n def _border(self, idx, location=\"left\"):\n return [f\"border-{location}: 2px solid #444;\" for val in idx]\n\n def border(\n self,\n subset=None,\n location=\"bottom\",\n part=\"data\",\n width=\"2px\",\n style=\"solid\",\n color=\"#444\",\n ):\n \"\"\"\n Add a border to data cells, columns or index.\n\n Parameters\n ----------\n subset : IndexSlice, optional\n An argument to ``DataFrame.loc`` that restricts which elements\n ``border`` is applied to. If ``part`` is \"columns\" or \"index\"\n subset should be present in either the columns or the index.\n\n location : str, optional\n Location of the border, default is \"bottom\". Can be \"top\", \"bottom\",\n \"right\" or \"left\".\n\n part : str, optional\n If ``part`` is \"data\", the border will be applied to the data cells.\n Set part to \"index\" or to \"column\" to add a border to the index or\n header, respectively.\n\n width : str, int or float, optional\n Valid CSS value for border width.\n\n style : str, optional\n Valid CSS value for border style.\n\n color : str, optional\n Valid CSS value for border color.\n\n Returns\n -------\n self : ExtraStyler\n\n Examples\n --------\n >>> df = pd.DataFrame(np.random.randn(4, 2), columns=['a', 'b'])\n >>> ExtraStyler(df).border(part=\"columns)\n \"\"\"\n if part == \"data\":\n self.apply(self._border, subset=subset, location=location)\n else:\n self.col_heading_style[\"props\"].append(\n (f\"border-{location}\", f\"{width} {style} {color}\")\n )\n return self\n\n def _align(self, idx, location=\"center\"):\n return [f\"text-align:{location};\" for val in idx]\n\n def align(self, subset=None, location=\"center\", axis=0):\n \"\"\"\n Align text.\n\n Parameters\n ----------\n subset : IndexSlice, optional\n An argument to ``DataFrame.loc`` that restricts which elements\n ``center_align`` is applied to.\n\n location : str, optional\n \"center\", \"left\" or \"right\"\n\n axis : {0 or 'index', 1 or 'columns', None}, default 0\n Apply to each column (``axis=0`` or ``'index'``), to each row\n (``axis=1`` or ``'columns'``), or to the entire DataFrame at once\n with ``axis=None``.\n\n Returns\n -------\n self : ExtraStyler\n \"\"\"\n self.apply(self._align, subset=subset, location=location, axis=axis)\n return self\n\n def to_precision_str(self, subset=None, precision=0, include_zero=True):\n subset = pd.IndexSlice[:, :] if subset is None else subset\n subset = non_reducing_slice(subset)\n\n def precision_str(x, precision=precision):\n if (include_zero or x > 0) and x <= 10 ** -precision:\n return f\"<{10**-precision}\"\n else:\n return f\"{{0:.{precision}f}}\".format(x)\n\n self.display_data.loc[subset] = self.data.loc[subset].applymap(precision_str)\n return self\n\n def _circle(\n self,\n subset=None,\n show_text=True,\n color=None,\n cmap=None,\n vmin=None,\n vmax=None,\n scale=False,\n size=25,\n min_size=5,\n morph=False,\n ):\n subset = pd.IndexSlice[:, :] if subset is None else subset\n subslice = non_reducing_slice(subset)\n\n if color:\n palette = sns.color_palette([color])\n # print(palette)\n elif cmap is None:\n palette = sns.light_palette((210, 90, 60), input=\"husl\", n_colors=10)\n else:\n # if isinstance(palette, str):\n palette = sns.color_palette(cmap)\n\n # Make sure we don't select text columns\n if len(palette) > 1:\n subslice = pd.IndexSlice[\n self.data.loc[subslice].index,\n self.data.loc[subslice].select_dtypes(exclude=[\"object\"]).columns,\n ]\n idx = self._current_index(subslice)\n\n self.circle_styles = self.circle_styles or []\n circle_id = len(self.circle_styles) + 1\n\n props = [\n (\"height\", f\"{size}px\"),\n (\"width\", f\"{size}px\"),\n (\"border-radius\", \"50%\"),\n (\"color\", \"#000\"),\n (\"line-height\", f\"{size}px\"),\n (\"display\", \"inline-block\"),\n (\"text-align\", \"center\"),\n (\"vertical-align\", \"middle\"),\n ]\n\n self.circle_styles.append({\"name\": f\"circle{circle_id}\", \"props\": props})\n self.palette_styles = self.palette_styles or []\n for i, color in enumerate(palette.as_hex()):\n props = [(\"background-color\", color)]\n if scale:\n circle_size = min_size + ((size - min_size) / len(palette) * (i + 1))\n props += [\n (\"height\", f\"{circle_size}px\"),\n (\"width\", f\"{circle_size}px\"),\n (\"line-height\", f\"{circle_size}px\"),\n (\"text-align\", \"center\"),\n ]\n if morph:\n props += [(\"border-radius\", f\"{50 - int(50 / len(palette)) * i}%\")]\n self.palette_styles.append(\n {\"name\": f\"color{circle_id}_{i}\", \"props\": props}\n )\n\n if len(palette) > 1:\n vmax = (\n self.data.loc[subslice].max().max() * 1.01\n if vmax is None\n else vmax * 1.01\n )\n text = self.display_data.iloc[idx].astype(str) if show_text else \"\"\n self.display_data.iloc[idx] = (\n f\"<div class='circle{circle_id} color{circle_id}_\"\n + (self.data.loc[subslice] / (vmax / len(palette)))\n .astype(int)\n .astype(str)\n + \"'>\"\n + text\n + \"</div>\"\n )\n else:\n text = self.display_data.iloc[idx].astype(str) if show_text else \"\"\n self.display_data.iloc[idx] = (\n f\"<div class='circle{circle_id} color{circle_id}_0'>\" + text + \"</div>\"\n )\n\n return self\n\n def add_circle(self, **kwargs):\n self._data_todo.append((lambda instance: instance._circle, (), kwargs))\n return self\n\n def wrap(self, **kwargs):\n self._data_todo.append((lambda instance: instance._wrap, (), kwargs))\n return self\n\n def add_tooltip(self, tip, **kwargs):\n self._data_todo.append((lambda instance: instance._tooltip, (tip,), kwargs))\n return self\n\n def convert_to_image(self, **kwargs):\n self._data_todo.append(\n (lambda instance: instance._convert_to_image, (), kwargs)\n )\n return self\n\n def rename(self, columns=None, index=None):\n self.display_data = self.display_data.rename(columns=columns, index=index)\n return self\n\n def _emoji_score(self, series, emoji_str=None, bins=None):\n if emoji_str is None:\n emoji_str = \":star:\"\n if bins is None:\n bins = 3\n\n if isinstance(bins, int):\n labels = range(1, bins + 1)\n else:\n labels = range(1, len(bins))\n\n return [\n emoji.emojize(emoji_str * val, use_aliases=True)\n for val in pd.cut(series, bins=bins, labels=labels)\n ]\n\n def _emoji_scale(self, series, emojis=None, bins=None):\n emoji_dict = {\n \"thumbs\": [\":thumbsdown:\", \":thumbsup:\"],\n \"check\": [\":cross_mark:\", \":white_check_mark:\"],\n \"smiley\": [\n \":crying_face:\",\n \":slightly_frowning_face:\",\n \":neutral_face:\",\n \":slightly_smiling_face:\",\n \":grin:\",\n ],\n \"black_square\": [\n \":black_small_square:\",\n \":black_medium_small_square:\",\n \":black_medium_square:\",\n \":black_large_square:\",\n ],\n \"white_square\": [\n \":white_small_square:\",\n \":white_medium_small_square:\",\n \":white_medium_square:\",\n \":white_large_square:\",\n ],\n }\n\n if emojis is None:\n emojis = \"smiley\"\n\n if emojis in emoji_dict:\n labels = emoji_dict[emojis]\n if bins is None:\n bins = len(labels)\n\n return [\n emoji.emojize(val, use_aliases=True)\n for val in pd.cut(series, bins=bins, labels=labels)\n ]\n\n def emoji_scale(self, subset=None, emojis=None, bins=None, axis=0):\n subset = pd.IndexSlice[:, :] if subset is None else subset\n subset = non_reducing_slice(subset)\n\n idx = self._current_index(subset=subset)\n\n result = self.display_data.iloc[idx].apply(\n self._emoji_scale, axis=axis, result_type=\"expand\", args=(emojis, bins)\n )\n self.display_data.iloc[idx] = result.values\n\n return self.align(subset=subset, location=\"center\", axis=axis)\n\n def emoji_score(self, subset=None, emoji_str=None, bins=None, axis=0):\n subset = pd.IndexSlice[:, :] if subset is None else subset\n subset = non_reducing_slice(subset)\n\n idx = self._current_index(subset=subset)\n result = self.display_data.iloc[idx].apply(\n self._emoji_score, axis=axis, result_type=\"expand\", args=(emoji_str, bins)\n )\n self.display_data.iloc[idx] = result.values\n\n return self.align(subset=subset, location=\"left\", axis=axis)\n\n def emojify(self, subset=None):\n subset = pd.IndexSlice[:, :] if subset is None else subset\n subset = non_reducing_slice(subset)\n\n idx = self._current_index(subset=subset)\n result = self.display_data.iloc[idx].applymap(emoji.emojize)\n self.display_data.iloc[idx] = result.values\n\n return self\n\n def scaled_background_gradient(\n self,\n subset=None,\n cmap=\"RdBu_r\",\n low=0,\n high=0,\n center_zero=False,\n vmin=None,\n vmax=None,\n ):\n if center_zero:\n sub = pd.IndexSlice[:, :] if subset is None else subset\n sub = non_reducing_slice(sub)\n\n vmax = (\n self.data.loc[sub]\n .replace({np.inf: np.nan, -np.inf: np.nan})\n .max(skipna=True)\n .max()\n if vmax is None\n else vmax\n )\n vmin = (\n self.data.loc[sub]\n .replace({np.inf: np.nan, -np.inf: np.nan})\n .min(skipna=True)\n .min()\n if vmin is None\n else vmin\n )\n vmax = max(abs(vmax), abs(vmin))\n vmin = -vmax\n\n r = self.background_gradient(\n subset=subset,\n cmap=cmap,\n vmin=vmin,\n vmax=vmax,\n low=low,\n high=high,\n )\n\n return r\n\n\ndef get_roc_values(motif, fg_file, bg_file, genome):\n \"\"\"Calculate ROC AUC values for ROC plots.\"\"\"\n try:\n stats = calc_stats(\n fg_file=fg_file,\n bg_file=bg_file,\n motifs=motif,\n genome=genome,\n stats=[\"roc_values\"],\n ncpus=1,\n )\n (x, y) = list(stats.values())[0][\"roc_values\"]\n return None, x, y\n except Exception as e:\n print(motif)\n print(motif.id)\n print(str(e))\n raise\n\n\ndef create_roc_plots(pfmfile, fgfa, background, outdir, genome):\n \"\"\"Make ROC plots for all motifs.\"\"\"\n motifs = read_motifs(pfmfile, fmt=\"pwm\", as_dict=True)\n ncpus = int(MotifConfig().get_default_params()[\"ncpus\"])\n pool = Pool(processes=ncpus)\n jobs = {}\n for bg, fname in background.items():\n for m_id, m in motifs.items():\n\n k = \"{}_{}\".format(str(m), bg)\n jobs[k] = pool.apply_async(\n get_roc_values, (motifs[m_id], fgfa, fname, genome)\n )\n imgdir = os.path.join(outdir, \"images\")\n if not os.path.exists(imgdir):\n os.mkdir(imgdir)\n\n roc_img_file = os.path.join(outdir, \"images\", \"{}_roc.{}.png\")\n\n for motif in motifs.values():\n for bg in background:\n k = \"{}_{}\".format(str(motif), bg)\n error, x, y = jobs[k].get()\n if error:\n logger.error(\"Error in thread: %s\", error)\n logger.error(\"Motif: %s\", motif)\n sys.exit(1)\n roc_plot(roc_img_file.format(motif.id, bg), x, y)\n\n\ndef _create_text_report(inputfile, motifs, closest_match, stats, outdir):\n \"\"\"Create text report of motifs with statistics and database match.\"\"\"\n my_stats = {}\n for motif in motifs:\n match = closest_match[motif.id]\n my_stats[str(motif)] = {}\n for bg in list(stats.values())[0].keys():\n if str(motif) not in stats:\n logger.error(\"####\")\n logger.error(\"{} not found\".format(str(motif)))\n for s in sorted(stats.keys()):\n logger.error(s)\n logger.error(\"####\")\n else:\n my_stats[str(motif)][bg] = stats[str(motif)][bg].copy()\n my_stats[str(motif)][bg][\"best_match\"] = \"_\".join(\n match[0].split(\"_\")[:-1]\n )\n my_stats[str(motif)][bg][\"best_match_pvalue\"] = match[1][-1]\n\n header = (\"# GimmeMotifs version {}\\n\" \"# Inputfile: {}\\n\").format(\n __version__, inputfile\n )\n\n write_stats(my_stats, os.path.join(outdir, \"stats.{}.txt\"), header=header)\n\n\ndef _create_graphical_report(\n inputfile, pwm, background, closest_match, outdir, stats, best_id=None\n):\n \"\"\"Create main gimme_motifs output html report.\"\"\"\n if best_id is None:\n best_id = {}\n\n logger.debug(\"Creating graphical report\")\n\n class ReportMotif(object):\n \"\"\"Placeholder for motif stats.\"\"\"\n\n pass\n\n config = MotifConfig()\n\n imgdir = os.path.join(outdir, \"images\")\n if not os.path.exists(imgdir):\n os.mkdir(imgdir)\n\n motifs = read_motifs(pwm, fmt=\"pfm\")\n\n roc_img_file = \"%s_roc.%s\"\n\n dbpwm = config.get_default_params()[\"motif_db\"]\n pwmdir = config.get_motif_dir()\n\n dbmotifs = read_motifs(os.path.join(pwmdir, dbpwm), as_dict=True)\n\n report_motifs = []\n for motif in motifs:\n\n rm = ReportMotif()\n rm.id = motif.id\n rm.id_href = {\"href\": \"#%s\" % motif.id}\n rm.id_name = {\"name\": motif.id}\n rm.img = {\"src\": os.path.join(\"images\", \"%s.png\" % motif.id)}\n motif.plot_logo(fname=os.path.join(outdir, \"images/{}.png\".format(motif.id)))\n\n # TODO: fix best ID\n rm.best = \"Gimme\" # best_id[motif.id]\n\n rm.consensus = motif.to_consensus()\n rm.stars = int(\n np.mean([stats[str(motif)][bg].get(\"stars\", 0) for bg in background]) + 0.5\n )\n\n rm.bg = {}\n for bg in background:\n rm.bg[bg] = {}\n this_stats = stats.get(str(motif), {}).get(bg)\n # TODO: fix these stats\n rm.bg[bg][\"e\"] = \"%0.2f\" % this_stats.get(\"enr_at_fpr\", 1.0)\n rm.bg[bg][\"p\"] = \"%0.2f\" % this_stats.get(\"phyper_at_fpr\", 1.0)\n rm.bg[bg][\"auc\"] = \"%0.3f\" % this_stats.get(\"roc_auc\", 0.5)\n rm.bg[bg][\"mncp\"] = \"%0.3f\" % this_stats.get(\"mncp\", 1.0)\n rm.bg[bg][\"roc_img\"] = {\n \"src\": \"images/\"\n + os.path.basename(roc_img_file % (motif.id, bg))\n + \".png\"\n }\n rm.bg[bg][\"roc_img_link\"] = {\n \"href\": \"images/\"\n + os.path.basename(roc_img_file % (motif.id, bg))\n + \".png\"\n }\n\n rm.histogram_img = {\"data\": \"images/%s_histogram.svg\" % motif.id}\n rm.histogram_link = {\"href\": \"images/%s_histogram.svg\" % motif.id}\n\n match_id = closest_match[motif.id][0]\n dbmotifs[match_id].plot_logo(\n fname=os.path.join(outdir, \"images/{}.png\".format(match_id))\n )\n\n rm.match_img = {\"src\": \"images/{}.png\".format(match_id)}\n rm.match_id = closest_match[motif.id][0]\n rm.match_pval = \"%0.2e\" % closest_match[motif.id][1][-1]\n\n report_motifs.append(rm)\n\n total_report = os.path.join(outdir, \"gimme.denovo.html\")\n\n star_img = os.path.join(config.get_template_dir(), \"star.png\")\n shutil.copyfile(star_img, os.path.join(outdir, \"images\", \"star.png\"))\n\n env = jinja2.Environment(\n loader=jinja2.FileSystemLoader([config.get_template_dir()])\n )\n template = env.get_template(\"report_template.jinja.html\")\n # TODO: title\n result = template.render(\n motifs=report_motifs,\n inputfile=inputfile,\n date=datetime.today().strftime(\"%d/%m/%Y\"),\n version=__version__,\n bg_types=list(background.keys()),\n )\n\n with open(total_report, \"wb\") as f:\n f.write(result.encode(\"utf-8\"))\n\n\ndef create_denovo_motif_report(\n inputfile, pfmfile, fgfa, background, locfa, outdir, params, stats=None\n):\n \"\"\"Create text and graphical (.html) motif reports.\"\"\"\n logger.info(\"creating de novo reports\")\n\n motifs = read_motifs(pfmfile, fmt=\"pwm\")\n\n # ROC plots\n create_roc_plots(pfmfile, fgfa, background, outdir, params[\"genome\"])\n\n # Closest match in database\n mc = MotifComparer()\n closest_match = mc.get_closest_match(motifs)\n\n if stats is None:\n stats = {}\n for bg, bgfa in background.items():\n for m, s in calc_stats(fg_file=fgfa, bg_file=bgfa, motifs=motifs).items():\n if m not in stats:\n stats[m] = {}\n stats[m][bg] = s\n\n stats = add_star(stats)\n\n if not params:\n params = {}\n cutoff_fpr = params.get(\"cutoff_fpr\", 0.9)\n lsize = np.median([len(seq) for seq in Fasta(locfa).seqs])\n\n # Location plots\n logger.debug(\"Creating localization plots\")\n for motif in motifs:\n logger.debug(\" {} {}\".format(motif.id, motif))\n outfile = os.path.join(outdir, \"images/{}_histogram.svg\".format(motif.id))\n motif_localization(locfa, motif, lsize, outfile, cutoff=cutoff_fpr)\n\n # Create reports\n _create_text_report(inputfile, motifs, closest_match, stats, outdir)\n _create_graphical_report(\n inputfile, pfmfile, background, closest_match, outdir, stats\n )\n\n\ndef motif_to_factor_series(series, pfmfile=None, motifs=None):\n if motifs is None:\n motifs = read_motifs(pfmfile, as_dict=True)\n\n if isinstance(series, pd.Index):\n index = series\n else:\n index = series.index\n\n factors = [motifs[motif].format_factors(html=True) for motif in series]\n return pd.Series(data=factors, index=index)\n\n\ndef motif_to_img_series(series, pfmfile=None, motifs=None, outdir=\".\", subdir=\"logos\"):\n if motifs is None:\n motifs = read_motifs(pfmfile, as_dict=True)\n\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n if not os.path.exists(os.path.join(outdir, subdir)):\n os.makedirs(os.path.join(outdir, subdir))\n\n img_series = []\n for motif in series:\n if motif not in motifs:\n raise ValueError(f\"Motif {motif} does not occur in motif database\")\n fname = subdir + \"/{}.png\".format(re.sub(r\"[^a-zA-Z0-9\\-]+\", \"_\", motif))\n if not os.path.exists(fname):\n motifs[motif].plot_logo(fname=os.path.join(outdir, fname))\n img_series.append(fname)\n\n if isinstance(series, pd.Index):\n index = series\n else:\n index = series.index\n return pd.Series(data=img_series, index=index)\n\n\ndef maelstrom_html_report(outdir, infile, pfmfile=None, threshold=3):\n\n # Read the maelstrom text report\n df = pd.read_table(infile, index_col=0)\n\n # Columns with maelstrom rank aggregation value\n value_cols = df.columns[\n ~df.columns.str.contains(\"corr\") & ~df.columns.str.contains(\"% with motif\")\n ]\n # Columns with correlation values\n corr_cols = df.columns[df.columns.str.contains(\"corr\")]\n\n df = df[np.any(abs(df[value_cols]) >= threshold, 1)]\n\n # Add motif logo's\n df.insert(\n 0,\n \"logo\",\n motif_to_img_series(df.index, pfmfile=pfmfile, outdir=outdir, subdir=\"logos\"),\n )\n # Add factors that can bind to the motif\n df.insert(0, \"factors\", motif_to_factor_series(df.index, pfmfile=pfmfile))\n\n rename_columns = {\"factors\": FACTOR_TOOLTIP}\n\n df_styled = (\n ExtraStyler(df)\n .set_precision(2)\n .convert_to_image(\n subset=[\"logo\"],\n height=30,\n )\n .scaled_background_gradient(\n subset=value_cols, center_zero=True, low=1 / 1.75, high=1 / 1.75\n )\n .border(subset=list(value_cols[:1]), location=\"left\")\n .border(part=\"columns\", location=\"bottom\")\n .set_table_attributes('class=\"sortable-theme-slick\" data-sortable')\n .align(subset=list(value_cols), location=\"center\")\n .set_font(\"Nunito Sans\")\n .rename(columns=rename_columns)\n )\n\n if len(corr_cols) > 0:\n df_styled = (\n df_styled.wrap(subset=list(corr_cols))\n .align(subset=list(corr_cols), location=\"center\")\n .scaled_background_gradient(\n subset=corr_cols,\n cmap=\"PuOr_r\",\n center_zero=True,\n low=1 / 1.75,\n high=1 / 1.75,\n )\n )\n\n for col in df.columns:\n if \"% with motif\" in col:\n df_styled = (\n df_styled.add_circle(subset=[col], cmap=\"Purples\", vmax=100, size=30)\n .wrap(subset=[col])\n .align(subset=[col], location=\"center\")\n .border(subset=[col], location=\"left\")\n .to_precision_str(subset=[col])\n )\n\n df_styled = df_styled.wrap().render()\n\n with open(outdir + \"/gimme.maelstrom.report.html\", \"w\", encoding=\"utf-8\") as f:\n f.write(df_styled)\n\n\ndef roc_html_report(\n outdir,\n infile,\n pfmfile,\n outname=\"gimme.motifs.html\",\n threshold=0.01,\n use_motifs=None,\n link_matches=False,\n):\n df = pd.read_table(infile, index_col=0)\n df.rename_axis(None, inplace=True)\n\n motifs = read_motifs(pfmfile, as_dict=True)\n if use_motifs is not None:\n motifs = {k: v for k, v in motifs.items() if k in use_motifs}\n idx = list(motifs.keys())\n df = df.loc[idx]\n\n df.insert(2, \"corrected P-value\", multipletests(df[\"P-value\"], method=\"fdr_bh\")[1])\n df.insert(3, \"-log10 P-value\", -np.log10(df[\"corrected P-value\"]))\n df = df[df[\"corrected P-value\"] <= threshold]\n\n cols = [\n \"factors\",\n \"logo\",\n \"% matches input\",\n \"%matches background\",\n \"-log10 P-value\",\n \"ROC AUC\",\n \"PR AUC\",\n \"Enr. at 1% FPR\",\n \"Recall at 10% FDR\",\n ]\n\n if link_matches:\n df[\"# matches\"] = (\n \"<a href=motif_scan_results/\"\n + df.index.to_series().str.replace(r\"[^a-zA-Z0-9\\-]+\", \"_\")\n + \".matches.bed>\"\n + df[\"# matches\"].astype(str)\n + \"</a>\"\n )\n\n # Add motif logo's\n df.insert(\n 0,\n \"logo\",\n motif_to_img_series(\n df.index, pfmfile=pfmfile, motifs=motifs, outdir=outdir, subdir=\"logos\"\n ),\n )\n # Add factors that can bind to the motif\n df.insert(\n 0, \"factors\", motif_to_factor_series(df.index, pfmfile=pfmfile, motifs=motifs)\n )\n\n rename_columns = {\"factors\": FACTOR_TOOLTIP}\n\n df = df[cols]\n\n bar_cols = [\n \"% matches input\",\n \"%matches background\",\n \"-log10 P-value\",\n \"ROC AUC\",\n \"PR AUC\",\n \"Enr. at 1% FPR\",\n \"Recall at 10% FDR\",\n ]\n\n df[\"% matches input\"] = df[\"% matches input\"].astype(int)\n df[\"%matches background\"] = df[\"%matches background\"].astype(int)\n rename_columns = {\"factors\": FACTOR_TOOLTIP}\n df = df.sort_values(\"ROC AUC\", ascending=False)\n with open(os.path.join(outdir, outname), \"w\", encoding=\"utf-8\") as f:\n if df.shape[0] > 0:\n f.write(\n ExtraStyler(df)\n .convert_to_image(\n subset=[\"logo\"],\n height=30,\n )\n .add_circle(\n subset=[\"% matches input\", \"%matches background\"],\n vmax=100,\n cmap=\"Purples\",\n )\n .scaled_background_gradient(\n \"-log10 P-value\", vmin=0, high=0.3, cmap=\"Reds\"\n )\n .scaled_background_gradient(\n \"ROC AUC\", vmin=0.5, vmax=1, high=0.3, cmap=\"Reds\"\n )\n .scaled_background_gradient(\n \"PR AUC\", vmin=0, vmax=1, high=0.3, cmap=\"Reds\"\n )\n .scaled_background_gradient(\n \"Enr. at 1% FPR\", vmin=1, high=0.3, cmap=\"Reds\"\n )\n .scaled_background_gradient(\n \"Recall at 10% FDR\", vmin=0, vmax=1, high=0.7, cmap=\"Reds\"\n )\n .set_precision(2)\n .set_table_attributes('class=\"sortable-theme-slick\" data-sortable')\n .wrap(subset=cols)\n .align(subset=bar_cols, location=\"center\")\n .rename(columns=rename_columns)\n .to_precision_str(subset=[\"% matches input\", \"%matches background\"])\n .render()\n )\n else:\n f.write(\"<body>No enriched motifs found.</body>\")\n"
] |
[
[
"pandas.Series",
"pandas.read_table",
"numpy.log10",
"pandas.cut",
"pandas.core.indexing._non_reducing_slice"
]
] |
tommylee3003/SDBSCAN
|
[
"b7b1f5f5aacdd2bdd69935ede58bd61cc6121a9c"
] |
[
"fastkNN.py"
] |
[
"from annoy import AnnoyIndex\r\nimport numpy as np\r\nfrom scipy.sparse import csr_matrix\r\n\r\n\r\nclass fastkNN:\r\n def __init__(self, n_neighbors, n_trees=5, metric='euclidean', return_distance=False):\r\n self.n_neighbors = n_neighbors\r\n self.n_trees = n_trees\r\n self.metric = metric\r\n self.return_distance = return_distance\r\n\r\n def fit(self, X):\r\n\r\n model = AnnoyIndex(X.shape[1], self.metric)\r\n for i in range(X.shape[0]):\r\n model.add_item(i, X[i])\r\n\r\n model.build(self.n_trees)\r\n nn = []\r\n for i in range(X.shape[0]):\r\n nn.append(model.get_nns_by_item(i, self.n_neighbors + 1, search_k=-1, include_distances=self.return_distance))\r\n self._nn = np.asarray(nn)\r\n self._fit_X = X\r\n return self\r\n\r\n def kneighbors(self):\r\n nn = self._nn\r\n indptr = np.asarray(nn[:, 0, :][:, 1:], dtype=np.int64)\r\n\r\n if self.return_distance:\r\n distance = nn[:, 1, :][:, 1:]\r\n return (distance, indptr)\r\n else:\r\n return (indptr)\r\n\r\n def kneighbors_graph(self, n_neighbors=None):\r\n if n_neighbors is None:\r\n n_neighbors = self.n_neighbors\r\n n_samples = self._fit_X.shape[0]\r\n n_nonzero = n_samples * n_neighbors\r\n A_indptr = np.arange(0, n_nonzero + 1, n_neighbors)\r\n nn = self._nn\r\n if not self.return_distance:\r\n A_data = np.ones(n_samples * n_neighbors, dtype=np.int8)\r\n A_ind = nn[:, 1: (n_neighbors+1)]\r\n else:\r\n A_data = nn[:, 1, :][:, 1: (n_neighbors+1)]\r\n A_data = np.ravel(A_data)\r\n A_ind = nn[:, 0, :][:, 1: (n_neighbors+1)]\r\n\r\n kneighbors_graph = csr_matrix((A_data, A_ind.ravel(), A_indptr), shape=(n_samples, n_samples))\r\n\r\n return kneighbors_graph"
] |
[
[
"numpy.asarray",
"numpy.arange",
"numpy.ravel",
"numpy.ones"
]
] |
Actis92/pytorch_tabular
|
[
"78dabf5e7b97d8ff24db4bc83d9d0a2273941bbe"
] |
[
"pytorch_tabular/feature_extractor.py"
] |
[
"# Pytorch Tabular\n# Author: Manu Joseph <manujoseph@gmail.com>\n# For license information, see LICENSE.TXT\nfrom collections import defaultdict\n\nimport pandas as pd\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom tqdm.autonotebook import tqdm\n\nfrom pytorch_tabular.models import NODEModel, TabNetModel\nfrom pytorch_tabular.models.mixture_density import BaseMDN\n\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\nimport torch\n\n\nclass DeepFeatureExtractor(BaseEstimator, TransformerMixin):\n def __init__(\n self, tabular_model, extract_keys=[\"backbone_features\"], drop_original=True\n ):\n \"\"\"Initializes the Transformer and extracts the neural features\n\n Args:\n tabular_model (TabularModel): The trained TabularModel object\n \"\"\"\n assert not (\n isinstance(tabular_model.model, NODEModel)\n or isinstance(tabular_model.model, TabNetModel)\n or isinstance(tabular_model.model, BaseMDN)\n ), \"FeatureExtractor doesn't work for Mixture Density Networks, NODE Model, & Tabnet Model\"\n self.tabular_model = tabular_model\n self.extract_keys = extract_keys\n self.drop_original = drop_original\n\n def fit(self, X, y=None):\n \"\"\"Just for compatibility. Does not do anything\"\"\"\n return self\n\n def transform(self, X: pd.DataFrame, y=None):\n \"\"\"Transforms the categorical columns specified to the trained neural features from the model\n\n Args:\n X (pd.DataFrame): DataFrame of features, shape (n_samples, n_features). Must contain columns to encode.\n y ([type], optional): Only for compatibility. Not used. Defaults to None.\n\n Raises:\n ValueError: [description]\n\n Returns:\n pd.DataFrame: The encoded dataframe\n \"\"\"\n\n X_encoded = X.copy(deep=True)\n orig_features = X_encoded.columns\n self.tabular_model.model.eval()\n inference_dataloader = (\n self.tabular_model.datamodule.prepare_inference_dataloader(X_encoded)\n )\n logits_predictions = defaultdict(list)\n for batch in tqdm(inference_dataloader, desc=\"Generating Features...\"):\n for k, v in batch.items():\n if isinstance(v, list) and (len(v) == 0):\n # Skipping empty list\n continue\n batch[k] = v.to(self.tabular_model.model.device)\n _, ret_value = self.tabular_model.model.predict(\n batch, ret_model_output=True\n )\n for k in self.extract_keys:\n if k in ret_value.keys():\n logits_predictions[k].append(ret_value[k].detach().cpu())\n\n for k, v in logits_predictions.items():\n v = torch.cat(v, dim=0).numpy()\n if v.ndim == 1:\n v = v.reshape(-1, 1)\n for i in range(v.shape[-1]):\n if v.shape[-1] > 1:\n X_encoded[f\"{k}_{i}\"] = v[:, i]\n else:\n X_encoded[f\"{k}\"] = v[:, i]\n\n if self.drop_original:\n X_encoded.drop(columns=orig_features, inplace=True)\n return X_encoded\n\n def fit_transform(self, X: pd.DataFrame, y=None):\n \"\"\"Encode given columns of X based on the learned features.\n\n Args:\n X (pd.DataFrame): DataFrame of features, shape (n_samples, n_features). Must contain columns to encode.\n y ([type], optional): Only for compatibility. Not used. Defaults to None.\n\n Returns:\n pd.DataFrame: The encoded dataframe\n \"\"\"\n self.fit(X, y)\n return self.transform(X)\n\n def save_as_object_file(self, path):\n if not self._mapping:\n raise ValueError(\n \"`fit` method must be called before `save_as_object_file`.\"\n )\n pickle.dump(self.__dict__, open(path, \"wb\"))\n\n def load_from_object_file(self, path):\n for k, v in pickle.load(open(path, \"rb\")).items():\n setattr(self, k, v)\n"
] |
[
[
"torch.cat"
]
] |
aikonbrasil/CarND-Advanced-Lane-Lines
|
[
"9fa0dcfcb2ead8629ea8cbd911c45e6940a7124e"
] |
[
"main.py"
] |
[
"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport glob\nfrom math import fabs\n# Import everything needed to edit/save/watch video clips\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML\nglobal objpoints\nglobal imgpoints\nglobal src\nglobal dst\nglobal globalCounter\nglobal left_lane_inds\nglobal right_lane_inds\nglobal left_fitx_mean\nglobal right_fitx_mean\nglobal global_threshold\nglobalCounter = 0\n\n###############################################################################\ndef cal_undistort(img, objpoints, imgpoints):\n img1 = np.copy(img)\n #gray = cv2.cvtColor(img1,cv2.COLOR_RGB2GRAY)\n #ret, corners = cv2.findChessboardCorners(gray, (9,6), None)\n #img1 = cv2.drawChessboardCorners(img1, (9,6), corners, ret)\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)\n undist = cv2.undistort(img1, mtx, dist, None, mtx)\n return undist\n\n###############################################################################\nflag_plot = False\n###############################################################################\n# CAMERA CALIBRATION - script\n##############################################################################\n# Prepare object points\nnx = 9 # Number of inside corners in x\nny = 6 # Number of inside corners in y\n\n# Read in and make a list of calibration images\nimages = glob.glob('camera_cal/calibration*.jpg')\n#fname = 'camera_cal/calibration3.jpg'\n#img = cv2.imread(fname)\n\n# Arrays to store object points and image points from all the images\nobjpoints = [] # 3D points in real world space\nimgpoints = [] # 2D points in image plane\n\n# Prepare object points, like (0,0,0), (1,0,0), (2,0,0) ... ,(7,5,0)\nobjp = np.zeros((nx*ny,3), np.float32)\nobjp[:,:2] = np.mgrid[0:nx,0:ny].T.reshape(-1,2) #x, y coordinates\n\nfor fname in images:\n # Read each images\n img = mpimg.imread(fname)\n\n # Convert image to grayscale\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n\n # Find the chessboard corners\n ret, corners = cv2.findChessboardCorners(gray, (nx, ny), None)\n\n if ret == True:\n #print('ENTROU NO IF')\n # Appending data for imgpoints and objpoints arrays\n imgpoints.append(corners)\n objpoints.append(objp)\n\n # draw and display the corners\n #img_corners_detected = cv2.drawChessboardCorners(img, (nx, ny), corners, ret)\n #plt.imshow(img_corners_detected)\n #plt.show()\nif flag_plot == True:\n img = mpimg.imread('camera_cal/calibration5.jpg')\n undistorted = cal_undistort(img, objpoints, imgpoints)\n\n f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))\n f.tight_layout()\n ax1.imshow(img)\n ax1.set_title('Original Image', fontsize=50)\n ax2.imshow(undistorted)\n ax2.set_title('Undistorted Image', fontsize=50)\n plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)\n plt.show()\n\n###############################################################################\n# PIPELINE (Test images) - Provide an example of a distortion-corrected images\n##############################################################################\n\n# Loading a test image\nif flag_plot == True:\n img = mpimg.imread('test_images/straight_lines2.jpg')\n undistorted = cal_undistort(img, objpoints, imgpoints)\n f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))\n f.tight_layout()\n ax1.imshow(img)\n ax1.set_title('Original Image', fontsize=50)\n ax2.imshow(undistorted)\n ax2.set_title('Undistorted Image', fontsize=50)\n plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)\n plt.show()\n\n###############################################################################\n# PIPELINE (thresholding) Describe how (and identify where in your code) you\n# used color transforms, gradients or other methods to create a thresholded\n# binary image. Provide an example of a binary image result.\n###############################################################################\n\n# Edit this function to create your own pipeline.\ndef pipeline(img, s_thresh=(170, 255), sx_thresh=(20, 100), d_thresh=(0, np.pi/2), mag_thresh=(0,255)):\n img = np.copy(img)\n # Convert to HLS color space and separate the V channel\n hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS).astype(np.float)\n l_channel = hls[:,:,1]\n s_channel = hls[:,:,2]\n # ********** Technique 1 - Sobel x\n sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0) # Take the derivative in x\n abs_sobelx = np.absolute(sobelx) # Absolute x derivative to accentuate lines away from horizontal\n scaled_sobel = np.uint8(255*abs_sobelx/np.max(abs_sobelx))\n # Threshold x gradient\n sxbinary = np.zeros_like(scaled_sobel)\n sxbinary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1\n\n\n # ********* Technique 2 - Threshold Direction\n sobely = cv2.Sobel(l_channel, cv2.CV_64F, 0, 1) # Take the derivative in y\n abs_sobely = np.absolute(sobely) # Absolute y derivative to accentuate lines away from horizontal\n # Using np.arctan2(abs_sobely, abs_sobelx) to calculate the direction of the gradient\n absgraddir = np.arctan2(abs_sobely, abs_sobelx)\n # Threshold direction gradient\n sxbinary_direction = np.zeros_like(absgraddir)\n sxbinary_direction[(absgraddir >= d_thresh[0]) & (absgraddir <= d_thresh[1])] = 1\n sxbinary_direction = np.uint8(sxbinary_direction)\n\n # ************Technique 3 - Threshold color S channel\n s_binary = np.zeros_like(s_channel)\n s_binary = np.uint8(s_binary)\n s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1\n\n # **********Technique 4 - Abs_sobelxy\n # Calculate the magnitude\n abs_sobelxy = np.sqrt(np.square(sobelx)+np.square(sobely))\n # 4) Scale to 8-bit (0 - 255) and convert to type = np.uint8\n scaled_sobelxy = np.uint8(255*abs_sobelxy/np.max(abs_sobelxy))\n # 5) Create a binary mask where mag thresholds are met\n sxybinary = np.zeros_like(scaled_sobelxy)\n sxybinary[(scaled_sobelxy >= mag_thresh[0]) & (scaled_sobelxy <= mag_thresh[1])] = 1\n\n\n # Combine the two binary thresholds\n combined_binary = np.zeros_like(sxbinary)\n #combined_binary[(s_binary == 1) | (sxbinary == 1) & (sxbinary_direction == 1)] = 1\n combined_binary[(s_binary == 1) | (sxbinary == 1)] = 1\n #combined_binary[(s_binary == 1) | (sxbinary == 1) | (sxybinary == 1)] = 1\n # Stack each channel\n # Note color_binary[:, :, 0] is all 0s, effectively an all black image. It might\n # be beneficial to replace this channel with something else.\n #color_binary = np.dstack(( np.zeros_like(sxbinary), sxbinary, s_binary)) * 255\n color_binary = np.dstack((sxybinary, sxbinary, s_binary)) * 255\n #return color_binary, combined_binary\n return sxbinary_direction, combined_binary\n\n\nif flag_plot == True:\n img = mpimg.imread('test_images/test2.jpg')\n image = cal_undistort(img, objpoints, imgpoints)\n result_mixcolor, result_binary = pipeline(image, s_thresh=(170, 255), sx_thresh=(20, 100), d_thresh = (0.75, 1.3), mag_thresh=(58,110))\n\n # Plot the result\n f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(24, 9))\n f.tight_layout()\n\n ax1.imshow(image)\n ax1.set_title('Original Image', fontsize=40)\n\n ax2.imshow(result_mixcolor)\n ax2.set_title('Color Binary', fontsize=40)\n plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)\n\n ax3.imshow(result_binary,cmap='gray')\n ax3.set_title('Binary Result', fontsize=40)\n plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)\n\n plt.show()\n\n\n###############################################################################\n# PIPELINE (Perspective Transform) Describe how (and identify where in your code)\n# you performed a perspective transform and provide an example of a transformed\n# image.\n###############################################################################\ndef corners_unwarp(img1, objpoints, imgpoints, src, dst):\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)\n undist = cv2.undistort(img1, mtx, dist, None, mtx)\n M = cv2.getPerspectiveTransform(src, dst)\n # e) use cv2.warpPerspective() to warp your image to a top-down view\n img_size = gray.shape[::-1]\n warped = cv2.warpPerspective(undist, M, img_size, flags=cv2.INTER_LINEAR)\n #delete the next two lines\n #M = None\n #warped = np.copy(img1)\n return warped, M\n\npoint_0 = [587,452]\npoint_1 = [691,452]\npoint_2 = [200,718]\npoint_3 = [1120,718]\nsrc = np.float32([point_0,point_1,point_2,point_3])\ndst = np.float32([[465,0],[920,0],[465,700],[920,700]])\nimages = glob.glob('test_images/*.jpg')\nfor frame in images:\n img = mpimg.imread(frame)\n#img = mpimg.imread('test_images/straight_lines1.jpg')\n undistorted = cal_undistort(img, objpoints, imgpoints)\n cv2.line(undistorted, tuple(point_2), tuple(point_0), color=[255,0,0], thickness=2)\n cv2.line(undistorted, tuple(point_0), tuple(point_1), color=[255,0,0], thickness=1)\n cv2.line(undistorted, tuple(point_1), tuple(point_3), color=[255,0,0], thickness=2)\n cv2.line(undistorted, tuple(point_2), tuple(point_3), color=[255,0,0], thickness=2)\n #plt.imshow(image)\n #plt.show()\n top_down, perspective_M = corners_unwarp(undistorted, objpoints, imgpoints, src, dst)\n #flag_plot = True\n if flag_plot == True:\n f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))\n f.tight_layout()\n ax1.imshow(undistorted)\n ax1.set_title('Undistorted Image', fontsize=30)\n ax2.imshow(top_down)\n ax2.set_title('Warped Image - bird´s eye view', fontsize=30)\n plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)\n plt.show()\n\n###############################################################################\n# PIPELINE (lane line pixels) Describe how (and identify where in your code) you\n# identified lane-line pixels and fit their positions with a polynomial?\n###############################################################################\ndef list_of_peaks(hist, maxrange,flag):\n #Convert histogram to simple list\n #hist = [val[0] for val in hist];\n\n #Generate a list of indices\n indices = list(range(0, maxrange));\n\n #Descending sort-by-key with histogram value as key\n s = [(x,y) for y,x in sorted(zip(hist,indices), reverse=True)]\n\n #Index of highest peak in histogram\n # Peaks over a threshold\n grupos_index = [] # 3D points in real world space\n grupos_valor = [] # 2D points in image plane\n index_of_highest_peak = s[0][0]\n #print(s)\n index_of_highest_peak = s[0][0]\n # Loop of the first 20 samples of list of peaks\n for ii in range(0,20):\n gradiente = s[ii][0] - s[ii+1][0]\n #print(gradiente)\n if flag == 1:\n if gradiente < -100:\n #print(\"Segundo Pico potencial util\")\n #print(s[ii+1][0])\n index_of_highest_peak = s[ii+1][0]\n break\n else:\n if gradiente > 250:\n print(\"Segundo Pico potencial util\")\n print(s)\n print(gradiente)\n print(s[ii+1][0])\n index_of_highest_peak = s[ii+1][0]\n break\n\n #index_of_second_highest_peak = s[1][0]\n #print(s)\n #print(\"PICO MAIOR no indice\")\n #print(index_of_highest_peak)\n return index_of_highest_peak\n\ndef histogram_analise(binary_warped):\n # Take a histogram of the bottom half of the image\n histogram = np.sum(binary_warped[binary_warped.shape[0]//2:,:], axis=0)\n suma_center_hist = np.sum(histogram[600:800])\n #print(suma_center_hist)\n #if suma_center_hist > 197:\n if suma_center_hist > 1100:\n threshold = 200\n else:\n threshold = 100\n return threshold\n\n\ndef findng_lines_slidingwindow(binary_warped):\n global left_lane_inds\n global right_lane_inds\n global global_threshold\n # Take a histogram of the bottom half of the image\n histogram = np.sum(binary_warped[binary_warped.shape[0]//2:,:], axis=0)\n # Create an output image to draw on and visualize the result\n out_img = np.dstack((binary_warped, binary_warped, binary_warped))*255\n # Find the peak of the left and right halves of the histogram\n # These will be the starting point for the left and right lines\n midpoint = np.int(histogram.shape[0]/2)\n leftx_base = np.argmax(histogram[400:midpoint])+400\n rightx_base = np.argmax(histogram[midpoint:1060]) + midpoint\n #print(midpoint)\n #print('Pico raw izquerda')\n #print(leftx_base)\n #print(\"ENTRO PARA CALCULAR PICO\")\n peak_1 = list_of_peaks(histogram[:midpoint],midpoint, flag=1)\n #peak_2 = list_of_peaks(histogram[midpoint:],midpoint, flag=2)\n #print('1er pico elaborado:')\n #print(peak_1)\n #leftx_base = peak_1\n #rightx_base = peak_2 + midpoint\n\n\n # Choose the number of sliding windows\n nwindows = 9\n # Set height of windows\n window_height = np.int(binary_warped.shape[0]/nwindows)\n # Identify the x and y positions of all nonzero pixels in the image\n nonzero = binary_warped.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n # Current positions to be updated for each window\n leftx_current = leftx_base\n rightx_current = rightx_base\n # Set the width of the windows +/- margin\n margin = 50\n # Set minimum number of pixels found to recenter window\n minpix = 50\n # Create empty lists to receive left and right lane pixel indices\n left_lane_inds = []\n right_lane_inds = []\n sum_dados_left = []\n sum_dados_right = []\n\n # Step through the windows one by one\n for window in range(nwindows):\n # Identify window boundaries in x and y (and right and left)\n win_y_low = binary_warped.shape[0] - (window+1)*window_height\n win_y_high = binary_warped.shape[0] - window*window_height\n win_xleft_low = leftx_current - margin\n win_xleft_high = leftx_current + margin\n win_xright_low = rightx_current - margin\n win_xright_high = rightx_current + margin\n # Draw the windows on the visualization image\n cv2.rectangle(out_img,(win_xleft_low,win_y_low),(win_xleft_high,win_y_high),\n (0,255,0), 2)\n cv2.rectangle(out_img,(win_xright_low,win_y_low),(win_xright_high,win_y_high),\n (0,255,0), 2)\n # Identify the nonzero pixels in x and y within the window\n good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &\n (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]\n good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &\n (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]\n # Append these indices to the lists\n left_lane_inds.append(good_left_inds)\n right_lane_inds.append(good_right_inds)\n # If you found > minpix pixels, recenter next window on their mean position\n if len(good_left_inds) > minpix:\n leftx_current = np.int(np.mean(nonzerox[good_left_inds]))\n if len(good_right_inds) > minpix:\n rightx_current = np.int(np.mean(nonzerox[good_right_inds]))\n\n\n\n # Concatenate the arrays of indices\n left_lane_inds = np.concatenate(left_lane_inds)\n right_lane_inds = np.concatenate(right_lane_inds)\n\n # Extract left and right line pixel positions\n leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds]\n rightx = nonzerox[right_lane_inds]\n righty = nonzeroy[right_lane_inds]\n\n # Fit a second order polynomial to each\n left_fit = np.polyfit(lefty, leftx, 2)\n right_fit = np.polyfit(righty, rightx, 2)\n\n # Fit a second order polynomial in meters\n ym_per_pix = 30/720 # meters per pixel in y dimension\n xm_per_pix = 3.7/700 # meters per pixel in x dimension\n\n # Fit new polynomials to x,y in world space\n left_fit_cr = np.polyfit(lefty*ym_per_pix, leftx*xm_per_pix, 2)\n right_fit_cr = np.polyfit(righty*ym_per_pix, rightx*xm_per_pix, 2)\n\n # Calculate the new radii of curvature\n y_eval = np.max(lefty)\n y_evall = np.max(righty)\n left_curverad = ((1 + (2*left_fit_cr[0]*y_eval*ym_per_pix + left_fit_cr[1])**2)**1.5) / np.absolute(2*left_fit_cr[0])\n right_curverad = ((1 + (2*right_fit_cr[0]*y_evall*ym_per_pix + right_fit_cr[1])**2)**1.5) / np.absolute(2*right_fit_cr[0])\n # Now our radius of curvature is in meters\n #print('Left_line_curvature = ',left_curverad, 'm',' Right_line_curvature = ', right_curverad, 'm')\n\n\n return left_lane_inds, right_lane_inds, left_fit, right_fit, out_img, nonzeroy, nonzerox, histogram, left_curverad, right_curverad\n\ndef findng_lines_targeted(binary_warped,left_fit, right_fit):\n #************************************************************************\n nonzero = binary_warped.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n margin = 100\n left_lane_inds = ((nonzerox > (left_fit[0]*(nonzeroy**2) + left_fit[1]*nonzeroy +\n left_fit[2] - margin)) & (nonzerox < (left_fit[0]*(nonzeroy**2) +\n left_fit[1]*nonzeroy + left_fit[2] + margin)))\n\n right_lane_inds = ((nonzerox > (right_fit[0]*(nonzeroy**2) + right_fit[1]*nonzeroy +\n right_fit[2] - margin)) & (nonzerox < (right_fit[0]*(nonzeroy**2) +\n right_fit[1]*nonzeroy + right_fit[2] + margin)))\n\n # Again, extract left and right line pixel positions\n leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds]\n rightx = nonzerox[right_lane_inds]\n righty = nonzeroy[right_lane_inds]\n # Fit a second order polynomial to each\n left_fit = np.polyfit(lefty, leftx, 2)\n right_fit = np.polyfit(righty, rightx, 2)\n # Generate x and y values for plotting\n ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0] )\n left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]\n right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]\n # END OF CODE OPTIMZED for this function without windowing solution\n #\n ym_per_pix = 30/720 # meters per pixel in y dimension\n xm_per_pix = 3.7/700 # meters per pixel in x dimension\n\n # Fit new polynomials to x,y in world space\n left_fit_cr = np.polyfit(lefty*ym_per_pix, leftx*xm_per_pix, 2)\n right_fit_cr = np.polyfit(righty*ym_per_pix, rightx*xm_per_pix, 2)\n\n # Calculate the new radii of curvature\n y_eval = np.max(lefty)\n y_evall = np.max(righty)\n left_curverad = ((1 + (2*left_fit_cr[0]*y_eval*ym_per_pix + left_fit_cr[1])**2)**1.5) / np.absolute(2*left_fit_cr[0])\n right_curverad = ((1 + (2*right_fit_cr[0]*y_evall*ym_per_pix + right_fit_cr[1])**2)**1.5) / np.absolute(2*right_fit_cr[0])\n # Now our radius of curvature is in meters\n #print('Left_line_curvature = ',left_curverad, 'm',' Right_line_curvature = ', right_curverad, 'm')\n\n\n return left_lane_inds, right_lane_inds, left_fit, right_fit, nonzeroy, nonzerox, left_curverad, right_curverad\n\nimages = []\n#images = glob.glob('test_images/*.jpg')\n#images = glob.glob('evaluation_images/*.jpg')\n#images = glob.glob('test_images/test5.jpg')\nfor frame in images:\n print(frame)\n img = mpimg.imread(frame)\n # for Video : input--> img output --> result\n image = cal_undistort(img, objpoints, imgpoints)\n\n point_0 = [587,452]\n point_1 = [691,452]\n point_2 = [200,718]\n point_3 = [1120,718]\n\n #image = mpimg.imread('test_images/test1.jpg')\n # Applying Threshold\n\n result_mixcolor, result_binary = pipeline(image, s_thresh=(100, 255), sx_thresh=(20, 100), d_thresh = (0.7, 1.3), mag_thresh=(58,110))\n\n #binary_warped, perspective_M = corners_unwarp(result_binary, objpoints, imgpoints, src, dst)\n binary_warped, perspective_M = corners_unwarp(result_binary, objpoints, imgpoints, src, dst)\n\n variable_threshold = histogram_analise(binary_warped)\n print(\"VARIABLE THRESHOLD\")\n print(variable_threshold)\n if variable_threshold == 200:\n print(\"entrou !\")\n result_mixcolor, result_binary = pipeline(image, s_thresh=(200, 255), sx_thresh=(20, 100), d_thresh = (0.7, 1.3), mag_thresh=(58,110))\n binary_warped, perspective_M = corners_unwarp(result_binary, objpoints, imgpoints, src, dst)\n\n left_lane_inds, right_lane_inds, left_fit, right_fit, out_img, nonzeroy, nonzerox, histogram, left_curverad, right_curverad= findng_lines_slidingwindow(binary_warped)\n\n # Calculations of polynoms points\n ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0] )\n left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]\n right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]\n\n\n # Preparing and format for undistort with detected green region\n warped = binary_warped\n # Create an image to draw the lines on\n warp_zero = np.zeros_like(warped).astype(np.uint8)\n color_warp = np.dstack((warp_zero, warp_zero, warp_zero))\n\n # Recast the x and y points into usable format for cv2.fillPoly()\n pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])\n pts = np.hstack((pts_left, pts_right))\n\n # Draw the lane onto the warped blank image\n cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0))\n Minv = cv2.getPerspectiveTransform(dst, src) # Inverse transformation\n # Warp the blank back to original image space using inverse perspective matrix (Minv)\n newwarp = cv2.warpPerspective(color_warp, Minv, (image.shape[1], image.shape[0]))\n # Combine the result with the original image\n undist = image\n result = cv2.addWeighted(undist, 1, newwarp, 0.3, 0)\n\n # ***********visualization\n # Generate x and y values for plotting\n flag_plot = True\n if flag_plot == True:\n out_img[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0]\n out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255]\n\n f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(10, 5))\n f.tight_layout()\n\n ax1.imshow(result_binary,cmap='gray')\n ax1.set_title('Binary Image', fontsize=20)\n\n #ax2.imshow(binary_warped,cmap='gray')\n #ax2.set_title('Binary Warped Result', fontsize=20)\n #plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)\n\n ax2.imshow(out_img)\n ax2.plot(left_fitx, ploty, color='yellow')\n ax2.plot(right_fitx, ploty, color='yellow')\n ax2.set_title('Line with position polynomial', fontsize=20)\n\n ax4.plot(histogram)\n ax4.set_title('Histogram',fontsize=20)\n\n ax3.imshow(result)\n ax3.set_title('Original (undistorted) image with lane area drawn', fontsize=15)\n plt.show()\n\ndef addingText(img,text1, text2):\n\n font = cv2.FONT_HERSHEY_SIMPLEX\n bottomLeftCornerOfText1 = (10,50)\n bottomLeftCornerOfText2 = (10,100)\n fontScale = 1\n fontColor = (255,255,255)\n lineType = 2\n\n cv2.putText(img,'Radius of Curvature = '+text1+'(m)',bottomLeftCornerOfText1,font,fontScale,fontColor,lineType)\n cv2.putText(img,'Vehicle is '+text2+'m left of center',bottomLeftCornerOfText2,font,fontScale,fontColor,lineType)\n cv2.putText(img,'Advanced Lane Finding',(10,130),font,0.6,fontColor,lineType)\n cv2.putText(img,'Author: Dick Carrillo Melgarejo',(10,160),font,0.6,fontColor,lineType)\n\n return img\n\n################################################################################\n# Video\n################################################################################\ndef process_image(img):\n global globalCounter\n global left_fit\n global right_fit\n global left_fitx_mean\n global right_fitx_mean\n #gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n image = cal_undistort(img, objpoints, imgpoints)\n point_0 = [587,452]\n point_1 = [691,452]\n point_2 = [200,718]\n point_3 = [1120,718]\n\n #image = mpimg.imread('test_images/test1.jpg')\n # Applying Threshold\n result_mixcolor, result_binary = pipeline(image, s_thresh=(100, 255), sx_thresh=(20, 100), d_thresh = (0.75, 1.3), mag_thresh=(58,110))\n binary_warped, perspective_M = corners_unwarp(result_binary, objpoints, imgpoints, src, dst)\n\n\n variable_threshold = histogram_analise(binary_warped)\n #print(\"VARIABLE THRESHOLD\")\n #print(variable_threshold)\n if variable_threshold == 200:\n #print(\"entrou !\")\n result_mixcolor, result_binary = pipeline(image, s_thresh=(200, 255), sx_thresh=(20, 100), d_thresh = (0.7, 1.3), mag_thresh=(58,110))\n binary_warped, perspective_M = corners_unwarp(result_binary, objpoints, imgpoints, src, dst)\n\n #print(globalCounter)\n if globalCounter < 2:\n left_lane_inds, right_lane_inds, left_fit, right_fit, out_img, nonzeroy, nonzerox, histogram, left_curverad, right_curverad= findng_lines_slidingwindow(binary_warped)\n #print(\"Using WINDOWING VERSION of FINDING LINES\")\n else:\n left_lane_inds, right_lane_inds, left_fit, right_fit, nonzeroy, nonzerox, left_curverad, right_curverad = findng_lines_targeted(binary_warped,left_fit, right_fit)\n #print(\"Using OPTIMIZED VERSION of FINDING LINES\")\n if fabs(left_curverad-right_curverad) > 500:\n globalCounter = 0\n\n globalCounter += 1\n\n # Calculations of polynoms points\n ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0] )\n left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]\n right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]\n #print(type(left_fitx))\n #print(left_fit.size)\n #print(left_fitx_mean.size)\n left_fitx_mean = left_fitx*0.3 + left_fitx_mean*0.7\n right_fitx_mean = right_fitx*0.1 + right_fitx_mean*0.9\n\n left_fitx = left_fitx_mean\n right_fitx = right_fitx_mean\n\n\n # Preparing and format for undistort with detected green region\n warped = binary_warped\n # Create an image to draw the lines on\n #out_img[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0]\n #out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255]\n warp_zero_r = np.zeros_like(warped).astype(np.uint8)\n warp_zero_g = np.zeros_like(warped).astype(np.uint8)\n warp_zero_b = np.zeros_like(warped).astype(np.uint8)\n warp_zero_r[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = 255\n\n # calculating offset of the car respect the center line.\n distancia_emPixels_l = np.mean(nonzerox[left_lane_inds])\n distancia_emPixels_r = np.mean(nonzerox[right_lane_inds])\n pto_medio_medido = distancia_emPixels_r/2+distancia_emPixels_l/2\n offset_pixels = fabs(pto_medio_medido-640)\n offset_meters = offset_pixels*3.7/700\n #print(offset_pixels)\n #print(offset_pixels*3.7/700)\n\n warp_zero_b[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = 255\n color_warp = np.dstack((warp_zero_r, warp_zero_g, warp_zero_b))\n\n # Recast the x and y points into usable format for cv2.fillPoly()\n pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])\n pts = np.hstack((pts_left, pts_right))\n\n # Draw the lane onto the warped blank image\n cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0))\n Minv = cv2.getPerspectiveTransform(dst, src) # Inverse transformation\n # Warp the blank back to original image space using inverse perspective matrix (Minv)\n newwarp = cv2.warpPerspective(color_warp, Minv, (image.shape[1], image.shape[0]))\n # Combine the result with the original image\n undist = image\n result = cv2.addWeighted(undist, 1, newwarp, 0.3, 0)\n curvature = left_curverad/2+right_curverad/2\n string1 = \"%0.1f\" %curvature\n string2 = \"%0.1f\" %offset_meters\n result = addingText(result,string1, string2)\n\n return result\n\nif True: # To Generate the Video should be True\n globalCounter = 0\n left_fitx_mean = np.ones(720)*400\n right_fitx_mean = np.ones(720)*800\n video_output = 'outputvideo.mp4'\n clip1 = VideoFileClip(\"project_video.mp4\")\n #white_clip = clip1.fl_image(process_image).subclip(23,25)\n white_clip = clip1.fl_image(process_image)\n white_clip.write_videofile(video_output, audio=False)\n print('finished')\n"
] |
[
[
"numpy.polyfit",
"numpy.linspace",
"numpy.arctan2",
"matplotlib.image.imread",
"numpy.int",
"numpy.concatenate",
"numpy.zeros_like",
"numpy.max",
"numpy.mean",
"numpy.square",
"numpy.hstack",
"numpy.uint8",
"numpy.copy",
"numpy.argmax",
"numpy.float32",
"matplotlib.pyplot.subplots_adjust",
"numpy.zeros",
"numpy.int_",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.sum",
"numpy.absolute",
"matplotlib.pyplot.subplots",
"numpy.dstack",
"numpy.ones",
"numpy.vstack"
]
] |
andrewtarzia/MCHammer
|
[
"983ffb374bf14fcda57141cbf53e2239481ec587"
] |
[
"tests/collapser/test_collapser.py"
] |
[
"import numpy as np\nfrom mchammer import get_atom_distance\n\n\ndef test_c_get_subunit_distances(\n collapser,\n coll_molecule,\n coll_subunits,\n coll_su_dists,\n coll_position_matrix,\n):\n test = coll_molecule.with_position_matrix(coll_position_matrix)\n for i, dist in enumerate(collapser._get_subunit_distances(\n mol=test,\n subunits=coll_subunits,\n )):\n print(i)\n assert np.isclose(dist, coll_su_dists[i], atol=1E-6)\n\n\ndef test_c_get_new_position_matrix(\n collapser,\n coll_position_matrix,\n coll_position_matrix2,\n coll_molecule,\n coll_subunits,\n coll_step,\n coll_vectors,\n coll_scales,\n):\n test_mol = coll_molecule.with_position_matrix(coll_position_matrix)\n test_pos_mat = collapser._get_new_position_matrix(\n mol=test_mol,\n subunits=coll_subunits,\n step_size=coll_step,\n vectors=coll_vectors,\n scales=coll_scales,\n )\n\n for i in range(len(coll_position_matrix2)):\n test = test_pos_mat[i]\n given = coll_position_matrix2[i]\n assert np.all(np.isclose(test, given, atol=1E-6))\n\n\ndef test_c_get_bb_vectors(\n collapser, coll_molecule, coll_subunits, su_vectors, su_scales,\n):\n test_vectors, test_scales = collapser._get_subunit_vectors(\n coll_molecule, coll_subunits\n )\n for t, s in zip(test_vectors, su_vectors):\n test = test_vectors[t]\n su_v = su_vectors[s]\n assert np.all(np.equal(test, su_v))\n test = test_scales[t]\n su_s = su_scales[s]\n assert np.all(np.equal(test, su_s))\n\n\ndef test_c_get_result(\n collapser, coll_molecule, coll_final_position_matrix\n):\n original_pos_mat = coll_molecule.get_position_matrix()\n subunits = coll_molecule.get_subunits(bond_pair_ids=((0, 3), ))\n test_mol, results = collapser.get_result(\n mol=coll_molecule,\n bond_pair_ids=((0, 3), ),\n subunits=subunits,\n )\n\n final_min_distance = min(\n dist for dist in collapser._get_subunit_distances(\n test_mol, subunits\n )\n )\n # Give it some wiggle room.\n assert np.isclose(1.4947505, final_min_distance, atol=1E-8)\n\n # Check position matrix because this code is deterministic.\n test_pos_mat = test_mol.get_position_matrix()\n for i in range(len(coll_final_position_matrix)):\n test = test_pos_mat[i]\n given = coll_final_position_matrix[i]\n assert np.all(np.isclose(test, given, atol=1E-8))\n\n # Test all other bond lengths are equivalent.\n for bond in coll_molecule.get_bonds():\n if (bond.get_atom1_id(), bond.get_atom2_id()) != (0, 3):\n test = get_atom_distance(\n position_matrix=results.get_position_matrix(),\n atom1_id=bond.get_atom1_id(),\n atom2_id=bond.get_atom2_id(),\n )\n bond_length = get_atom_distance(\n position_matrix=original_pos_mat,\n atom1_id=bond.get_atom1_id(),\n atom2_id=bond.get_atom2_id(),\n )\n assert np.isclose(test, bond_length, atol=1E-6)\n\n\ndef test_c_get_trajectory(\n collapser, coll_molecule, coll_final_position_matrix\n):\n original_pos_mat = coll_molecule.get_position_matrix()\n subunits = coll_molecule.get_subunits(bond_pair_ids=((0, 3), ))\n test_mol, results = collapser.get_trajectory(\n mol=coll_molecule,\n bond_pair_ids=((0, 3), ),\n subunits=subunits,\n )\n test_mol = coll_molecule.with_position_matrix(\n results.get_final_position_matrix()\n )\n assert results.get_step_count() == 35\n\n final_min_distance = min(\n dist for dist in collapser._get_subunit_distances(\n test_mol, subunits\n )\n )\n # Give it some wiggle room.\n assert np.isclose(1.4947505, final_min_distance, atol=1E-8)\n\n # Check position matrix because this code is deterministic.\n test_pos_mat = test_mol.get_position_matrix()\n for i in range(len(coll_final_position_matrix)):\n test = test_pos_mat[i]\n given = coll_final_position_matrix[i]\n assert np.all(np.isclose(test, given, atol=1E-8))\n\n # Test all other bond lengths are equivalent.\n for bond in coll_molecule.get_bonds():\n if (bond.get_atom1_id(), bond.get_atom2_id()) != (0, 3):\n test = get_atom_distance(\n position_matrix=results.get_final_position_matrix(),\n atom1_id=bond.get_atom1_id(),\n atom2_id=bond.get_atom2_id(),\n )\n bond_length = get_atom_distance(\n position_matrix=original_pos_mat,\n atom1_id=bond.get_atom1_id(),\n atom2_id=bond.get_atom2_id(),\n )\n assert np.isclose(test, bond_length, atol=1E-6)\n"
] |
[
[
"numpy.equal",
"numpy.isclose"
]
] |
skyseed-berlin/unsupervised-segmentation
|
[
"2a0078ca871e7c8d87a9905330670c5ae2d35ae8"
] |
[
"src/main_spatial_pooling.py"
] |
[
"from src.models.spatial_pooling import SpatialPooling\nimport argparse\nimport cv2 as cv\nimport numpy as np \n\ndef main(input_img, window_size, target_segment, output):\n\n \"\"\"\n Takes pre-segmented input image and saves a greyscale output image reflecting\n the percentage of target segment (list or numpy array) in windows of specified window_size (in pixels).\n\n Example usage: main(input=\"path/to/input_image.png\", target_segment=[5,5,5], output=\"path/to/output_image.png\")\n \"\"\"\n\n img = cv.imread(input_img)\n\n # if segments unknown, pick target segment via command line prompt\n if target_segment is None:\n \n segments = np.unique(img.reshape(-1, img.shape[2]), axis=0)\n\n print(\"Please choose target segment:\")\n for idx, element in enumerate(segments): \n print(\"{}) {}\".format(idx+1,element))\n \n i = input(\"Enter number: \")\n \n try:\n if 0 < int(i) <= len(segments):\n target_segment = segments[int(i)-1]\n except:\n pass\n\n # possible: pick segment with the lowest total channel value that is not pitch black\n # darkness = np.sum(segments, axis=0)\n # target_segment = segments[np.where(darkness == np.amin(darkness[darkness>0])), :].flatten()\n\n pooled = SpatialPooling(img, target_segment=target_segment)\n\n result = pooled.fraction_of_target_segment(window_size=window_size) # this needs to be reduced to actual dimensions (remove overlaps)\n\n result_uint = np.array(result*255).astype('uint8')\n gray_image = cv.cvtColor(result_uint, cv.COLOR_GRAY2BGR)\n\n cv.imwrite(output, gray_image)\n\n\n\nif __name__ == \"__main__\":\n\n # parse command-line arguments\n\n parser = argparse.ArgumentParser(description='Spatial Smoothing of a Segmented Image')\n\n parser.add_argument('--input', help='input image file name', required=True)\n parser.add_argument('--target_segment', help='channel values of target segment', required=False)\n parser.add_argument('--output', help='output image file name', required=True)\n parser.add_argument('--window_size_px', help='size of sliding window in pixel', required=False)\n parser.add_argument('--window_size_m', help='size of sliding window in m (gsd)', required=False)\n parser.add_argument('--gsd', help='ground sampling distance. resolution of aerial image (in sqm/pixel)', required=False)\n\n args = parser.parse_args()\n\n if args.window_size_px is not None:\n \n window_size = args.window_size_px\n\n elif args.window_size_m is not None and args.gsd is not None:\n \n window_size = round(float(args.window_size_m)/float(args.gsd))\n \n else:\n parser.error(\"either --window_size_px or --window_size_m and --gsd have to be set!\")\n\n if args.target_segment is not None:\n\n target_segment = eval(args.target_segment)\n\n else:\n target_segment = None\n\n # run main fcn \n\n main(input_img=args.input, window_size=window_size, target_segment=target_segment, output=args.output)"
] |
[
[
"numpy.array"
]
] |
FGeri/kornia
|
[
"92fa259601679031dc59c82ffe6862a1b5c8878a",
"92fa259601679031dc59c82ffe6862a1b5c8878a"
] |
[
"kornia/losses/tversky.py",
"kornia/geometry/epipolar/projection.py"
] |
[
"from typing import Optional\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom kornia.utils import one_hot\n\n# based on:\n# https://github.com/kevinzakka/pytorch-goodies/blob/master/losses.py\n\n\ndef tversky_loss(input: torch.Tensor, target: torch.Tensor,\n alpha: float, beta: float, eps: float = 1e-8) -> torch.Tensor:\n r\"\"\"Function that computes Tversky loss.\n\n See :class:`~kornia.losses.TverskyLoss` for details.\n \"\"\"\n if not torch.is_tensor(input):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\"\n .format(type(input)))\n\n if not len(input.shape) == 4:\n raise ValueError(\"Invalid input shape, we expect BxNxHxW. Got: {}\"\n .format(input.shape))\n\n if not input.shape[-2:] == target.shape[-2:]:\n raise ValueError(\"input and target shapes must be the same. Got: {} and {}\"\n .format(input.shape, input.shape))\n\n if not input.device == target.device:\n raise ValueError(\n \"input and target must be in the same device. Got: {} and {}\" .format(\n input.device, target.device))\n\n # compute softmax over the classes axis\n input_soft: torch.Tensor = F.softmax(input, dim=1)\n\n # create the labels one hot tensor\n target_one_hot: torch.Tensor = one_hot(\n target, num_classes=input.shape[1],\n device=input.device, dtype=input.dtype)\n\n # compute the actual dice score\n dims = (1, 2, 3)\n intersection = torch.sum(input_soft * target_one_hot, dims)\n fps = torch.sum(input_soft * (-target_one_hot + 1.), dims)\n fns = torch.sum((-input_soft + 1.) * target_one_hot, dims)\n\n numerator = intersection\n denominator = intersection + alpha * fps + beta * fns\n tversky_loss = numerator / (denominator + eps)\n return torch.mean(-tversky_loss + 1.)\n\n\nclass TverskyLoss(nn.Module):\n r\"\"\"Criterion that computes Tversky Coeficient loss.\n\n According to [1], we compute the Tversky Coefficient as follows:\n\n .. math::\n\n \\text{S}(P, G, \\alpha; \\beta) =\n \\frac{|PG|}{|PG| + \\alpha |P \\setminus G| + \\beta |G \\setminus P|}\n\n where:\n - :math:`P` and :math:`G` are the predicted and ground truth binary\n labels.\n - :math:`\\alpha` and :math:`\\beta` control the magnitude of the\n penalties for FPs and FNs, respectively.\n\n Notes:\n - :math:`\\alpha = \\beta = 0.5` => dice coeff\n - :math:`\\alpha = \\beta = 1` => tanimoto coeff\n - :math:`\\alpha + \\beta = 1` => F beta coeff\n\n Shape:\n - Input: :math:`(N, C, H, W)` where C = number of classes.\n - Target: :math:`(N, H, W)` where each value is\n :math:`0 ≤ targets[i] ≤ C−1`.\n\n Examples:\n >>> N = 5 # num_classes\n >>> loss = kornia.losses.TverskyLoss(alpha=0.5, beta=0.5)\n >>> input = torch.randn(1, N, 3, 5, requires_grad=True)\n >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)\n >>> output = loss(input, target)\n >>> output.backward()\n\n References:\n [1]: https://arxiv.org/abs/1706.05721\n \"\"\"\n\n def __init__(self, alpha: float, beta: float, eps: float = 1e-8) -> None:\n super(TverskyLoss, self).__init__()\n self.alpha: float = alpha\n self.beta: float = beta\n self.eps: float = eps\n\n def forward( # type: ignore\n self,\n input: torch.Tensor,\n target: torch.Tensor) -> torch.Tensor:\n return tversky_loss(input, target, self.alpha, self.beta, self.eps)\n",
"\"\"\"Module for image projections.\"\"\"\nfrom typing import Union\n\nimport torch\n\nfrom kornia.geometry.epipolar import numeric\n\n\ndef intrinsics_like(focal: float, input: torch.Tensor) -> torch.Tensor:\n r\"\"\"Returns a 3x3 instrinsics matrix, with same size as the input.\n\n The center of projection will be based in the input image size.\n\n Args:\n focal (float): the focal length for tha camera matrix.\n input (torch.Tensor): image tensor that will determine the batch size and image height\n and width. It is assumed to be a tensor in the shape of :math:`(B, C, H, W)`.\n\n Returns:\n torch.Tensor: The camera matrix with the shape of :math:`(B, 3, 3)`.\n\n \"\"\"\n assert len(input.shape) == 4, input.shape\n assert focal > 0, focal\n\n B, _, H, W = input.shape\n\n intrinsics = numeric.eye_like(3, input)\n intrinsics[..., 0, 0] *= focal\n intrinsics[..., 1, 1] *= focal\n intrinsics[..., 0, 2] += 1. * W / 2\n intrinsics[..., 1, 2] += 1. * H / 2\n return intrinsics\n\n\ndef random_intrinsics(low: Union[float, torch.Tensor],\n high: Union[float, torch.Tensor]) -> torch.Tensor:\n r\"\"\"Generates a random camera matrix based on a given uniform distribution.\n\n Args:\n low (Union[float, torch.Tensor]): lower range (inclusive).\n high (Union[float, torch.Tensor]): upper range (exclusive).\n\n Returns:\n torch.Tensor: The random camera matrix with the shape of :math:`(1, 3, 3)`.\n\n \"\"\"\n sampler = torch.distributions.Uniform(low, high)\n fx, fy, cx, cy = [sampler.sample((1,)) for _ in range(4)]\n zeros, ones = torch.zeros_like(fx), torch.ones_like(fx)\n camera_matrix: torch.Tensor = torch.cat([\n fx, zeros, cx,\n zeros, fy, cy,\n zeros, zeros, ones,\n ])\n return camera_matrix.view(1, 3, 3)\n\n\ndef scale_intrinsics(\n camera_matrix: torch.Tensor, scale_factor: Union[float, torch.Tensor]) -> torch.Tensor:\n r\"\"\"Scale a camera matrix containing the intrinsics.\n\n Applies the scaling factor to the focal length and center of projection.\n\n Args:\n camera_matrix (torch.Tensor): the camera calibration matrix containing the intrinsic\n parameters. The expected shape for the tensor is :math:`(B, 3, 3)`.\n scale_factor (Union[float, torch.Tensor]): the scaling factor to be applied.\n\n Returns:\n torch.Tensor: The scaled camera matrix with shame shape as input :math:`(B, 3, 3)`.\n\n \"\"\"\n K_scale = camera_matrix.clone()\n K_scale[..., 0, 0] *= scale_factor\n K_scale[..., 1, 1] *= scale_factor\n K_scale[..., 0, 2] *= scale_factor\n K_scale[..., 1, 2] *= scale_factor\n return K_scale\n\n\ndef projection_from_KRt(K: torch.Tensor, R: torch.Tensor, t: torch.Tensor) -> torch.Tensor:\n r\"\"\"Get the projection matrix P from K, R and t.\n\n This function estimate the projection matrix by solving the following equation: :math:`P = K * [R|t]`.\n\n Args:\n K (torch.Tensor): the camera matrix with the instrinsics with shape :math:`(B, 3, 3)`.\n R (torch.Tensor): The rotation matrix with shape :math:`(B, 3, 3)`.\n t (torch.Tensor): The translation vector with shape :math:`(B, 3, 1)`.\n\n Returns:\n torch.Tensor: The projection matrix P with shape :math:`(B, 4, 4)`.\n\n \"\"\"\n assert K.shape[-2:] == (3, 3), K.shape\n assert R.shape[-2:] == (3, 3), R.shape\n assert t.shape[-2:] == (3, 1), t.shape\n assert len(K.shape) == len(R.shape) == len(t.shape)\n\n Rt: torch.Tensor = torch.cat([R, t], dim=-1) # 3x4\n Rt_h = torch.nn.functional.pad(Rt, [0, 0, 0, 1], \"constant\", 0.) # 4x4\n Rt_h[..., -1, -1] += 1.\n\n K_h: torch.Tensor = torch.nn.functional.pad(K, [0, 1, 0, 1], \"constant\", 0.) # 4x4\n K_h[..., -1, -1] += 1.\n\n return K @ Rt\n\n\ndef depth(R: torch.Tensor, t: torch.Tensor, X: torch.Tensor) -> torch.Tensor:\n r\"\"\"Returns the depth of a point transformed by a rigid transform.\n\n Args:\n R (torch.Tensor): The rotation matrix with shape :math:`(*, 3, 3)`.\n t (torch.Tensor): The translation vector with shape :math:`(*, 3, 1)`.\n X (torch.Tensor): The 3d points with shape :math:`(*, 3)`.\n\n Returns:\n torch.Tensor: The depth value per point with shape :math:`(*, 1)`.\n\n \"\"\"\n X_tmp = R @ X.transpose(-2, -1)\n X_out = X_tmp[..., 2, :] + t[..., 2, :]\n return X_out\n\n\n# adapted from:\n# https://github.com/opencv/opencv_contrib/blob/master/modules/sfm/src/fundamental.cpp#L61\n# https://github.com/mapillary/OpenSfM/blob/master/opensfm/multiview.py#L14\n\n\ndef _nullspace(A):\n '''Compute the null space of A.\n Return the smallest singular value and the corresponding vector.\n '''\n u, s, vh = torch.svd(A)\n return s[..., -1], vh[..., -1]\n\n\ndef projections_from_fundamental(F_mat: torch.Tensor) -> torch.Tensor:\n r\"\"\"Get the projection matrices from the Fundamenal Matrix.\n\n Args:\n F_mat (torch.Tensor): the fundamenal matrix with the shape :math:`(*, 3, 3)`.\n\n Returns:\n torch.Tensor: The projection matrices with shape :math:`(*, 4, 4, 2)`.\n\n \"\"\"\n assert len(F_mat.shape) >= 2, F_mat.shape\n assert F_mat.shape[-2:] == (3, 3), F_mat.shape\n\n R1 = numeric.eye_like(3, F_mat) # Bx3x3\n t1 = numeric.vec_like(3, F_mat) # Bx3\n\n Ft_mat = F_mat.transpose(-2, -1)\n\n _, e2 = _nullspace(Ft_mat)\n\n R2 = numeric.cross_product_matrix(e2) @ F_mat # Bx3x3\n t2 = e2[..., :, None] # Bx3x1\n\n P1 = torch.cat([R1, t1], dim=-1) # Bx3x4\n P2 = torch.cat([R2, t2], dim=-1) # Bx3x4\n\n return torch.stack([P1, P2], dim=-1)\n"
] |
[
[
"torch.mean",
"torch.nn.functional.softmax",
"torch.sum",
"torch.is_tensor"
],
[
"torch.svd",
"torch.cat",
"torch.zeros_like",
"torch.stack",
"torch.distributions.Uniform",
"torch.ones_like",
"torch.nn.functional.pad"
]
] |
WenjinW/PGL
|
[
"ce6f64caeb409572750550ce183577b26598d8d0"
] |
[
"pgl/utils/helper.py"
] |
[
"# Copyright (c) 2020 PaddlePaddle 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\nimport numpy as np\nimport paddle\nfrom paddle.fluid.layers import core\nfrom paddle.fluid.layer_helper import LayerHelper\nfrom paddle.fluid.data_feeder import convert_dtype, check_variable_and_dtype, check_type, check_dtype\nfrom paddle.fluid.framework import Variable, in_dygraph_mode, convert_np_dtype_to_dtype_\nimport paddle.fluid.layers as L\n\n\ndef check_is_tensor(*data):\n \"\"\"Check if the given datas have paddle.Tensor\n \"\"\"\n for d in data:\n if isinstance(d, paddle.Tensor) or isinstance(d, Variable):\n return True\n return False\n\n\ndef scatter(x, index, updates, overwrite=True, name=None):\n \"\"\"\n **Scatter Layer**\n Output is obtained by updating the input on selected indices based on updates.\n \n .. code-block:: python\n \n import numpy as np\n #input:\n x = np.array([[1, 1], [2, 2], [3, 3]])\n index = np.array([2, 1, 0, 1])\n # shape of updates should be the same as x\n # shape of updates with dim > 1 should be the same as input\n updates = np.array([[1, 1], [2, 2], [3, 3], [4, 4]])\n overwrite = False\n # calculation:\n if not overwrite:\n for i in range(len(index)):\n x[index[i]] = np.zeros((2))\n for i in range(len(index)):\n if (overwrite):\n x[index[i]] = updates[i]\n else:\n x[index[i]] += updates[i]\n # output:\n out = np.array([[3, 3], [6, 6], [1, 1]])\n out.shape # [3, 2]\n **NOTICE**: The order in which updates are applied is nondeterministic, \n so the output will be nondeterministic if index contains duplicates.\n Args:\n x (Tensor): The input N-D Tensor with ndim>=1. Data type can be float32, float64.\n index (Tensor): The index 1-D Tensor. Data type can be int32, int64. The length of index cannot exceed updates's length, and the value in index cannot exceed input's length.\n updates (Tensor): update input with updates parameter based on index. shape should be the same as input, and dim value with dim > 1 should be the same as input.\n overwrite (bool): The mode that updating the output when there are same indices. \n If True, use the overwrite mode to update the output of the same index,\n if False, use the accumulate mode to update the output of the same index.Default value is True.\n name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name` .\n \n Returns:\n Tensor: The output is a Tensor with the same shape as x.\n Examples:\n .. code-block:: python\n \n import paddle\n x = paddle.to_tensor([[1, 1], [2, 2], [3, 3]], dtype='float32')\n index = paddle.to_tensor([2, 1, 0, 1], dtype='int64')\n updates = paddle.to_tensor([[1, 1], [2, 2], [3, 3], [4, 4]], dtype='float32')\n \n output1 = paddle.scatter(x, index, updates, overwrite=False)\n # [[3., 3.],\n # [6., 6.],\n # [1., 1.]]\n output2 = paddle.scatter(x, index, updates, overwrite=True)\n # CPU device:\n # [[3., 3.],\n # [4., 4.],\n # [1., 1.]]\n # GPU device maybe have two results because of the repeated numbers in index\n # result 1:\n # [[3., 3.],\n # [4., 4.],\n # [1., 1.]]\n # result 2:\n # [[3., 3.],\n # [2., 2.],\n # [1., 1.]]\n \"\"\"\n if in_dygraph_mode():\n return core.ops.scatter(x, index, updates, 'overwrite', overwrite)\n\n check_variable_and_dtype(\n x, 'dtype', ['float32', 'int32', 'int64', 'float64'], 'scatter')\n check_type(overwrite, 'overwrite', bool, 'scatter')\n helper = LayerHelper('scatter', **locals())\n out = helper.create_variable_for_type_inference(x.dtype)\n helper.append_op(\n type=\"scatter\",\n inputs={\"X\": x,\n \"Ids\": index,\n \"Updates\": updates},\n attrs={'overwrite': overwrite},\n outputs={\"Out\": out})\n return out\n\n\ndef generate_segment_id_from_index(index):\n if check_is_tensor(index):\n zeros = paddle.zeros(index[-1] + 1, dtype=\"int32\")\n index = index[:-1]\n segments = scatter(\n zeros, index, paddle.ones_like(\n index, dtype=\"int32\"))\n segments = paddle.cumsum(segments)[:-1] - 1\n return segments\n else:\n segments = np.zeros(index[-1] + 1, dtype=\"int32\")\n index = index[:-1]\n segments[index] += 1\n segments = np.cumsum(segments)[:-1] - 1\n return segments\n\n\ndef maybe_num_nodes(edges):\n \"\"\"Guess the number of nodes from edges\n \n Args:\n\n edges: numpy.ndarry of paddle.Tensor\n\n Return:\n\n An int or paddle.Tensor about the number of nodes.\n \"\"\"\n if isinstance(edges, Variable):\n return paddle.max(edges) + 1\n\n if len(edges) == 0:\n return 0\n\n if check_is_tensor(edges):\n return paddle.max(edges) + 1\n else:\n return np.max(edges) + 1\n\n\ndef unique_segment(data, dtype=\"int64\"):\n \"\"\"Return Segment Id from data\n \"\"\"\n if in_dygraph_mode():\n attr_dtype = convert_np_dtype_to_dtype_(dtype)\n unique, index, _ = core.ops.unique_with_counts(data, \"dtype\",\n attr_dtype)\n return unique, index\n else:\n unique, index, _ = L.unique_with_counts(data)\n return unique, index\n"
] |
[
[
"numpy.max",
"numpy.zeros",
"numpy.cumsum"
]
] |
urkax/CollageNet
|
[
"337098b40afbf0b3c8514f80a9953a797988938d"
] |
[
"code/EC2_VAE/model.py"
] |
[
"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.distributions import Normal\n\n\nclass VAE(nn.Module):\n def __init__(self,\n roll_dims,\n hidden_dims,\n rhythm_dims,\n condition_dims,\n z1_dims,\n z2_dims,\n n_step,\n eps,\n k=1000):\n super(VAE, self).__init__()\n self.gru_0 = nn.GRU(\n roll_dims + condition_dims,\n hidden_dims,\n batch_first=True,\n bidirectional=True) # encode\n self.linear_mu = nn.Linear(hidden_dims * 2, z1_dims + z2_dims) # z mean\n self.linear_var = nn.Linear(hidden_dims * 2, z1_dims + z2_dims) # z var\n self.grucell_0 = nn.GRUCell(z2_dims + rhythm_dims,\n hidden_dims) # rhythm decoder\n self.grucell_1 = nn.GRUCell(\n z1_dims + roll_dims + rhythm_dims + condition_dims, hidden_dims) # global decoder 1\n self.grucell_2 = nn.GRUCell(hidden_dims, hidden_dims) # global decoder 2\n self.linear_init_0 = nn.Linear(z2_dims, hidden_dims) # z linear before grucell_0\n self.linear_out_0 = nn.Linear(hidden_dims, rhythm_dims) # rhythm out linear after grucell_0\n self.linear_init_1 = nn.Linear(z1_dims, hidden_dims) # z linear before grucell_1\n self.linear_out_1 = nn.Linear(hidden_dims, roll_dims) # global out linear after grucell_2\n\n self.n_step = n_step\n self.roll_dims = roll_dims\n self.hidden_dims = hidden_dims\n self.eps = eps\n self.rhythm_dims = rhythm_dims\n self.sample = None\n self.rhythm_sample = None\n self.iteration = 0\n self.z1_dims = z1_dims\n self.z2_dims = z2_dims\n self.k = torch.FloatTensor([k])\n self.condition_dims = condition_dims\n\n def _sampling(self, x):\n # x: [batch size, rhythm_dims], log_softmax\n # get index of x\n idx = x.max(1)[1]\n x = torch.zeros_like(x)\n arange = torch.arange(x.size(0)).long()\n if torch.cuda.is_available():\n arange = arange.cuda()\n x[arange, idx] = 1\n return x\n\n def encoder(self, x, condition):\n # self.gru_0.flatten_parameters()\n if self.condition_dims > 0:\n x = torch.cat((x, condition), -1)\n\n x = self.gru_0(x)[-1] # h_n of shape [num_layers * num_directions, batch, hidden_size]\n x = x.transpose_(0, 1).contiguous() # [batch, 1 * 2, hidden_size]\n x = x.view(x.size(0), -1) # [batch, 2*hidden_size]\n mu = self.linear_mu(x)\n std = (self.linear_var(x) * 0.5).exp_() # 本来没有*0.5,有错\n distribution_1 = Normal(mu[:, :self.z1_dims], std[:, :self.z1_dims])\n distribution_2 = Normal(mu[:, self.z1_dims:], std[:, self.z1_dims:])\n return distribution_1, distribution_2\n\n def rhythm_decoder(self, z):\n out = torch.zeros((z.size(0), self.rhythm_dims))\n out[:, -1] = 1.\n out = out.cuda()\n x = []\n t = torch.tanh(self.linear_init_0(z))\n hx = t\n for i in range(self.n_step):\n out = torch.cat([out, z], 1)\n hx = self.grucell_0(out, hx)\n out = F.log_softmax(self.linear_out_0(hx), 1)\n x.append(out)\n if self.training:\n p = torch.rand(1).item()\n if p < self.eps:\n out = self.rhythm_sample[:, i, :] # teacher forcing\n else:\n out = self._sampling(out)\n else:\n out = self._sampling(out)\n return torch.stack(x, 1)\n\n def final_decoder(self, z, rhythm, condition):\n out = torch.zeros((z.size(0), self.roll_dims))\n out[:, -1] = 1.\n out = out.cuda()\n x, hx = [], [None, None]\n t = torch.tanh(self.linear_init_1(z))\n hx[0] = t\n \n for i in range(self.n_step):\n if self.condition_dims == 0:\n out = torch.cat([out, rhythm[:, i, :], z], 1)\n else:\n out = torch.cat([out, rhythm[:, i, :], z, condition[:, i, :]], 1)\n # two layer gru\n hx[0] = self.grucell_1(out, hx[0])\n if i == 0:\n hx[1] = hx[0]\n hx[1] = self.grucell_2(hx[0], hx[1])\n out = F.log_softmax(self.linear_out_1(hx[1]), 1)\n x.append(out)\n if self.training:\n p = torch.rand(1).item()\n if p < self.eps:\n out = self.sample[:, i, :]\n else:\n out = self._sampling(out)\n else:\n out = self._sampling(out)\n return torch.stack(x, 1)\n\n def decoder(self, z1, z2, condition=None):\n rhythm = self.rhythm_decoder(z2)\n return self.final_decoder(z1, rhythm, condition)\n\n def forward(self, x, condition):\n # x [32, 130]\n if self.training:\n self.sample = x\n self.rhythm_sample = x[:, :, :-2].sum(-1).unsqueeze(-1)\n self.rhythm_sample = torch.cat((self.rhythm_sample, x[:, :, -2:]),\n -1)\n self.iteration += 1\n dis1, dis2 = self.encoder(x, condition)\n z1 = dis1.rsample()\n z2 = dis2.rsample()\n recon_rhythm = self.rhythm_decoder(z2)\n recon = self.final_decoder(z1, recon_rhythm, condition)\n output = (recon, recon_rhythm, dis1.mean, dis1.stddev, dis2.mean,\n dis2.stddev)\n return output\n"
] |
[
[
"torch.cat",
"torch.nn.GRU",
"torch.zeros_like",
"torch.nn.Linear",
"torch.FloatTensor",
"torch.rand",
"torch.cuda.is_available",
"torch.distributions.Normal",
"torch.stack",
"torch.nn.GRUCell"
]
] |
carmanzhang/cornac
|
[
"215efd0ffa7b8ee1afe1ac6b5cc650ee6303ace3",
"215efd0ffa7b8ee1afe1ac6b5cc650ee6303ace3",
"215efd0ffa7b8ee1afe1ac6b5cc650ee6303ace3"
] |
[
"cornac/models/cdl/cdl.py",
"cornac/models/cvaecf/recom_cvaecf.py",
"cornac/models/global_avg/recom_global_avg.py"
] |
[
"# Copyright 2018 The Cornac 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\nimport tensorflow.compat.v1 as tf\n\nfrom ...utils import get_rng\nfrom ...utils.init_utils import xavier_uniform\n\nact_functions = {\n \"sigmoid\": tf.nn.sigmoid,\n \"tanh\": tf.nn.tanh,\n \"elu\": tf.nn.elu,\n \"relu\": tf.nn.relu,\n \"relu6\": tf.nn.relu6,\n \"leaky_relu\": tf.nn.leaky_relu,\n \"identity\": tf.identity,\n}\n\n\n# Stacked Denoising Autoencoder\ndef sdae(X_corrupted, layers, dropout_rate=0.0, act_fn=\"relu\", seed=None, name=\"SDAE\"):\n fn = act_functions.get(act_fn, None)\n if fn is None:\n raise ValueError(\n \"Invalid type of activation function {}\\n\"\n \"Supported functions: {}\".format(act_fn, act_functions.keys())\n )\n\n # Weight initialization\n L = len(layers)\n rng = get_rng(seed)\n weights, biases = [], []\n with tf.variable_scope(name):\n for i in range(L - 1):\n w = xavier_uniform((layers[i], layers[i + 1]), random_state=rng)\n weights.append(\n tf.get_variable(\n name=\"W_{}\".format(i), dtype=tf.float32, initializer=tf.constant(w)\n )\n )\n biases.append(\n tf.get_variable(\n name=\"b_{}\".format(i),\n dtype=tf.float32,\n shape=(layers[i + 1]),\n initializer=tf.zeros_initializer(),\n )\n )\n\n # Construct the auto-encoder\n h_value = X_corrupted\n for i in range(L - 1):\n # The encoder\n if i <= int(L / 2) - 1:\n h_value = fn(tf.add(tf.matmul(h_value, weights[i]), biases[i]))\n # The decoder\n elif i > int(L / 2) - 1:\n h_value = fn(tf.add(tf.matmul(h_value, weights[i]), biases[i]))\n # The dropout for all the layers except the final one\n if i < (L - 2):\n h_value = tf.nn.dropout(h_value, rate=dropout_rate)\n # The encoder output value\n if i == int(L / 2) - 1:\n encoded_value = h_value\n\n sdae_value = h_value\n\n # L2 loss\n loss_w = tf.constant(0.0)\n for i in range(L - 1):\n loss_w = tf.add(loss_w, tf.nn.l2_loss(weights[i]) + tf.nn.l2_loss(biases[i]))\n\n return sdae_value, encoded_value, loss_w\n\n\nclass Model:\n def __init__(\n self,\n n_users,\n n_items,\n n_vocab,\n k,\n layers,\n lambda_u,\n lambda_v,\n lambda_n,\n lambda_w,\n lr,\n dropout_rate,\n U,\n V,\n act_fn,\n seed,\n ):\n self.n_vocab = n_vocab\n self.n_users = n_users\n self.n_items = n_items\n self.lambda_u = lambda_u\n self.lambda_v = lambda_v\n self.lambda_n = lambda_n\n self.lambda_w = lambda_w\n self.layers = layers\n self.lr = lr # learning rate\n self.k = k # latent dimension\n self.dropout_rate = dropout_rate\n self.U_init = tf.constant(U)\n self.V_init = tf.constant(V)\n self.act_fn = act_fn\n self.seed = seed\n\n self._build_graph()\n\n def _build_graph(self):\n self.text_mask = tf.placeholder(\n dtype=tf.float32, shape=[None, self.n_vocab], name=\"mask_input\"\n )\n self.text_input = tf.placeholder(\n dtype=tf.float32, shape=[None, self.n_vocab], name=\"text_input\"\n )\n self.ratings = tf.placeholder(\n dtype=tf.float32, shape=[self.n_users, None], name=\"rating_input\"\n )\n self.C = tf.placeholder(\n dtype=tf.float32, shape=[self.n_users, None], name=\"C_input\"\n )\n\n with tf.variable_scope(\"CDL_Variable\"):\n self.U = tf.get_variable(\n name=\"U\", dtype=tf.float32, initializer=self.U_init\n )\n self.V = tf.get_variable(\n name=\"V\", dtype=tf.float32, initializer=self.V_init\n )\n\n self.item_ids = tf.placeholder(dtype=tf.int32)\n real_batch_size = tf.cast(tf.shape(self.text_input)[0], tf.int32)\n V_batch = tf.reshape(\n tf.gather(self.V, self.item_ids), shape=[real_batch_size, self.k]\n )\n\n corrupted_text = tf.multiply(self.text_input, self.text_mask)\n sdae_value, encoded_value, loss_w = sdae(\n X_corrupted=corrupted_text,\n layers=self.layers,\n dropout_rate=self.dropout_rate,\n act_fn=self.act_fn,\n seed=self.seed,\n name=\"SDAE_Variable\",\n )\n\n loss_1 = self.lambda_u * tf.nn.l2_loss(self.U) + self.lambda_w * loss_w\n loss_2 = self.lambda_v * tf.nn.l2_loss(V_batch - encoded_value)\n loss_3 = self.lambda_n * tf.nn.l2_loss(sdae_value - self.text_input)\n\n predictions = tf.matmul(self.U, V_batch, transpose_b=True)\n squared_error = tf.square(self.ratings - predictions)\n loss_4 = tf.reduce_sum(tf.multiply(self.C, squared_error))\n\n self.loss = loss_1 + loss_2 + loss_3 + loss_4\n\n # Generate optimizer\n optimizer1 = tf.train.AdamOptimizer(self.lr)\n optimizer2 = tf.train.AdamOptimizer(self.lr)\n\n train_var_list1, train_var_list2 = [], []\n\n for var in tf.trainable_variables():\n if \"CDL_Variable\" in var.name:\n train_var_list1.append(var)\n elif \"SDAE_Variable\" in var.name:\n train_var_list2.append(var)\n\n gvs = optimizer1.compute_gradients(self.loss, var_list=train_var_list1)\n capped_gvs = [(tf.clip_by_value(grad, -5.0, 5.0), var) for grad, var in gvs]\n self.opt1 = optimizer1.apply_gradients(capped_gvs)\n\n gvs = optimizer2.compute_gradients(self.loss, var_list=train_var_list2)\n capped_gvs = [(tf.clip_by_value(grad, -5.0, 5.0), var) for grad, var in gvs]\n self.opt2 = optimizer2.apply_gradients(capped_gvs)\n",
"# Copyright 2018 The Cornac 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\nimport numpy as np\nfrom ..recommender import Recommender\nfrom ...exception import ScoreException\n\n\nclass CVAECF(Recommender):\n \"\"\"Conditional Variational Autoencoder for Collaborative Filtering.\n\n Parameters\n ----------\n z_dim: int, optional, default: 20\n The dimension of the stochastic user factors ``z'' representing the preference information.\n\n h_dim: int, optional, default: 20\n The dimension of the stochastic user factors ``h'' representing the auxiliary data.\n\n autoencoder_structure: list, default: [20]\n The number of neurons of encoder/decoder hidden layer for CVAE.\n For example, when autoencoder_structure = [20],\n the CVAE encoder structures will be [y_dim, 20, z_dim] and [x_dim, 20, h_dim],\n the decoder structure will be [z_dim + h_dim, 20, y_dim], where y and x are respectively the preference and \\\n auxiliary data.\n\n act_fn: str, default: 'tanh'\n Name of the activation function used between hidden layers of the auto-encoder.\n Supported functions: ['sigmoid', 'tanh', 'elu', 'relu', 'relu6']\n\n likelihood: str, default: 'mult'\n Name of the likelihood function used for modeling user preferences.\n Supported choices:\n\n mult: Multinomial likelihood\n bern: Bernoulli likelihood\n gaus: Gaussian likelihood\n pois: Poisson likelihood\n\n n_epochs: int, optional, default: 100\n The number of epochs for SGD.\n\n batch_size: int, optional, default: 128\n The batch size.\n\n learning_rate: float, optional, default: 0.001\n The learning rate for Adam.\n\n beta: float, optional, default: 1.0\n The weight of the KL term KL(q(z|y)||p(z)) as in beta-VAE.\n\n alpha_1: float, optional, default: 1.0\n The weight of the KL term KL(q(h|x)||p(h|x)).\n\n alpha_2: float, optional, default: 1.0\n The weight of the KL term KL(q(h|x)||q(h|y)).\n\n name: string, optional, default: 'CVAECF'\n The name of the recommender model.\n\n trainable: boolean, optional, default: True\n When False, the model is not trained, and Cornac assumes that the model is already \\\n pre-trained.\n\n verbose: boolean, optional, default: False\n When True, some running logs are displayed.\n\n seed: int, optional, default: None\n Random seed for parameters initialization.\n\n use_gpu: boolean, optional, default: False\n If True and your system supports CUDA then training is performed on GPUs.\n\n user auxiliary data : See \"cornac/examples/cvaecf_filmtrust.py\" for an example of how to use \\\n cornac's graph modality to load and provide the ``user network'' for CVAECF.\n\n References\n ----------\n * Lee, Wonsung, Kyungwoo Song, and Il-Chul Moon. \"Augmented variational autoencoders for collaborative filtering \\\n with auxiliary information.\" Proceedings of ACM CIKM. 2017.\n \"\"\"\n\n def __init__(\n self,\n name=\"CVAECF\",\n z_dim=20,\n h_dim=20,\n autoencoder_structure=[20],\n act_fn=\"tanh\",\n likelihood=\"mult\",\n n_epochs=100,\n batch_size=128,\n learning_rate=0.001,\n beta=1.0,\n alpha_1=1.0,\n alpha_2=1.0,\n trainable=True,\n verbose=False,\n seed=None,\n use_gpu=False,\n ):\n Recommender.__init__(self, name=name, trainable=trainable, verbose=verbose)\n self.z_dim = z_dim\n self.h_dim = h_dim\n self.autoencoder_structure = autoencoder_structure\n self.act_fn = act_fn\n self.likelihood = likelihood\n self.batch_size = batch_size\n self.n_epochs = n_epochs\n self.learning_rate = learning_rate\n self.beta = beta\n self.alpha_1 = alpha_1\n self.alpha_2 = alpha_2\n self.seed = seed\n self.use_gpu = use_gpu\n\n def fit(self, train_set, val_set=None):\n \"\"\"Fit the model to observations.\n\n Parameters\n ----------\n train_set: :obj:`cornac.data.Dataset`, required\n User-Item preference data as well as additional modalities.\n\n val_set: :obj:`cornac.data.Dataset`, optional, default: None\n User-Item preference data for model selection purposes (e.g., early stopping).\n\n Returns\n -------\n self : object\n \"\"\"\n Recommender.fit(self, train_set, val_set)\n\n import torch\n from .cvaecf import CVAE, learn\n\n self.device = (\n torch.device(\"cuda:0\")\n if (self.use_gpu and torch.cuda.is_available())\n else torch.device(\"cpu\")\n )\n\n if self.trainable:\n if self.seed is not None:\n torch.manual_seed(self.seed)\n torch.cuda.manual_seed(self.seed)\n\n if not hasattr(self, \"cvae\"):\n n_items = train_set.matrix.shape[1]\n n_users = train_set.matrix.shape[0]\n self.cvae = CVAE(\n self.z_dim,\n self.h_dim,\n [n_items] + self.autoencoder_structure,\n [n_users] + self.autoencoder_structure,\n self.act_fn,\n self.likelihood,\n ).to(self.device)\n\n learn(\n self.cvae,\n self.train_set,\n n_epochs=self.n_epochs,\n batch_size=self.batch_size,\n learn_rate=self.learning_rate,\n beta=self.beta,\n alpha_1=self.alpha_1,\n alpha_2=self.alpha_2,\n verbose=self.verbose,\n device=self.device,\n )\n\n elif self.verbose:\n print(\"%s is trained already (trainable = False)\" % (self.name))\n\n return self\n\n def score(self, user_idx, item_idx=None):\n \"\"\"Predict the scores/ratings of a user for an item.\n\n Parameters\n ----------\n user_idx: int, required\n The index of the user for whom to perform score prediction.\n\n item_idx: int, optional, default: None\n The index of the item for which to perform score prediction.\n If None, scores for all known items will be returned.\n\n Returns\n -------\n res : A scalar or a Numpy array\n Relative scores that the user gives to the item or to all known items\n\n \"\"\"\n import torch\n\n if item_idx is None:\n if self.train_set.is_unk_user(user_idx):\n raise ScoreException(\n \"Can't make score prediction for (user_id=%d)\" % user_idx\n )\n\n y_u = self.train_set.matrix[user_idx].copy()\n y_u.data = np.ones(len(y_u.data))\n y_u = torch.tensor(y_u.A, dtype=torch.float32, device=self.device)\n z_u, _ = self.cvae.encode_qz(y_u)\n\n x_u = self.train_set.user_graph.matrix[user_idx].copy()\n x_u.data = np.ones(len(x_u.data))\n x_u = torch.tensor(x_u.A, dtype=torch.float32, device=self.device)\n h_u, _ = self.cvae.encode_qhx(x_u)\n\n known_item_scores = self.cvae.decode(z_u, h_u).data.cpu().numpy().flatten()\n\n return known_item_scores\n else:\n if self.train_set.is_unk_user(user_idx) or self.train_set.is_unk_item(\n item_idx\n ):\n raise ScoreException(\n \"Can't make score prediction for (user_id=%d, item_id=%d)\"\n % (user_idx, item_idx)\n )\n\n y_u = self.train_set.matrix[user_idx].copy()\n y_u.data = np.ones(len(y_u.data))\n y_u = torch.tensor(y_u.A, dtype=torch.float32, device=self.device)\n z_u, _ = self.cvae.encode_qz(y_u)\n\n x_u = self.train_set.user_graph.matrix[user_idx].copy()\n x_u.data = np.ones(len(x_u.data))\n x_u = torch.tensor(x_u.A, dtype=torch.float32, device=self.device)\n h_u, _ = self.cvae.encode_qhx(x_u)\n\n user_pred = self.cvae.decode(z_u, h_u).data.cpu().numpy().flatten()[item_idx]\n\n return user_pred\n",
"# Copyright 2018 The Cornac 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\nimport numpy as np\n\nfrom ..recommender import Recommender\nfrom ...exception import ScoreException\n\n\nclass GlobalAvg(Recommender):\n \"\"\"Global Average baseline for rating prediction. Rating predictions equal to average rating\n of training data (not personalized).\n\n Parameters\n ----------\n name: string, default: 'GlobalAvg'\n The name of the recommender model.\n\n \"\"\"\n\n def __init__(self, name=\"GlobalAvg\"):\n super().__init__(name=name, trainable=False)\n\n def score(self, user_idx, item_idx=None):\n \"\"\"Predict the scores/ratings of a user for an item.\n\n Parameters\n ----------\n user_idx: int, required\n The index of the user for whom to perform score prediction.\n\n item_idx: int, optional, default: None\n The index of the item for which to perform score prediction.\n If None, scores for all known items will be returned.\n\n Returns\n -------\n res : A scalar or a Numpy array\n Relative scores that the user gives to the item or to all known items\n \"\"\"\n if item_idx is None:\n return np.full(self.train_set.num_items, self.train_set.global_mean)\n else:\n return self.train_set.global_mean\n"
] |
[
[
"tensorflow.compat.v1.square",
"tensorflow.compat.v1.nn.dropout",
"tensorflow.compat.v1.train.AdamOptimizer",
"tensorflow.compat.v1.get_variable",
"tensorflow.compat.v1.multiply",
"tensorflow.compat.v1.trainable_variables",
"tensorflow.compat.v1.gather",
"tensorflow.compat.v1.zeros_initializer",
"tensorflow.compat.v1.matmul",
"tensorflow.compat.v1.placeholder",
"tensorflow.compat.v1.shape",
"tensorflow.compat.v1.clip_by_value",
"tensorflow.compat.v1.nn.l2_loss",
"tensorflow.compat.v1.variable_scope",
"tensorflow.compat.v1.constant"
],
[
"torch.cuda.manual_seed",
"torch.manual_seed",
"torch.tensor",
"torch.cuda.is_available",
"torch.device"
],
[
"numpy.full"
]
] |
gipfelen/dgcnn
|
[
"59e58fe3da69517d4d2a270c7ddb52697963253a"
] |
[
"tensorflow/part_seg/affordance_net.py"
] |
[
"import os\nfrom os.path import join as opj\nimport numpy as np\nfrom torch.utils.data import Dataset\n#from utils.provider import rotate_point_cloud_SO3, rotate_point_cloud_y\nimport pickle as pkl\nfrom sklearn.model_selection import train_test_split\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\ndataset_path=os.path.abspath(os.path.join(BASE_DIR, '../../../3d-point-capsule-affordances-DCG/dataset/affordance_net'))\n\nall_classes = {'Bag': 0, 'Bed': 1, 'Bottle': 2, 'Bowl': 3, 'Chair': 4, 'Clock': 5, 'Dishwasher': 6, 'Display': 7, 'Door': 8, 'Earphone': 9, 'Faucet': 10, 'Hat': 11, 'Keyboard': 12, 'Knife': 13, 'Laptop': 14, 'Microwave': 15, 'Mug': 16, 'Refrigerator': 17, 'Scissors': 18, 'StorageFurniture': 19, 'Table': 20, 'TrashCan': 21, 'Vase': 22}\ndef pc_normalize(pc):\n centroid = np.mean(pc, axis=0)\n pc = pc - centroid\n m = np.max(np.sqrt(np.sum(pc**2, axis=1)))\n pc = pc / m\n return pc, centroid, m\n\nclass AffordNetDataset(Dataset):\n def __init__(self, data_dir=dataset_path, split='train', partial=False, rotate='None', semi=False):\n super().__init__()\n self.data_dir = data_dir\n self.split = split\n self.split_file = \"train\" if split == \"test\" else split\n\n self.partial = partial\n self.rotate = rotate\n self.semi = semi\n\n self.load_data()\n\n self.affordance = self.all_data[0][\"affordance\"]\n\n return\n\n def load_data(self):\n self.all_data = []\n if self.semi:\n with open(opj(self.data_dir, 'semi_label_1.pkl'), 'rb') as f:\n temp_data = pkl.load(f)\n else:\n if self.partial:\n with open(opj(self.data_dir, 'partial_%s_data.pkl' % self.split_file), 'rb') as f:\n temp_data = pkl.load(f)\n elif self.rotate != \"None\" and self.split_file != 'train':\n with open(opj(self.data_dir, 'rotate_%s_data.pkl' % self.split_file), 'rb') as f:\n temp_data_rotate = pkl.load(f)\n with open(opj(self.data_dir, 'full_shape_%s_data.pkl' % self.split_file), 'rb') as f:\n temp_data = pkl.load(f)\n else:\n with open(opj(self.data_dir, 'full_shape_%s_data.pkl' % self.split_file), 'rb') as f:\n temp_data = pkl.load(f)\n if self.split_file == \"train\":\n temp_data_train, temp_data_test = train_test_split(temp_data, test_size=0.20, random_state=42) \n if self.split == \"train\":\n temp_data = temp_data_train\n else:\n temp_data = temp_data_test\n for index, info in enumerate(temp_data):\n if self.partial:\n partial_info = info[\"partial\"]\n for view, data_info in partial_info.items():\n temp_info = {}\n temp_info[\"shape_id\"] = info[\"shape_id\"]\n temp_info[\"semantic class\"] = info[\"semantic class\"]\n temp_info[\"affordance\"] = info[\"affordance\"]\n temp_info[\"view_id\"] = view\n temp_info[\"data_info\"] = data_info\n self.all_data.append(temp_info)\n elif self.split != 'train' and self.rotate != 'None':\n rotate_info = temp_data_rotate[index][\"rotate\"][self.rotate]\n full_shape_info = info[\"full_shape\"]\n for r, r_data in rotate_info.items():\n temp_info = {}\n temp_info[\"shape_id\"] = info[\"shape_id\"]\n temp_info[\"semantic class\"] = info[\"semantic class\"]\n temp_info[\"affordance\"] = info[\"affordance\"]\n temp_info[\"data_info\"] = full_shape_info\n temp_info[\"rotate_matrix\"] = r_data.astype(np.float32)\n self.all_data.append(temp_info)\n else:\n temp_info = {}\n temp_info[\"shape_id\"] = info[\"shape_id\"]\n temp_info[\"semantic class\"] = info[\"semantic class\"]\n temp_info[\"affordance\"] = info[\"affordance\"]\n temp_info[\"data_info\"] = info[\"full_shape\"]\n self.all_data.append(temp_info)\n\n def __getitem__(self, index):\n\n data_dict = self.all_data[index]\n modelid = data_dict[\"shape_id\"]\n modelcat = data_dict[\"semantic class\"]\n\n data_info = data_dict[\"data_info\"]\n model_data = data_info[\"coordinate\"].astype(np.float32)\n labels = data_info[\"label\"]\n for aff in self.affordance:\n temp = labels[aff].astype(np.float32).reshape(-1, 1)\n model_data = np.concatenate((model_data, temp), axis=1)\n\n datas = model_data[:, :3]\n targets = model_data[:, 3:]\n\n if self.rotate != 'None':\n if self.split == 'train':\n if self.rotate == 'so3':\n datas = rotate_point_cloud_SO3(\n datas[np.newaxis, :, :]).squeeze()\n elif self.rotate == 'z':\n datas = rotate_point_cloud_y(\n datas[np.newaxis, :, :]).squeeze()\n else:\n r_matrix = data_dict[\"rotate_matrix\"]\n datas = (np.matmul(r_matrix, datas.T)).T\n\n datas, _, _ = pc_normalize(datas)\n\n max_target_index = np.argmax(targets,axis=1)\n max_target_value = np.max(targets,axis=1)\n\n max_target_index = np.where(max_target_value == 0.,18,max_target_index)\n\n modelcat_index = all_classes[modelcat]\n\n return datas, max_target_index, modelcat_index\n\n def __len__(self):\n return len(self.all_data)\n\nif __name__ == '__main__':\n d = AffordNetDataset(dataset_path,split='train')\n\n for i in d:\n \n ps, targets, modelcat = i\n\n print(modelcat)\n"
] |
[
[
"numpy.matmul",
"sklearn.model_selection.train_test_split",
"numpy.concatenate",
"numpy.max",
"numpy.argmax",
"numpy.mean",
"numpy.where",
"numpy.sum"
]
] |
seangholson/lqubo
|
[
"05bf1dd03cf76349b981a543e751217beb4a1b0b"
] |
[
"perm_LQUBO/results/plot_tsp_convergence.py"
] |
[
"import pandas as pd\nimport matplotlib.pyplot as plt\n\nsize_domain = {'tsp': ['4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20']}\n\nknown_num_iterations = 100\niteration_domain = [(i+1)*5 for i in range(int(known_num_iterations/5))]\n\nconvergence_data = {'tsp': {\n 'LQUBO': [],\n 'New_LQUBO': []\n}}\n\n\nfor instance in convergence_data:\n for solver in convergence_data[instance]:\n for iteration_number in range(int(known_num_iterations/5)):\n convergence_data[instance][solver].append(pd.read_csv(\"../results/convergence/\" + instance + \"_\" + solver +\n \"_20.csv\")['convergence percent error vals'][\n iteration_number]*100)\n\n\ndef plot_tsp_convergence():\n\n plt.plot(iteration_domain, convergence_data['tsp']['LQUBO'], 'o-', label='LQUBO')\n plt.plot(iteration_domain, convergence_data['tsp']['New_LQUBO'], 'o:', label='New LQUBO')\n plt.xlabel('Iteration')\n plt.ylabel('Percent Error')\n plt.suptitle('Convergence of LQUBO Algorithm n = 20 Random TSP')\n plt.legend(loc='upper right')\n plt.show()\n\n\nplot_tsp_convergence()\n\n\n"
] |
[
[
"matplotlib.pyplot.legend",
"pandas.read_csv",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.suptitle",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
UCSD-SEELab/smarthomeDeploymentCode
|
[
"7d9be41b5229f84402c25e7d66b9b3626af5dad6"
] |
[
"Library/deployModels/HLdeployer/loadModel.py"
] |
[
"import tensorflow as tf\nfrom tensorflow.python.framework import tensor_util\nimport numpy as np\n\nclass loadModel():\n def __init__(self, conf):\n assert \"sensor\" in conf.keys(), \"Sensor name needs to be given\"\n assert \"modelDir\" in conf.keys(), \"Unable to find Model directory\"\n\n self.sensorName = conf[\"sensor\"]\n self.modelDir = conf[\"modelDir\"]\n with open(conf[\"modelDir\"] + \"variable_list.txt\") as fp:\n self.variableList = eval(fp.read())\n self.frozenModel = self.modelDir + conf[\"sensor\"] + \"_frozen.pb\"\n self.sess = tf.Session()\n self.graph_def = tf.GraphDef()\n self.loadGraph()\n\n def loadGraph(self):\n with tf.gfile.GFile(self.frozenModel, \"r\") as f:\n self.graph_def.ParseFromString(f.read())\n\n def load_frozen_model(self, sensor_input):\n if type(sensor_input) is not np.ndarray:\n sensor_input = np.array(sensor_input)\n\n new_input = tf.placeholder(tf.float32, [None, sensor_input.shape[1]], self.sensorName)\n keep_prob = tf.placeholder(tf.float32)\n \n variable_name = self.sensorName + \"_output\"\n for idx, var in enumerate(self.variableList):\n if variable_name in var:\n variable_name = var\n break\n \n output = tf.import_graph_def(\n self.graph_def,\n input_map={\"input/\" + self.sensorName+\":0\": new_input, \"input/keepprob:0\": keep_prob},\n return_elements = [variable_name+\":0\"]\n )\n \n results = self.sess.run(output, feed_dict={new_input: sensor_input, keep_prob : 1.0})\n\n return results\n\n def compute(self, inputData):\n return self.load_frozen_model(inputData)\n\n\n \nif __name__==\"__main__\":\n import json\n with open(\"../test/config.json\") as fp:\n conf = json.load(fp)\n\n model = loadModel(conf)\n res = model.compute([[2.0, 3.0]])\n print(res)\n \n"
] |
[
[
"tensorflow.import_graph_def",
"tensorflow.gfile.GFile",
"tensorflow.placeholder",
"tensorflow.Session",
"tensorflow.GraphDef",
"numpy.array"
]
] |
NijatZeynalov/Fuel-consumption-of-vehicles
|
[
"e7af523bb976b75d8f5f6c7ac797af105b149ae7"
] |
[
"explot_data_analysis.py"
] |
[
"import pandas as pd\r\nimport seaborn as sns\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom scipy import stats\r\nfrom scipy.stats import norm, skew\r\n\r\nfrom sklearn.preprocessing import RobustScaler, StandardScaler\r\nfrom sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet\r\nfrom sklearn.model_selection import train_test_split, GridSearchCV\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom sklearn.base import clone\r\n\r\n\r\n# warning\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\n\r\ncolumn_name = [\"MPG\", \"Cylinders\", \"Displacement\",\"Horsepower\",\"Weight\",\"Acceleration\",\"Model Year\", \"Origin\"]\r\ndata = pd.read_csv(\"auto-mpg.data\", names = column_name, na_values = \"?\", comment = \"\\t\",sep = \" \", skipinitialspace = True)\r\n\r\ndata = data.rename(columns = {\"MPG\":\"target\"})\r\n\r\ncorr_matrix = data.corr()\r\nsns.clustermap(corr_matrix, annot = True, fmt = \".2f\")\r\nplt.title(\"Correlation btw features\")\r\nplt.show()\r\n\r\nthreshold = 0.75\r\nfiltre = np.abs(corr_matrix[\"target\"])>threshold\r\ncorr_features = corr_matrix.columns[filtre].tolist()\r\nsns.clustermap(data[corr_features].corr(), annot = True, fmt = \".2f\")\r\nplt.title(\"Correlation btw features\")\r\nplt.show()\r\n\r\n#multicollinearity\r\nsns.pairplot(data, diag_kind = \"kde\", markers = \"+\")\r\nplt.show()\r\n\r\n#cylinders and origin can be categorical (feature engineering)\r\n\r\n\r\nplt.figure()\r\nsns.countplot(data[\"Cylinders\"])\r\nprint(data[\"Cylinders\"].value_counts())\r\n\r\nplt.figure()\r\nsns.countplot(data[\"Origin\"])\r\nprint(data[\"Origin\"].value_counts())\r\n\r\n# box\r\nfor c in data.columns:\r\n plt.figure()\r\n sns.boxplot(x = c, data = data, orient = \"v\")"
] |
[
[
"pandas.read_csv",
"numpy.abs",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
knu2xs/ba-tools
|
[
"74e2731ea9eb6ab8c9a93574ccbd3b5c9d549a5e"
] |
[
"src/ba_tools/analysis.py"
] |
[
"\"\"\"\nMethods to analyze hypotehtical scenarios.\n\"\"\"\n\nimport arcgis\nimport arcpy\nfrom arcgis.geometry import Point\nimport logging\nimport pandas as pd\nimport pathlib\nfrom tempfile import gettempdir\n\nfrom ._data import data\nfrom . import proximity\nfrom .utils import get_dataframe, get_logger, get_destination_id_list_from_near_df_for_origin_id\nfrom .enrich import enrich_all\n\n\ndef _get_min_uid(df, uid_field, start_value=None):\n match = False\n idx = start_value if start_value else 1\n while match is False:\n if idx not in df[uid_field].astype('int64').values:\n uid = idx\n match = True\n elif idx >= df[uid_field].astype('int64').max():\n idx = idx + 1000\n else:\n idx = idx + 1\n return uid\n\n\ndef get_master_dataframe(origin_geography_layer: arcpy._mp.Layer, origin_id_field: str,\n brand_location_layer: arcpy._mp.Layer, brand_id_field: str,\n competitor_location_layer: arcpy._mp.Layer, competitor_id_field: str,\n destination_count: int = 6, overwrite_intermediate: bool = False,\n logger: logging.Logger = None):\n \"\"\"\n Build the master dataframe used for initial model development using a combination of geographic customer origin\n geographies, brand locations, and competitor locations.\n :param origin_geography_layer: Layer of origin geographies where people are coming from - ideally US Census\n Block Groups.\n :param origin_id_field: String field name uniquely identifying the origin geographies.\n :param brand_location_layer: Point location layer where the brand locations are at.\n :param brand_id_field: String field name uniquely identifying the brand locations.\n :param competitor_location_layer: Point location layer where the competitor locations are at.\n :param competitor_id_field: String field name uniquely identifying the competitor locations.\n :param destination_count: Optional integer count of the number of locations to find for each origin geography.\n The default is six.\n :param overwrite_intermediate: Optional boolean indicating if this analysis should overwrite previous runs. The\n default is False indicating to use previous runs if previous attempts were unsuccessful.\n :param logger: Optional Logger object instance with details for saving results of attempting to build data.\n :return: Pandas dataframe with all the data assembled and ready for modeling.\n \"\"\"\n # set up logging\n if logger is None:\n logger = get_logger('INFO')\n\n # get a temporary directory, the standard one, to work with\n temp_dir = pathlib.Path(gettempdir())\n\n # set paths for where to save intermediate data results\n enrich_all_out = temp_dir / 'origin_enrich_all.csv'\n nearest_brand_out = temp_dir / 'nearest_brand.csv'\n nearest_comp_out = temp_dir / 'nearest_competition.csv'\n\n # if starting from scratch, clean everything out\n if overwrite_intermediate:\n for out_file in [enrich_all_out, nearest_brand_out, nearest_comp_out]:\n if out_file.exists():\n out_file.unlink()\n\n enrich_df, nearest_brand_df, nearest_comp_df = None, None, None\n\n # enrich all contributing origin geographies with all available demographics\n if not enrich_all_out.exists() or overwrite_intermediate:\n try:\n logger.info(f'Starting to enrich {origin_geography_layer}.')\n enrich_df = enrich_all(origin_geography_layer, id_field=origin_id_field)\n enrich_df.rename({origin_id_field: 'origin_id'}, axis=1, inplace=True)\n enrich_df.set_index('origin_id', drop=True, inplace=True)\n enrich_df.to_csv(str(enrich_all_out))\n logger.info(\n f'Successfully enriched origin geographies. The output is located at {str(enrich_all_out)}.')\n\n except Exception as e:\n logger.error(f'Failed to enrich {origin_geography_layer}.\\n{e}')\n\n else:\n enrich_df = pd.read_csv(enrich_all_out)\n logger.info(f'Enriched origin geographies already exist at {str(enrich_all_out)}.')\n\n # create a nearest table for all store locations\n if not nearest_brand_out.exists() or overwrite_intermediate:\n try:\n logger.info('Starting to find closest store locations.')\n nearest_brand_df = proximity.closest_dataframe_from_origins_destinations(\n origin_geography_layer, origin_id_field, brand_location_layer, brand_id_field,\n network_dataset=data.usa_network_dataset, destination_count=destination_count\n )\n nearest_brand_df.set_index('origin_id', drop=True, inplace=True)\n nearest_brand_df.to_csv(str(nearest_brand_out))\n logger.info('Successfully solved closest store locations.')\n\n except Exception as e:\n logger.error(f'Failed to solve closest stores.\\n{e}')\n\n else:\n nearest_brand_df = pd.read_csv(nearest_brand_out, index_col=0)\n logger.info(f'Closest store solution already exists at {str(nearest_brand_out)}.')\n\n # create a nearest table for all competition locations\n if not nearest_comp_out.exists():\n try:\n logger.info('Starting to find closest competition locations')\n nearest_comp_df = proximity.closest_dataframe_from_origins_destinations(\n origin_geography_layer, origin_id_field, competitor_location_layer,\n competitor_id_field, network_dataset=data.usa_network_dataset, destination_count=destination_count\n )\n nearest_comp_df.set_index('origin_id', drop=True, inplace=True)\n nearest_comp_df.columns = [c.replace('proximity', 'proximity_competition') for c in\n nearest_comp_df.columns]\n nearest_comp_df.columns = [c.replace('destination', 'destination_competition') for c in\n nearest_comp_df.columns]\n nearest_comp_df.to_csv(str(nearest_comp_out))\n logger.info('Successfully solved closest competition locations.')\n\n except Exception as e:\n logger.error(f'Failed to solve closest competition.\\n{e}')\n\n else:\n nearest_comp_df = pd.read_csv(nearest_comp_out)\n logger.info(f'Closest competition solution already exists at {str(nearest_comp_out)}')\n\n # if we made it this far, and all three dataframes were successfully created, assemble into an output dataframe\n if enrich_df is None or nearest_brand_df is None or nearest_comp_df is None:\n raise Exception('Could not create all three output results. Please view logs to see more.')\n else:\n master_df = enrich_df.join(nearest_brand_df).join(nearest_comp_df)\n\n return master_df\n\n\ndef get_master_csv(origin_geography_layer: arcpy._mp.Layer, origin_id_field: str,\n brand_location_layer: arcpy._mp.Layer, brand_id_field: str,\n competitor_location_layer: arcpy._mp.Layer, competitor_id_field: str,\n output_csv_file: [str, pathlib.Path], destination_count: int = 6,\n overwrite_intermediate: bool = False, logger: logging.Logger = None):\n \"\"\"\n Build the master dataframe used for initial model development and save as a CSV using a combination of\n geographic customer origin geographies, brand locations, and competitor locations.\n :param origin_geography_layer: Layer of origin geographies where people are coming from - ideally US Census\n Block Groups.\n :param origin_id_field: String field name uniquely identifying the origin geographies.\n :param brand_location_layer: Point location layer where the brand locations are at.\n :param brand_id_field: String field name uniquely identifying the brand locations.\n :param competitor_location_layer: Point location layer where the competitor locations are at.\n :param competitor_id_field: String field name uniquely identifying the competitor locations.\n :param output_csv_file: Path to output CSV file where the prepped data will be saved.\n :param destination_count: Optional integer count of the number of locations to find for each origin geography.\n The default is six.\n :param overwrite_intermediate: Optional boolean indicating if this analysis should overwrite previous runs. The\n default is False indicating to use previous runs if previous attempts were unsuccessful.\n :param logger: Optional Logger object instance with details for saving results of attempting to build data.\n :return: Pandas dataframe with all the data assembled and ready for modeling.\n \"\"\"\n master_df = get_master_dataframe(origin_geography_layer, origin_id_field, brand_location_layer, brand_id_field,\n competitor_location_layer, competitor_id_field, destination_count,\n overwrite_intermediate, logger)\n\n master_df.to_csv(output_csv_file)\n\n if not isinstance(pathlib.Path, output_csv_file):\n output_csv_file = pathlib.Path(output_csv_file)\n return output_csv_file\n\n\ndef get_add_new_closest_dataframe(origins: [str, pd.DataFrame], origin_id_field: str, destinations: [str, pd.DataFrame],\n destination_id_field: str, closest_table: [str, pd.DataFrame], new_destination: Point,\n gis: arcgis.gis.GIS = None, origin_weighting_points: [str, pd.DataFrame] = None\n ) -> pd.DataFrame:\n \"\"\"\n Calculate the impact of a location being added to the retail landscape.\n :param origins: Polygons in a Spatially Enabled Dataframe or string path to Feature Class delineating starting\n locations for closest analysis.\n :param origin_id_field: Field or column name used to uniquely identify each origin.\n :param destinations: Spatially Enabled Dataframe or string path to Feature Class containing all destinations.\n :param destination_id_field: Field or column name used to uniquely identify each destination location.\n :param closest_table: Path to CSV, table, or Dataframe containing solution for nearest locations.\n :param new_destination: Geometry of new location being added to the retail landscape.\n :param origin_weighting_points: Points potentially used to calculate a centroid based on population density\n represented by the weighting points instead of simply the geometric centroid.\n :return: Data frame with rebalanced closest table only for affected origins.\n \"\"\"\n # read in the existing closest table solution\n closest_orig_df = closest_table if isinstance(closest_table, pd.DataFrame) else pd.read_csv(closest_table)\n\n # get a list of the destination columns from the existing closest table\n dest_cols = [col for col in closest_orig_df.columns if col.startswith('destination_id')]\n\n # get a count of the nth number of locations solved for\n dest_count = len(dest_cols)\n\n # load the original origins into a dataframe and format it for analysis\n origin_df_poly = get_dataframe(origins)\n origin_df = proximity.prep_sdf_for_nearest(origin_df_poly, origin_id_field, origin_weighting_points)\n\n # load the original destinations into a dataframe and format it for analysis\n dest_df = get_dataframe(destinations)\n dest_df = proximity.prep_sdf_for_nearest(dest_df, destination_id_field)\n\n # create new destination dataframe for analysis\n new_id = _get_min_uid(origin_df, 'ID') # creates lowest numbered id available, or 1000 higher than top value\n new_df = pd.DataFrame([[new_id, new_id, new_destination]], columns=['ID', 'Name', 'SHAPE'])\n new_df.spatial.set_geometry('SHAPE')\n\n # ensure the dataframes are in the same spatial reference and then get the id of the origin the new point resides in\n coincidence_new_dest = new_destination.project_as(origin_df.spatial.sr)\n for row in origin_df_poly.itertuples(name='dest'):\n geom = row.SHAPE\n if geom.contains(coincidence_new_dest):\n dest_id = getattr(row, origin_id_field)\n\n # get the destination ids of the existing nth closest destinations\n dest_subset_ids = get_destination_id_list_from_near_df_for_origin_id(closest_orig_df, dest_id)\n\n # by cross referencing from the destination ids, get the origin ids allocated to the exiting locations\n subset_origin_ids = pd.concat([closest_orig_df[closest_orig_df[dest_col].isin(dest_subset_ids)]['origin_id']\n for dest_col in dest_cols]).unique()\n\n # get a subset dataframe of the origins allocated to the closest nth locations\n subset_origin_df = origin_df[origin_df['ID'].astype('int64').isin(subset_origin_ids)].copy()\n\n # add the new location to the destination dataframe\n dest_analysis_df = pd.concat([dest_df, new_df], sort=False)\n dest_analysis_df.spatial.set_geometry('SHAPE')\n dest_analysis_df.reset_index(inplace=True, drop=True)\n\n # if a GIS is provided, use online resources to solve for the closest destination to the affected area\n if gis is not None:\n\n # solve for the closest destination to the affected area\n closest_subset_df = proximity.closest_dataframe_from_origins_destinations(subset_origin_df, 'ID',\n dest_analysis_df, 'ID',\n gis=gis,\n destination_count=dest_count)\n\n # otherwise, use local resources\n else:\n\n # solve for the closest destination to the affected area\n closest_subset_df = proximity.closest_dataframe_from_origins_destinations(subset_origin_df, 'ID',\n dest_analysis_df, 'ID',\n network_dataset=data.usa_network_dataset,\n destination_count=dest_count)\n\n return closest_subset_df\n\n\ndef get_remove_existing_closest_dataframe(origins: [str, pd.DataFrame], origin_id_field: str,\n destinations: [str, pd.DataFrame],\n destination_id_field: str, closest_table: [str, pd.DataFrame],\n remove_destination_id: str,\n origin_weighting_points: [str, pd.DataFrame] = None) -> pd.DataFrame:\n \"\"\"\n Calculate the impact of a location being removed from the retail landscape.\n :param origins: Polygons in a Spatially Enabled Dataframe or string path to Feature Class delineating starting\n locations for closest analysis.\n :param origin_id_field: Field or column name used to uniquely identify each origin.\n :param destinations: Spatially Enabled Dataframe or string path to Feature Class containing all destinations.\n :param destination_id_field: Field or column name used to uniquely identify each destination location.\n :param closest_table: Path to CSV, table, or Dataframe containing solution for nearest locations.\n :param remove_destination_id: Unique ID of location being removed from the retail landscape.\n :param origin_weighting_points: Points potentially used to calculate a centroid based on population density\n represented by the weighting points instead of simply the geometric centroid.\n :return: Data frame with rebalanced closest table only for affected origins.\n \"\"\"\n # read in the existing closest table solution\n closest_orig_df = pd.read_csv(closest_table)\n\n # get a list of the destination columns from the existing closest table\n dest_cols = [col for col in closest_orig_df.columns if col.startswith('destination_id')]\n\n # get a count of the nth number of locations solved for\n dest_count = len(dest_cols)\n\n # load the original origins into a dataframe and format it for analysis\n origin_df = get_dataframe(origins)\n origin_df = proximity.prep_sdf_for_nearest(origin_df, origin_id_field, origin_weighting_points)\n\n # load the original destinations into a dataframe and format it for analysis\n dest_df = get_dataframe(destinations)\n dest_df = proximity.prep_sdf_for_nearest(dest_df, destination_id_field)\n\n # extract the location from the destinations to be removed and put it in a separate dataframe\n new_df = dest_df[dest_df['ID'] == str(remove_destination_id)].copy()\n\n # remove the location from the destinations\n dest_df = dest_df[dest_df['ID'] != str(remove_destination_id)].copy()\n\n # get the nth closest destination locations to the new destination location\n closest_dest_df = proximity.get_closest_solution(new_df, 'ID', dest_df, 'ID',\n network_dataset=data.usa_network_dataset,\n destination_count=dest_count)\n\n # get the destination ids of the existing nth closest destinations\n dest_subset_ids = closest_dest_df['destination_id'].values\n\n # by cross referencing from the destination ids, get the origin ids allocated to the exiting locations\n subset_origin_ids = pd.concat([closest_orig_df[closest_orig_df[dest_col].isin(dest_subset_ids)]['origin_id']\n for dest_col in dest_cols]).unique()\n\n # get a subset dataframe of the origins allocated to the closest nth locations\n subset_origin_df = origin_df[origin_df['ID'].astype('int64').isin(subset_origin_ids)].copy()\n\n # solve for the closest destination to the affected area\n closest_subset_df = proximity.closest_dataframe_from_origins_destinations(subset_origin_df, 'ID', dest_df,\n 'ID',\n network_dataset=data.usa_network_dataset,\n destination_count=dest_count)\n\n return closest_subset_df\n"
] |
[
[
"pandas.concat",
"pandas.read_csv",
"pandas.DataFrame"
]
] |
SidsMav2000/Handwritten-Digit-Recognition
|
[
"81492cb49b4bed4631947e6ae6391f0bfebc9a2a"
] |
[
"gui_digit_recognizer.py"
] |
[
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri May 8 12:43:12 2020\r\n\r\n@author: Siddharth\r\n\"\"\"\r\n\r\nfrom keras.models import load_model\r\nfrom tkinter import *\r\nimport tkinter as tk\r\nimport win32gui\r\nfrom PIL import ImageGrab, Image\r\nimport numpy as np\r\n\r\nmodel = load_model('mnist.h5')\r\n\r\ndef predict_digit(img):\r\n #resize image to 28x28 pixels\r\n img = img.resize((28,28))\r\n #convert rgb to grayscale\r\n img = img.convert('L')\r\n img = np.array(img)\r\n #reshaping to support our model input and normalizing\r\n img = img.reshape(1,28,28,1)\r\n img = img/255.0\r\n #predicting the class\r\n res = model.predict([img])[0]\r\n return np.argmax(res), max(res)\r\n\r\nclass App(tk.Tk):\r\n def __init__(self):\r\n tk.Tk.__init__(self)\r\n\r\n self.x = self.y = 0\r\n \r\n # Creating elements\r\n self.canvas = tk.Canvas(self, width=300, height=300, bg = \"white\", cursor=\"cross\")\r\n self.label = tk.Label(self, text=\"Draw..\", font=(\"Helvetica\", 48))\r\n self.classify_btn = tk.Button(self, text = \"Recognise\", command = self.classify_handwriting) \r\n self.button_clear = tk.Button(self, text = \"Clear\", command = self.clear_all)\r\n \r\n # Grid structure\r\n self.canvas.grid(row=0, column=0, pady=2, sticky=W, )\r\n self.label.grid(row=0, column=1,pady=2, padx=2)\r\n self.classify_btn.grid(row=1, column=1, pady=2, padx=2)\r\n self.button_clear.grid(row=1, column=0, pady=2)\r\n \r\n #self.canvas.bind(\"<Motion>\", self.start_pos)\r\n self.canvas.bind(\"<B1-Motion>\", self.draw_lines)\r\n\r\n def clear_all(self):\r\n self.canvas.delete(\"all\")\r\n \r\n def classify_handwriting(self):\r\n HWND = self.canvas.winfo_id() # get the handle of the canvas\r\n rect = win32gui.GetWindowRect(HWND) # get the coordinate of the canvas\r\n a,b,c,d = rect\r\n rect=(a+4,b+4,c-4,d-4)\r\n im = ImageGrab.grab(rect)\r\n\r\n digit, acc = predict_digit(im)\r\n self.label.configure(text= str(digit)+', '+ str(int(acc*100))+'%')\r\n\r\n def draw_lines(self, event):\r\n self.x = event.x\r\n self.y = event.y\r\n r=8\r\n self.canvas.create_oval(self.x-r, self.y-r, self.x + r, self.y + r, fill='black')\r\n \r\napp = App()\r\nmainloop()\r\n"
] |
[
[
"numpy.array",
"numpy.argmax"
]
] |
YeeU/InverseRenderNet
|
[
"88851168b10f4bca9d35c7341a4a67b59fea98c2"
] |
[
"model/loss_layer.py"
] |
[
"# formulate loss function based on supplied ground truth and outputs from network\n\nimport importlib\nimport tensorflow as tf\nimport numpy as np\nimport os\nfrom model import SfMNet, lambSH_layer, pred_illuDecomp_layer, sup_illuDecomp_layer, reproj_layer\n\ndef loss_formulate(albedos, nm_pred, am_sup, nm_gt, inputs, dms, cams, scale_xs, scale_ys, masks, pair_label, preTrain_flag, am_smt_w_var, reproj_w_var, reg_loss_flag=True):\n\n\t# define gamma nonlinear mapping factor\n\tgamma = tf.constant(2.2)\n\n\talbedos = tf.nn.sigmoid(albedos) * masks + tf.constant(1e-4)\n\n\t### pre-process nm_pred such that in range (-1,1)\n\tnm_pred_norm = tf.sqrt(tf.reduce_sum(nm_pred**2, axis=-1, keepdims=True)+tf.constant(1.))\n\tnm_pred_xy = nm_pred / nm_pred_norm\n\tnm_pred_z = tf.constant(1.) / nm_pred_norm\n\tnm_pred_xyz = tf.concat([nm_pred_xy, nm_pred_z], axis=-1) * masks\n\n\t# selete normal map used in rendering - gt or pred\n\tnormals = nm_gt if preTrain_flag else nm_pred_xyz\n\n\n\t# reconstruct SH lightings from predicted statistical SH lighting model\n\tlighting_model = '../hdr_illu_pca'\n\tlighting_vectors = tf.constant(np.load(os.path.join(lighting_model,'pcaVector.npy')),dtype=tf.float32)\n\tlighting_means = tf.constant(np.load(os.path.join(lighting_model,'mean.npy')),dtype=tf.float32)\n\tlightings_var = tf.constant(np.load(os.path.join(lighting_model,'pcaVariance.npy')),dtype=tf.float32)\n\t\n\tif preTrain_flag:\n\t\tlightings = sup_illuDecomp_layer.illuDecomp(inputs,albedos,nm_gt,gamma)\n\telse:\n\t\tlightings =pred_illuDecomp_layer.illuDecomp(inputs,albedos,nm_pred_xyz,gamma,masks)\n\n\tlightings_pca = tf.matmul((lightings - lighting_means), pinv(lighting_vectors))\n\n\t# recompute lightings from lightins_pca which could add weak constraint on lighting reconstruction \n\tlightings = tf.matmul(lightings_pca,lighting_vectors) + lighting_means \n\n\t# reshape 27-D lightings to 9*3 lightings\n\tlightings = tf.reshape(lightings,[tf.shape(lightings)[0],9,3])\n\n\n\t### lighting prior loss\n\tvar = tf.reduce_mean(lightings_pca**2,axis=0)\n\n\tillu_prior_loss = tf.losses.absolute_difference(var, lightings_var)\n\n\tillu_prior_loss = tf.log(illu_prior_loss + 1.)\n\n\n\t### stereo supervision based on albedos reprojection consistancy\n\treproj_tb = tf.to_float(tf.equal(pair_label,tf.transpose(pair_label)))\n\treproj_tb = tf.cast(tf.matrix_set_diag(reproj_tb, tf.zeros([tf.shape(inputs)[0]])),tf.bool)\n\treproj_list = tf.where(reproj_tb)\n\timg1_inds = tf.expand_dims(reproj_list[:,0],axis=-1)\n\timg2_inds = tf.expand_dims(reproj_list[:,1],axis=-1)\n\talbedo1 = tf.gather_nd(albedos,img1_inds)\n\tdms1 = tf.gather_nd(dms,img1_inds)\n\tcams1 = tf.gather_nd(cams,img1_inds)\n\talbedo2 = tf.gather_nd(albedos,img2_inds)\n\tcams2 = tf.gather_nd(cams,img2_inds)\n\tscale_xs1 = tf.gather_nd(scale_xs, img1_inds)\n\tscale_xs2 = tf.gather_nd(scale_xs, img2_inds)\n\tscale_ys1 = tf.gather_nd(scale_ys, img1_inds)\n\tscale_ys2 = tf.gather_nd(scale_ys, img2_inds)\n\n\tinput1 = tf.gather_nd(inputs, img1_inds)\n\n\t# mask_indices contains indices for image index inside batch and spatial locations, and ignores the rgb channel index\n\treproj_albedo1, reproj_mask = reproj_layer.map_reproj(dms1,albedo2,cams1,cams2,scale_xs1,scale_xs2,scale_ys1,scale_ys2)\n\n\treproj_albedo1 = reproj_albedo1+tf.constant(1e-4) # numerical stable constant\n\n\n\n\t### scale intensities for each image\n\tnum_imgs = tf.shape(reproj_mask)[0]\n\tim_ = tf.constant(0)\n\toutput = tf.TensorArray(dtype=tf.float32,size=num_imgs)\t\n\n\tdef body(im_, output):\n\t\treproj_mask_ = reproj_mask[im_]\n\t\talbedo1_ = tf.boolean_mask(albedo1[im_],reproj_mask_)\n\t\treproj_albedo1_ = tf.boolean_mask(reproj_albedo1[im_],reproj_mask_)\n\n\n\t\tk = tf.reduce_sum(albedo1_*reproj_albedo1_,keepdims=True)/(tf.reduce_sum(reproj_albedo1_**2,keepdims=True)+tf.constant(1e-4))\n\n\t\toutput = output.write(im_,k)\n\t\tim_ += tf.constant(1)\n\n\t\treturn im_, output\n\n\tdef condition(im_, output):\n\t\treturn tf.less(im_,num_imgs)\n\n\t_,output = tf.while_loop(condition, body, loop_vars=[im_, output])\n\n\n\tks = tf.expand_dims(output.stack(), axis=-1)\n\n\n\n\talbedo1_pixels = tf.boolean_mask(albedo1, reproj_mask)\n\treproj_albedo1_pixels = tf.boolean_mask(reproj_albedo1*ks, reproj_mask)\n\treproj_err = tf.losses.mean_squared_error(cvtLab(albedo1_pixels), cvtLab(reproj_albedo1_pixels))\n\n\n\t### formulate loss based on paired batches ###\n\t# self-supervision based on intensity reconstruction\n\tshadings, renderings_mask = lambSH_layer.lambSH_layer(tf.ones_like(albedos), normals, lightings, 1.)\n\n\t# compare rendering intensity by Lab\n\tinputs_pixels = cvtLab(tf.boolean_mask(inputs,renderings_mask))\n\trenderings = cvtLab(tf.boolean_mask(tf.pow(albedos*shadings,1./gamma),renderings_mask))\n\trender_err = tf.losses.mean_squared_error(inputs_pixels,renderings)\n\n\n\t### compute rendering loss from cross-projected alebdo map\n\tcross_shadings = tf.gather_nd(shadings, img1_inds)\n\tinputs_pixels = cvtLab(tf.boolean_mask(input1,reproj_mask))\n\tcross_renderings = cvtLab(tf.boolean_mask(tf.pow(tf.nn.relu(cross_shadings*reproj_albedo1*ks), 1./gamma),reproj_mask))\n\tcross_render_err = tf.losses.mean_squared_error(inputs_pixels,cross_renderings)\n\n\n\t### measure smoothness of albedo map\n\tGx = tf.constant(1/2)*tf.expand_dims(tf.expand_dims(tf.constant([[-1,1]], dtype=tf.float32), axis=-1), axis=-1)\n\tGy = tf.constant(1/2)*tf.expand_dims(tf.expand_dims(tf.constant([[-1],[1]], dtype=tf.float32), axis=-1), axis=-1)\n\tGx_3 = tf.tile(Gx, multiples=(1,1,3,1))\t\n\tGy_3 = tf.tile(Gy, multiples=(1,1,3,1))\t\n\talbedo_lab = tf.reshape(cvtLab(tf.reshape(albedos,[-1,3])),[-1,200,200,3])\n\n\taGx = tf.nn.conv2d(albedos, Gx_3, padding='SAME', strides=(1,1,1,1))\n\taGy = tf.nn.conv2d(albedos, Gy_3, padding='SAME', strides=(1,1,1,1))\n\taGxy = tf.concat([aGx,aGy], axis=-1)\n\n\n\t# compute pixel-wise smoothness weights by angle distance between neighbour pixels' chromaticities\n\tinputs_pad = tf.pad(inputs, paddings=tf.constant([[0,0], [0,1], [0,1], [0,0]]))\n\tchroma_pad = tf.nn.l2_normalize(inputs_pad, axis=-1)\n\n\tchroma = chroma_pad[:,:-1,:-1,:]\n\tchroma_X = chroma_pad[:,:-1,1:,:]\n\tchroma_Y = chroma_pad[:,1:,:-1,:]\n\tchroma_Gx = tf.reduce_sum(chroma*chroma_X, axis=-1, keepdims=True)**tf.constant(2.) - tf.constant(1.)\n\tchroma_Gy = tf.reduce_sum(chroma*chroma_Y, axis=-1, keepdims=True)**tf.constant(2.) - tf.constant(1.)\n\tchroma_Gx = tf.exp(chroma_Gx / tf.constant(0.0001))\n\tchroma_Gy = tf.exp(chroma_Gy / tf.constant(0.0001))\n\tchroma_Gxy = tf.concat([chroma_Gx, chroma_Gy], axis=-1)\n\n\tint_pad = tf.reduce_sum(inputs_pad**tf.constant(2.), axis=-1, keepdims=True)\n\tint = int_pad[:,:-1,:-1,:]\n\tint_X = int_pad[:,:-1,1:,:]\n\tint_Y = int_pad[:,1:,:-1,:]\n\n\tint_Gx = tf.where(condition=int < int_X, x=int, y=int_X)\n\tint_Gy = tf.where(condition=int < int_Y, x=int, y=int_Y)\n\tint_Gx = tf.constant(1.) + tf.exp(- int_Gx / tf.constant(.8))\n\tint_Gy = tf.constant(1.) + tf.exp(- int_Gy / tf.constant(.8))\n\tint_Gxy = tf.concat([int_Gx, int_Gy], axis=-1)\n\n\tGxy_weights = int_Gxy * chroma_Gxy\n\talbedo_smt_error = tf.reduce_mean(tf.abs(aGxy)*Gxy_weights)\n\n\n\t### albedo map pseudo-supervision loss\n\tif preTrain_flag:\n\t\tam_loss = tf.constant(0.)\n\telse:\n\t\tamSup_mask = tf.not_equal(tf.reduce_sum(nm_gt,axis=-1),0)\n\t\tam_sup_pixel = cvtLab(tf.boolean_mask(am_sup, amSup_mask))\n\t\talbedos_pixel = cvtLab(tf.boolean_mask(albedos, amSup_mask))\n\t\tam_loss = tf.losses.mean_squared_error(am_sup_pixel, albedos_pixel)\n\n\n\n\t### regualarisation loss\n\treg_loss = sum(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES))\n\n\n\t### compute nm_pred error\n\tnmSup_mask = tf.not_equal(tf.reduce_sum(nm_gt,axis=-1),0)\n\tnm_gt_pixel = tf.boolean_mask(nm_gt, nmSup_mask)\n\tnm_pred_pixel = tf.boolean_mask(nm_pred_xyz, nmSup_mask)\n\tnm_prod = tf.reduce_sum(nm_pred_pixel * nm_gt_pixel, axis=-1, keepdims=True)\t\n\tnm_cosValue = tf.constant(0.9999)\n\tnm_prod = tf.clip_by_value(nm_prod, -nm_cosValue, nm_cosValue)\n\tnm_angle = tf.acos(nm_prod) + tf.constant(1e-4)\n\tnm_loss = tf.reduce_mean(nm_angle**2)\n\n\n\n\t### compute gradient loss\n\tnm_pred_Gx = conv2d_nosum(nm_pred_xyz, Gx)\n\tnm_pred_Gy = conv2d_nosum(nm_pred_xyz, Gy)\n\tnm_pred_Gxy = tf.concat([nm_pred_Gx, nm_pred_Gy], axis=-1)\n\tnormals_Gx = conv2d_nosum(nm_gt, Gx)\n\tnormals_Gy = conv2d_nosum(nm_gt, Gy)\n\tnormals_Gxy = tf.concat([normals_Gx, normals_Gy], axis=-1)\n\n\tnm_pred_smt_error = tf.losses.mean_squared_error(nm_pred_Gxy, normals_Gxy)\n\n\n\t### total loss\n\trender_err *= tf.constant(.1)\n\treproj_err *= tf.constant(.05) * reproj_w_var\n\tcross_render_err *= tf.constant(.1)\n\tam_loss *= tf.constant(.1)\n\tillu_prior_loss *= tf.constant(.01)\n\talbedo_smt_error *= tf.constant(50.) * am_smt_w_var\n\tnm_pred_smt_error *= tf.constant(1.)\n\tnm_loss *= tf.constant(1.)\n\n\n\n\tif reg_loss_flag == True:\n\t\tloss = render_err + reproj_err + cross_render_err + reg_loss + illu_prior_loss + albedo_smt_error + nm_pred_smt_error + nm_loss + am_loss\n\telse:\n\t\tloss = render_err + reproj_err + cross_render_err + illu_prior_loss + albedo_smt_error + nm_pred_smt_error + nm_loss + am_loss\n\n\treturn lightings, albedos, nm_pred_xyz, loss, render_err, reproj_err, cross_render_err, reg_loss, illu_prior_loss, albedo_smt_error, nm_pred_smt_error, nm_loss, am_loss\n\n\n\n# input RGB is 2d tensor with shape (n_pix, 3)\ndef cvtLab(RGB):\n\n\t# threshold definition\n\tT = tf.constant(0.008856)\n\n\t# matrix for converting RGB to LUV color space\n\tcvt_XYZ = tf.constant([[0.412453,0.35758,0.180423],[0.212671,0.71516,0.072169],[0.019334,0.119193,0.950227]])\n\n\t# convert RGB to XYZ\n\tXYZ = tf.matmul(RGB,tf.transpose(cvt_XYZ))\n\n\t# normalise for D65 white point\n\tXYZ /= tf.constant([[0.950456, 1., 1.088754]])*100\n\n\tmask = tf.to_float(tf.greater(XYZ,T))\n\n\tfXYZ = XYZ**(1/3)*mask + (1.-mask)*(tf.constant(7.787)*XYZ + tf.constant(0.137931))\n\n\tM_cvtLab = tf.constant([[0., 116., 0.], [500., -500., 0.], [0., 200., -200.]])\n\n\tLab = tf.matmul(fXYZ, tf.transpose(M_cvtLab)) + tf.constant([[-16., 0., 0.]])\n\tmask = tf.to_float(tf.equal(Lab, tf.constant(0.)))\n\n\tLab += mask * tf.constant(1e-4)\n\n\treturn Lab\n\n\n\n\n\n# compute pseudo inverse for input matrix\ndef pinv(A, reltol=1e-6):\n\t# compute SVD of input A\n\ts, u, v = tf.svd(A)\n\n\t# invert s and clear entries lower than reltol*s_max\n\tatol = tf.reduce_max(s) * reltol\n\ts = tf.where(s>atol, s, atol*tf.ones_like(s))\n\ts_inv = tf.diag(1./s)\n\n\t# compute v * s_inv * u_t as psuedo inverse\n\treturn tf.matmul(v, tf.matmul(s_inv, tf.transpose(u)))\n\n\n\n# compute regular 2d convolution on 3d data\ndef conv2d_nosum(input, kernel):\n\tinput_x = input[:,:,:,0:1]\n\tinput_y = input[:,:,:,1:2]\n\tinput_z = input[:,:,:,2:3]\n\n\toutput_x = tf.nn.conv2d(input_x, kernel, strides=(1,1,1,1), padding='SAME')\n\toutput_y = tf.nn.conv2d(input_y, kernel, strides=(1,1,1,1), padding='SAME')\n\toutput_z = tf.nn.conv2d(input_z, kernel, strides=(1,1,1,1), padding='SAME')\n\n\treturn tf.concat([output_x,output_y,output_z], axis=-1)\n\n\n\n# compute regular 2d convolution on 3d data\ndef conv2d_nosum_2ch(input, kernel):\n\tinput_x = input[:,:,:,0:1]\n\tinput_y = input[:,:,:,1:2]\n\n\toutput_x = tf.nn.conv2d(input_x, kernel, strides=(1,1,1,1), padding='SAME')\n\toutput_y = tf.nn.conv2d(input_y, kernel, strides=(1,1,1,1), padding='SAME')\n\n\treturn tf.concat([output_x,output_y], axis=-1)\n\n\n\n\n\n\n\n\n"
] |
[
[
"tensorflow.concat",
"tensorflow.reduce_sum",
"tensorflow.diag",
"tensorflow.losses.absolute_difference",
"tensorflow.where",
"tensorflow.nn.conv2d",
"tensorflow.boolean_mask",
"tensorflow.while_loop",
"tensorflow.greater",
"tensorflow.get_collection",
"tensorflow.tile",
"tensorflow.nn.l2_normalize",
"tensorflow.matmul",
"tensorflow.nn.sigmoid",
"tensorflow.gather_nd",
"tensorflow.shape",
"tensorflow.TensorArray",
"tensorflow.less",
"tensorflow.pow",
"tensorflow.svd",
"tensorflow.clip_by_value",
"tensorflow.nn.relu",
"tensorflow.losses.mean_squared_error",
"tensorflow.reduce_max",
"tensorflow.constant",
"tensorflow.transpose",
"tensorflow.reduce_mean",
"tensorflow.reshape",
"tensorflow.ones_like",
"tensorflow.expand_dims",
"tensorflow.log",
"tensorflow.acos",
"tensorflow.abs"
]
] |
ivallesp/simplestELM
|
[
"d724f1d64f500c7612457f8d169fda9b39c25d90"
] |
[
"example.py"
] |
[
"# -*- coding: utf-8 -*-\n__author__ = 'ivanvallesperez'\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import load_diabetes\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVR\nfrom sklearn.tree import DecisionTreeRegressor\n\nfrom ELM import ELMRegressor\n\ntest_maes_dictionary = dict()\n\nplt.style.use('ggplot')\nsns.set_context(\"talk\")\nnp.random.seed(0)\n\n## DATA PREPROCESSING\ndiabetes = load_diabetes()\nX, y = diabetes[\"data\"], diabetes[\"target\"]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=2)\n\nstdScaler_data = StandardScaler()\nX_train = stdScaler_data.fit_transform(X_train)\nX_test = stdScaler_data.transform(X_test)\n\nstdScaler_target = StandardScaler()\ny_train = stdScaler_target.fit_transform(np.expand_dims(y_train,1)) # /max(y_train)\ny_test = stdScaler_target.transform(np.expand_dims(y_test,1)) # /max(y_train)\nmax_y_train = max(abs(y_train))\ny_train = y_train / max_y_train\ny_test = y_test / max_y_train\n\n## ELM TRAINING\nMAE_TRAIN_MINS = []\nMAE_TEST_MINS = []\n\nfor M in range(1, 200, 1):\n MAES_TRAIN = []\n MAES_TEST = []\n # print \"Training with %s neurons...\"%M\n for i in range(30):\n ELM = ELMRegressor(M)\n ELM.fit(X_train, y_train)\n prediction = ELM.predict(X_train)\n MAES_TRAIN.append(mean_absolute_error(y_train,\n prediction))\n\n prediction = ELM.predict(X_test)\n MAES_TEST.append(mean_absolute_error(y_test,\n prediction))\n MAE_TEST_MINS.append(min(MAES_TEST))\n MAE_TRAIN_MINS.append(MAES_TRAIN[np.argmin(MAES_TEST)])\n\nprint(\"Minimum MAE ELM =\", min(MAE_TEST_MINS))\ntest_maes_dictionary[\"ELM\"] = min(MAE_TEST_MINS)\n\n## LINEAR REGRESSION TRAINING\nmae = []\nlr = LinearRegression()\nlr.fit(X_train, y_train)\nprediction = lr.predict(X_test)\nmae.append(mean_absolute_error(y_test, prediction))\nprint(\"Minimum MAE LR =\", min(mae))\ntest_maes_dictionary[\"LinReg\"] = min(mae)\n\n## K-NEAREST NEIGHBORS TRAINING\nmae = []\nfor N in range(1, 51):\n kn = KNeighborsRegressor()\n kn.fit(X_train, y_train)\n prediction = kn.predict(X_test)\n mae.append(mean_absolute_error(y_test, prediction))\nprint(\"Minimum MAE KNN =\", min(mae))\ntest_maes_dictionary[\"KNN\"] = min(mae)\n\n## DECISION TREES TRAINING\nmae = []\nfor max_depth in range(1, 51):\n for min_samples_split in range(5, 102, 5):\n tree = DecisionTreeRegressor(max_depth=max_depth, min_samples_split=min_samples_split)\n tree.fit(X_train, y_train)\n prediction = tree.predict(X_test)\n mae.append(mean_absolute_error(y_test, prediction))\nprint(\"Minimum MAE TREE = \", min(mae))\ntest_maes_dictionary[\"Dec. Tree\"] = min(mae)\n\n## SUPPORT VECTORS MACHINE TRAINING\nmae = []\nfor kernel in [\"rbf\", \"linear\", \"poly\", \"sigmoid\"]:\n svr = SVR(kernel=kernel)\n svr.fit(X_train, y_train)\n prediction = svr.predict(X_test)\n mae.append(mean_absolute_error(y_test, prediction))\nprint(\"Minimum MAE SVR = \", min(mae))\ntest_maes_dictionary[\"SVM\"] = min(mae)\n\n## RANDOM FOREST TRAINING\nmae = []\nfor n_estimators in range(10, 1100, 100):\n rf = RandomForestRegressor(n_estimators=n_estimators)\n rf.fit(X_train, y_train)\n prediction = rf.predict(X_test)\n mae.append(mean_absolute_error(y_test, prediction))\nprint(\"Minimum MAE R.Forest = \", min(mae))\ntest_maes_dictionary[\"R. Forest\"] = min(mae)\n\n#############################################################################################\n## PLOTTING THE RESULTS\ndf = pd.DataFrame()\ndf[\"test\"] = MAE_TEST_MINS\ndf[\"train\"] = MAE_TRAIN_MINS\n\nax = df.plot(figsize=(16, 7))\nax.set_xlabel(\"Number of Neurons in the hidden layer\")\nax.set_ylabel(\"Mean Absolute Error\")\nax.set_title(\n \"Extreme Learning Machine error obtained for the Diabetes dataset \\n when varying the number of neurons in the \"\n \"hidden layer (min. at 23 neurons)\")\nplt.show()\n\nplt.figure(figsize=(16, 7))\nD = test_maes_dictionary\nplt.bar(range(len(D)), D.values(), align='center')\nplt.xticks(range(len(D)), D.keys())\nplt.ylabel(\"Mean Absolute Error\")\nplt.title(\"Error Comparison between Classic Regression Models and ELM\")\nplt.show()\n"
] |
[
[
"sklearn.ensemble.RandomForestRegressor",
"numpy.expand_dims",
"sklearn.tree.DecisionTreeRegressor",
"numpy.random.seed",
"matplotlib.pyplot.title",
"sklearn.metrics.mean_absolute_error",
"sklearn.datasets.load_diabetes",
"sklearn.model_selection.train_test_split",
"pandas.DataFrame",
"sklearn.neighbors.KNeighborsRegressor",
"sklearn.svm.SVR",
"matplotlib.pyplot.ylabel",
"numpy.argmin",
"sklearn.linear_model.LinearRegression",
"sklearn.preprocessing.StandardScaler",
"matplotlib.pyplot.show",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.figure"
]
] |
hanskyy/simple-rl
|
[
"5d0ff35af21eb656057a4130742c34c3bf01eecb"
] |
[
"Algorithm/A2C_mountain_car.py"
] |
[
"import gym\nimport numpy as np\nimport tensorflow as tf\n\n\nclass Memory(object):\n def __init__(self):\n self.ep_obs, self.ep_act, self.ep_rwd = [], [], []\n\n def store_transition(self, obs0, act, rwd):\n self.ep_obs.append(obs0)\n self.ep_act.append(act)\n self.ep_rwd.append(rwd)\n\n def covert_to_array(self):\n array_obs = np.vstack(self.ep_obs)\n array_act = np.vstack(self.ep_act)\n array_rwd = np.array(self.ep_rwd)\n return array_obs, array_act, array_rwd\n\n def reset(self):\n self.ep_obs, self.ep_act, self.ep_rwd = [], [], []\n\n\nclass ActorNetwork(object):\n def __init__(self, act_dim, name):\n self.act_dim = act_dim\n self.name = name\n\n def step(self, obs, reuse):\n with tf.variable_scope(self.name, reuse=reuse):\n h1 = tf.layers.dense(obs, 64, activation=tf.nn.relu)\n h2 = tf.layers.dense(h1, 64, activation=tf.nn.relu)\n mu = 2 * tf.layers.dense(h2, self.act_dim, activation=tf.nn.tanh)\n sigma = tf.layers.dense(h2, self.act_dim, activation=tf.nn.softplus)\n pd = tf.distributions.Normal(loc=mu, scale=sigma)\n return pd\n\n def choose_action(self, obs, reuse=False):\n pd = self.step(obs, reuse)\n action = tf.squeeze(pd.sample(1), axis=0)\n action = tf.clip_by_value(action, -1.0, 1.0)\n return action\n\n def get_neglogp(self, obs, act, reuse=True):\n pd = self.step(obs, reuse)\n neglogp = pd.prob(act)\n return neglogp\n\n\nclass ValueNetwork(object):\n def __init__(self, name):\n self.name = name\n\n def step(self, obs, reuse):\n with tf.variable_scope(self.name, reuse=reuse):\n h1 = tf.layers.dense(obs, 64, activation=tf.nn.relu)\n h2 = tf.layers.dense(h1, 64, activation=tf.nn.relu)\n value = tf.layers.dense(inputs=h2, units=1)\n return value\n\n def get_value(self, obs, reuse=False):\n value = self.step(obs, reuse)\n return value\n\n\nclass ActorCritic:\n def __init__(self, act_dim, obs_dim, lr_actor, lr_value, gamma):\n self.act_dim = act_dim\n self.obs_dim = obs_dim\n self.lr_actor = lr_actor\n self.lr_value = lr_value\n self.gamma = gamma\n\n self.OBS = tf.placeholder(tf.float32, [None, self.obs_dim], name=\"observation\")\n self.ACT = tf.placeholder(tf.float32, [None, self.act_dim], name=\"action\")\n self.Q_VAL = tf.placeholder(tf.float32, [None, 1], name=\"q_value\")\n\n actor = ActorNetwork(self.act_dim, 'actor')\n critic = ValueNetwork('critic')\n self.memory = Memory()\n\n self.action = actor.choose_action(self.OBS)\n neglogp = actor.get_neglogp(self.OBS, self.ACT)\n self.value = critic.get_value(self.OBS)\n self.advantage = self.Q_VAL - self.value\n\n actor_loss = tf.reduce_mean(neglogp * self.advantage)\n self.actor_train_op = tf.train.AdamOptimizer(self.lr_actor).minimize(actor_loss)\n\n value_loss = tf.reduce_mean(tf.square(self.advantage))\n self.value_train_op = tf.train.AdamOptimizer(self.lr_value).minimize(value_loss)\n\n self.sess = tf.Session()\n self.sess.run(tf.global_variables_initializer())\n\n def step(self, obs):\n if obs.ndim < 2: obs = obs[np.newaxis, :]\n action = self.sess.run(self.action, feed_dict={self.OBS: obs})\n action = np.squeeze(action, 1).clip(action, env.action_space.low[0], env.action_space.high[0])\n\n value = self.sess.run(self.value, feed_dict={self.OBS: obs})\n return action, value\n\n def learn(self, last_value, done):\n obs, act, rwd = self.memory.covert_to_array()\n\n q_value = self.compute_q_value(last_value, done, rwd)\n\n self.sess.run(self.actor_train_op, {self.OBS: obs, self.ACT: act, self.Q_VAL: q_value})\n self.sess.run(self.value_train_op, {self.OBS: obs, self.Q_VAL: q_value})\n\n self.memory.reset()\n\n def compute_q_value(self, last_value, done, rwd):\n q_value = np.zeros_like(rwd)\n value = 0 if done else last_value\n for t in reversed(range(0, len(rwd))):\n value = value * self.gamma + rwd[t]\n q_value[t] = value\n return q_value[:, np.newaxis]\n\n\nenv = gym.make('MountainCarContinuous-v0')\nenv.seed(1)\nenv = env.unwrapped\n\nagent = ActorCritic(act_dim=env.action_space.shape[0], obs_dim=env.observation_space.shape[0],\n lr_actor=0.0001, lr_value=0.0002, gamma=0.99)\n\nnepisode = 1000\nnstep = 200\n\nfor i_episode in range(nepisode):\n obs0 = env.reset()\n ep_rwd = 0\n\n for t in range(nstep):\n act, _ = agent.step(obs0)\n\n obs1, rwd, done, info = env.step(act)\n\n agent.memory.store_transition(obs0, act, rwd)\n ep_rwd += rwd\n\n obs0 = obs1\n\n if t == nstep - 1:\n _, last_value = agent.step(obs1)\n agent.learn(last_value, done)\n\n print('Ep: %i' % i_episode, \"|Ep_r: %i\" % ep_rwd)"
] |
[
[
"tensorflow.clip_by_value",
"tensorflow.distributions.Normal",
"tensorflow.reduce_mean",
"numpy.squeeze",
"tensorflow.placeholder",
"tensorflow.layers.dense",
"tensorflow.global_variables_initializer",
"numpy.zeros_like",
"tensorflow.Session",
"tensorflow.square",
"tensorflow.variable_scope",
"tensorflow.train.AdamOptimizer",
"numpy.array",
"numpy.vstack"
]
] |
alngo/linear_regression
|
[
"695d838d31fd2a41c98a8153e50c53a97159f282"
] |
[
"libml/utils/csv.py"
] |
[
"# **************************************************************************** #\n# #\n# ::: :::::::: #\n# csv.py :+: :+: :+: #\n# +:+ +:+ +:+ #\n# By: alngo <alngo@student.42.fr> +#+ +:+ +#+ #\n# +#+#+#+#+#+ +#+ #\n# Created: 2020/02/24 09:44:54 by alngo #+# #+# #\n# Updated: 2020/03/02 11:25:42 by alngo ### ########.fr #\n# #\n# **************************************************************************** #\n\nimport pandas as pd\nimport sys\n\n\ndef read_csv(path):\n parameters = None\n try:\n parameters = pd.read_csv(path)\n except FileNotFoundError:\n print(f'File at path: \"{path}\" not found')\n sys.exit(1)\n except:\n print(f'An unexpected error occured on read_csv')\n sys.exit(1)\n return parameters\n\n\ndef write_csv(data, output):\n df = pd.DataFrame(data=data, index=[0])\n df.to_csv(output, index=None)\n\n\ndef check_csv(*fields):\n def wrapper(func):\n def new_f(self, *args, **kwargs):\n try:\n columns = self.data.columns.tolist()\n if (len(columns) != len(fields)):\n raise IndexError\n for (a, b) in zip(columns, fields):\n if (a != b):\n raise IndexError\n except IndexError:\n print(f\"Can't process {func.__name__}: invalid csv\")\n sys.exit(1)\n except:\n print(f'An unexpected error occured on read_csv')\n sys.exit(1)\n return func(self, *args, **kwargs)\n new_f.__name__ = func.__name__\n return new_f\n return wrapper\n\n"
] |
[
[
"pandas.read_csv",
"pandas.DataFrame"
]
] |
finbarrtimbers/ai-workbox-screencasts-deep-learning
|
[
"a55e70a50854cb65e29792eadd8c5f7ac370a44d"
] |
[
"tensorflow/checkpointing.py"
] |
[
"import tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n# We load the MNIST dataset using a helper function; in future lessons we'll\n# cover how to load other datasets\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\ndef create_mnist_model():\n # create tf variables and initialize them\n # x is going to be our data, which are 28 x 28 pixel images. We represent them\n # here as a series of N 784 length vectors (784 == 28 * 28)\n # For the shape of x, we set it to be a None x 784 size tensor as we don't know\n # the number of images we're inputting, but we know each image is a 784\n # dimensional vector\n x = tf.placeholder(tf.float32, shape=[None, 784])\n\n # Because we're using a ReLU activation function, you want your variables to be\n # initialized to a positive value, which is why we have a bias of 0.1\n # See Deep Learning, by Goodfellow et. al, for more insight into the theory\n W = tf.get_variable(\"weights\", shape=[784, 10],\n initializer=tf.glorot_uniform_initializer())\n b = tf.get_variable(\"bias\", [10],\n initializer=tf.constant_initializer(0.1))\n\n # the output of our simple model\n y = tf.nn.relu(tf.matmul(x, W) + b)\n\n return x, y\n\n# Our model output (logits)\nx, y = create_mnist_model()\n\n# the placeholder to contain the correct answers\ny_ = tf.placeholder(tf.float32, [None, 10])\n\n# our scoring function\ncross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=y_)\n\n# We'll use this to make predictions with our model\ncorrect_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n# To train the model, we use gradient descent, with a learning step of 0.5\n# What this does is tells Tensorflow to use Gradient Descent, with a learning\n# rate of 0.001, to find the weights that minimize the cross_entropy of our model\nlearning_rate = 0.001\ntrain_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)\n\nsess = tf.InteractiveSession()\ntf.global_variables_initializer().run()\nsaver = tf.train.Saver(max_to_keep=100)\n\n# We run our training for 1000 steps\nMAX_STEPS = 50\nfor step in range(MAX_STEPS):\n print(f\"training step: {step}/{MAX_STEPS}\")\n\n # at each step, we get a batch of 100 random images frmo our training set\n batch_xs, batch_ys = mnist.train.next_batch(100)\n\n # we then run those images through our model\n sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n\n # we want to see how good our model is\n if step % 10 == 0:\n print(\"model accuracy: \")\n print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n y_: mnist.test.labels}))\n saver.save(sess, 'model.ckpt', global_step=step)\n\n# Add ops to save and restore all the variables.\n# If you do not pass any arguments to tf.train.Saver(), the saver handles all\n# variables in the graph. Each variable is saved under the name that was passed\n# when the variable was created.\nsave_path = saver.save(sess, \"model.ckpt\", global_step=step)\n"
] |
[
[
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.matmul",
"tensorflow.InteractiveSession",
"tensorflow.cast",
"tensorflow.placeholder",
"tensorflow.constant_initializer",
"tensorflow.global_variables_initializer",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.glorot_uniform_initializer",
"tensorflow.train.Saver",
"tensorflow.argmax",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets"
]
] |
marcosroriz/uaibus
|
[
"336cca6d278dbe5dab143eafbcaa11a8ef72f68b",
"336cca6d278dbe5dab143eafbcaa11a8ef72f68b"
] |
[
"uaibus/uaipreprocess.py",
"uaibus/uainn.py"
] |
[
"#!/bin/env python\n# import pudb\n# pu.db\n\nimport csv\nimport datetime\nimport logging\nimport click\nimport sys\nimport numpy as np\nfrom collections import defaultdict\nfrom math import asin, atan2, cos, radians, sin, sqrt\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\ndef distance(lat1, lng1, lat2, lng2):\n R = 6371000 # raio da terra em metros\n rlat1 = radians(lat1)\n rlng1 = radians(lng1)\n rlat2 = radians(lat2)\n rlng2 = radians(lng2)\n\n dlat = rlat2 - rlat1\n dlng = rlng2 - rlng1\n\n a = sin(dlat / 2) ** 2 + cos(rlat1) * cos(rlat2) * sin(dlng / 2) ** 2\n c = 2 * atan2(sqrt(a), sqrt(1 - a))\n\n distance = R * c\n return distance\n\n\ndef closest(lat, lng, stops):\n mindist = sys.maxsize\n\n for id, stopdata in stops.items():\n stoplat = stopdata[\"lat\"]\n stoplng = stopdata[\"lng\"]\n\n stopdist = distance(lat, lng, stoplat, stoplng)\n\n if stopdist <= mindist:\n mindist = stopdist\n\n return mindist\n\n\ndef getstops(stopsfile):\n stops = {}\n file = open(stopsfile, \"r\")\n freader = csv.DictReader(file)\n\n for line in freader:\n pid = int(line[\"pid\"])\n id = str(line[\"id\"])\n lat = float(line[\"latitude\"])\n lng = float(line[\"longitude\"])\n nome = str(line[\"nome\"])\n\n stops[id] = {\"pid\": pid, \"id\": id, \"lat\": lat, \"lng\": lng,\n \"nome\": nome, \"in\": 0, \"out\": 0}\n\n return stops\n\n\ndef parselog(logfile, stops, winsize):\n tracker = {}\n file = open(logfile, \"r\")\n filereader = csv.DictReader(file)\n\n for line in filereader:\n if line[\"lat\"] != \"\" and line[\"lng\"] != \"\":\n date = datetime.datetime.strptime(line[\"date\"], '%Y-%m-%d %H:%M:%S')\n lat = float(line[\"lat\"])\n lng = float(line[\"lng\"])\n mac = str(line[\"mac\"])\n rssi = int(line[\"rssi\"])\n speed = float(line[\"speed\"])\n passengerdata = [date, lat, lng, mac, rssi, speed]\n\n if mac not in tracker:\n tracker[mac] = [passengerdata]\n else:\n tracker[mac].append(passengerdata)\n\n return tracker\n\n\ndef derivelog(rawtracker, stops, winsize):\n # Derive complex data from rawtracker into final tracker\n finaltracker = {}\n histtracker = {}\n\n for mac, sentbeacons in rawtracker.items():\n finaltracker[mac] = []\n histtracker[mac] = []\n\n for beacon in sentbeacons:\n date = beacon[0]\n lat = beacon[1]\n lng = beacon[2]\n rssi = beacon[4]\n speed = beacon[5]\n\n # Derived Data\n stopdist = closest(lat, lng, stops) # Min Dist to a bus stop\n wintravtime = 0 # Travelled time within beacons in time window\n wintravdist = 0 # Travelled distance within time window\n winfrequence = 1 # Number of beacons within time window\n totaltravtime = 0 # Total travelled time of this beacon\n totaltravdist = 0 # Total travelled distance of this beacon\n totalfrequence = 1 # Number of beacons sent by this user\n\n # Get the travelled dist in winsize (assume that trav = 0)\n oldestwinlat = lat\n oldestwinlng = lng\n oldestlat = lat\n oldestlng = lng\n\n for prevdata in reversed(histtracker[mac]):\n prevdatadate = prevdata[0]\n timediff = (date - prevdatadate).total_seconds()\n if timediff <= winsize:\n wintravtime = timediff\n totaltravtime = timediff\n winfrequence = winfrequence + 1\n totalfrequence = totalfrequence + 1\n oldestwinlat = prevdata[1]\n oldestwinlng = prevdata[2]\n oldestlat = prevdata[1]\n oldestlng = prevdata[2]\n else:\n totaltravtime = timediff\n totalfrequence = totalfrequence + 1\n oldestlat = prevdata[1]\n oldestlng = prevdata[2]\n\n # Travelled Distances\n wintravdist = distance(lat, lng, oldestwinlat, oldestwinlng)\n totaltravdist = distance(lat, lng, oldestlat, oldestlng)\n\n # Complex output data for this beacon = raw + derived data\n outdata = [date, lat, lng, mac, rssi, speed,\n stopdist, wintravdist, wintravtime, winfrequence,\n totaltravdist, totaltravtime, totalfrequence]\n\n # Save output\n finaltracker[mac].append(outdata)\n histtracker[mac].append(outdata)\n\n return finaltracker\n\n\ndef toarff(sentbeacon, clazz):\n out = \",\".join(str(x) for x in sentbeacon[4:]) + \",\"\n if clazz == 0:\n out = out + \"OUT\"\n else:\n out = out + \"IN\"\n return out + \"\\n\"\n\n\ndef output(finaltracker, outlog, outarff, clazz):\n # Output to outlog and outarff\n # Also store statistics\n stat = defaultdict(list)\n\n with open(outlog, 'w', newline='') as outputcsvfile, \\\n open(outarff, 'w', newline='') as arfffile:\n\n outwriter = csv.writer(outputcsvfile)\n outwriter.writerow([\"date\", \"lat\", \"lng\", \"mac\",\n \"rssi\", \"speed\", \"stopdist\",\n \"wintravdist\", \"wintravtime\", \"winfrequence\",\n \"totaltravdist\", \"totaltravtime\", \"totalfrequence\",\n \"clazz\"])\n\n arfffile.write(\"@RELATION uaibus\\n\\n\")\n arfffile.write(\"@ATTRIBUTE rssi NUMERIC\\n\")\n arfffile.write(\"@ATTRIBUTE speed NUMERIC\\n\")\n arfffile.write(\"@ATTRIBUTE stopdist NUMERIC\\n\")\n arfffile.write(\"@ATTRIBUTE wintravdist NUMERIC\\n\")\n arfffile.write(\"@ATTRIBUTE wintravtime NUMERIC\\n\")\n arfffile.write(\"@ATTRIBUTE winfrequence NUMERIC\\n\")\n arfffile.write(\"@ATTRIBUTE totaltravdist NUMERIC\\n\")\n arfffile.write(\"@ATTRIBUTE totaltravtime NUMERIC\\n\")\n arfffile.write(\"@ATTRIBUTE totalfrequence NUMERIC\\n\")\n arfffile.write(\"@ATTRIBUTE clazz {IN, OUT}\\n\\n\")\n arfffile.write(\"@DATA\\n\")\n\n for mac, sentbeacons in finaltracker.items():\n for beacon in sentbeacons:\n outwriter.writerow(beacon + [clazz])\n arfffile.write(toarff(beacon, clazz))\n\n # For Statistics\n stat['rssi'].append(beacon[4])\n stat['speed'].append(beacon[5])\n stat['stopdist'].append(beacon[6])\n stat['wintravdist'].append(beacon[7])\n stat['wintravtime'].append(beacon[8])\n stat['winfrequence'].append(beacon[9])\n stat['totaltravdist'].append(beacon[10])\n stat['totaltravtime'].append(beacon[11])\n stat['totalfrequence'].append(beacon[12])\n stat['clazz'].append(clazz)\n\n outputcsvfile.flush()\n arfffile.flush()\n\n return stat\n\n\ndef outplot(stat, legend, x, y, z, clazz):\n # Plot 3D\n fig = plt.figure()\n plt.rc('text', usetex=True)\n # plt.rc('font', family='serif')\n plt.rcParams['text.latex.unicode'] = True\n\n ax = Axes3D(fig)\n plabel = \"Fora do Ônibus\"\n if clazz == 1:\n plabel = \"Dentro do Ônibus\"\n\n ax.scatter(stat[x], stat[y], stat[z], alpha=0.2, label=plabel, c=\"C0\")\n # ax.scatter3D(x, y, z, c=z, cmap='tab20c')\n ax.set_xlabel(legend[x])\n ax.set_ylabel(legend[y])\n ax.set_zlabel(legend[z])\n ax.legend(loc=8, borderaxespad=0)\n # leg.draggable(True)\n ax.set_title(r'Dispersão dos pacotes $ProbeRequest$ dos passageiros')\n fig.savefig(\"test.png\")\n fig.tight_layout()\n fig.subplots_adjust(left=-0.11)\n plt.show()\n\n\n@click.command()\n@click.option(\"--inlog\", default=\"uailog.csv\", help=\"Input File\")\n@click.option(\"--outlog\", default=\"uai.out.csv\", help=\"Output File\")\n@click.option(\"--outarff\", default=\"uai.out.arff\", help=\"ARFF Output File\")\n@click.option(\"--instops\", default=\"lane.csv\",\n help=\"Bus stops (stations) file\")\n@click.option(\"--clazz\", default=0,\n help=\"Data class (0 outside bus, 1 inside bus)\")\n@click.option(\"--winsize\", default=120,\n help=\"Maximum time (window size) in seconds between beacons \")\n@click.option(\"--x\", default=\"rssi\", help=\"X Variable (Plot)\")\n@click.option(\"--y\", default=\"totaltravtime\", help=\"Y Variable (Plot)\")\n@click.option(\"--z\", default=\"totaltravdist\", help=\"Z Variable (Plot)\")\ndef main(inlog, instops, clazz, winsize, outlog, outarff, x, y, z):\n # Config logging\n logging.basicConfig()\n logger = logging.getLogger(\"uaibus.uaipreprocess\")\n logger.setLevel(logging.INFO)\n\n # Read and parse stations\n stops = getstops(instops)\n\n # Read and parse basic variables in rawtracker\n rawtracker = parselog(inlog, stops, winsize)\n\n # Read and derive complex variables in the final tracker\n finaltracker = derivelog(rawtracker, stops, winsize)\n\n # Output to outfile and retrieve statistics\n stat = output(finaltracker, outlog, outarff, clazz)\n\n # Plot\n legend = {\n 'rssi' : r'RSSI (dB)',\n 'speed' : r'Velocidade do Ônibus (km/h)',\n 'stopdist' : r'Distância ao ponto de Ônibus mais próximo (m)',\n 'wintravdist' : r'Distância (m) entre beacons na janela ($\\Delta$)',\n 'wintravtime' : r'Tempo entre beacons na janela (\\Delta$) em (s)',\n 'winfrequence' : r'Número de beacons recebidos ($\\Delta$)',\n 'totaltravdist' : r'Distância total percorrida pelo dispositivo (m)',\n 'totaltravtime' : r'Tempo total percorrido pelo dispositivo (s)',\n 'totalfrequence' : r'Número total de beacons recebidos',\n 'clazz' : r'Classificação do beacon'\n }\n outplot(stat, legend, x, y, z, clazz)\n\n\nif __name__ == \"__main__\":\n main()\n",
"#!/bin/env python\n# import pudb\n# pu.db\n\nimport click\nimport numpy as np\nimport pandas as pd\nfrom sklearn.externals import joblib\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.preprocessing import StandardScaler\n\n\n@click.command()\n@click.option(\"--outsidecsv\", default=\"outside.csv\", help=\"Outside signals\")\n@click.option(\"--insidecsv\", default=\"inside.csv\", help=\"Inside signals\")\n@click.option(\"--testcsv\", default=\"test.out.csv\", help=\"Test signals\")\ndef main(outsidecsv, insidecsv, testcsv):\n # dropcolumns = [\"date\", \"lat\", \"lng\", \"mac\"]\n dropcolumns = [\"date\", \"lat\", \"lng\", \"stopdist\", \"mac\",\n \"totaltravdist\", \"totaltravtime\", \"totalfrequence\"]\n\n outdf = pd.read_csv(outsidecsv)\n indf = pd.read_csv(insidecsv)\n testdf = pd.read_csv(testcsv)\n\n outdf.drop(dropcolumns, axis=1, inplace=True)\n indf.drop(dropcolumns, axis=1, inplace=True)\n testdf.drop(dropcolumns, axis=1, inplace=True)\n\n singledf = pd.concat([outdf, indf])\n X = singledf.drop('clazz', axis=1)\n y = singledf['clazz']\n\n scaler = StandardScaler()\n scaler.fit(X)\n Xtrain = scaler.transform(X)\n ytrain = y\n\n params_grid = [\n {\n 'learning_rate': [\"constant\", \"invscaling\", \"adaptive\"],\n 'hidden_layer_sizes': [(10, 10), (10, 5),\n (20, 10), (20, 5),\n (50, 10), (50, 25), (50, 30),\n (100, 50), (100, 25), (100, 10)\n ],\n 'alpha': [0.1, 0.01, 0.001, 0.2, 0.02, 0.002, 0.5, 0.05, 0.005],\n # 'alpha': [0.1],\n 'tol': [1e-10],\n 'activation': [\"logistic\", \"relu\", \"tanh\"],\n # 'activation': [\"relu\"],\n 'max_iter': [5000000]\n },\n # {\n # 'kernel': ['linear'],\n # 'C': [1, 10, 100, 1000, 10000],\n # 'class_weight': ['balanced', {1: 2}, {1: 3}, {1: 4}, {1: 5},\n # {1: 10}, {1: 20}, {1: 50}]\n # },\n # {\n # 'kernel': ['poly'],\n # 'degree': [2, 3, 4],\n # 'C': [1, 10, 100, 1000, 10000, 100000],\n # 'class_weight': ['balanced', {1: 2}, {1: 3}, {1: 4}, {1: 5},\n # {1: 10}, {1: 20}, {1: 50}]\n # }\n ]\n\n nn = GridSearchCV(MLPClassifier(), params_grid, n_jobs=8, verbose=True)\n nn.fit(Xtrain, ytrain)\n print(\"Best params:\")\n print(nn.best_params_)\n\n print(\"\\n-----------\\nTrain Results:\")\n ytrainpred = nn.predict(Xtrain)\n print(confusion_matrix(ytrain, ytrainpred))\n print(classification_report(ytrain, ytrainpred))\n\n y_true = pd.Series(ytrain.tolist())\n y_pred = pd.Series(ytrainpred.tolist())\n\n print(pd.crosstab(y_true, y_pred, rownames=['True'],\n colnames=['Predicted'], margins=True))\n\n print(\"\\n-----------\\nTest Results:\")\n # svclassifier = SVC(kernel='rbf', tol=1e-15, class_weight={1 : 100},\n # verbose=True, C=100000, max_iter=10000000)\n # svclassifier = linear_model.SGDClassifier(loss=\"hinge\", tol=1e-5,\n # class_weight={1:5})\n # svclassifier.fit(Xtrain, ytrain)\n\n Xtest = testdf.drop('clazz', axis=1)\n Xtest = scaler.transform(Xtest)\n ytest = testdf['clazz']\n ypred = nn.predict(Xtest)\n\n print(confusion_matrix(ytest, ypred))\n print(classification_report(ytest, ypred))\n\n # Save Classifier and scaler\n joblib.dump(scaler, \"scaler.pkl\")\n joblib.dump(nn.best_estimator_, 'svmclassifier.pkl')\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.figure"
],
[
"sklearn.neural_network.MLPClassifier",
"sklearn.externals.joblib.dump",
"pandas.concat",
"pandas.read_csv",
"pandas.crosstab",
"sklearn.metrics.confusion_matrix",
"sklearn.preprocessing.StandardScaler",
"sklearn.metrics.classification_report"
]
] |
shawnwang-tech/TraverseNet
|
[
"8e27957f798d5a71e4c8975fa03f41f704607e23"
] |
[
"module/astgcn_block.py"
] |
[
"# -*- coding:utf-8 -*-\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n\n\nclass Spatial_Attention_layer(nn.Module):\n '''\n compute spatial attention scores\n '''\n def __init__(self, DEVICE, in_channels, num_of_vertices, num_of_timesteps):\n super(Spatial_Attention_layer, self).__init__()\n self.W1 = nn.Parameter(torch.FloatTensor(num_of_timesteps).to(DEVICE))\n self.W2 = nn.Parameter(torch.FloatTensor(in_channels, num_of_timesteps).to(DEVICE))\n self.W3 = nn.Parameter(torch.FloatTensor(in_channels).to(DEVICE))\n self.bs = nn.Parameter(torch.FloatTensor(1, num_of_vertices, num_of_vertices).to(DEVICE))\n self.Vs = nn.Parameter(torch.FloatTensor(num_of_vertices, num_of_vertices).to(DEVICE))\n\n\n def forward(self, x):\n '''\n :param x: (batch_size, N, F_in, T)\n :return: (B,N,N)\n '''\n\n lhs = torch.matmul(torch.matmul(x, self.W1), self.W2) # (b,N,F,T)(T)->(b,N,F)(F,T)->(b,N,T)\n\n rhs = torch.matmul(self.W3, x).transpose(-1, -2) # (F)(b,N,F,T)->(b,N,T)->(b,T,N)\n\n product = torch.matmul(lhs, rhs) # (b,N,T)(b,T,N) -> (B, N, N)\n\n S = torch.matmul(self.Vs, torch.sigmoid(product + self.bs)) # (N,N)(B, N, N)->(B,N,N)\n\n S_normalized = F.softmax(S, dim=1)\n\n return S_normalized\n\n\nclass cheb_conv_withSAt(nn.Module):\n '''\n K-order chebyshev graph convolution\n '''\n\n def __init__(self, K, cheb_polynomials, in_channels, out_channels):\n '''\n :param K: int\n :param in_channles: int, num of channels in the input sequence\n :param out_channels: int, num of channels in the output sequence\n '''\n super(cheb_conv_withSAt, self).__init__()\n self.K = K\n self.cheb_polynomials = cheb_polynomials\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.DEVICE = cheb_polynomials[0].device\n self.Theta = nn.ParameterList([nn.Parameter(torch.FloatTensor(in_channels, out_channels).to(self.DEVICE)) for _ in range(K)])\n\n def forward(self, x, spatial_attention):\n '''\n Chebyshev graph convolution operation\n :param x: (batch_size, N, F_in, T)\n :return: (batch_size, N, F_out, T)\n '''\n\n batch_size, num_of_vertices, in_channels, num_of_timesteps = x.shape\n\n outputs = []\n\n for time_step in range(num_of_timesteps):\n\n graph_signal = x[:, :, :, time_step] # (b, N, F_in)\n\n output = torch.zeros(batch_size, num_of_vertices, self.out_channels).to(self.DEVICE) # (b, N, F_out)\n\n for k in range(self.K):\n\n T_k = self.cheb_polynomials[k] # (N,N)\n\n T_k_with_at = T_k.mul(spatial_attention) # (N,N)*(N,N) = (N,N) 多行和为1, 按着列进行归一化\n\n theta_k = self.Theta[k] # (in_channel, out_channel)\n\n rhs = T_k_with_at.permute(0, 2, 1).matmul(graph_signal) # (N, N)(b, N, F_in) = (b, N, F_in) 因为是左乘,所以多行和为1变为多列和为1,即一行之和为1,进行左乘\n\n output = output + rhs.matmul(theta_k) # (b, N, F_in)(F_in, F_out) = (b, N, F_out)\n\n outputs.append(output.unsqueeze(-1)) # (b, N, F_out, 1)\n\n return F.relu(torch.cat(outputs, dim=-1)) # (b, N, F_out, T)\n\n\nclass Temporal_Attention_layer(nn.Module):\n def __init__(self, DEVICE, in_channels, num_of_vertices, num_of_timesteps):\n super(Temporal_Attention_layer, self).__init__()\n self.U1 = nn.Parameter(torch.FloatTensor(num_of_vertices).to(DEVICE))\n self.U2 = nn.Parameter(torch.FloatTensor(in_channels, num_of_vertices).to(DEVICE))\n self.U3 = nn.Parameter(torch.FloatTensor(in_channels).to(DEVICE))\n self.be = nn.Parameter(torch.FloatTensor(1, num_of_timesteps, num_of_timesteps).to(DEVICE))\n self.Ve = nn.Parameter(torch.FloatTensor(num_of_timesteps, num_of_timesteps).to(DEVICE))\n\n def forward(self, x):\n '''\n :param x: (batch_size, N, F_in, T)\n :return: (B, T, T)\n '''\n _, num_of_vertices, num_of_features, num_of_timesteps = x.shape\n\n lhs = torch.matmul(torch.matmul(x.permute(0, 3, 2, 1), self.U1), self.U2)\n # x:(B, N, F_in, T) -> (B, T, F_in, N)\n # (B, T, F_in, N)(N) -> (B,T,F_in)\n # (B,T,F_in)(F_in,N)->(B,T,N)\n\n rhs = torch.matmul(self.U3, x) # (F)(B,N,F,T)->(B, N, T)\n\n product = torch.matmul(lhs, rhs) # (B,T,N)(B,N,T)->(B,T,T)\n\n E = torch.matmul(self.Ve, torch.sigmoid(product + self.be)) # (B, T, T)\n\n E_normalized = F.softmax(E, dim=1)\n\n return E_normalized\n\n\nclass cheb_conv(nn.Module):\n '''\n K-order chebyshev graph convolution\n '''\n\n def __init__(self, K, cheb_polynomials, in_channels, out_channels):\n '''\n :param K: int\n :param in_channles: int, num of channels in the input sequence\n :param out_channels: int, num of channels in the output sequence\n '''\n super(cheb_conv, self).__init__()\n self.K = K\n self.cheb_polynomials = cheb_polynomials\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.DEVICE = cheb_polynomials[0].device\n self.Theta = nn.ParameterList([nn.Parameter(torch.FloatTensor(in_channels, out_channels).to(self.DEVICE)) for _ in range(K)])\n\n def forward(self, x):\n '''\n Chebyshev graph convolution operation\n :param x: (batch_size, N, F_in, T)\n :return: (batch_size, N, F_out, T)\n '''\n\n batch_size, num_of_vertices, in_channels, num_of_timesteps = x.shape\n\n outputs = []\n\n for time_step in range(num_of_timesteps):\n\n graph_signal = x[:, :, :, time_step] # (b, N, F_in)\n\n output = torch.zeros(batch_size, num_of_vertices, self.out_channels).to(self.DEVICE) # (b, N, F_out)\n\n for k in range(self.K):\n\n T_k = self.cheb_polynomials[k] # (N,N)\n\n theta_k = self.Theta[k] # (in_channel, out_channel)\n\n rhs = graph_signal.permute(0, 2, 1).matmul(T_k).permute(0, 2, 1)\n\n output = output + rhs.matmul(theta_k)\n\n outputs.append(output.unsqueeze(-1))\n\n return F.relu(torch.cat(outputs, dim=-1))\n\n\nclass ASTGCN_block(nn.Module):\n\n def __init__(self, DEVICE, in_channels, K, nb_chev_filter, nb_time_filter, time_strides, cheb_polynomials, num_of_vertices, num_of_timesteps):\n super(ASTGCN_block, self).__init__()\n self.TAt = Temporal_Attention_layer(DEVICE, in_channels, num_of_vertices, num_of_timesteps)\n self.SAt = Spatial_Attention_layer(DEVICE, in_channels, num_of_vertices, num_of_timesteps)\n self.cheb_conv_SAt = cheb_conv_withSAt(K, cheb_polynomials, in_channels, nb_chev_filter)\n self.time_conv = nn.Conv2d(nb_chev_filter, nb_time_filter, kernel_size=(1, 3), stride=(1, time_strides), padding=(0, 1))\n self.residual_conv = nn.Conv2d(in_channels, nb_time_filter, kernel_size=(1, 1), stride=(1, time_strides))\n self.ln = nn.LayerNorm(nb_time_filter) #需要将channel放到最后一个维度上\n\n def forward(self, x):\n '''\n :param x: (batch_size, N, F_in, T)\n :return: (batch_size, N, nb_time_filter, T)\n '''\n batch_size, num_of_vertices, num_of_features, num_of_timesteps = x.shape\n\n # TAt\n temporal_At = self.TAt(x) # (b, T, T)\n\n x_TAt = torch.matmul(x.reshape(batch_size, -1, num_of_timesteps), temporal_At).reshape(batch_size, num_of_vertices, num_of_features, num_of_timesteps)\n\n # SAt\n spatial_At = self.SAt(x_TAt)\n\n # cheb gcn\n spatial_gcn = self.cheb_conv_SAt(x, spatial_At) # (b,N,F,T)\n # spatial_gcn = self.cheb_conv(x)\n\n # convolution along the time axis\n time_conv_output = self.time_conv(spatial_gcn.permute(0, 2, 1, 3)) # (b,N,F,T)->(b,F,N,T) 用(1,3)的卷积核去做->(b,F,N,T)\n\n # residual shortcut\n x_residual = self.residual_conv(x.permute(0, 2, 1, 3)) # (b,N,F,T)->(b,F,N,T) 用(1,1)的卷积核去做->(b,F,N,T)\n\n x_residual = self.ln(F.relu(x_residual + time_conv_output).permute(0, 3, 2, 1)).permute(0, 2, 3, 1)\n # (b,F,N,T)->(b,T,N,F) -ln-> (b,T,N,F)->(b,N,F,T)\n\n return x_residual\n"
] |
[
[
"torch.nn.functional.softmax",
"torch.sigmoid",
"torch.cat",
"torch.zeros",
"torch.nn.Conv2d",
"torch.nn.LayerNorm",
"torch.matmul",
"torch.nn.functional.relu",
"torch.FloatTensor"
]
] |
chenjianqu/RAFT
|
[
"a0d44278287e335f27577c9c2f8912bafbbe471c"
] |
[
"core/utils/utils.py"
] |
[
"import typing\n\nimport torch\nimport torch.nn.functional as F\nimport numpy as np\nfrom scipy import interpolate\n\n\nclass InputPadder:\n \"\"\" Pads images such that dimensions are divisible by 8 \"\"\"\n def __init__(self, dims, mode='sintel'):\n self.ht, self.wd = dims[-2:]\n pad_ht = (((self.ht // 8) + 1) * 8 - self.ht) % 8\n pad_wd = (((self.wd // 8) + 1) * 8 - self.wd) % 8\n if mode == 'sintel':\n self._pad = [pad_wd//2, pad_wd - pad_wd//2, pad_ht//2, pad_ht - pad_ht//2]\n else:\n self._pad = [pad_wd//2, pad_wd - pad_wd//2, 0, pad_ht]\n\n def pad(self, *inputs):\n return [F.pad(x, self._pad, mode='replicate') for x in inputs]\n\n def unpad(self,x):\n ht, wd = x.shape[-2:]\n c = [self._pad[2], ht-self._pad[3], self._pad[0], wd-self._pad[1]]\n return x[..., c[0]:c[1], c[2]:c[3]]\n\ndef forward_interpolate(flow):\n flow = flow.detach().cpu().numpy()\n dx, dy = flow[0], flow[1]\n\n ht, wd = dx.shape\n x0, y0 = np.meshgrid(np.arange(wd), np.arange(ht))\n\n x1 = x0 + dx\n y1 = y0 + dy\n \n x1 = x1.reshape(-1)\n y1 = y1.reshape(-1)\n dx = dx.reshape(-1)\n dy = dy.reshape(-1)\n\n valid = (x1 > 0) & (x1 < wd) & (y1 > 0) & (y1 < ht)\n x1 = x1[valid]\n y1 = y1[valid]\n dx = dx[valid]\n dy = dy[valid]\n\n flow_x = interpolate.griddata(\n (x1, y1), dx, (x0, y0), method='nearest', fill_value=0)\n\n flow_y = interpolate.griddata(\n (x1, y1), dy, (x0, y0), method='nearest', fill_value=0)\n\n flow = np.stack([flow_x, flow_y], axis=0)\n return torch.from_numpy(flow).float()\n\n\ndef bilinear_sampler(img:torch.Tensor, coords:torch.Tensor, mode:str='bilinear', mask:bool=False)->typing.List[torch.Tensor]:\n \"\"\" Wrapper for grid_sample, uses pixel coordinates \"\"\"\n H, W = img.shape[-2:]\n xgrid, ygrid = coords.split([1,1], dim=-1)\n xgrid = 2*xgrid/(W-1) - 1\n ygrid = 2*ygrid/(H-1) - 1\n\n grid = torch.cat([xgrid, ygrid], dim=-1)\n img = F.grid_sample(img, grid, align_corners=True)\n\n if mask:\n mask_tensor = (xgrid > -1) & (ygrid > -1) & (xgrid < 1) & (ygrid < 1)\n return [img, mask_tensor.float()]\n\n return [img]\n\n\ndef stack(x:typing.List[torch.Tensor],dim:int)->torch.Tensor:\n return torch.stack(x,dim=dim)\n\ndef coords_grid(batch:int, ht:int, wd:int, device:torch.device)->torch.Tensor:\n coords = torch.meshgrid(torch.arange(ht, device=device), torch.arange(wd, device=device))\n coords = stack([coords[1],coords[0]], dim=0).float()\n\n return coords[None].repeat(batch, 1, 1, 1)\n\n\ndef upflow8(flow:torch.Tensor, mode:str='bilinear')->torch.Tensor:\n new_size = (8 * flow.shape[2], 8 * flow.shape[3])\n return 8 * F.interpolate(flow, size=new_size, mode=mode, align_corners=True)\n"
] |
[
[
"torch.cat",
"numpy.arange",
"torch.arange",
"numpy.stack",
"torch.from_numpy",
"torch.nn.functional.grid_sample",
"torch.nn.functional.interpolate",
"scipy.interpolate.griddata",
"torch.stack",
"torch.nn.functional.pad"
]
] |
mhw32/prototransformer-public
|
[
"710b531e16d8ba6f62488e366c0cfe6ce72f8ad2"
] |
[
"src/agents/nlp.py"
] |
[
"import os\nimport numpy as np\nfrom tqdm import tqdm\nfrom itertools import chain\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom transformers import (\n RobertaConfig,\n RobertaModel,\n get_linear_schedule_with_warmup,\n)\nfrom src.utils import utils\nfrom src.models.codelstm import CodeLSTMEncoder\nfrom src.models.monkeypatch import RobertaModel\nfrom src.models.context import ContextEncoder, AttentionEncoder\nfrom src.agents.base import BaseAgent\nfrom src.objectives.prototype import batch_euclidean_dist\nfrom src.datasets.nlp import MetaNewsGroup, SupNewsGroup\nfrom src.datasets.amazon import FewShotAmazonSentiment\nfrom src.datasets.text import (\n FewShot20News,\n FewShotAmazon,\n FewShotHuffPost,\n FewShotRCV1,\n FewShotReuters,\n FewShotFewRel,\n)\n\n\nclass BaseNLPMetaAgent(BaseAgent):\n\n def __init__(self, config):\n super().__init__(config)\n\n self.train_loss = []\n self.train_acc = []\n self.test_acc = []\n self.test_acc_stdevs = []\n self.temp = []\n\n def _load_datasets(self):\n if self.config.dataset.name == 'newsgroup':\n self.train_dataset = MetaNewsGroup(\n data_root=self.config.data_root,\n n_ways=self.config.dataset.train.n_ways,\n n_shots=self.config.dataset.train.n_shots,\n n_queries=self.config.dataset.train.n_queries,\n smlmt_tasks_factor=self.config.dataset.train.smlmt_tasks_factor,\n train=True,\n )\n self.test_dataset = MetaNewsGroup(\n data_root=self.config.data_root,\n n_ways=self.config.dataset.train.n_ways,\n n_shots=self.config.dataset.train.n_shots,\n n_queries=self.config.dataset.test.n_queries,\n smlmt_tasks_factor=self.config.dataset.train.smlmt_tasks_factor,\n train=False,\n )\n elif self.config.dataset.name == 'amazon':\n self.train_dataset = FewShotAmazonSentiment(\n data_root=self.config.dataset.data_root,\n n_shots=self.config.dataset.train.n_shots,\n n_queries=self.config.dataset.train.n_queries,\n smlmt_tasks_factor=self.config.dataset.train.smlmt_tasks_factor,\n train=True,\n )\n # NOTE: val/dev dataset.\n self.test_dataset = FewShotAmazonSentiment(\n data_root=self.config.dataset.data_root,\n n_shots=self.config.dataset.test.n_shots,\n n_queries=self.config.dataset.test.n_queries,\n smlmt_tasks_factor=self.config.dataset.train.smlmt_tasks_factor,\n train=False,\n )\n elif 'fs' in self.config.dataset.name:\n class_dict = {\n 'fs_20news': FewShot20News,\n 'fs_amazon': FewShotAmazon,\n 'fs_huffpost': FewShotHuffPost,\n 'fs_rcv1': FewShotRCV1,\n 'fs_reuters': FewShotReuters,\n 'fs_fewrel': FewShotFewRel,\n }\n DatasetClass = class_dict[self.config.dataset.name]\n self.train_dataset = DatasetClass(\n data_root=self.config.dataset.data_root,\n n_ways=self.config.dataset.train.n_ways,\n n_shots=self.config.dataset.train.n_shots,\n n_queries=self.config.dataset.train.n_queries,\n split='train',\n )\n # validation (test is not used here)\n self.test_dataset = DatasetClass(\n data_root=self.config.dataset.data_root,\n n_ways=self.config.dataset.test.n_ways,\n n_shots=self.config.dataset.test.n_shots,\n n_queries=self.config.dataset.test.n_queries,\n split='val',\n )\n else:\n raise Exception(f'Dataset {self.config.dataset.name} not supported.')\n\n def _load_loaders(self):\n self.train_loader, self.train_len = self._create_dataloader(\n self.train_dataset,\n self.config.optim.batch_size, \n shuffle=True,\n )\n self.test_loader, self.test_len = self._create_test_dataloader(\n self.test_dataset,\n self.config.optim.batch_size,\n )\n\n def _create_model(self):\n if self.config.model.name == 'roberta':\n model = RobertaModel.from_pretrained(self.config.model.config, is_tam=self.config.model.task_tam)\n utils.reset_model_for_training(model)\n\n if self.config.model.finetune:\n for param in model.parameters():\n param.requires_grad = False\n for param in model.pooler.parameters():\n param.requires_grad = True\n # only allow some parameters to be finetuned\n for param in model.encoder.layer[-self.config.model.finetune_layers:].parameters():\n param.requires_grad = True\n\n self.model = model.to(self.device)\n\n elif self.config.model.name == 'roberta_scratch':\n config = RobertaConfig.from_pretrained(self.config.model.config)\n model = RobertaModel(config, is_tam=self.config.model.task_tam)\n utils.reset_model_for_training(model)\n\n if self.config.model.finetune:\n for param in model.parameters():\n param.requires_grad = False\n\n for param in model.encoder.layer[-self.config.model.finetune_layers:].parameters():\n param.requires_grad = True\n\n elif self.config.model.name == 'lstm':\n model = CodeLSTMEncoder(\n self.train_dataset.vocab_size,\n d_model=768,\n n_encoder_layers=4,\n dropout=0.1,\n )\n\n else:\n raise Exception(f'Model {self.config.model.name} not supported.')\n\n self.model = model.to(self.device)\n\n tau = nn.Parameter(torch.ones(1)).to(self.device)\n tau = tau.detach().requires_grad_(True)\n self.tau = tau\n \n def _all_parameters(self):\n return chain(self.model.parameters(), [self.tau])\n\n def _create_optimizer(self):\n optimizer = torch.optim.AdamW(\n self._all_parameters(),\n lr=self.config.optim.learning_rate,\n betas=(0.9, 0.999),\n eps=1e-6,\n weight_decay=0.01,\n )\n num_training_steps = len(self.train_dataset) * self.config.optim.num_epochs\n scheduler = get_linear_schedule_with_warmup(\n optimizer,\n num_warmup_steps=self.config.optim.warmup_steps,\n num_training_steps=num_training_steps,\n )\n self.optim = optimizer\n self.scheduler = scheduler\n self.config.optim.use_scheduler = True\n\n def train_one_epoch(self):\n raise NotImplementedError\n\n def eval_test(self):\n raise NotImplementedError\n\n def train(self):\n for epoch in range(self.current_epoch, self.config.optim.num_epochs):\n self.current_epoch = epoch\n self.train_one_epoch()\n\n if (self.config.validate and epoch % self.config.validate_freq == 0):\n self.eval_test()\n\n self.save_checkpoint()\n\n if self.iter_with_no_improv > self.config.optim.patience:\n self.logger.info(\"Exceeded patience. Stop training...\")\n break\n\n def save_metrics(self):\n out_dict = {\n 'model_state_dict': self.model.state_dict(),\n 'optim_state_dict': self.optim.state_dict(),\n 'tau': self.tau,\n 'epoch': self.current_epoch,\n 'iteration': self.current_iteration,\n 'loss': self.current_loss,\n 'val_iteration': self.current_val_iteration,\n 'val_metric': self.current_val_metric,\n 'config': self.config,\n 'train_acc': np.array(self.train_acc),\n 'train_loss': np.array(self.train_loss),\n 'test_acc': np.array(self.test_acc),\n 'test_acc_stdevs': np.array(self.test_acc_stdevs),\n 'temp': np.array(self.temp),\n }\n return out_dict\n\n def load_checkpoint(\n self,\n filename,\n checkpoint_dir=None,\n load_model=True,\n load_optim=False,\n load_epoch=False,\n ):\n if checkpoint_dir is None:\n checkpoint_dir = self.config.checkpoint_dir\n filename = os.path.join(checkpoint_dir, filename)\n\n try:\n self.logger.info(\"Loading checkpoint '{}'\".format(filename))\n checkpoint = torch.load(filename, map_location='cpu')\n\n if load_epoch:\n self.current_epoch = checkpoint['epoch']\n self.current_iteration = checkpoint['iteration']\n self.current_val_iteration = checkpoint['val_iteration']\n self.train_loss = list(checkpoint['train_loss'])\n self.train_acc = list(checkpoint['train_acc'])\n self.test_acc = list(checkpoint['test_acc'])\n self.test_acc_stdevs = list(checkpoint['test_acc_stdevs'])\n self.temp = list(checkpoint['temp'])\n self.current_val_metric = checkpoint['val_metric']\n\n if load_model:\n model_state_dict = checkpoint['model_state_dict']\n self.model.load_state_dict(model_state_dict)\n self.tau.data = checkpoint['tau'].to(self.tau.device)\n\n if load_optim:\n optim_state_dict = checkpoint['optim_state_dict']\n self.optim.load_state_dict(optim_state_dict)\n\n self.logger.info(\"Checkpoint loaded successfully from '{}' at (epoch {}) at (iteration {})\\n\"\n .format(filename, checkpoint['epoch'], checkpoint['iteration']))\n\n return checkpoint\n\n except OSError as e:\n self.logger.info(\"Checkpoint doesnt exists: [{}]\".format(filename))\n raise e\n\n\nclass NLPPrototypeNetAgent(BaseNLPMetaAgent):\n\n def compute_loss(self, support_features, support_targets, query_features, query_targets):\n batch_size, nway, nquery, dim = query_features.size()\n prototypes = torch.mean(support_features, dim=2)\n query_features_flat = query_features.view(batch_size, nway * nquery, dim)\n\n dists = self.tau * batch_euclidean_dist(query_features_flat, prototypes)\n logprobas = F.log_softmax(-dists, dim=2).view(batch_size, nway, nquery, -1)\n\n loss = -logprobas.gather(3, query_targets.unsqueeze(3)).squeeze()\n loss = loss.view(-1).mean()\n\n acc = utils.get_accuracy(logprobas.view(batch_size, nway*nquery, -1),\n query_targets.view(batch_size, nway*nquery)) \n return loss, acc, logprobas\n\n def compute_masked_means(self, outputs, masks):\n dim = outputs.size(2)\n masks_dim = masks.unsqueeze(2).repeat(1, 1, dim)\n masked_outputs = outputs * masks_dim \n partition = torch.sum(masks, dim=1, keepdim=True)\n masked_outputs = torch.sum(masked_outputs, dim=1) / partition\n return masked_outputs\n\n def forward(self, batch, n_shots, n_queries):\n support_toks = batch['support_toks'].to(self.device)\n support_lens = batch['support_lens'].to(self.device)\n support_masks = batch['support_masks'].to(self.device)\n support_labs = batch['support_labs'].to(self.device)\n query_toks = batch['query_toks'].to(self.device)\n query_lens = batch['query_lens'].to(self.device)\n query_masks = batch['query_masks'].to(self.device)\n query_labs = batch['query_labs'].to(self.device)\n\n batch_size = support_toks.size(0)\n n_ways = support_toks.size(1)\n seq_len = support_toks.size(-1)\n\n # support_toks: batch_size*n_ways*n_shots x seq_len\n support_toks = support_toks.view(-1, seq_len)\n support_lens = support_lens.view(-1)\n support_masks = support_masks.view(-1, seq_len).long()\n\n # query_toks: batch_size*n_ways*n_queries x seq_len\n query_toks = query_toks.view(-1, seq_len)\n query_lens = query_lens.view(-1)\n query_masks = query_masks.view(-1, seq_len).long()\n\n if self.config.model.task_tam:\n side_info = batch['side_info'].to(self.device) # 1 x 768\n # support_sides : batch_size*n_ways*n_shots x bert_dim\n # query_sides : batch_size*n_ways*n_queries x bert_dim\n support_sides = side_info.repeat(batch_size * n_ways * n_shots, 1)\n query_sides = side_info.repeat(batch_size * n_ways * n_queries, 1)\n \n # support_sides: batch_size*n_ways*n_shots x 1 x bert_dim\n # query_sides : batch_size*n_ways*n_queries x 1 x bert_dim\n support_sides = support_sides.unsqueeze(1)\n query_sides = query_sides.unsqueeze(1)\n else:\n support_sides, query_sides = None, None\n\n if self.config.model.name == 'lstm':\n support_features = self.model(support_toks, support_lens, tam_embeds=support_sides)\n query_features = self.model(query_toks, query_lens, tam_embeds=query_sides)\n else:\n support_features = self.model(input_ids=support_toks, attention_mask=support_masks, tam_embeds=support_sides)[0]\n query_features = self.model(input_ids=query_toks, attention_mask=query_masks, tam_embeds=query_sides)[0]\n support_features = self.compute_masked_means(support_features, support_masks)\n query_features = self.compute_masked_means(query_features, query_masks)\n\n loss, top1, logprobas = self.compute_loss(\n support_features.view(batch_size, n_ways, n_shots, -1),\n support_labs.view(batch_size, n_ways, n_shots),\n query_features.view(batch_size, n_ways, n_queries, -1),\n query_labs.view(batch_size, n_ways, n_queries),\n )\n return loss, top1, logprobas\n\n def train_one_epoch(self):\n tqdm_batch = tqdm(total=len(self.train_loader),\n desc=\"[Epoch {}]\".format(self.current_epoch))\n self.model.train()\n loss_meter = utils.AverageMeter() \n all_task_types = range(2)\n acc_meters = [utils.AverageMeter() for _ in all_task_types]\n\n for batch in self.train_loader:\n n_shots = self.config.dataset.train.n_shots\n n_queries = self.config.dataset.train.n_queries\n loss, acc, _ = self.forward(batch, n_shots, n_queries)\n task_type = batch['task_type'].cpu().numpy()\n\n self.optim.zero_grad()\n loss.backward()\n self.optim.step()\n\n if self.config.optim.use_scheduler:\n self.scheduler.step()\n\n with torch.no_grad():\n loss_meter.update(loss.item())\n postfix = {\"Loss\": loss_meter.avg}\n for t_, t in enumerate(all_task_types):\n if sum(task_type == t) > 0:\n acc_meters[t_].update(acc[task_type == t].mean())\n postfix[f\"Acc{t}\"] = acc_meters[t_].avg\n self.current_iteration += 1\n tqdm_batch.set_postfix(postfix)\n tqdm_batch.update()\n tqdm_batch.close()\n\n self.current_loss = loss_meter.avg\n self.train_loss.append(loss_meter.avg)\n accuracies = [acc_meters[t].avg for t in all_task_types]\n print(f'Meta-Train Tasks: {accuracies}')\n self.train_acc.append(accuracies)\n self.temp.append(self.tau.item())\n print(f'Temperature: {self.tau.item()}')\n\n def eval_split(self, name, loader):\n tqdm_batch = tqdm(total=len(loader), desc=f\"[{name}]\")\n self.model.eval()\n loss_meter = utils.AverageMeter()\n all_task_types = range(2)\n acc_meters = [utils.AverageMeter() for _ in all_task_types]\n acc_stores = [[] for _ in all_task_types]\n\n with torch.no_grad():\n for batch in loader:\n n_shots = self.config.dataset.train.n_shots\n n_queries = self.config.dataset.test.n_queries\n loss, acc, _ = self.forward(batch, n_shots, n_queries)\n task_type = batch['task_type'].cpu().numpy()\n \n loss_meter.update(loss.item())\n postfix = {\"Loss\": loss_meter.avg}\n for t_, t in enumerate(all_task_types):\n if sum(task_type == t) > 0:\n acc_meters[t_].update(acc[task_type == t].mean())\n postfix[f\"Acc{t}\"] = acc_meters[t_].avg\n acc_stores[t_].append(acc[task_type == t].mean())\n tqdm_batch.update()\n tqdm_batch.close()\n\n accuracies = [acc_meters[t].avg for t in all_task_types]\n accuracy_stdevs = [np.std(acc_stores[t]) for t in all_task_types]\n return loss_meter.avg, accuracies, accuracy_stdevs\n\n def eval_test(self):\n _, acc_means, acc_stdevs = self.eval_split('Test', self.test_loader)\n print(f'Meta-Val Tasks: {acc_means}')\n\n self.current_val_iteration += 1\n self.current_val_metric = sum(acc_means)\n self.test_acc.append(acc_means)\n self.test_acc_stdevs.append(acc_stdevs)\n\n if self.current_val_metric >= self.best_val_metric:\n self.best_val_metric = self.current_val_metric\n self.iter_with_no_improv = 0\n else:\n self.iter_with_no_improv += 1\n\n\nclass NLPMatchingNetAgent(NLPPrototypeNetAgent):\n\n def _create_model(self):\n super()._create_model()\n self.fce_f = ContextEncoder(768, num_layers=self.config.model.fce.n_encoder_layers)\n self.fce_g = AttentionEncoder(768, unrolling_steps=self.config.model.fce.unrolling_steps)\n self.fce_f = self.fce_f.to(self.device)\n self.fce_g = self.fce_g.to(self.device)\n\n def _all_parameters(self):\n return chain(self.model.parameters(), self.fce_f.parameters(), self.fce_g.parameters(), [self.tau])\n\n def compute_loss(self, support_features, support_targets, query_features, query_targets):\n batch_size, n_ways, n_shots, d_model = support_features.size()\n n_queries = query_features.size(2)\n\n support_features = support_features.view(batch_size, n_ways * n_shots, d_model)\n query_features = query_features.view(batch_size, n_ways * n_queries, d_model)\n support_features = self.fce_f(support_features)\n query_features = self.fce_g(support_features, query_features)\n\n dists = self.tau * batch_euclidean_dist(query_features, support_features)\n attentions = F.softmax(-dists, dim=2)\n\n support_targets = support_targets.view(batch_size, n_ways * n_shots)\n support_targets_1hot = torch.zeros(batch_size, n_ways * n_shots, n_ways)\n support_targets_1hot = support_targets_1hot.to(support_targets.device)\n support_targets_1hot.scatter_(2, support_targets.unsqueeze(2), 1)\n\n probas = torch.bmm(attentions, support_targets_1hot)\n probas = probas.view(batch_size, n_ways, n_queries, n_ways)\n\n probas = probas.clamp(1e-8, 1 - 1e-8)\n logprobas = torch.log(probas)\n \n loss = -logprobas.gather(3, query_targets.unsqueeze(3)).squeeze()\n loss = loss.view(-1).mean()\n\n acc = utils.get_accuracy(logprobas.view(batch_size, n_ways * n_queries, -1),\n query_targets.view(batch_size, n_ways * n_queries)) \n\n return loss, acc, logprobas\n\n def save_metrics(self):\n out_dict = {\n 'model_state_dict': self.model.state_dict(),\n 'optim_state_dict': self.optim.state_dict(),\n 'fce_f_state_dict': self.fce_f.state_dict(),\n 'fce_g_state_dict': self.fce_g.state_dict(),\n 'tau': self.tau,\n 'epoch': self.current_epoch,\n 'iteration': self.current_iteration,\n 'loss': self.current_loss,\n 'val_iteration': self.current_val_iteration,\n 'val_metric': self.current_val_metric,\n 'config': self.config,\n 'train_acc': np.array(self.train_acc),\n 'train_loss': np.array(self.train_loss),\n 'test_acc': np.array(self.test_acc),\n 'test_acc_stdevs': np.array(self.test_acc_stdevs),\n 'temp': np.array(self.temp),\n }\n return out_dict\n\n def load_checkpoint(self, filename, checkpoint_dir=None, load_model=True, load_optim=False, load_epoch=False):\n if checkpoint_dir is None:\n checkpoint_dir = self.config.checkpoint_dir\n filename = os.path.join(checkpoint_dir, filename)\n\n try:\n self.logger.info(\"Loading checkpoint '{}'\".format(filename))\n checkpoint = torch.load(filename, map_location='cpu')\n\n if load_epoch:\n self.current_epoch = checkpoint['epoch']\n self.current_iteration = checkpoint['iteration']\n self.current_val_iteration = checkpoint['val_iteration']\n self.train_loss = list(checkpoint['train_loss'])\n self.train_acc = list(checkpoint['train_acc'])\n self.test_acc = list(checkpoint['test_acc'])\n self.test_acc_stdevs = list(checkpoint['test_acc_stdevs'])\n self.temp = list(checkpoint['temp'])\n self.current_val_metric = checkpoint['val_metric']\n\n if load_model:\n model_state_dict = checkpoint['model_state_dict']\n fce_f_state_dict = checkpoint['fce_f_state_dict']\n fce_g_state_dict = checkpoint['fce_g_state_dict']\n self.model.load_state_dict(model_state_dict)\n self.fce_f.load_state_dict(fce_f_state_dict)\n self.fce_g.load_state_dict(fce_g_state_dict)\n self.tau.data = checkpoint['tau'].to(self.tau.device)\n\n if load_optim:\n optim_state_dict = checkpoint['optim_state_dict']\n self.optim.load_state_dict(optim_state_dict)\n\n self.logger.info(\"Checkpoint loaded successfully from '{}' at (epoch {}) at (iteration {})\\n\"\n .format(filename, checkpoint['epoch'], checkpoint['iteration']))\n\n return checkpoint\n\n except OSError as e:\n self.logger.info(\"Checkpoint doesnt exists: [{}]\".format(filename))\n raise e\n\n\nclass BaseNLPSupAgent(BaseAgent):\n\n def __init__(self, config):\n super().__init__(config)\n \n self.train_loss = []\n self.train_acc = []\n self.test_acc = []\n\n def _load_datasets(self):\n if self.config.dataset.name == 'newsgroup':\n self.train_dataset = SupNewsGroup(\n task_index=self.config.dataset.task_index,\n data_root=self.config.data_root,\n n_ways=self.config.dataset.train.n_ways,\n n_shots=self.config.dataset.train.n_shots,\n n_queries=self.config.dataset.train.n_queries,\n train=True,\n )\n self.test_dataset = SupNewsGroup(\n task_index=self.config.dataset.task_index,\n data_root=self.config.data_root,\n n_ways=self.config.dataset.train.n_ways,\n n_shots=self.config.dataset.train.n_shots,\n n_queries=self.config.dataset.test.n_queries,\n train=False,\n )\n else:\n raise Exception(f'Dataset {self.config.dataset.name} not supported.')\n\n def _load_loaders(self):\n self.train_loader, self.train_len = self._create_dataloader(\n self.train_dataset,\n self.config.optim.batch_size, \n shuffle=True,\n )\n self.test_loader, self.test_len = self._create_test_dataloader(\n self.test_dataset,\n self.config.optim.batch_size,\n )\n\n def _create_model(self):\n model = RobertaModel.from_pretrained(self.config.model.config, is_tam=self.config.model.task_tam)\n utils.reset_model_for_training(model)\n\n if self.config.model.finetune:\n for param in model.parameters():\n param.requires_grad = False\n for param in model.pooler.parameters():\n param.requires_grad = True\n # only allow some parameters to be finetuned\n for param in model.encoder.layer[-self.config.model.finetune_layers:].parameters():\n param.requires_grad = True\n\n self.model = model.to(self.device)\n\n classifier = nn.Linear(self.config.model.d_model, 1)\n self.classifier = classifier.to(self.device)\n\n def _create_optimizer(self):\n optimizer = torch.optim.AdamW(\n chain(self.model.parameters(), self.classifier.parameters()),\n lr=self.config.optim.learning_rate,\n betas=(0.9, 0.999),\n eps=1e-6,\n weight_decay=0.01,\n )\n self.optim = optimizer\n\n def compute_masked_means(self, outputs, masks):\n # we don't want to include padding tokens \n # outputs : B x T x D\n # masks : B x T\n dim = outputs.size(2)\n masks_dim = masks.unsqueeze(2).repeat(1, 1, dim)\n # masked_outputs : B x T x D\n masked_outputs = outputs * masks_dim # makes the masked entries 0\n # masked_outputs: B x D / B x 1 => B x D\n partition = torch.sum(masks, dim=1, keepdim=True)\n masked_outputs = torch.sum(masked_outputs, dim=1) / partition\n return masked_outputs\n\n def forward(self, batch):\n batch_size, n_ways, n_shots, max_seq_len = batch['tokens'].size()\n\n tokens = batch['tokens'].to(self.device)\n masks = batch['masks'].to(self.device)\n labels = batch['labels'].to(self.device)\n\n tokens = tokens.view(batch_size * n_ways * n_shots, max_seq_len)\n masks = masks.view(batch_size * n_ways * n_shots, max_seq_len)\n labels = labels.view(batch_size * n_ways * n_shots)\n\n if self.config.model.task_tam:\n side_info = batch['side_info'].to(self.device)\n side_info = side_info.repeat(batch_size * n_ways * n_shots, 1)\n features = self.model(input_ids=tokens, attention_mask=masks, \n tam_embeds=side_info.unsqueeze(1))[0]\n else:\n features = self.model(input_ids=tokens, attention_mask=masks)[0]\n\n features = self.compute_masked_means(features, masks)\n\n logits = self.classifier(F.relu(features))\n probas = torch.sigmoid(logits)\n labels = labels.unsqueeze(1).float()\n loss = F.binary_cross_entropy(probas, labels)\n \n with torch.no_grad():\n preds = torch.round(probas)\n correct = preds.eq(labels).sum().item()\n acc = 100. / (batch_size * n_ways * n_shots) * correct\n\n return loss, acc, probas\n\n def train_one_epoch(self):\n tqdm_batch = tqdm(total=len(self.train_loader),\n desc=\"[Epoch {}]\".format(self.current_epoch))\n self.model.train()\n loss_meter = utils.AverageMeter() \n acc_meter = utils.AverageMeter()\n\n for batch in self.train_loader:\n loss, acc, _ = self.forward(batch)\n\n self.optim.zero_grad()\n loss.backward()\n self.optim.step()\n\n with torch.no_grad():\n loss_meter.update(loss.item())\n acc_meter.update(acc)\n postfix = {\"Loss\": loss_meter.avg, \"Acc\": acc_meter.avg}\n self.current_iteration += 1\n tqdm_batch.set_postfix(postfix)\n tqdm_batch.update()\n tqdm_batch.close()\n\n self.current_loss = loss_meter.avg\n self.train_loss.append(loss_meter.avg)\n print(f'Meta-Train Tasks: {acc_meter.avg}')\n self.train_acc.append(acc_meter.avg)\n\n def eval_split(self, name, loader):\n tqdm_batch = tqdm(total=len(loader), desc=f\"[{name}]\")\n self.model.eval()\n loss_meter = utils.AverageMeter()\n acc_meter = utils.AverageMeter()\n\n with torch.no_grad():\n for batch in loader:\n loss, acc, _ = self.forward(batch)\n loss_meter.update(loss.item())\n acc_meter.update(acc)\n postfix = {\"Loss\": loss_meter.avg, \"Acc\": acc_meter.avg}\n tqdm_batch.set_postfix(postfix)\n tqdm_batch.update()\n tqdm_batch.close()\n\n return loss_meter.avg, acc_meter.avg\n\n def eval_test(self):\n _, acc = self.eval_split('Test', self.test_loader)\n print(f'Meta-Val Tasks: {acc}')\n\n self.current_val_iteration += 1\n self.current_val_metric = acc\n self.test_acc.append(acc)\n\n if self.current_val_metric >= self.best_val_metric:\n self.best_val_metric = self.current_val_metric\n self.iter_with_no_improv = 0\n else:\n self.iter_with_no_improv += 1\n\n def train(self):\n for epoch in range(self.current_epoch, self.config.optim.num_epochs):\n self.current_epoch = epoch\n self.train_one_epoch()\n\n if (self.config.validate and epoch % self.config.validate_freq == 0):\n self.eval_test()\n\n self.save_checkpoint()\n\n if self.iter_with_no_improv > self.config.optim.patience:\n self.logger.info(\"Exceeded patience. Stop training...\")\n break\n\n def save_metrics(self):\n out_dict = {\n 'model_state_dict': self.model.state_dict(),\n 'optim_state_dict': self.optim.state_dict(),\n 'epoch': self.current_epoch,\n 'iteration': self.current_iteration,\n 'loss': self.current_loss,\n 'val_iteration': self.current_val_iteration,\n 'val_metric': self.current_val_metric,\n 'config': self.config,\n 'train_acc': np.array(self.train_acc),\n 'train_loss': np.array(self.train_loss),\n 'test_acc': np.array(self.test_acc),\n }\n return out_dict\n\n def load_checkpoint(\n self,\n filename,\n checkpoint_dir=None,\n load_model=True,\n load_optim=False,\n load_epoch=False,\n ):\n if checkpoint_dir is None:\n checkpoint_dir = self.config.checkpoint_dir\n filename = os.path.join(checkpoint_dir, filename)\n\n try:\n self.logger.info(\"Loading checkpoint '{}'\".format(filename))\n checkpoint = torch.load(filename, map_location='cpu')\n\n if load_epoch:\n self.current_epoch = checkpoint['epoch']\n self.current_iteration = checkpoint['iteration']\n self.current_val_iteration = checkpoint['val_iteration']\n self.train_loss = list(checkpoint['train_loss'])\n self.train_acc = list(checkpoint['train_acc'])\n self.test_acc = list(checkpoint['test_acc'])\n self.current_val_metric = checkpoint['val_metric']\n\n if load_model:\n model_state_dict = checkpoint['model_state_dict']\n self.model.load_state_dict(model_state_dict)\n\n if load_optim:\n optim_state_dict = checkpoint['optim_state_dict']\n self.optim.load_state_dict(optim_state_dict)\n\n self.logger.info(\"Checkpoint loaded successfully from '{}' at (epoch {}) at (iteration {})\\n\"\n .format(filename, checkpoint['epoch'], checkpoint['iteration']))\n\n return checkpoint\n\n except OSError as e:\n self.logger.info(\"Checkpoint doesnt exists: [{}]\".format(filename))\n raise e\n"
] |
[
[
"torch.mean",
"torch.nn.functional.softmax",
"torch.sigmoid",
"torch.ones",
"torch.nn.functional.log_softmax",
"torch.zeros",
"torch.load",
"torch.round",
"torch.sum",
"torch.nn.Linear",
"numpy.std",
"torch.nn.functional.relu",
"torch.log",
"torch.bmm",
"torch.nn.functional.binary_cross_entropy",
"torch.no_grad",
"numpy.array"
]
] |
Pikaurd/CLUT-from-images
|
[
"3a3d0776527927018bf0f7abe6985e56c5bc022e"
] |
[
"main.py"
] |
[
"#!/usr/bin/env python3\n\nfrom typing import Tuple\nfrom functools import partial, lru_cache\nfrom math import floor\n\nimport imageio\nimport scipy.misc\nimport numpy as np\n\n\nwidth = 512\nheight = 512\nchannels = 3\n\n\ndef generate_identify_color_matrix():\n img = np.zeros((width, height, channels), dtype=np.uint8)\n for by in range(8):\n for bx in range(8):\n for g in range(64):\n for r in range(64):\n x = r + bx * 64\n y = g + by * 64\n img[y][x][0] = int(r * 255.0 / 63.0 + 0.5)\n img[y][x][1] = int(g * 255.0 / 63.0 + 0.5)\n img[y][x][2] = int((bx + by * 8.0) * 255.0 / 63.0 + 0.5)\n return img\n\n\ndef generate_identify_color_matrix_v2():\n img = np.zeros((width, height, channels), dtype=np.uint8)\n\n\n\ndef generate_color_matrix_from_image(img, dest=None):\n lut = np.zeros((width, height, channels), dtype=np.uint8)\n img_list = img.tolist() if dest is None else dest.tolist()\n for iy in range(img.shape[1]):\n for ix in range(img.shape[0]):\n r, g, b = img_list[ix][iy]\n x, y, bx, by = color_coordinate(r, g, b)\n lut_y = y + by * 64\n lut_x = x + bx * 64\n lut[lut_y][lut_x][0] = r\n lut[lut_y][lut_x][1] = g\n lut[lut_y][lut_x][2] = b\n # print('{r} {g} {b} {x} {y} {bx} {by} {lut_x} {lut_y}'.format(r=r, g=g, b=b, x=x, y=y, bx=bx, by=by, lut_x=lut_x, lut_y=lut_y))\n return lut\n\n\ndef fill_color_matrix(lut, img, dest=None):\n lut = lut.copy()\n img_list = img.tolist() if dest is None else dest.tolist()\n for iy in range(img.shape[1]):\n for ix in range(img.shape[0]):\n r, g, b = img_list[ix][iy]\n x, y, bx, by = color_coordinate(r, g, b)\n lut_y = y + by * 64\n lut_x = x + bx * 64\n lut[lut_y][lut_x][0] = r\n lut[lut_y][lut_x][1] = g\n lut[lut_y][lut_x][2] = b\n # print('{r} {g} {b} {x} {y} {bx} {by} {lut_x} {lut_y}'.format(r=r, g=g, b=b, x=x, y=y, bx=bx, by=by, lut_x=lut_x, lut_y=lut_y))\n return lut\n\n\n\n\n@lru_cache(maxsize=512)\ndef color_coordinate(r, g, b) -> Tuple[int, int, int, int]:\n x, y, bx, by = 0, 0, 0, 0\n x = floor(r / 4.0)\n y = floor(g / 4.0)\n bx, by = blue_coordinate(floor(b / 4.0))\n return x, y, bx, by\n\n\n@lru_cache(maxsize=64)\ndef blue_coordinate(b: int) -> Tuple[int, int]:\n assert b >= 0 and b <= 63, 'GOT {}'.format(b)\n x, y = 0, 0\n y = floor(floor(b) / 8.0)\n x = int(floor(b) - y * 8.0)\n return x, y\n\n\ndef show(img):\n import matplotlib.pyplot as plt\n plt.imshow(img)\n plt.show()\n\n\ndef write(img, uri):\n imageio.imwrite(uri, img, 'PNG')\n\n\nif __name__ == '__main__':\n import os\n import inspect\n\n current_file_path = os.path.abspath(inspect.getfile(inspect.currentframe()))\n dir_name = os.path.dirname(current_file_path)\n asset_dir = os.path.join(dir_name, 'assets')\n\n identity_lut = generate_identify_color_matrix()\n # source_path = os.path.join(asset_dir, 'identity.png')\n filterd_path = os.path.join(asset_dir, 'YV2.JPG')\n filterd_im = imageio.imread(filterd_path)\n result_im = generate_color_matrix_from_image(identity_lut, filterd_im)\n show(result_im)\n\n print(asset_dir)\n"
] |
[
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.show",
"numpy.zeros"
]
] |
dougalsutherland/POT
|
[
"faa4744597f93e7005bd48729441562e092e3ab6"
] |
[
"examples/plot_OTDA_classes.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\n========================\nOT for domain adaptation\n========================\n\n\"\"\"\n\nimport matplotlib.pylab as pl\nimport ot\n\n\n\n\n#%% parameters\n\nn=150 # nb samples in source and target datasets\n\nxs,ys=ot.datasets.get_data_classif('3gauss',n)\nxt,yt=ot.datasets.get_data_classif('3gauss2',n)\n\n\n\n\n#%% plot samples\n\npl.figure(1)\n\npl.subplot(2,2,1)\npl.scatter(xs[:,0],xs[:,1],c=ys,marker='+',label='Source samples')\npl.legend(loc=0)\npl.title('Source distributions')\n\npl.subplot(2,2,2)\npl.scatter(xt[:,0],xt[:,1],c=yt,marker='o',label='Target samples')\npl.legend(loc=0)\npl.title('target distributions')\n\n\n#%% OT estimation\n\n# LP problem\nda_emd=ot.da.OTDA() # init class\nda_emd.fit(xs,xt) # fit distributions\nxst0=da_emd.interp() # interpolation of source samples\n\n\n# sinkhorn regularization\nlambd=1e-1\nda_entrop=ot.da.OTDA_sinkhorn()\nda_entrop.fit(xs,xt,reg=lambd)\nxsts=da_entrop.interp()\n\n# non-convex Group lasso regularization\nreg=1e-1\neta=1e0\nda_lpl1=ot.da.OTDA_lpl1()\nda_lpl1.fit(xs,ys,xt,reg=reg,eta=eta)\nxstg=da_lpl1.interp()\n\n\n# True Group lasso regularization\nreg=1e-1\neta=2e0\nda_l1l2=ot.da.OTDA_l1l2()\nda_l1l2.fit(xs,ys,xt,reg=reg,eta=eta,numItermax=20,verbose=True)\nxstgl=da_l1l2.interp()\n\n\n#%% plot interpolated source samples\npl.figure(4,(15,8))\n\nparam_img={'interpolation':'nearest','cmap':'jet'}\n\npl.subplot(2,4,1)\npl.imshow(da_emd.G,**param_img)\npl.title('OT matrix')\n\n\npl.subplot(2,4,2)\npl.imshow(da_entrop.G,**param_img)\npl.title('OT matrix sinkhorn')\n\npl.subplot(2,4,3)\npl.imshow(da_lpl1.G,**param_img)\npl.title('OT matrix non-convex Group Lasso')\n\npl.subplot(2,4,4)\npl.imshow(da_l1l2.G,**param_img)\npl.title('OT matrix Group Lasso')\n\n\npl.subplot(2,4,5)\npl.scatter(xt[:,0],xt[:,1],c=yt,marker='o',label='Target samples',alpha=0.3)\npl.scatter(xst0[:,0],xst0[:,1],c=ys,marker='+',label='Transp samples',s=30)\npl.title('Interp samples')\npl.legend(loc=0)\n\npl.subplot(2,4,6)\npl.scatter(xt[:,0],xt[:,1],c=yt,marker='o',label='Target samples',alpha=0.3)\npl.scatter(xsts[:,0],xsts[:,1],c=ys,marker='+',label='Transp samples',s=30)\npl.title('Interp samples Sinkhorn')\n\npl.subplot(2,4,7)\npl.scatter(xt[:,0],xt[:,1],c=yt,marker='o',label='Target samples',alpha=0.3)\npl.scatter(xstg[:,0],xstg[:,1],c=ys,marker='+',label='Transp samples',s=30)\npl.title('Interp samples non-convex Group Lasso')\n\npl.subplot(2,4,8)\npl.scatter(xt[:,0],xt[:,1],c=yt,marker='o',label='Target samples',alpha=0.3)\npl.scatter(xstgl[:,0],xstgl[:,1],c=ys,marker='+',label='Transp samples',s=30)\npl.title('Interp samples Group Lasso')"
] |
[
[
"matplotlib.pylab.scatter",
"matplotlib.pylab.title",
"matplotlib.pylab.subplot",
"matplotlib.pylab.figure",
"matplotlib.pylab.imshow",
"matplotlib.pylab.legend"
]
] |
jack139/tongjian
|
[
"5827ae9ddbde744474f3058675c16a7749378507"
] |
[
"utils/prepare_data_ts.py"
] |
[
"# -*- coding: utf-8 -*-\n\nimport re\nimport codecs\nimport pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\nimport jiebazhc as jieba\nfrom . import utils\n\nX_BLANK = 'blank'\ny_BLANK = '让我想想'\n\n# 诗句分词\ndef pre_load(filename):\n content = utils.load_content_lines(filename)\n\n f = codecs.open(filename+'.2.txt', 'w', 'utf-8')\n\n for l in content:\n l = l.strip()\n if len(l)==0 or l[0]=='#': # 标题,忽略\n continue\n\n line = re.split(',|。|?|!', l)\n line = [i for i in line if len(i)>0]\n if len(line)!=2:\n print(line)\n #if len(line[0])!=len(line[1]):\n # print(line)\n\n \n left = jieba.cut(line[0])\n right = jieba.cut(line[1])\n\n f.write('%s -- %s\\n'% (' '.join([i for i in left]), ' '.join([i for i in right])) )\n\n f.close()\n\n\n# 分词后诗句处理 (一般需手工核对后)\ndef load_data(filename):\n content = utils.load_content(filename)\n\n content1 = content.replace('--','')\n segs = content1.split()\n segments = [i for i in segs if len(i)>0]\n segmentDF = pd.DataFrame({'segment':segments})\n #segmentDF = utils.remove_stopwords(segmentDF)\n\n #对词频进行统计。\n\n segStat = segmentDF.groupby(by=[\"segment\"])[\"segment\"].agg(count=\"count\").reset_index().sort_values(by=['count'],ascending=False)\n #print(segStat.head(100))\n\n # 准备 X \n\n # 词标签规范化\n leX = preprocessing.LabelEncoder()\n leX.fit(list(segStat['segment'])+[X_BLANK, y_BLANK])\n\n # 取得空位的label\n blank_label = leX.transform([X_BLANK])[0]\n blank_label_y = leX.transform([y_BLANK])[0]\n\n\n # 标签化\n lines = content.split('\\n')\n lines = [i for i in lines if len(i)>0]\n\n lines_data = []\n\n # 词标签化\n # 词特征组成: 词本身标签 + 前一个词标签 + 后一个词标签 , 如果前、后有空,则空标签\n X_data = []\n y_data = [] \n for line in lines:\n if len(line)==0:\n continue\n left, right = line.split('--')\n left = left.split()\n right = right.split()\n\n # 检查两句分词个数是否一致\n if len(left)!=len(right):\n print('skip:', line)\n continue\n\n # 检查两句分词,每词字数是否一致\n x=[len(left[i])==len(right[i]) for i in range(len(left))]\n if False in x:\n print('skip:', line)\n continue\n\n right_df = pd.DataFrame({'segment':right})\n right_data = leX.transform(right_df['segment'])\n\n for i in range(len(left)):\n # 每个词生成特征\n\n # 前一个词\n if i==0:\n last_word = X_BLANK\n else:\n last_word = left[i-1]\n\n # 后一个词\n if i+1==len(left):\n next_word = X_BLANK\n else:\n next_word = left[i+1]\n\n # 词特征标签\n word_feature = [left[i], last_word, next_word]\n word_df = pd.DataFrame({'segment':word_feature}) \n word_data = leX.transform(word_df['segment'])\n\n X_data.append(word_data)\n y_data.append(right_data[i])\n\n # 词特征标签2, 不考虑位置\n word_feature = [left[i], X_BLANK, X_BLANK]\n word_df = pd.DataFrame({'segment':word_feature}) \n word_data = leX.transform(word_df['segment'])\n\n X_data.append(word_data)\n y_data.append(right_data[i])\n\n\n # 添加空词标签\n word_feature = [X_BLANK, X_BLANK, X_BLANK]\n word_df = pd.DataFrame({'segment':word_feature}) \n word_data = leX.transform(word_df['segment'])\n X_data.append(word_data)\n y_data.append(blank_label_y)\n\n\n # 每扩充为等长\n max_len = max(map(len, X_data))\n #print(max_len)\n X_data = [ np.append(l[:max_len], [blank_label]*(max_len-len(l))) for l in X_data ]\n\n return X_data, y_data, leX, leX, max_len\n"
] |
[
[
"sklearn.preprocessing.LabelEncoder",
"pandas.DataFrame"
]
] |
Mdlglobal-atlassian-net/tensorboard
|
[
"67801ef8e4f22550b0babb893f4383af36473a26"
] |
[
"tensorboard/plugins/projector/projector_plugin.py"
] |
[
"# Copyright 2016 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\"\"\"The Embedding Projector plugin.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport functools\nimport imghdr\nimport math\nimport mimetypes\nimport os\nimport threading\n\nimport numpy as np\nfrom werkzeug import wrappers\n\nfrom google.protobuf import json_format\nfrom google.protobuf import text_format\n\nfrom tensorboard.backend.http_util import Respond\nfrom tensorboard.compat import tf\nfrom tensorboard.plugins import base_plugin\nfrom tensorboard.plugins.projector import metadata\nfrom tensorboard.plugins.projector.projector_config_pb2 import ProjectorConfig\nfrom tensorboard.util import tb_logging\n\nlogger = tb_logging.get_logger()\n\n# Number of tensors in the LRU cache.\n_TENSOR_CACHE_CAPACITY = 1\n\n# HTTP routes.\nCONFIG_ROUTE = \"/info\"\nTENSOR_ROUTE = \"/tensor\"\nMETADATA_ROUTE = \"/metadata\"\nRUNS_ROUTE = \"/runs\"\nBOOKMARKS_ROUTE = \"/bookmarks\"\nSPRITE_IMAGE_ROUTE = \"/sprite_image\"\n\n_IMGHDR_TO_MIMETYPE = {\n \"bmp\": \"image/bmp\",\n \"gif\": \"image/gif\",\n \"jpeg\": \"image/jpeg\",\n \"png\": \"image/png\",\n}\n_DEFAULT_IMAGE_MIMETYPE = \"application/octet-stream\"\n\n\nclass LRUCache(object):\n \"\"\"LRU cache.\n\n Used for storing the last used tensor.\n \"\"\"\n\n def __init__(self, size):\n if size < 1:\n raise ValueError(\"The cache size must be >=1\")\n self._size = size\n self._dict = collections.OrderedDict()\n\n def get(self, key):\n try:\n value = self._dict.pop(key)\n self._dict[key] = value\n return value\n except KeyError:\n return None\n\n def set(self, key, value):\n if value is None:\n raise ValueError(\"value must be != None\")\n try:\n self._dict.pop(key)\n except KeyError:\n if len(self._dict) >= self._size:\n self._dict.popitem(last=False)\n self._dict[key] = value\n\n\nclass EmbeddingMetadata(object):\n \"\"\"Metadata container for an embedding.\n\n The metadata holds different columns with values used for\n visualization (color by, label by) in the \"Embeddings\" tab in\n TensorBoard.\n \"\"\"\n\n def __init__(self, num_points):\n \"\"\"Constructs a metadata for an embedding of the specified size.\n\n Args:\n num_points: Number of points in the embedding.\n \"\"\"\n self.num_points = num_points\n self.column_names = []\n self.name_to_values = {}\n\n def add_column(self, column_name, column_values):\n \"\"\"Adds a named column of metadata values.\n\n Args:\n column_name: Name of the column.\n column_values: 1D array/list/iterable holding the column values. Must be\n of length `num_points`. The i-th value corresponds to the i-th point.\n\n Raises:\n ValueError: If `column_values` is not 1D array, or of length `num_points`,\n or the `name` is already used.\n \"\"\"\n # Sanity checks.\n if isinstance(column_values, list) and isinstance(\n column_values[0], list\n ):\n raise ValueError(\n '\"column_values\" must be a flat list, but we detected '\n \"that its first entry is a list\"\n )\n\n if isinstance(column_values, np.ndarray) and column_values.ndim != 1:\n raise ValueError(\n '\"column_values\" should be of rank 1, '\n \"but is of rank %d\" % column_values.ndim\n )\n if len(column_values) != self.num_points:\n raise ValueError(\n '\"column_values\" should be of length %d, but is of '\n \"length %d\" % (self.num_points, len(column_values))\n )\n if column_name in self.name_to_values:\n raise ValueError(\n 'The column name \"%s\" is already used' % column_name\n )\n\n self.column_names.append(column_name)\n self.name_to_values[column_name] = column_values\n\n\ndef _read_tensor_tsv_file(fpath):\n with tf.io.gfile.GFile(fpath, \"r\") as f:\n tensor = []\n for line in f:\n line = line.rstrip(\"\\n\")\n if line:\n tensor.append(list(map(float, line.split(\"\\t\"))))\n return np.array(tensor, dtype=\"float32\")\n\n\ndef _read_tensor_binary_file(fpath, shape):\n if len(shape) != 2:\n raise ValueError(\"Tensor must be 2D, got shape {}\".format(shape))\n tensor = np.fromfile(fpath, dtype=\"float32\")\n return tensor.reshape(shape)\n\n\ndef _assets_dir_to_logdir(assets_dir):\n sub_path = os.path.sep + metadata.PLUGINS_DIR + os.path.sep\n if sub_path in assets_dir:\n two_parents_up = os.pardir + os.path.sep + os.pardir\n return os.path.abspath(os.path.join(assets_dir, two_parents_up))\n return assets_dir\n\n\ndef _latest_checkpoints_changed(configs, run_path_pairs):\n \"\"\"Returns true if the latest checkpoint has changed in any of the runs.\"\"\"\n for run_name, assets_dir in run_path_pairs:\n if run_name not in configs:\n config = ProjectorConfig()\n config_fpath = os.path.join(assets_dir, metadata.PROJECTOR_FILENAME)\n if tf.io.gfile.exists(config_fpath):\n with tf.io.gfile.GFile(config_fpath, \"r\") as f:\n file_content = f.read()\n text_format.Merge(file_content, config)\n else:\n config = configs[run_name]\n\n # See if you can find a checkpoint file in the logdir.\n logdir = _assets_dir_to_logdir(assets_dir)\n ckpt_path = _find_latest_checkpoint(logdir)\n if not ckpt_path:\n continue\n if config.model_checkpoint_path != ckpt_path:\n return True\n return False\n\n\ndef _parse_positive_int_param(request, param_name):\n \"\"\"Parses and asserts a positive (>0) integer query parameter.\n\n Args:\n request: The Werkzeug Request object\n param_name: Name of the parameter.\n\n Returns:\n Param, or None, or -1 if parameter is not a positive integer.\n \"\"\"\n param = request.args.get(param_name)\n if not param:\n return None\n try:\n param = int(param)\n if param <= 0:\n raise ValueError()\n return param\n except ValueError:\n return -1\n\n\ndef _rel_to_abs_asset_path(fpath, config_fpath):\n fpath = os.path.expanduser(fpath)\n if not os.path.isabs(fpath):\n return os.path.join(os.path.dirname(config_fpath), fpath)\n return fpath\n\n\ndef _using_tf():\n \"\"\"Return true if we're not using the fake TF API stub implementation.\"\"\"\n return tf.__version__ != \"stub\"\n\n\nclass ProjectorPlugin(base_plugin.TBPlugin):\n \"\"\"Embedding projector.\"\"\"\n\n plugin_name = metadata.PLUGIN_NAME\n\n def __init__(self, context):\n \"\"\"Instantiates ProjectorPlugin via TensorBoard core.\n\n Args:\n context: A base_plugin.TBContext instance.\n \"\"\"\n self.multiplexer = context.multiplexer\n self.logdir = context.logdir\n self._handlers = None\n self.readers = {}\n self.run_paths = None\n self._configs = {}\n self.old_num_run_paths = None\n self.config_fpaths = None\n self.tensor_cache = LRUCache(_TENSOR_CACHE_CAPACITY)\n\n # Whether the plugin is active (has meaningful data to process and serve).\n # Once the plugin is deemed active, we no longer re-compute the value\n # because doing so is potentially expensive.\n self._is_active = False\n\n # The running thread that is currently determining whether the plugin is\n # active. If such a thread exists, do not start a duplicate thread.\n self._thread_for_determining_is_active = None\n\n if self.multiplexer:\n self.run_paths = self.multiplexer.RunPaths()\n\n def get_plugin_apps(self):\n self._handlers = {\n RUNS_ROUTE: self._serve_runs,\n CONFIG_ROUTE: self._serve_config,\n TENSOR_ROUTE: self._serve_tensor,\n METADATA_ROUTE: self._serve_metadata,\n BOOKMARKS_ROUTE: self._serve_bookmarks,\n SPRITE_IMAGE_ROUTE: self._serve_sprite_image,\n \"/index.js\": functools.partial(\n self._serve_file,\n os.path.join(\"tf_projector_plugin\", \"index.js\"),\n ),\n \"/projector_binary.html\": functools.partial(\n self._serve_file,\n os.path.join(\"tf_projector_plugin\", \"projector_binary.html\"),\n ),\n \"/projector_binary.js\": functools.partial(\n self._serve_file,\n os.path.join(\"tf_projector_plugin\", \"projector_binary.js\"),\n ),\n }\n return self._handlers\n\n def is_active(self):\n \"\"\"Determines whether this plugin is active.\n\n This plugin is only active if any run has an embedding.\n\n Returns:\n Whether any run has embedding data to show in the projector.\n \"\"\"\n if not self.multiplexer:\n return False\n\n if self._is_active:\n # We have already determined that the projector plugin should be active.\n # Do not re-compute that. We have no reason to later set this plugin to be\n # inactive.\n return True\n\n if self._thread_for_determining_is_active:\n # We are currently determining whether the plugin is active. Do not start\n # a separate thread.\n return self._is_active\n\n # The plugin is currently not active. The frontend might check again later.\n # For now, spin off a separate thread to determine whether the plugin is\n # active.\n new_thread = threading.Thread(\n target=self._determine_is_active,\n name=\"ProjectorPluginIsActiveThread\",\n )\n self._thread_for_determining_is_active = new_thread\n new_thread.start()\n return False\n\n def frontend_metadata(self):\n return base_plugin.FrontendMetadata(\n es_module_path=\"/index.js\", disable_reload=True,\n )\n\n def _determine_is_active(self):\n \"\"\"Determines whether the plugin is active.\n\n This method is run in a separate thread so that the plugin can\n offer an immediate response to whether it is active and\n determine whether it should be active in a separate thread.\n \"\"\"\n if self.configs:\n self._is_active = True\n self._thread_for_determining_is_active = None\n\n @property\n def configs(self):\n \"\"\"Returns a map of run paths to `ProjectorConfig` protos.\"\"\"\n run_path_pairs = list(self.run_paths.items())\n self._append_plugin_asset_directories(run_path_pairs)\n # If there are no summary event files, the projector should still work,\n # treating the `logdir` as the model checkpoint directory.\n if not run_path_pairs:\n run_path_pairs.append((\".\", self.logdir))\n if self._run_paths_changed() or _latest_checkpoints_changed(\n self._configs, run_path_pairs\n ):\n self.readers = {}\n self._configs, self.config_fpaths = self._read_latest_config_files(\n run_path_pairs\n )\n self._augment_configs_with_checkpoint_info()\n return self._configs\n\n def _run_paths_changed(self):\n num_run_paths = len(list(self.run_paths.keys()))\n if num_run_paths != self.old_num_run_paths:\n self.old_num_run_paths = num_run_paths\n return True\n return False\n\n def _augment_configs_with_checkpoint_info(self):\n for run, config in self._configs.items():\n for embedding in config.embeddings:\n # Normalize the name of the embeddings.\n if embedding.tensor_name.endswith(\":0\"):\n embedding.tensor_name = embedding.tensor_name[:-2]\n # Find the size of embeddings associated with a tensors file.\n if embedding.tensor_path:\n fpath = _rel_to_abs_asset_path(\n embedding.tensor_path, self.config_fpaths[run]\n )\n tensor = self.tensor_cache.get((run, embedding.tensor_name))\n if tensor is None:\n try:\n tensor = _read_tensor_tsv_file(fpath)\n except UnicodeDecodeError:\n tensor = _read_tensor_binary_file(\n fpath, embedding.tensor_shape\n )\n self.tensor_cache.set(\n (run, embedding.tensor_name), tensor\n )\n if not embedding.tensor_shape:\n embedding.tensor_shape.extend(\n [len(tensor), len(tensor[0])]\n )\n\n reader = self._get_reader_for_run(run)\n if not reader:\n continue\n # Augment the configuration with the tensors in the checkpoint file.\n special_embedding = None\n if config.embeddings and not config.embeddings[0].tensor_name:\n special_embedding = config.embeddings[0]\n config.embeddings.remove(special_embedding)\n var_map = reader.get_variable_to_shape_map()\n for tensor_name, tensor_shape in var_map.items():\n if len(tensor_shape) != 2:\n continue\n # Optimizer slot values are the same shape as embeddings\n # but are not embeddings.\n if \".OPTIMIZER_SLOT\" in tensor_name:\n continue\n embedding = self._get_embedding(tensor_name, config)\n if not embedding:\n embedding = config.embeddings.add()\n embedding.tensor_name = tensor_name\n if special_embedding:\n embedding.metadata_path = (\n special_embedding.metadata_path\n )\n embedding.bookmarks_path = (\n special_embedding.bookmarks_path\n )\n if not embedding.tensor_shape:\n embedding.tensor_shape.extend(tensor_shape)\n\n # Remove configs that do not have any valid (2D) tensors.\n runs_to_remove = []\n for run, config in self._configs.items():\n if not config.embeddings:\n runs_to_remove.append(run)\n for run in runs_to_remove:\n del self._configs[run]\n del self.config_fpaths[run]\n\n def _read_latest_config_files(self, run_path_pairs):\n \"\"\"Reads and returns the projector config files in every run\n directory.\"\"\"\n \"\"\"If no specific config exists, use the default config provided in\n the root directory.\"\"\"\n default_config_fpath = os.path.join(\n self.logdir, metadata.PROJECTOR_FILENAME\n )\n default_config = ProjectorConfig()\n if tf.io.gfile.exists(default_config_fpath):\n with tf.io.gfile.GFile(default_config_fpath, \"r\") as f:\n file_content = f.read()\n text_format.Merge(file_content, default_config)\n # Relative metadata paths do not work with subdirs, so convert\n # any metadata paths to absolute paths.\n for embedding in default_config.embeddings:\n embedding.metadata_path = _rel_to_abs_asset_path(\n embedding.metadata_path, default_config_fpath\n )\n configs = {}\n config_fpaths = {}\n for run_name, assets_dir in run_path_pairs:\n config = ProjectorConfig()\n config_fpath = os.path.join(assets_dir, metadata.PROJECTOR_FILENAME)\n if tf.io.gfile.exists(config_fpath):\n with tf.io.gfile.GFile(config_fpath, \"r\") as f:\n file_content = f.read()\n text_format.Merge(file_content, config)\n elif tf.io.gfile.exists(default_config_fpath):\n config = default_config\n has_tensor_files = False\n for embedding in config.embeddings:\n if embedding.tensor_path:\n if not embedding.tensor_name:\n embedding.tensor_name = os.path.basename(\n embedding.tensor_path\n )\n has_tensor_files = True\n break\n\n if not config.model_checkpoint_path:\n # See if you can find a checkpoint file in the logdir.\n logdir = _assets_dir_to_logdir(assets_dir)\n ckpt_path = _find_latest_checkpoint(logdir)\n if not ckpt_path and not has_tensor_files:\n continue\n if ckpt_path:\n config.model_checkpoint_path = ckpt_path\n\n # Sanity check for the checkpoint file existing.\n if (\n config.model_checkpoint_path\n and _using_tf()\n and not tf.io.gfile.glob(config.model_checkpoint_path + \"*\")\n ):\n logger.warn(\n 'Checkpoint file \"%s\" not found',\n config.model_checkpoint_path,\n )\n continue\n configs[run_name] = config\n config_fpaths[run_name] = config_fpath\n return configs, config_fpaths\n\n def _get_reader_for_run(self, run):\n if run in self.readers:\n return self.readers[run]\n\n config = self._configs[run]\n reader = None\n if config.model_checkpoint_path and _using_tf():\n try:\n reader = tf.train.load_checkpoint(config.model_checkpoint_path)\n except Exception: # pylint: disable=broad-except\n logger.warn('Failed reading \"%s\"', config.model_checkpoint_path)\n self.readers[run] = reader\n return reader\n\n def _get_metadata_file_for_tensor(self, tensor_name, config):\n embedding_info = self._get_embedding(tensor_name, config)\n if embedding_info:\n return embedding_info.metadata_path\n return None\n\n def _get_bookmarks_file_for_tensor(self, tensor_name, config):\n embedding_info = self._get_embedding(tensor_name, config)\n if embedding_info:\n return embedding_info.bookmarks_path\n return None\n\n def _canonical_tensor_name(self, tensor_name):\n if \":\" not in tensor_name:\n return tensor_name + \":0\"\n else:\n return tensor_name\n\n def _get_embedding(self, tensor_name, config):\n if not config.embeddings:\n return None\n for info in config.embeddings:\n if self._canonical_tensor_name(\n info.tensor_name\n ) == self._canonical_tensor_name(tensor_name):\n return info\n return None\n\n def _append_plugin_asset_directories(self, run_path_pairs):\n for run, assets in self.multiplexer.PluginAssets(\n metadata.PLUGIN_ASSETS_NAME\n ).items():\n if metadata.PROJECTOR_FILENAME not in assets:\n continue\n assets_dir = os.path.join(\n self.run_paths[run],\n metadata.PLUGINS_DIR,\n metadata.PLUGIN_ASSETS_NAME,\n )\n assets_path_pair = (run, os.path.abspath(assets_dir))\n run_path_pairs.append(assets_path_pair)\n\n @wrappers.Request.application\n def _serve_file(self, file_path, request):\n \"\"\"Returns a resource file.\"\"\"\n res_path = os.path.join(os.path.dirname(__file__), file_path)\n with open(res_path, \"rb\") as read_file:\n mimetype = mimetypes.guess_type(file_path)[0]\n return Respond(request, read_file.read(), content_type=mimetype)\n\n @wrappers.Request.application\n def _serve_runs(self, request):\n \"\"\"Returns a list of runs that have embeddings.\"\"\"\n return Respond(request, list(self.configs.keys()), \"application/json\")\n\n @wrappers.Request.application\n def _serve_config(self, request):\n run = request.args.get(\"run\")\n if run is None:\n return Respond(\n request, 'query parameter \"run\" is required', \"text/plain\", 400\n )\n if run not in self.configs:\n return Respond(\n request, 'Unknown run: \"%s\"' % run, \"text/plain\", 400\n )\n\n config = self.configs[run]\n return Respond(\n request, json_format.MessageToJson(config), \"application/json\"\n )\n\n @wrappers.Request.application\n def _serve_metadata(self, request):\n run = request.args.get(\"run\")\n if run is None:\n return Respond(\n request, 'query parameter \"run\" is required', \"text/plain\", 400\n )\n\n name = request.args.get(\"name\")\n if name is None:\n return Respond(\n request, 'query parameter \"name\" is required', \"text/plain\", 400\n )\n\n num_rows = _parse_positive_int_param(request, \"num_rows\")\n if num_rows == -1:\n return Respond(\n request,\n \"query parameter num_rows must be integer > 0\",\n \"text/plain\",\n 400,\n )\n\n if run not in self.configs:\n return Respond(\n request, 'Unknown run: \"%s\"' % run, \"text/plain\", 400\n )\n\n config = self.configs[run]\n fpath = self._get_metadata_file_for_tensor(name, config)\n if not fpath:\n return Respond(\n request,\n 'No metadata file found for tensor \"%s\" in the config file \"%s\"'\n % (name, self.config_fpaths[run]),\n \"text/plain\",\n 400,\n )\n fpath = _rel_to_abs_asset_path(fpath, self.config_fpaths[run])\n if not tf.io.gfile.exists(fpath) or tf.io.gfile.isdir(fpath):\n return Respond(\n request,\n '\"%s\" not found, or is not a file' % fpath,\n \"text/plain\",\n 400,\n )\n\n num_header_rows = 0\n with tf.io.gfile.GFile(fpath, \"r\") as f:\n lines = []\n # Stream reading the file with early break in case the file doesn't fit in\n # memory.\n for line in f:\n lines.append(line)\n if len(lines) == 1 and \"\\t\" in lines[0]:\n num_header_rows = 1\n if num_rows and len(lines) >= num_rows + num_header_rows:\n break\n return Respond(request, \"\".join(lines), \"text/plain\")\n\n @wrappers.Request.application\n def _serve_tensor(self, request):\n run = request.args.get(\"run\")\n if run is None:\n return Respond(\n request, 'query parameter \"run\" is required', \"text/plain\", 400\n )\n\n name = request.args.get(\"name\")\n if name is None:\n return Respond(\n request, 'query parameter \"name\" is required', \"text/plain\", 400\n )\n\n num_rows = _parse_positive_int_param(request, \"num_rows\")\n if num_rows == -1:\n return Respond(\n request,\n \"query parameter num_rows must be integer > 0\",\n \"text/plain\",\n 400,\n )\n\n if run not in self.configs:\n return Respond(\n request, 'Unknown run: \"%s\"' % run, \"text/plain\", 400\n )\n\n config = self.configs[run]\n\n tensor = self.tensor_cache.get((run, name))\n if tensor is None:\n # See if there is a tensor file in the config.\n embedding = self._get_embedding(name, config)\n\n if embedding and embedding.tensor_path:\n fpath = _rel_to_abs_asset_path(\n embedding.tensor_path, self.config_fpaths[run]\n )\n if not tf.io.gfile.exists(fpath):\n return Respond(\n request,\n 'Tensor file \"%s\" does not exist' % fpath,\n \"text/plain\",\n 400,\n )\n try:\n tensor = _read_tensor_tsv_file(fpath)\n except UnicodeDecodeError:\n tensor = _read_tensor_binary_file(\n fpath, embedding.tensor_shape\n )\n else:\n reader = self._get_reader_for_run(run)\n if not reader or not reader.has_tensor(name):\n return Respond(\n request,\n 'Tensor \"%s\" not found in checkpoint dir \"%s\"'\n % (name, config.model_checkpoint_path),\n \"text/plain\",\n 400,\n )\n try:\n tensor = reader.get_tensor(name)\n except tf.errors.InvalidArgumentError as e:\n return Respond(request, str(e), \"text/plain\", 400)\n\n self.tensor_cache.set((run, name), tensor)\n\n if num_rows:\n tensor = tensor[:num_rows]\n if tensor.dtype != \"float32\":\n tensor = tensor.astype(dtype=\"float32\", copy=False)\n data_bytes = tensor.tobytes()\n return Respond(request, data_bytes, \"application/octet-stream\")\n\n @wrappers.Request.application\n def _serve_bookmarks(self, request):\n run = request.args.get(\"run\")\n if not run:\n return Respond(\n request, 'query parameter \"run\" is required', \"text/plain\", 400\n )\n\n name = request.args.get(\"name\")\n if name is None:\n return Respond(\n request, 'query parameter \"name\" is required', \"text/plain\", 400\n )\n\n if run not in self.configs:\n return Respond(\n request, 'Unknown run: \"%s\"' % run, \"text/plain\", 400\n )\n\n config = self.configs[run]\n fpath = self._get_bookmarks_file_for_tensor(name, config)\n if not fpath:\n return Respond(\n request,\n 'No bookmarks file found for tensor \"%s\" in the config file \"%s\"'\n % (name, self.config_fpaths[run]),\n \"text/plain\",\n 400,\n )\n fpath = _rel_to_abs_asset_path(fpath, self.config_fpaths[run])\n if not tf.io.gfile.exists(fpath) or tf.io.gfile.isdir(fpath):\n return Respond(\n request,\n '\"%s\" not found, or is not a file' % fpath,\n \"text/plain\",\n 400,\n )\n\n bookmarks_json = None\n with tf.io.gfile.GFile(fpath, \"rb\") as f:\n bookmarks_json = f.read()\n return Respond(request, bookmarks_json, \"application/json\")\n\n @wrappers.Request.application\n def _serve_sprite_image(self, request):\n run = request.args.get(\"run\")\n if not run:\n return Respond(\n request, 'query parameter \"run\" is required', \"text/plain\", 400\n )\n\n name = request.args.get(\"name\")\n if name is None:\n return Respond(\n request, 'query parameter \"name\" is required', \"text/plain\", 400\n )\n\n if run not in self.configs:\n return Respond(\n request, 'Unknown run: \"%s\"' % run, \"text/plain\", 400\n )\n\n config = self.configs[run]\n embedding_info = self._get_embedding(name, config)\n\n if not embedding_info or not embedding_info.sprite.image_path:\n return Respond(\n request,\n 'No sprite image file found for tensor \"%s\" in the config file \"%s\"'\n % (name, self.config_fpaths[run]),\n \"text/plain\",\n 400,\n )\n\n fpath = os.path.expanduser(embedding_info.sprite.image_path)\n fpath = _rel_to_abs_asset_path(fpath, self.config_fpaths[run])\n if not tf.io.gfile.exists(fpath) or tf.io.gfile.isdir(fpath):\n return Respond(\n request,\n '\"%s\" does not exist or is directory' % fpath,\n \"text/plain\",\n 400,\n )\n f = tf.io.gfile.GFile(fpath, \"rb\")\n encoded_image_string = f.read()\n f.close()\n image_type = imghdr.what(None, encoded_image_string)\n mime_type = _IMGHDR_TO_MIMETYPE.get(image_type, _DEFAULT_IMAGE_MIMETYPE)\n return Respond(request, encoded_image_string, mime_type)\n\n\ndef _find_latest_checkpoint(dir_path):\n if not _using_tf():\n return None\n try:\n ckpt_path = tf.train.latest_checkpoint(dir_path)\n if not ckpt_path:\n # Check the parent directory.\n ckpt_path = tf.train.latest_checkpoint(\n os.path.join(dir_path, os.pardir)\n )\n return ckpt_path\n except tf.errors.NotFoundError:\n return None\n"
] |
[
[
"numpy.fromfile",
"numpy.array"
]
] |
arminrest/HSTkilonova_exptimes
|
[
"0ab77eeac6aaee2e9068ffc2f9d3bd8ff250302d",
"0ab77eeac6aaee2e9068ffc2f9d3bd8ff250302d"
] |
[
"tools.py",
"calcExpTimes.py"
] |
[
"#!/usr/bin/env python\nimport os, string, re, sys, math, types, pickle,six\nfrom subprocess import Popen, PIPE, STDOUT\nimport datetime\ntry:\n import astropy.io.fits as pyfits\nexcept ImportError:\n import pyfits\n \ntry: \n from configparser import SafeConfigParser\nexcept:\n from ConfigParser import SafeConfigParser\n\nfrom astropy.time import Time\n\nclass SMFieldSearch:\n def __init__(self, cmpin, ra, dec, path):\n self.cmpin = cmpin\n self.ra = ra\n self.dec = dec\n self.startpath = path\n\n self.photmatch = []\n self.cmpmatch = []\n\n smfield, smamp = self.parseCmp(self.cmpin)\n if smfield and smamp:\n self.locateCmp(smfield, smamp)\n\n #print(self.ra, self.dec, self.cmpmatch)\n\n self.search()\n\n #print(self.photmatch)\n\n def search(self):\n for cmpMatch in self.cmpmatch:\n self.scanCmp(cmpMatch)\n\n def parseCmp(self, cmpfile):\n p = re.compile('(sm\\d\\d).\\d{6,6}_\\d{4,4}.\\d{3,4}_(\\d{1,2})_sub.cmp')\n m = p.search(cmpfile)\n if m:\n return m.group(1), m.group(2)\n else :\n return None, None\n\n def locateCmp(self, smfield, amp):\n matches = []\n for datedir in os.listdir(self.startpath):\n absdatedir = os.path.join(self.startpath, datedir)\n if os.path.isdir(absdatedir) and (string.find(datedir, '_') != -1):\n ampdir = os.path.join(absdatedir, str(amp))\n if os.path.isdir(ampdir):\n for smfile in os.listdir(ampdir):\n abssmfile = os.path.join(ampdir, smfile)\n if smfile.startswith(smfield) and smfile.endswith('sub.cmp'):\n self.cmpmatch.append(abssmfile)\n\n def scanCmp(self, cmpfile, pixrad=2):\n import pcfitsio\n\n if not os.path.isfile(cmpfile):\n return None\n\n xs, ys = list(map(float, sky2xy(cmpfile, self.ra, self.dec)))\n\n if xs == None:\n return None\n\n for line in open(cmpfile).readlines()[1:]:\n\n xc, yc = list(map(float, line.split()[0:2]))\n\n dist = math.sqrt( (xs-xc)**2 + (ys-yc)**2 )\n\n #print(self.ra, self.dec, cmpfile, xs, ys, xc, yc, dist)\n\n if dist < pixrad:\n cptr = pcfitsio.fits_open_file(cmpfile, 0)\n mjd = pcfitsio.fits_read_key_dbl(cptr, 'MJD-OBS')[0]\n pcfitsio.fits_close_file(cptr)\n\n self.photmatch.append((mjd, line))\n\ndef sky2xy(fitsfile, ra, dec, coordsys='', opts=''):\n if not os.path.isfile(fitsfile):\n print(('ERROR sky2xy: could not find file ',fitsfile))\n return None, None\n so = os.popen('sky2xy %s %s %s %s %s' % (opts,fitsfile,str(ra),str(dec),coordsys))\n output = so.readlines()[0]\n so.close()\n\n return parse_sky2xy_output(output)\n\ndef sky2xy_list(fitsfile, radeclist, opts='-j',verbose=0):\n\n if not os.path.isfile(fitsfile):\n print(('error: fits file %s doesn\\'t exist' % (fitsfile)))\n return 1,None\n\n cmd = 'sky2xy %s %s ' % (opts,fitsfile)\n for radec in radeclist: cmd += ' %s' % (radec)\n errorflag,output = executecommand(cmd,'',verbose=verbose)\n if len(output) != len(radeclist):\n print(('RA/DEC:',radeclist))\n print(('sky2xy output:',output))\n print('error: inconsistent number of output X/Y position to input RA/DEC positions!')\n return 2,None\n\n xydict = {}\n irange = list(range(len(output)))\n for i in irange:\n\n xydict[radeclist[i]] = {}\n xydict[radeclist[i]]['unparsed'] = output[i]\n\n xydict[radeclist[i]]['x'],xydict[radeclist[i]]['y'] = parse_sky2xy_output(output[i])\n if xydict[radeclist[i]]['x']==None or xydict[radeclist[i]]['y']==None:\n print(('ERROR! cannot parse sky2xy output:',output[i]))\n return 1, None\n\n del irange,output\n return 0,xydict\n\ndef sky2xy_file(fitsfile, radecfile, opts='',verbose=0):\n if not os.path.isfile(fitsfile):\n print(('error: fits file %s doesn\\'t exist' % (fitsfile)))\n return 1,None\n\n cmd = 'sky2xy %s %s @%s' % (opts,fitsfile,radecfile)\n errorflag,output = executecommand(cmd,'')\n\n xylist = []\n irange = list(range(len(output)))\n for i in irange:\n x,y = parse_sky2xy_output(output[i])\n if x==None or y==None:\n print(('ERROR! cannot parse xy2sky output:',output[i]))\n return 1, None\n xylist.append((x,y))\n\n del irange,output\n return 0,xylist\n\n\ndef xy2sky(fitsfile, x, y, opts=''):\n if not os.path.isfile(fitsfile):\n return None, None\n\n so = os.popen('xy2sky ' + opts + ' ' + fitsfile + ' '+ str(x) + ' ' + str(y))\n output = so.readlines()[0]\n so.close()\n\n return parse_xy2sky_output(output)\n\ndef xy2sky_list(fitsfile, xylist, opts='-j'):\n\n if not os.path.isfile(fitsfile):\n print(('error: fits file %s doesn\\'t exist' % (fitsfile)))\n return 1,None\n\n cmd = 'xy2sky %s %s ' % (opts,fitsfile)\n for xy in xylist: cmd += xy\n errorflag,output = executecommand(cmd,'')\n\n if len(output) != len(xylist):\n print(('XY:',xylist))\n print(('xy2sky output:',output))\n print('error: inconsistent number of output RA/DEC position to input X/Y positions!')\n return 2,None\n\n radecdict = {}\n irange = list(range(len(output)))\n for i in irange:\n\n radecdict[xylist[i]] = {}\n radecdict[xylist[i]]['unparsed'] = output[i]\n\n radecdict[xylist[i]]['ra'],radecdict[xylist[i]]['dec'] = parse_xy2sky_output(output[i])\n if radecdict[xylist[i]]['ra']==None or radecdict[xylist[i]]['dec']==None:\n print(('ERROR! cannot parse xy2sky output:',output[i]))\n return 1, None\n del irange,output\n return 0,radecdict\n\ndef parse_xy2sky_output(output):\n fields = output.split()\n if 'FK5' in fields:\n system = 'FK5'\n elif 'J2000' in fields:\n system = 'J2000'\n elif 'FK4' in fields:\n system = 'FK4'\n elif 'B1950' in fields:\n system = 'B1950'\n else:\n return None, None\n\n if fields.index(system) == 2:\n return fields[0], fields[1]\n elif fields.index(system) == 5:\n return fields[3], fields[4]\n else:\n return None, None\n\ndef parse_sky2xy_output(output):\n fields = output.split()\n\n if 'FK5' in fields:\n system = 'FK5'\n elif 'J2000' in fields:\n system = 'J2000'\n elif 'FK4' in fields:\n system = 'FK4'\n elif 'B1950' in fields:\n system = 'B1950'\n else:\n return None, None\n\n if '(off' in fields or 'off' in fields:\n return None, None\n\n if fields.index(system) == 2:\n return list(map(float, (fields[4], fields[5])))\n elif fields.index(system) == 5:\n return list(map(float, (fields[3], fields[4])))\n else:\n return None, None\n\ndef calcPA(ra1,dec1,ra2,dec2):\n deg2rad=0.0174532925199 # math.pi / 180.\n rad2deg=57.2957795131 # 180.0 / math.pi\n ra1=RaInDeg(ra1)\n ra2=RaInDeg(ra2)\n dec1=DecInDeg(dec1)\n dec2=DecInDeg(dec2)\n dec1rad=dec1*deg2rad\n dec2rad=dec2*deg2rad\n\n if ra1-ra2>180:\n ra2=ra2+360.0\n if ra1-ra2<-180:\n ra2=ra2-360.0\n\n dRa = ra2*deg2rad - ra1*deg2rad\n\n pa_deg = rad2deg*math.atan2(math.sin(dRa),math.cos(dec1rad)*math.sin(dec2rad)/math.cos(dec2rad)-math.sin(dec1rad)*math.cos(dRa));\n return pa_deg\n\n# this uses skycoor from WCStools, but there is a bug in skycoor ...\ndef calcPAbad(ra1,dec1,ra2,dec2):\n ra1=RaInDeg(ra1)\n ra2=RaInDeg(ra2)\n dec1=DecInDeg(dec1)\n dec2=DecInDeg(dec2)\n # This is to get rid of a skycoor bug:\n # rest@000d60780e33(SM,v9.0)% skycoor -a 350.85 58.815 4.66116 61.87606\n #-66.791\n #rest@000d60780e33(SM,v9.0)% skycoor -a -9.15 58.815 4.66116 61.87606\n #66.791\n if ra1-ra2>180:\n ra2=ra2+360.0\n if ra1-ra2<-180:\n ra2=ra2-360.0\n\n #cmd = 'skycoor -a %f %f %f %f' % (ra1,dec1,ra2,dec2)\n cmd = 'skycoor -a %s %s %s %s' % (deg2sex(ra1,ra=True),deg2sex(dec1),deg2sex(ra2,ra=True),deg2sex(dec2))\n #print(cmd)\n errorflag,skycoorout = executecommand(cmd,'',verbose=0)\n if errorflag or len(skycoorout)<1:\n print(('ERROR: could not determine PA!',skycoorout))\n PA = None\n else:\n PA = float(skycoorout[0])\n if PA<0.0: PA+=360.0\n return PA\n\n# this routine moves length_arcsec along the position angle PA_deg from RA, DEC\n# PA:\n# 0..90 degree: NE quadrant\n# 90..180: SE quadrant\n# 0..-90: NW quadrant\n# -90..-180: SW quadrant\n# since skycoor has only accuracy to 1/1000 of degree, we can get the PA only to 3.6 arcsec\ndef moveRADEC(ra, dec, PA_deg, length_arcsec, precision_PA_arcsec = 3.6, precision_length_arcsec = 0.001, precision_arcsec=0.0001, verbose=0):\n deg2rad = 0.0174532925199 # math.pi / 180.0\n rad2deg = 57.2957795131 # 180.0 / math.pi\n arcsec2deg = 1.0/3600.0\n deg2arcsec = 3600.0\n\n PA_rad = PA_deg*deg2rad\n precision_PA_deg = precision_PA_arcsec * arcsec2deg\n precision_length_deg = precision_length_arcsec * arcsec2deg\n precision_deg = precision_arcsec * arcsec2deg\n length_deg = length_arcsec * arcsec2deg\n\n RAdeg = sex2deg(ra,ra=True)\n DECdeg = sex2deg(dec)\n if abs(DECdeg)>=90.0:\n print('ERROR: abs(Dec)>=90.0 are not allowed!')\n sys.exit(0)\n stopflag = 0\n cosDEC = math.cos(DECdeg*deg2rad)\n deltaRA = length_deg * math.sin(PA_rad)/cosDEC\n deltaDEC = length_deg * math.cos(PA_rad)\n iteration = 0\n if verbose>=2:\n print(('RA:%f DEC:%f PA:%.5f deg length:%.8f deg' % (RAdeg,DECdeg,PA_deg,length_deg)))\n while not stopflag:\n\n if verbose>=2:\n distance0 = skydist_degree(RAdeg,DECdeg,RAdeg+deltaRA,DECdeg+deltaDEC)\n\n PAtest_deg = calcPA(RAdeg,DECdeg,RAdeg+deltaRA,DECdeg+deltaDEC)\n if PAtest_deg-PA_deg>=90.0:PAtest_deg-=180.0\n if PAtest_deg-PA_deg<=-90.0:PAtest_deg+=180.0\n\n # First adjust the PA\n dDec = -length_deg*math.sin(PAtest_deg*deg2rad)*(PA_rad - PAtest_deg*deg2rad)\n dRa = length_deg*math.cos(PAtest_deg*deg2rad)*(PA_rad - PAtest_deg*deg2rad)/cosDEC\n\n deltaDEC += dDec\n deltaRA += dRa\n if abs(DECdeg+deltaDEC) >= 90:\n print('ERROR: the position is too close to the pole, not yet implemented!')\n return(2,None,None)\n\n if verbose>=2:\n PAtest1_deg = calcPA(RAdeg,DECdeg,RAdeg+deltaRA,DECdeg+deltaDEC)\n if PAtest1_deg-PA_deg>=90.0:PAtest1_deg-=180.0\n if PAtest1_deg-PA_deg<=-90.0:PAtest1_deg+=180.0\n distance1 = skydist_degree(RAdeg,DECdeg,RAdeg+deltaRA,DECdeg+deltaDEC)\n\n # Now adjust the length\n distance = skydist_degree(RAdeg,DECdeg,RAdeg+deltaRA,DECdeg+deltaDEC)\n distance_ratio = length_deg/distance\n deltaDEC *= distance_ratio\n deltaRA *= distance_ratio\n distance = skydist_degree(RAdeg,DECdeg,RAdeg+deltaRA,DECdeg+deltaDEC)\n\n if verbose>=2:\n PAtest2_deg = calcPA(RAdeg,DECdeg,RAdeg+deltaRA,DECdeg+deltaDEC)\n if PAtest2_deg-PA_deg>=90.0:PAtest2_deg-=180.0\n if PAtest2_deg-PA_deg<=-90.0:PAtest2_deg+=180.0\n distance2 = skydist_degree(RAdeg,DECdeg,RAdeg+deltaRA,DECdeg+deltaDEC)\n\n iteration +=1\n goodflag = (abs(length_deg - distance) < precision_length_deg) and (abs(PAtest_deg - PA_deg)<precision_PA_deg) \\\n or abs(dRa)+abs(dDec)<precision_deg\n\n stopflag = (iteration>=40) or goodflag\n\n if verbose==1:\n print(('iteration %d: %.8f %.8f -> %.8f %.8f (%.8e %.8e)' % (iteration,RAdeg,DECdeg,RAdeg+deltaRA,DECdeg+deltaDEC,dRa,dDec)))\n elif verbose >=2:\n print(('iteration %d: PA0:%.8f PA1:%.8f PA2:%.8f d0:%.8f d1:%.8f d2:%.8f deltaRa:%11.8f deltaDec:%11.8f (%.4e %.4e)' % (iteration,PAtest_deg,PAtest1_deg,PAtest2_deg,distance0,distance1,distance2,deltaRA,deltaDEC,dRa,dDec)))\n print(('(%.8e %.8e %.8e %.8e %.8e %.8e)' % (abs(length_deg - distance),precision_length_deg,abs(PAtest_deg - PA_deg),precision_PA_deg,abs(dRa)+abs(dDec),precision_deg)))\n\n\n #print('results:',RAdeg,DECdeg,RAdeg+deltaRA,DECdeg+deltaDEC)\n return(not goodflag,RAdeg+deltaRA,DECdeg+deltaDEC)\n\n\n### Converts sexigesimal notation to decimal degrees or decimal hours (if option 'ra=True' invoked)\ndef sex2deg(sexigecimal, ra=False):\n print(sexigecimal)\n ### 2005/12/02 - AR: make sure it is in sexagesimal format!\n # is it a string? if not check if it is None\n if not (type(sexigecimal) is str): #types.StringType):\n if type(sexigecimal) == None:\n raise RuntimeError(\"ERROR: sex2deg cannot handle 'None'!\")\n return sexigecimal\n # Does it have ':' or ' '? If not, it must be a float in string format, just convert it and return\n if re.search('\\:|\\s',sexigecimal) == None:\n return(float(sexigecimal))\n\n s1, s2, s3 = list(map(float, re.split('[DHMSdhms:\\s]', sexigecimal.strip())[0:3]))\n # Get the sign\n if re.search('-', sexigecimal):\n sign = -1\n else:\n sign = 1\n\n deg = abs(s1) + s2 / 60. + s3 / 3600.\n\n deg *= sign\n\n if ra:\n deg *= 15.\n\n return deg\n\n### Converts decimal degrees or hours (ra=True) to sexigesimal notation\n### [-+]DD:MM:SS.ss\n### the format is fixed at two decimals of precision for the decimal seconds.\n### No -/+ if ra=True\ndef deg2sex(degrees, ra=False, outputformatRA='%02d:%02d:%06.3f',outputformatDEC='%1s%02d:%02d:%05.2f'):\n if type(degrees) is str: # types.StringType:\n degrees=float(degrees)\n if ra:\n # a.k.a. indeg and outhours\n if degrees < 0.0:\n while degrees<0:degrees+=360.\n if degrees > 360.0:\n while degrees>360.0:degrees-=360.\n degrees /= 15.\n\n if degrees < 0:\n sign = '-'\n else:\n sign = '+'\n\n degrees = abs(degrees)\n\n d1 = (degrees - (degrees % 1))\n rem = (degrees % 1) * 60\n d2 = rem - (rem % 1)\n srem = (rem % 1) * 60\n d3 = srem\n\n if ra:\n return outputformatRA % (d1, d2, d3)\n else:\n return outputformatDEC % (sign, d1, d2, d3)\n\n# Returns the passed in RA in decimal degrees\n# input RA can be in 'HH:MM:SS.ss', 'HH MM SS.ss' or in decimal degrees\ndef RaInDeg(Ra):\n import types\n if type(Ra)==str: #types.StringType:\n if re.search('[DHMShms: ]',Ra.strip()):\n return(sex2deg(Ra,ra=True))\n return(float(Ra))\n else:\n return(Ra)\n\n# Returns the passed in Dec in decimal degrees\n# input Dec can be in 'DD:MM:SS.ss', 'DD MM SS.ss' or in decimal degrees\ndef DecInDeg(Dec):\n import types\n if type(Dec)==str:#types.StringType:\n if re.search('[DHMShms: ]',Dec.strip()):\n return(sex2deg(Dec,ra=False))\n return(float(Dec))\n else:\n return(Dec)\n\ndef executecommand(cmd,successword,errorlog=None,cmdlog=None,verbose=1):\n if verbose: print(('executing: ',cmd))\n\n# (cmd_in,cmd_out)=os.popen4(cmd)\n p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)\n cmd_in,cmd_out = p.stdin,p.stdout\n\n output = cmd_out.readlines()\n if successword=='':\n successflag = 1\n else:\n m = re.compile(successword)\n successflag = 0\n for line in output:\n if sys.version_info[0] >= 3:\n line = line.decode('utf-8')\n if m.search(line):\n successflag = 1\n errorflag = not successflag\n if errorflag:\n print(('error executing:',cmd))\n if errorlog != None:\n append2file(errorlog,['\\n error executing: '+cmd+'\\n'])\n append2file(errorlog,output)\n if cmdlog != None:\n append2file(cmdlog,['\\n error executing:',cmd])\n else:\n if cmdlog != None:\n append2file(cmdlog,[cmd])\n return errorflag, output\n\ndef append2file(filename,lines,verbose=0):\n if type(lines) is str:#types.StringType:\n lines = [lines,]\n if os.path.isfile(filename):\n buff = open(filename, 'a')\n else:\n buff = open(filename, 'w')\n r=re.compile('\\n$')\n for line in lines:\n if not r.search(line):\n buff.write(line+'\\n')\n if verbose: print((line+'\\n'))\n else:\n buff.write(line)\n if verbose: print(line)\n buff.close()\n\ndef makepath(path,raiseError=1):\n if path == '':\n return(0)\n if not os.path.isdir(path):\n os.makedirs(path)\n if not os.path.isdir(path):\n if raiseError == 1:\n raise RuntimeError('ERROR: Cannot create directory %s' % path)\n else:\n return(1)\n return(0)\n\ndef makepath4file(filename,raiseError=1):\n path = os.path.dirname(filename)\n if not os.path.isdir(path):\n return(makepath(path,raiseError=raiseError))\n else:\n return(0)\n\ndef hex2int(val):\n if type(val) is str:#types.StringType:\n val = int(eval(val))\n return(val)\n\ndef rmfile(filename,raiseError=1,gzip=False):\n \" if file exists, remove it \"\n if os.path.lexists(filename):\n os.remove(filename)\n if os.path.isfile(filename):\n if raiseError == 1:\n raise RuntimeError('ERROR: Cannot remove %s' % filename)\n else:\n return(1)\n if gzip and os.path.lexists(filename+'.gz'):\n os.remove(filename+'.gz')\n if os.path.isfile(filename+'.gz'):\n if raiseError == 1:\n raise RuntimeError('ERROR: Cannot remove %s' % filename+'.gz')\n else:\n return(2)\n return(0)\n\ndef rmfiles(filenames,raiseError=1,gzip=False):\n if not (type(filenames) is list):\n raise RuntimeError(\"List type expected as input to rmfiles\")\n errorflag = 0\n for filename in filenames:\n errorflag |= rmfile(filename,raiseError=raiseError,gzip=gzip)\n return(errorflag)\n\n# some little defs to compare lists and tuples\ndef unique(seq):\n if seq == None or seq == []: return []\n d = {}\n for x in seq:\n d[x] = 1\n return list(d.keys())\n\n# some little defs to compare lists and tuples\ndef unique_keeporder(seq):\n if seq == None or seq == []: return []\n d = {}\n for x in seq:\n d[x] = 0\n list = []\n for x in seq:\n d[x] += 1\n if d[x]==1:\n list.append(x)\n\n return list\n\ndef multiple(seq):\n if seq == None: return []\n d = {}\n for x in seq:\n if x in d:\n d[x] += 1\n else:\n d[x] = 1\n m = []\n for x in list(d.keys()):\n if d[x]>1:\n m.append(x)\n return m\n\ndef AnotB(A,B):\n \"returns elements that are in A, but not in B\"\n if A == None: return []\n if not (type(A) in [list,tuple]): A = [A,]\n if B == None: return A\n if not (type(B) in [list,tuple]): B = [B,]\n c = {}\n d = {}\n for x in A:\n c[x] = 1\n d[x] = 1\n for x in B:\n if x in c:\n if x in d:\n del(d[x])\n del c\n return list(d.keys())\n\ndef AorB(A,B):\n \"returns list of elements that are in A or in B\"\n if A == None and B == None: return []\n if B != None:\n if not (type(B) in [list,tuple]): B = [B,]\n if A != None:\n if not (type(A) in [list,tuple]): A = [A,]\n if A == None: return B\n if B == None: return A\n\n d = {}\n for x in A:\n d[x] = 1\n for x in B:\n d[x] = 1\n return list(d.keys())\n\n#def AandB(A,B):\n# \"returns list of elements that are in A and in B\"\n# if A == None or B == None: return []\n# if not (type(A) in [types.ListType,types.TupleType]): A = [A,]\n# if not (type(B) in [types.ListType,types.TupleType]): B = [B,]\n# c = {}\n# d = {}\n# for x in A:\n## c[x] = 1\n# for x in B:\n# if c.has_key(x):\n# d[x] = 1\n# del c\n# return d.keys()\n\ndef AandB(A,B):\n \"returns list of elements that are in A and in B, keeps the order from A\"\n if A == None or B == None: return []\n if not (type(A) in [list,tuple]): A = [A,]\n if not (type(B) in [list,tuple]): B = [B,]\n c = {}\n for x in B:\n c[x] = 0\n ablist = []\n for x in A:\n if x in c:\n ablist.append(x)\n c[x] = 1\n del c\n return ablist\n\ndef not_AandB(A,B):\n \"returns elements that are only in A or only in B\"\n if A == None or B == None: return self.AorB(A,B)\n if not (type(A) in [list,tuple]): A = [A,]\n if not (type(B) in [list,tuple]): B = [B,]\n d = {}\n for x in B:\n d[x] = 1\n for x in A:\n d[x] = 1\n crosssection = AandB(A,B)\n for x in crosssection:\n if x in d:\n del(d[x])\n return list(d.keys())\n\n#approximate sky dist (good for small angular distances not too close to pole)\ndef approxskydist_degree(ra1,dec1,ra2,dec2):\n deg2rad=0.0174532925199 # math.pi / 180.\n #convert all values to radians\n ra1 =RaInDeg(ra1)\n ra2 =RaInDeg(ra2)\n dec1=DecInDeg(dec1)\n dec2=DecInDeg(dec2)\n cosdec=min(abs(math.cos(dec1*deg2rad)),abs(math.cos(dec2*deg2rad)))\n return (math.sqrt(cosdec*cosdec*(ra2-ra1)*(ra2-ra1)+(dec2-dec1)*(dec2-dec1)))\n\n# true angular distance between two position in the sky\n#http://www2.sjsu.edu/faculty/watkins/sphere.htm\n#cos(A) = sin(phi2)sin(phi1)+ cos(phi2)cos(phi1)cos(theta2 - theta1)\n#longitude=theta=RA\n#latitude=phi=DEC\n#cos(A) = sin(DEC2)sin(DEC1)+ cos(DEC2)cos(DEC1)cos(RA2 - RA1)\n#works also at RA=0 etc:\n#skydist_degree(ra1,dec1,ra2,dec2) = skydist_degree(ra1+360,dec1+360,ra2-360,dec2-360) etc!\ndef skydist_degree(ra1,dec1,ra2,dec2):\n deg2rad=0.0174532925199 # math.pi / 180.\n #convert all values to radians\n ra1 =RaInDeg(ra1)*deg2rad\n ra2 =RaInDeg(ra2)*deg2rad\n dec1=DecInDeg(dec1)*deg2rad\n dec2=DecInDeg(dec2)*deg2rad\n if ((ra1==ra2) and (dec1==dec2)): return 0\n return math.acos(math.sin(dec2)*math.sin(dec1)+ math.cos(dec2)*math.cos(dec1)*math.cos(ra2 - ra1))*180.0/math.pi\n\ndef sphcor(decdeg):\n # spherical correction for RA distances as a function of dec\n # as in delta_radeg *= sphcor(decdeg)\n return math.cos(decdeg * math.pi / 180.)\n\n# returns a dictionary d[file][fitskey] containing the values of the fitskeys,\n# with file and fitskey from the filelist and keylist\n# if a file doesn't exist, d[file]=None, or exception raised if erroriffilenotexist\n# if a fitskey doesn't exist, then d[file][fitskey] == None, or exception raised if errorifkeynotexist\ndef getfitskeys(filelist,fitskeylist,erroriffilenotexist=True,errorifkeynotexist=False):\n if isinstance(filelist,six.string_types): filelist = [filelist,]\n if isinstance(fitskeylist,six.string_types): fitskeylist = [fitskeylist,]\n if not (type(fitskeylist) is list):\n raise RuntimeError('Error: def getfitskeys expects a list of fits keys')\n if not (type(filelist) is list):\n raise RuntimeError('Error: def getfitskeys expects a list of files')\n\n # GSN - 20100615 - replace -pau with -paub so that blanks in the fits keys don't cause a bork\n cmd = 'gethead -paub '\n filelist2use = []\n filelist2skip = []\n for file in filelist:\n if os.path.isfile(file):\n cmd = cmd + ' %s' % file\n filelist2use.append(file)\n else:\n if erroriffilenotexist:\n raise RuntimeError('ERROR: file %s does not exist!' % (file))\n filelist2skip.append(file)\n\n for fitskey in fitskeylist:\n cmd = cmd + ' %s' % fitskey\n #(gethead_in,gethead_out)=os.popen4(cmd)\n p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)\n gethead_in,gethead_out = p.stdin,p.stdout\n lines = gethead_out.readlines()\n\n if len(lines)!=len(filelist2use):\n for line in lines: print(line)\n raise RuntimeError('ERROR: something went wrong with '+cmd+'! output has different # of lines than there are files!')\n\n r = re.compile('[A-Z]+:')\n fitsvaldict = {}\n for i in range(len(lines)):\n lines[i] = lines[i].strip()\n entries = re.split('\\s+',lines[i].decode('utf-8'))\n # error checking\n if not (entries[0] == filelist2use[i]):\n raise RuntimeError('ERROR: something went wrong with %s! output has file %s, which is not equal to %s' % (cmd,entries[0],filelist2use[i]))\n if len(entries)-1 != len(fitskeylist):\n print(('parsed line:',entries))\n raise RuntimeError('ERROR: something went wrong with %s! file %s returned different number of values (%d) then fits keys (%d): %s' % (cmd,filelist2use[i],len(entries)-1,len(fitskeylist),lines[i]))\n if r.match(entries[1]):\n raise RuntimeError('ERROR: something went wrong with %s! There seems to be a gethead error message (%s) for file %s:' % (cmd,entries[1],filelist2use[i]))\n\n # fill the dictionary\n fitsvaldict[filelist2use[i]]={}\n for f in range(len(fitskeylist)):\n if entries[f+1] == '___':\n if errorifkeynotexist: # raise exception if wanted\n raise RuntimeError('ERROR: key %s does not exist in file %s!' % (fitskeylist[f],filelist2use[i]))\n entries[f+1] = None\n fitsvaldict[filelist2use[i]][fitskeylist[f]] = entries[f+1]\n\n # set the files that don't exist to None\n for file in filelist2skip: fitsvaldict[file] = None\n\n return(fitsvaldict)\n\ndef check4default(val,default):\n if val==\"default\":\n returnval=default\n else:\n returnval=val\n return(returnval)\n\n# returns c, so that f_ref = f *c, where f is the flux for a zeropoint\n# of ZPT, and f_ref is the corresponding flux at a zeropoint of ZPTref\ndef c_f2fref(ZPTref,ZPT):\n c = 10.0**(-0.4*(ZPT - ZPTref))\n return(c)\n\ndef mag2flux(mag, dmag, offset=0):\n flux = 10.**(-0.4 * (mag-offset))\n dflux = 0.4 * math.log(10.0) * dmag * flux\n return flux, dflux\n\ndef flux2mag(flux, dflux):\n mag = -2.5 * log10(flux)\n dmag = 2.5 / log(10.0) * dflux / flux\n return mag, dmag\n\ndef getkeys(hdr, comp):\n keys = []\n cstr = re.compile(comp)\n keys = hdr.getkeys(comp)\n return keys\n\ndef calcMJD(datetimestructure):\n # 1858-11-17 00:00:00.00 = MJD 0\n date0 = datetime.datetime(1858, 11, 17, 0, 0, 0, 0)\n delta = datetimestructure - date0\n MJD = delta.days + (delta.seconds + delta.microseconds / 1.e6) / 86400.\n return(MJD)\n\ndef returnMJD():\n import datetime\n now = datetime.datetime.now()\n\n # 1858-11-17 00:00:00.00 = MJD 0\n MJD0 = datetime.datetime(1858, 11, 17, 0, 0, 0, 0)\n\n delta = now - MJD0\n return delta.days + (delta.seconds + delta.microseconds / 1.e6) / 86400.\n\ndef pickledfilename(filename):\n if test4pickled(filename):\n return(filename)\n else:\n return(filename+'.pickled')\n\ndef unpickledfilename(filename):\n if test4pickled(filename):\n filename = re.sub('\\.pickled$','',filename)\n return(filename)\n else:\n return(filename)\n\ndef test4pickled(filename):\n if re.search('\\.pickled$',filename):\n return(1)\n else:\n return(0)\n\ndef pickleobject(object, outfile):\n f = open(outfile, 'w')\n p = pickle.Pickler(f)\n p.dump(object)\n f.close()\n\ndef unpickleobject(filename):\n f = open(filename, 'r')\n p = pickle.Unpickler(f)\n object = p.load()\n f.close()\n return object\n\ndef isfile_or_gz(filename,checkfilesize=False,checkdouble=False):\n isfileFlag = os.path.isfile(filename)\n if os.path.isfile(filename):\n if checkfilesize and os.path.getsize(filename)==0:\n return(False)\n if checkdouble and os.path.isfile(filename+'.gz'):\n return(False)\n return(True)\n if os.path.isfile(filename+'.gz'):\n if checkfilesize and os.path.getsize(filename+'.gz')==0:\n return(False)\n return(True)\n return(False)\n\ndef SetFitsKeywords(filename,args,options='',verbose=False):\n cmd = 'sethead %s %s %s 2>&1' % (filename,options,args)\n if verbose: print(cmd)\n so = os.popen(cmd)\n output = so.readlines()\n so.close()\n if len(output)>0:\n print(('ERROR: something went wrong setting the fits keywords with command %s:' % cmd))\n for line in output:\n print(line)\n return 1\n return 0\n\ndef GetFitsKeywords(filename,keywordlist,options='',verbose=False):\n if (not os.path.isfile(filename)):\n return 10,[]\n\n cmd = 'gethead -g %s %s' % (options,filename)\n for keyword in keywordlist:\n cmd += ' '+keyword\n cmd += ' 2>&1'\n if verbose: print(cmd)\n so = os.popen(cmd)\n output = so.readlines()\n so.close()\n if len(output)!=len(keywordlist):\n print(('ERROR: something went wrong getting the fits keywords with command %s, inconsistent number of output lines %d!=%d' % (cmd,len(output),len(keywordlist))))\n for line in output:\n print(line)\n return 11,[]\n errorflag = 0\n keyvals = []\n for i in range(len(output)):\n m = re.match('(%s)\\s*=\\s*(.*)' % keywordlist[i],output[i])\n if m and len(m.groups())==2:\n keytest = m.groups()[0]\n if keytest != keywordlist[i]:\n print(('ERROR: inconsistent keyword returned from gethead %s!=%s' % (keywordlist[i],keytest)))\n return 12,[]\n keyvals.append(m.groups()[1])\n else:\n if re.match('%s\\s+not\\s+found' % keywordlist[i],output[i]):\n keyvals.append(None)\n errorflag = 1\n else:\n print(('ERROR: something is wrong with keyword %s: %s' % (keywordlist[i],output[i])))\n return 13,[]\n return errorflag,keyvals\n\n# writeFits*: from actions.py\n\ndef writeFitsStamp(lc, lckey, fname, outfile, boxsizePix=200):\n fitsfile = lc.getentry(lckey, fname)\n if fitsfile == None:\n return 1\n\n ra = lc.getentry(lckey, 'Ra')\n dec = lc.getentry(lckey, 'Dec')\n chopstr = ','.join((ra, dec, str(boxsizePix)+'p'))\n cmdStr = ' '.join(('fitscopy -w', chopstr, fitsfile, outfile))\n print(cmdStr)\n cmd = command.Command(cmdStr)\n cmd.execute()\n\n if not os.path.isfile(outfile):\n print(('Problem saving', outfile))\n return 1\n\n return 0\n\n\ndef writeFitsStamps(lc, lckey, saveImAs=None, saveTmplAs=None, saveSubAs=None, boxsizePix=200):\n if saveImAs != None:\n writeFitsStamp(lc, lckey, 'longinimfitsfile', saveImAs, boxsizePix)\n if saveTmplAs != None:\n writeFitsStamp(lc, lckey, 'longtmplfitsfile', saveTmplAs, boxsizePix)\n if saveSubAs != None:\n writeFitsStamp(lc, lckey, 'longsubfitsfile', saveSubAs, boxsizePix)\n\n# Armin: HACK: temporary, I have to pass directly the fits filename\ndef writeFitsStampTemporary(fitsfile, ra, dec, outfile, boxsizePix=200):\n chopstr = ','.join((ra, dec, str(boxsizePix)+'p'))\n cmdStr = ' '.join(('fitscopy -w', chopstr, fitsfile, outfile))\n print(cmdStr)\n (cmd_in,cmd_out) = os.popen4(cmdStr)\n for line in cmd_out.readlines():\n print(('Potential problem saving', outfile,':',line))\n pass\n\n if not os.path.isfile(outfile):\n print(('Problem saving', outfile))\n return 1\n\n return 0\n\ndef writeAllImages(outname, fitsfiles, badimflag, ra, dec, size=150, nX=8, xhair=1,MJDbase=0.0,xflipflag=0):\n import imDisp\n from PIL import Image, ImageDraw, ImageFont\n #import numarray as num\n import numpy as num\n #import mx.DateTime\n\n print(('VVVVVVVVVVVVVVV',xflipflag))\n\n phot2filters= {0x00:'VR',0x02:'B',0x03:'V',0x04:'R',0x05:'I',\n 0x12:'u',0x13:'g',0x14:'r',0x15:'i',0x16:'z',0x17:'y'}\n \n\n font = 'helvB08.pil'\n #dfont = ImageFont.load_path(font)\n dfont = None\n\n nX = min(nX, len(fitsfiles))\n\n #nY = int(len(fitsfiles) / nX) + 1\n # Armin: above made two rows if nX=3 and len(fitsfiles)=3\n nY = int(len(fitsfiles) / nX)\n if len(fitsfiles) / float(nX) > nY:\n nY += 1\n\n buff1 = 2\n sizeX = nX * size + (nX - 1) * buff1\n sizeY = nY * size + (nY - 1) * buff1\n #comp = Image.new('L', (sizeX, sizeY), 255)\n comp = Image.new('RGB', (sizeX, sizeY), \"white\")\n\n X = 0\n Y = 0\n n = 0\n\n data = num.zeros((size, size))\n\n\n #print(\"FITSFILES: \", fitsfiles)\n for i in range(len(fitsfiles)):\n fitsfile = fitsfiles[i]\n if fitsfile == None:\n continue\n\n if not os.path.isfile(fitsfile):\n continue\n\n try:\n fptr = pyfits.open(fitsfile)\n except:\n print('ERROR: could not open fitsfile')\n continue\n\n ##\n # get header and scaling\n if fitsfile.endswith('diff.fits'):\n # these stats are not calculated anymore...\n skykey = 'DMEAN00'\n sigkey = 'DSIGE00'\n else:\n skykey = 'SKYADU'\n sigkey = 'SKYSIG'\n\n#\ttry:\n# # D. Jones - adjusting for new pyfits version\n#\t sky = float(skykey in fptr[0].header)\n#\t sky = float(fptr[0].header.has_key(skykey))\n#\texcept:\n#\t print('WACKY ERROR.. file exists but key index odd...',fitsfile)\n#\t continue\n\n if skykey in fptr[0].header:\n# if fptr[0].header.has_key(skykey):\n sky = float(fptr[0].header[skykey])\n #print('Found sky in header key %s: %.1f' % (skykey,sky))\n else:\n print(('WARNING! could not find sky %s in header of %s' % (skykey,fitsfile)))\n sky = 0.1\n\n if sigkey in fptr[0].header:\n# if fptr[0].header.has_key(sigkey):\n sigsky = float(fptr[0].header[sigkey])\n #print('Found skysig in header key %s: %.1f' % (sigkey,sigsky))\n else:\n sigsky = num.sqrt(sky)\n print(('WARNING! could not find skysig %s in header of %s' % (sigkey,fitsfile)))\n\n #print('Image %s: SKYADU:%.2f SKYSIG:%.2f' % (fitsfile,sky,sigsky))\n\n if 'FILTER' in fptr[0].header:\n filter = fptr[0].header['FILTER'][0:2]\n else:\n if 'PHOTCODE' in fptr[0].header:\n phot = hex2int(fptr[0].header['PHOTCODE']) & 0xff\n if phot in phot2filters:\n filter = phot2filters[phot]\n else:\n filter='n/a'\n datestr = None\n if 'MJD-OBS' in fptr[0].header:\n dateobject=Time(fptr[0].header['MJD-OBS'],format='mjd', scale='utc')\n datestr=dateobject.iso \n elif 'DATE-OBS' in fptr[0].header:\n# if fptr[0].header.has_key('DATE-OBS'):\n datestr = fptr[0].header['DATE-OBS']\n# elif 'DATE' in fptr[0].header:\n# elif fptr[0].header.has_key('DATE'):\n# datestr = fptr[0].header['DATE']\n #try:\n # date = mx.DateTime.DateTimeFrom(re.sub('[\\'T]', ' ', datestr))\n # datestr = date.date\n # mjdstr = date.mjd\n #except:\n # # This is a hack: DateTimeFrom does not take 60.0 seconds\n # temp = re.sub('60\\.0$', '59.99999999', datestr)\n # date = mx.DateTime.DateTimeFrom(re.sub('[\\'T]', ' ', temp))\n # datestr = date.date\n # mjdstr = date.mjd\n #label = \"%s : %8.2f : %s\" % (date.date, date.mjd-MJDbase, filter)\n\n diffimflag=0\n if 'TMPLSUBD' in fptr[0].header:\n# if fptr[0].header.has_key('TMPLSUBD'):\n diffimflag=1\n\n if datestr != None:\n #label = \"%s : %s\" % (datestr, filter)\n# label = \"%s :\" % (datestr, filter)\n# flabel = \"%s\" % (filter)\n label = \" : %s\" % (datestr)\n if diffimflag:\n flabel = \"%s\" % (filter)\n else:\n flabel = \"%s\" % (filter)\n else:\n #label = \"DATE UNKOWN: %s\" % (filter)\n label = \" : DATE UNKOWN\"\n xfits = fptr[0].header['NAXIS1']\n yfits = fptr[0].header['NAXIS2']\n\n #smax = sky + 2.5 * 1.5 * sigsky\n #smin = sky - 2.5 * 1.0 * sigsky\n if diffimflag:\n smax = sky + 2.5 * 1.5 * sigsky\n smin = sky - 2.5 * 1.0 * sigsky\n scaling = imDisp.LimLinearScale(smin, smax)\n else:\n smax = sky + 2.5 * 1.5 * sigsky\n smin = sky - 2.5 * 1.0 * sigsky\n scaling = imDisp.LimLinearScale(smin, smax)\n\n # get header and scaling\n ##\n\n ##\n # get data limits and data\n x, y = list(map(float, sky2xy(fitsfile, ra, dec)))\n\n xmin = int(x - size/2)\n xmax = xmin + size\n\n ymin = int(y - size/2)\n ymax = ymin + size\n\n if xmin > xfits or ymin > yfits:\n # off the image totally!\n continue\n\n ffx0 = max(1, xmin)\n ffy0 = max(1, ymin)\n ffx1 = min(xfits, xmax)\n ffy1 = min(yfits, ymax)\n\n arx0 = ffx0 - xmin\n ary0 = ffy0 - ymin\n arx1 = size - (xmax - ffx1)\n ary1 = size - (ymax - ffy1)\n\n\n\n data = num.zeros((size, size))\n try:\n data[ary0:ary1, arx0:arx1] = fptr[0].data[ffy0:ffy1, ffx0:ffx1].copy()\n except:\n data = num.zeros((size, size))\n\n # get data limits and data\n ##\n\n\n if xflipflag:\n print('imagecutout: XFLIP')\n im = Image.frombytes('P',(size, size), scaling(data).astype(num.int8).tobytes(),'raw','P').transpose(Image.FLIP_TOP_BOTTOM).transpose(Image.FLIP_LEFT_RIGHT)\n else:\n #im = Image.fromstring('P',(size, size), scaling(data).astype(num.int8).tostring(),'raw','P').transpose(Image.FLIP_TOP_BOTTOM)\n im = Image.frombytes('P',(size, size), scaling(data).astype(num.int8).tobytes(),'raw','P').transpose(Image.FLIP_TOP_BOTTOM)\n\n\n\n\n draw = ImageDraw.Draw(im)\n draw.rectangle([0, 0, size, 11], fill=128)\n #draw.text( [5, 0], label, font=dfont, fill=255)\n color=255\n fcolor=\"cyan\"\n if badimflag!=None:\n if badimflag[i]:\n color=\"red\"\n fcolor=color\n #draw.text( [5, 0], label, font=dfont, fill=color)\n\n ##draw.text( [5, 0], flabel, font=dfont, fill=fcolor)\n ##draw.text( [10, 0], label, font=dfont, fill=color)\n ##if diffimflag:\n ## draw.text( [5, 15], \"DIFF\", font=dfont, fill=fcolor)\n draw.text( [5, 0], flabel, fill=fcolor)\n draw.text( [10, 0], label, fill=color)\n if diffimflag:\n draw.text( [5, 15], \"DIFF\", fill=fcolor)\n\n if xhair:\n rad1 = 15\n rad2 = 25\n angle = math.sin(math.pi / 4.)\n\n #xc = xmin + (xmax - xmin) / 2\n #yc = ymin + (ymax - ymin) / 2\n xc = size / 2\n yc = size / 2\n\n for tx in [-1, 1]:\n for ty in [-1, 1]:\n x1 = xc + tx * rad1 * angle\n y1 = yc + ty * rad1 * angle\n x2 = xc + tx * rad2 * angle\n y2 = yc + ty * rad2 * angle\n #draw.line( [x1, y1, x2, y2], fill=255)\n #draw.line( [x1, y1, x2, y2], fill=\"red\",width=4.0)\n draw.line( [x1, y1, x2, y2], fill=fcolor,width=4)\n comp.paste(im, (X,Y))\n\n n += 1\n\n if n % nX == 0:\n X = 0\n Y += size + buff1\n else:\n X += size + buff1\n\n del im, draw\n fptr.close()\n\n comp.save(outname)\n del font, comp, data\n\n# Extend generic ConfigParser so that environment variables are substituted\nclass ConfigParser_env(SafeConfigParser):\n def __init__(self):\n SafeConfigParser.__init__(self)\n self.envvarpattern=re.compile('\\$(\\w+)')\n\n def getstring(self,section,paramname):\n s = self.subenvvarplaceholder(self.get(section,paramname))\n return(s)\n\n def gethex(self,section,paramname):\n val = int(eval(self.get(section,paramname)))\n return(val)\n\n def subenvvarplaceholder(self,s):\n envvarnames=self.envvarpattern.findall(s)\n if envvarnames:\n for name in envvarnames:\n envval=os.environ[name]\n subpattern='\\$%s' % (name)\n s = re.sub(subpattern,envval,s)\n return(s)\n\n def setval_nosection(self,option,val,allflag=False,throwerror=True):\n sections = self.sections()\n foundflag=False\n errorflag=False\n for section in sections:\n if self.has_option(section,option):\n errorflag = self.set(section,option,val)\n if errorflag!=None and throwerror:\n raise RuntimeError(\"ERROR %s %s %s\" % (section,option,val))\n foundflag=True\n if not allflag:\n break\n if (not foundflag) and throwerror:\n raise RuntimeError(\"ERROR: could not find section=%s, parameter=%s!\" % (section,option))\n\n return(not foundflag)\n\n def setvals_nosection(self,option_val_list,allflag=False,throwerror=True):\n if option_val_list == None: return(0)\n errorflag = False\n for (option,val) in option_val_list:\n errorflag |= self.setval_nosection(option,val,allflag=allflag,throwerror=throwerror)\n return(errorflag)\n\n def setvals(self,section_option_val_list,throwerror=True):\n if section_option_val_list == None: return(0)\n errorflagall = False\n for (section,option,val) in section_option_val_list:\n if not self.has_option(section,option):\n errorflagall = True\n if throwerror:\n raise RuntimeError(\"ERROR: section=%s, parameter=%s does not exist!\" % (section,option))\n continue\n errorflag = self.set(section,option,val)\n if errorflag != None:\n errorflagall = True\n if throwerror:\n raise RuntimeError(\"ERROR: could not set section=%s, parameter=%s to value %s!\" % (section,option,val))\n return(errorflagall)\n\nif __name__ == '__main__':\n ra = '00:00:00.01'\n dec = '00:00:00.01'\n\n\n",
"#!/usr/bin/env python\nimport sys, os, math, re, sys, copy\n# put the tools directory into the path\n#sys.path.append(os.path.join(os.environ['PIPE_PYTHONSCRIPTS'],'tools'))\n#sys.path.append(os.environ['PIPE_PYTHONSCRIPTS'])\nfrom texttable import txttableclass\nfrom tools import makepath4file\nimport argparse\nimport numpy as np\n\nclass calcexpclass(txttableclass):\n def __init__(self, *args, **kwargs):\n txttableclass.__init__(self, *args, **kwargs)\n\n self.verbose = False\n\n self.lc = txttableclass()\n self.lcfilters = []\n self.lc.magoffset = None\n\n self.phasecol = 'time'\n\n self.UVfilters = ['f218w','f225w','f275w','f336w']\n self.Ofilters = ['f438w','f606w','f814w']\n self.IRfilters = ['f110w','f160w']\n self.IRspec = ['WFC3_IR_G102','WFC3_IR_G141']\n self.NUVspec = ['WFC3_G280_2500','STIS_G230L_2500','STIS_PRISM_2500']\n self.FUVspec = ['STIS_PRISM_1500_SN3','STIS_G140L_1500_SN3']\n # which filter was used to calculate Spec exposure time\n self.filter4specmode = {'WFC3_IR_G102':'f110w','WFC3_IR_G141':'f110w','WFC3_G280_2500':'f275w','STIS_G230L_2500':'f275w','STIS_PRISM_2500':'f275w','STIS_PRISM_1500_SN3':'f218w','STIS_G140L_1500_SN3':'f218w'}\n\n self.UVoutcols = ['f218w','f225w','f275w','f336w']\n \n self.imaging_exptime = txttableclass()\n self.IRspec_exptime = txttableclass()\n self.UVspec_exptime = txttableclass()\n\n self.reftime = None\n self.reffilter = None\n self.refmag = None\n self.ref_d_Mpc = None\n \n self.dt_KN = None\n self.dt_trigger = None\n\n self.lc_maxmag = 31.0\n \n def norm2d(self,target_d_Mpc):\n\n self.ref_d_Mpc = target_d_Mpc\n \n self.lc.magoffset = +5.0*math.log10(target_d_Mpc*1E6)-5\n print('mag offset to %.0f Mpc: %.2f' % (target_d_Mpc,self.lc.magoffset))\n return(0)\n\n def norm2mag(self,norm2mag):\n (reftime,reffilter,refmag) = norm2mag\n \n self.reftime = float(reftime)\n self.reffilter = reffilter\n self.refmag = float(refmag)\n\n goodlckeys = self.lc.CUT_none_vals(self.reffilter)\n self.lc.initspline(self.phasecol,self.reffilter,keys=goodlckeys)\n m = self.lc.spline(self.reftime)\n self.lc.magoffset = self.refmag - m\n print('mag in filter %s at phase %.2f in lcfile %s: %.2f' % (self.reffilter,self.reftime,self.lc.filename,m))\n print('reference mag: %.2f, thus adding %.2f to all magnitudes of lc in lcfile' % (self.refmag,self.lc.magoffset))\n\n return(0)\n\n def apply_magoffset(self,magoffset=None):\n if magoffset is not None:\n self.lc.magoffset = magoffset\n \n if self.lc.magoffset is None:\n print('NO NORMALIZATION!!!')\n return(0)\n \n print('Applying magoffset %f' % self.lc.magoffset)\n for col in self.lc.cols:\n if re.search('^f',col)==None:\n continue\n print(col)\n for key in self.lc.allrowkeys:\n if self.lc.getentry(key,col)==None:\n continue\n #print(key,col,self.lc.getentry(key,col))\n self.lc.setentry(key,col,self.lc.getentry(key,col)+self.lc.magoffset)\n if self.verbose:\n self.lc.printtxttable()\n\n return(0)\n \n def loadlc(self,lcname):\n print('Loading %s' % lcname)\n self.lc.setpattern4undefined('^nan$') \n if self.lc.loadfile(lcname):\n raise RuntimeError(\"Could not load %s\" % lcname)\n self.lc.filename = lcname\n self.lc.configcols(self.phasecol,'f','%.2f')\n self.lcfilters = []\n for col in self.lc.cols:\n if (re.search('^f',col)==None) and (re.search(col,'UBVRIugriz')==None) and (not(col in ['uvw2','uvm2','uvw1'])):\n continue\n self.lcfilters.append(col)\n self.lc.configcols(col,'f','%.2f')\n # some of the faint mags get unreliable, remove them\n keys = self.lc.CUT_inrange(col,self.lc_maxmag,None)\n for key in keys: self.lc.setentry(key,col,None)\n print('lcfilters: '+','.join(self.lcfilters))\n return(0)\n\n def load_exptime_table(self,tt,filename):\n tt.setpattern4undefined('^nan$') \n print('Loading %s' % filename)\n if tt.loadfile(filename):\n raise RuntimeError(\"Could not load %s\" % filename)\n if 'mag' in tt.cols: tt.configcols('mag','f','%.1f')\n if 'm_f275w' in tt.cols: tt.configcols('m_f275w','f','%.1f')\n if 'm_f218w' in tt.cols: tt.configcols('m_f218w','f','%.1f')\n for col in tt.cols:\n if col in ['mag','m_f275w','m_f218w','_id','_mask']:continue\n print(col)\n tt.configcols(col,'f','%.0f')\n\n def load_imaging_exptime_table(self,filename):\n self.load_exptime_table(self.imaging_exptime,filename)\n if self.verbose:\n self.imaging_exptime.printtxttable()\n\n def load_IRspec_exptime_table(self):\n #Annalisa put the IR spec exposure times into the imaging exposure table. Let's just link them then...\n self.IRspec_exptime = self.imaging_exptime\n \n def load_UVspec_exptime_table(self,filename):\n #Annalisa put the IR spec exposure times into the imaging exposure table. Let's just link them then...\n self.load_exptime_table(self.UVspec_exptime,filename)\n if self.verbose:\n self.UVspec_exptime.printtxttable()\n \n def init_outputtable(self,phasemin,phasemax,phasestep,dt_KN,dt_trigger):\n if dt_KN==None:\n self.dt_KN = self.reftime\n else:\n self.dt_KN = dt_KN\n\n self.dt_trigger = dt_trigger\n \n self.configcols(['phaseGW','phaseKN','phaseTrig'],'f','%.2f',visible=1)\n for phaseGW in np.arange(phasemin,phasemax,phasestep):\n phaseKN = phaseGW - self.dt_KN\n phasetrigger = phaseKN - self.dt_trigger\n self.newrow({'phaseGW':phaseGW,'phaseKN':phaseKN,'phaseTrig':phasetrigger})\n #if self.verbose:\n # self.printtxttable()\n\n def calcexptime_UVspec(self,specmodes):\n for specmode in specmodes:\n reffilter = self.filter4specmode[specmode]\n magcol = 'm_%s' % reffilter\n #print('VVVV',specmodes,magcol,self.UVspec_exptime.cols,specmode)\n self.configcols(['t_%s' % specmode],'f','%.0f',visible=1)\n\n # init light curve spline for given filter\n # get the good keys (i.e. no none vals) for the given light curve\n goodlckeys = self.lc.CUT_none_vals(reffilter)\n self.lc.initspline(self.phasecol,reffilter,keys=goodlckeys)\n maxmag4lc = self.lc.maxentry(reffilter,keys=goodlckeys)+0.1\n maxphase4lc = self.lc.maxentry(self.phasecol,keys=goodlckeys)\n\n # get the good keys (i.e. no none vals) for the given specmode in the exposure time table\n goodkeys = self.UVspec_exptime.CUT_none_vals(specmode)\n # init the spline in the exposure time table for the given specmode\n self.UVspec_exptime.initspline(magcol,specmode,keys=goodkeys,interpolationtype='logspline')\n\n # get the maximum magnitude for which we have an exposure time value for given specmode\n maxmag4exptime = np.amin((maxmag4lc,self.UVspec_exptime.maxentry(magcol,keys=goodkeys)+0.1))\n if self.verbose:\n print('Max mag for %s:' % specmode,maxmag4exptime)\n \n for key in self.allrowkeys:\n m = self.lc.spline(self.getentry(key,'phaseGW'))\n if m<=maxmag4exptime:\n exptime = self.UVspec_exptime.spline(m)\n else:\n exptime = None\n # never go beyond what we have in the light curve\n if self.getentry(key,'phaseGW')>maxphase4lc:\n exptime = None\n #print(filt,self.getentry(key,'phaseGW'),m,exptime)\n self.setentry(key,'t_%s' % specmode,exptime)\n\n def calcexptime_IRspec(self):\n for specmode in self.IRspec:\n reffilter = self.filter4specmode[specmode]\n self.configcols(['t_%s' % specmode],'f','%.0f',visible=1)\n # init light curve spline for given filter\n goodlckeys = self.lc.CUT_none_vals(reffilter)\n self.lc.initspline(self.phasecol,reffilter,keys=goodlckeys)\n maxmag4lc = self.lc.maxentry(reffilter,keys=goodlckeys)+0.1\n maxphase4lc = self.lc.maxentry(self.phasecol,keys=goodlckeys)\n\n # get the good keys (i.e. no none vals) for the given specmode in the exposure time table\n goodkeys = self.IRspec_exptime.CUT_none_vals('t_%s' % specmode)\n\n # init the spline in the exposure time table for the given specmode\n self.IRspec_exptime.initspline('mag','t_%s' % specmode,keys=goodkeys,interpolationtype='logspline')\n\n # get the maximum magnitude for which we have an exposure time value for given specmode\n #maxmag4exptime = self.IRspec_exptime.maxentry('mag',keys=goodkeys)+0.1\n maxmag4exptime = np.amin((maxmag4lc,self.IRspec_exptime.maxentry('mag',keys=goodkeys)+0.1))\n if self.verbose:\n print('Max mag for t_%s:' % specmode,maxmag4exptime)\n \n #print 'VVV',specmode\n #if specmode == 'WFC3_IR_G102':\n # print np.arange(18.0,23.0,0.1)\n # for m in np.arange(18.0,23.0,0.1):\n # print m,self.IRspec_exptime.spline(m)\n # sys.exit(0)\n \n #print 'VVV',specmode,reffilter\n #if specmode == 'WFC3_IR_G102':\n # print np.arange(0.0,10.0,0.11)\n # for t in np.arange(0.0,10.0,0.11):\n # print t,self.lc.spline(t)\n # sys.exit(0)\n \n for key in self.allrowkeys:\n m = self.lc.spline(self.getentry(key,'phaseGW'))\n if m<=maxmag4exptime:\n exptime = self.IRspec_exptime.spline(m)\n else:\n exptime = None\n # never go beyond what we have in the light curve\n if self.getentry(key,'phaseGW')>maxphase4lc:\n exptime = None\n #print(filt,self.getentry(key,'phaseGW'),m,exptime)\n self.setentry(key,'t_%s' % specmode,exptime)\n \n def calcexptime_imaging(self):\n filters = copy.deepcopy(self.UVfilters)\n filters.extend(self.Ofilters)\n filters.extend(self.IRfilters)\n for filt in filters:\n # init new columns\n self.configcols(['m_%s' % filt],'f','%.2f',visible=1)\n self.configcols(['t_%s' % filt],'f','%.0f',visible=1)\n\n # init light curve spline for given filter\n goodlckeys = self.lc.CUT_none_vals(filt)\n self.lc.initspline(self.phasecol,filt,keys=goodlckeys)\n maxmag4lc = self.lc.maxentry(filt,keys=goodlckeys)+0.1\n maxphase4lc = self.lc.maxentry(self.phasecol,keys=goodlckeys)\n\n # get the good keys (i.e. no none vals) for the given filter in the exposure time table\n goodkeys = self.imaging_exptime.CUT_none_vals('t_%s' % filt)\n\n # init the spline in the exposure time table for the given filter\n self.imaging_exptime.initspline('mag','t_%s' % filt,keys=goodkeys,interpolationtype='logspline')\n\n # get the maximum magnitude for which we have an exposure time value for given filter\n #maxmag4exptime = self.imaging_exptime.maxentry('mag',keys=goodkeys)+0.1\n maxmag4exptime = np.amin((maxmag4lc,self.imaging_exptime.maxentry('mag',keys=goodkeys)+0.1))\n if self.verbose:\n print('Max mag for t_%s:' % filt,maxmag4exptime)\n\n for key in self.allrowkeys:\n #print(self.getentry(key,'phaseGW'),filt)\n m = self.lc.spline(self.getentry(key,'phaseGW'))\n if m<=maxmag4exptime:\n exptime = self.imaging_exptime.spline(m)\n else:\n exptime = None\n\n #print(self.getentry(key,'phaseGW'),maxphase4lc,m,maxmag4lc,maxmag4exptime)\n # never go beyond what we have in the light curve\n if self.getentry(key,'phaseGW')>maxphase4lc:\n m = None\n exptime = None\n #print(filt,self.getentry(key,'phaseGW'),m,exptime)\n self.setentry(key,'m_%s' % filt,m)\n self.setentry(key,'t_%s' % filt,exptime)\n\n\n def getoutputcols_imaging(self, filts, showmags=False):\n cols=[]\n for filt in filts:\n if showmags:\n cols.append('m_%s' % filt)\n cols.append('t_%s' % filt)\n return(cols)\n \n def getoutputcols(self, showmags=False, saveNUV=True, saveFUV=False, saveIR=False, saveO=False, skip_savespec=False):\n cols = ['phaseGW','phaseKN','phaseTrig']\n if saveNUV:\n cols.extend(self.getoutputcols_imaging(self.UVfilters,showmags=showmags))\n if not skip_savespec:\n for specmode in self.NUVspec:\n cols.append('t_%s' % specmode)\n if saveFUV and (not skip_savespec):\n for specmode in self.FUVspec:\n cols.append('t_%s' % specmode)\n if saveO:\n cols.extend(self.getoutputcols_imaging(self.Ofilters,showmags=showmags))\n if saveIR:\n cols.extend(self.getoutputcols_imaging(self.IRfilters,showmags=showmags))\n if not skip_savespec:\n for specmode in self.IRspec:\n cols.append('t_%s' % specmode)\n \n return(cols)\n \n \n def savetable(self,cols=None):\n if cols is None:\n print('WARNING: No columns to save!! returning...')\n return(1)\n makepath4file(self.outbasename)\n print('Saving %s' % '%s.txt' % self.outbasename)\n self.save2file('%s.txt' % self.outbasename,cols=cols)\n\n return(0)\n \n def savelatextable(self, tt, outfilename=None, cols=None):\n if cols is None:\n print('WARNING: No columns to save!! returning...')\n return(1)\n\n if outfilename==None:\n outfilename = '%s.tex' % self.outbasename\n \n makepath4file(outfilename)\n tt.outputundefined='$\\dots$' \n for col in cols:\n if re.search('^t_',col) or (col in self.FUVspec) or (col in self.NUVspec) or (col in self.IRspec) :\n tt.setcol2latexphantom(col,latexphantomflag=True)\n\n print('Saving %s' % outfilename)\n tt.save2plaintextable(outfilename,cols=cols)\n\n tt.outputundefined='-'\n for col in cols:\n tt.setcol2latexphantom(col,latexphantomflag=False)\n \n return(0)\n \n def setoutbasename(self,outrootdir=None,outsubdir=None,outbasename=None,addsuffix=None,skip_refinfo=False):\n if outrootdir == None:\n outrootdir = '.'\n s = os.path.abspath(outrootdir)\n if outsubdir is not None:\n s += '/%s' % outsubdir\n if outbasename is None:\n (outbasename,suffix) = os.path.splitext(os.path.basename(self.lc.filename))\n if self.lc.magoffset is not None:\n # remove references to the distance from output filename\n m = re.search('([\\_|\\.]*)\\d+Mpc([\\_|\\.]*)',outbasename)\n if m is not None:\n l = len(m.groups()[0])+len(m.groups()[1])\n print(l)\n if l==0:\n outbasename = re.sub('[\\_|\\.]*\\d+Mpc[\\_|\\.]*','',outbasename)\n elif l==1:\n outbasename = re.sub('[\\_|\\.]*\\d+Mpc[\\_|\\.]*','',outbasename)\n elif l>=2:\n outbasename = re.sub('[\\_|\\.]*\\d+Mpc[\\_|\\.]*','_',outbasename)\n \n\n s += '/%s' % outbasename\n\n if not skip_refinfo:\n if self.reftime is not None:\n s+='_t%.2f_%s_%.2f' % (self.reftime,self.reffilter,self.refmag)\n elif self.ref_d_Mpc is not None:\n s+='_%.0fMpc' % (self.ref_d_Mpc)\n else:\n RuntimeError('Cannot add ref info into the outbasename!')\n\n if addsuffix is not None:\n s += '.%s' % addsuffix\n\n self.outbasename = s\n print('outbasename: %s' % self.outbasename)\n return(0)\n \nif __name__ == '__main__':\n calcExp = calcexpclass()\n\n parser = argparse.ArgumentParser()\n\n \n parser.add_argument(\"--norm2d\", type=float, help=(\"target distance in Mpc: if \\d+Mpc is in the filename, then it is used as input distance, otherwise it is assumed that it is in absolute mags.\"))\n parser.add_argument(\"--norm2mag\",nargs=3, help=(\"phase filter mag: normalizes lightcurves so that it has mag in filter at phase.\"))\n #time difference between KN and to GW discovery in days, reference filter, reference mag\"\n #parser.add_argument(\"reftime\", type=float, help=(\"time difference between KN and to GW discovery in days\"))\n #parser.add_argument(\"reffilter\", help=(\"reference filter\"))\n #parser.add_argument(\"refmag\", type=float, help=(\"reference mag in reference filter\"))\n\n parser.add_argument('-v', '--verbose', help=\"verbose level (default=%(default)s)\",\n action=\"store_true\", default=False)\n parser.add_argument('-m', '--showmags', help=\"show the mags in the output tex table (default=%(default)s)\",\n action=\"store_true\", default=False)\n parser.add_argument( '--savetable', help=\"save the table. columns depend on --saveNUV, --saveIR etc\",\n action=\"store_true\", default=False)\n parser.add_argument( '--savelatex', help=\"save the latex table\",\n action=\"store_true\", default=False)\n parser.add_argument( '--saveNUV', help=\"save NUV info into output\",\n action=\"store_true\", default=False)\n parser.add_argument( '--saveFUV', help=\"save FUV info into output\",\n action=\"store_true\", default=False)\n parser.add_argument( '--saveIR', help=\"save IR info into output\",\n action=\"store_true\", default=False)\n parser.add_argument( '--saveO', help=\"save optical info into output\",\n action=\"store_true\", default=False)\n parser.add_argument( '--skip_savespec', help=\"Skip the spec info in the output\",\n action=\"store_true\", default=False)\n\n #parser.add_argument('--lc', default='./GW170817_40Mpc.txt',\n# parser.add_argument('--lc', default='./kilonova_phottable_gw170817_40Mpc.txt',\n parser.add_argument('--lc', default='./models/KasenModels_AbsMag/gw170817_boosted.txt',\n help='lightcurve filename (default=%(default)s)')\n parser.add_argument('--imaging_IRspec_exptime', default='./exp_times_imaging_IRgrism.txt',\n help='exposure time table for imaging and NIR Grism spectroscopy (default=%(default)s)')\n parser.add_argument('--UVspec_exptime', default='./exp_times_UVspec.txt',\n help='exposure time table for UV spectroscopy (default=%(default)s)')\n\n parser.add_argument(\"--addoutsuffix\", default=None, help=(\"time difference between KN and GW discovery in days. If not specified, then it is assumed that dt_KN=reftime\"))\n\n parser.add_argument(\"--dt_KN\", type=float, default=None, help=(\"time difference between KN and GW discovery in days. If not specified, then it is assumed that dt_KN=reftime\"))\n parser.add_argument(\"--dt_trigger\", type=float, default=0.1, help=(\"time difference between HST trigger and KN discovery in days\"))\n parser.add_argument(\"--phasemin\", type=float, default=0.0, help=(\"minimum phase since GW discovery in days (default=%(default)s)\"))\n parser.add_argument(\"--phasemax\", type=float, default=14.1, help=(\"maximum phase since GW discovery in days (default=%(default)s)\"))\n parser.add_argument(\"--phasestep\", type=float, default=0.5, help=(\"phase stepsize in days (default=%(default)s)\"))\n\n parser.add_argument('--outrootdir', default=None,\n help=('output root directory.'\n '(default=%(default)s)'))\n parser.add_argument('--outbasename', default=None,\n help=('output basename. If None, then the basename of input lc is taken'\n '(default=%(default)s)'))\n parser.add_argument('--outsubdir', default=None,\n help=('subdir added to the output root directory (and filename) '\n '(default=%(default)s)'))\n parser.add_argument('--addsuffix', default=None,\n help='suffix added to the output basename (default=%(default)s)')\n parser.add_argument('--skip_refinfo', help=\"Skip putting the ref info (reftime, refmag, reffilter) into the filename (default=%(default)s)\",\n action=\"store_true\", default=False)\n\n\n \n args = parser.parse_args()\n calcExp.verbose=args.verbose\n\n # load lightcurve table and calculate delta mag to move light curves to reference mag in reference filter\n calcExp.loadlc(args.lc)\n #calcExp.calc_magoffset(args.reftime,args.reffilter,args.refmag)\n if args.norm2mag is not None: \n calcExp.norm2mag(args.norm2mag)\n if args.norm2d is not None: \n calcExp.norm2d(args.norm2d)\n \n calcExp.apply_magoffset()\n\n calcExp.setoutbasename(outrootdir=args.outrootdir,outsubdir=args.outsubdir,\n outbasename=args.outbasename,addsuffix=args.addsuffix,\n skip_refinfo=args.skip_refinfo)\n # load imaging exposure time tables\n calcExp.load_imaging_exptime_table(args.imaging_IRspec_exptime)\n # load IRspec exposure time tables\n calcExp.load_IRspec_exptime_table()\n # load UVspec exposure time tables\n calcExp.load_UVspec_exptime_table(args.UVspec_exptime)\n\n if 1==1:\n outputdir=os.path.dirname(calcExp.outbasename)\n calcExp.savelatextable(calcExp.imaging_exptime,outfilename='%s/UVim_exptime.tex' % outputdir,cols=['mag','t_f218w','t_f225w','t_f275w','t_f336w'])\n calcExp.savelatextable(calcExp.IRspec_exptime,outfilename='%s/IR_exptime.tex' % outputdir,cols=['mag','t_f110w','t_f160w','t_WFC3_IR_G102','t_WFC3_IR_G141'])\n calcExp.savelatextable(calcExp.UVspec_exptime,outfilename='%s/UV_exptime.tex' % outputdir,cols=['m_f275w','WFC3_G280_2500','STIS_G230L_2500','STIS_PRISM_2500','m_f218w','STIS_PRISM_1500_SN3','STIS_G140L_1500_SN3'])\n calcExp.savelatextable(calcExp.UVspec_exptime,outfilename='%s/NUV_exptime.tex' % outputdir,cols=['m_f275w','WFC3_G280_2500','STIS_G230L_2500','STIS_PRISM_2500'])\n calcExp.savelatextable(calcExp.UVspec_exptime,outfilename='%s/FUV_exptime.tex' % outputdir,cols=['m_f218w','STIS_PRISM_1500_SN3','STIS_G140L_1500_SN3'])\n \n #initialize the output table: calculate the phases\n calcExp.init_outputtable(args.phasemin,args.phasemax,args.phasestep,args.dt_KN,args.dt_trigger)\n\n # fill up output table with imaging exposure times and mags\n calcExp.calcexptime_imaging()\n\n # fill up output table with IR spec exposure times \n calcExp.calcexptime_IRspec()\n\n # fill up output table with UV spec exposure times \n calcExp.calcexptime_UVspec(calcExp.NUVspec)\n calcExp.calcexptime_UVspec(calcExp.FUVspec)\n\n outcols = calcExp.getoutputcols(showmags=args.showmags, saveNUV=args.saveNUV, saveFUV=args.saveFUV, saveIR=args.saveIR, saveO=args.saveO, skip_savespec=args.skip_savespec)\n \n if calcExp.verbose:\n calcExp.printtxttable(cols=outcols)\n\n # Save the table\n if args.savetable:\n calcExp.savetable(cols=outcols)\n\n # Save the latextable\n if args.savelatex:\n calcExp.savelatextable(calcExp,cols=outcols)\n"
] |
[
[
"numpy.zeros",
"numpy.sqrt"
],
[
"numpy.arange"
]
] |
Notselwyn/NEAT-Car-Racing
|
[
"74e272c6ce0c1fc6ca978dae45970765f644d711"
] |
[
"stats.py"
] |
[
"from http.server import BaseHTTPRequestHandler, HTTPServer\r\nimport json\r\nimport matplotlib.pyplot as plt\r\n\r\nglobal avg_performance_list\r\nglobal best_performance_list\r\nglobal genome_count_list\r\nglobal gen_performance_list\r\nglobal manager\r\n\r\n\r\nclass Graph:\r\n def __init__(self, title, ylabel):\r\n self.figure, self.ax = plt.subplots()\r\n self.lines, = self.ax.plot([], [])\r\n self.ax.set_xlabel(\"Generation\")\r\n self.ax.set_ylabel(ylabel)\r\n self.ax.set_title(title)\r\n self.ax.grid()\r\n self.update([], 0)\r\n\r\n\r\n def update(self, arr, gen):\r\n self.lines.set_xdata(range(int(gen)))\r\n self.lines.set_ydata(arr)\r\n if len(arr) != 0:\r\n self.ax.set_xlim(0, int(gen))\r\n self.ax.set_ylim(0, int(max(arr)*1.10))\r\n self.ax.relim()\r\n self.figure.canvas.draw()\r\n self.figure.canvas.flush_events()\r\n\r\n\r\nclass Manager:\r\n def __init__(self, labels: list[tuple]):\r\n plt.ion()\r\n self.graphs = []\r\n for ylabel, title in labels:\r\n self.graphs.append(Graph(title, ylabel))\r\n\r\n def update(self, data: list[tuple]):\r\n for pos, (data_arr, gen) in enumerate(data):\r\n self.graphs[pos].update(data_arr, gen)\r\n\r\n\r\nclass MessageHandler(BaseHTTPRequestHandler):\r\n def do_POST(self):\r\n global avg_performance_list\r\n global best_performance_list\r\n global genome_count_list\r\n global gen_performance_list\r\n global manager\r\n\r\n self.send_response(200)\r\n length = int(self.headers.get('Content-length', 0))\r\n data = json.loads(self.rfile.read(length).decode())\r\n avg_performance_list += [data[\"af\"]]\r\n best_performance_list += [data[\"bf\"]]\r\n genome_count_list += [data[\"gc\"]]\r\n gen_performance_list += [data[\"gbf\"]]\r\n generation = data[\"gen\"]\r\n manager.update(((genome_count_list, generation),\r\n (gen_performance_list, generation),\r\n (best_performance_list, generation),\r\n (avg_performance_list, generation)))\r\n\r\n print(f\"Added data: {data}\")\r\n\r\n\r\ndef neat_stats():\r\n global avg_performance_list\r\n global best_performance_list\r\n global genome_count_list\r\n global gen_performance_list\r\n global manager\r\n\r\n best_performance_list = []\r\n genome_count_list = []\r\n gen_performance_list = []\r\n avg_performance_list = []\r\n manager = Manager(((\"Genomes\", \"Genome Count\"),\r\n (\"Fitness\", \"Best Fitness Per Generation\"),\r\n (\"Fitness\", \"Best Fitness All Time\"),\r\n (\"Fitness\", \"Average Fitness Per Generation\")))\r\n\r\n server_address = (\"127.0.0.1\", 1234)\r\n httpd = HTTPServer(server_address, MessageHandler)\r\n print(\"Booted stats listener: waiting for requests\")\r\n httpd.serve_forever()"
] |
[
[
"matplotlib.pyplot.ion",
"matplotlib.pyplot.subplots"
]
] |
cjy513203427/SML_Assignment
|
[
"630e5b73d2ce222f4adb29f91d2ee3007f8972ff"
] |
[
"assignment3/code/lr_1c.py"
] |
[
"# -*- encoding: utf-8 -*-\n'''\n@File : lr_1c.py \n@Modify Time @Author @Desciption\n------------ ------- -----------\n2021/7/5 18:30 Jonas None\n'''\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ntrain_data = np.loadtxt(\"lin_reg_train.txt\")\ntest_data = np.loadtxt(\"lin_reg_test.txt\")\n\n# get value of X and y\ndef Xy(data):\n n = len(data)\n X = np.zeros((2, n))\n y = np.zeros((n, 1))\n for i in range(0, n):\n X[0, i] = data[i, 0]\n X[1, i] = 1\n y[i, 0] = data[i, 1]\n\n return X, y\n\n# lamda @ I\ndef lambda_I(alpha, beta):\n c = alpha / beta\n I = np.zeros((2, 2))\n for i in range(0, 2):\n I[i][i] = c\n\n return I\n\n# get w\ndef parameter_posterior(X, y, ci):\n return np.linalg.inv(X @ X.T + ci) @ X @ y\n\ndef predicted_value(x, w):\n # y = np.empty((len(x), 1))\n # for i in range(0, len(y)):\n # y[i] = x[i] @ w\n #\n # return y\n\n x_transpose = np.transpose(x)\n x_i=np.empty((1,2))\n y=np.empty((len(x_transpose),1))\n for i in range(0,len(y)):\n x_i=x_transpose[i]\n y[i]=np.matmul(x_i,w)\n return y\n\ndef RMSE(y_pre, y):\n n = len(y_pre)\n sum = 0\n for i in range(0, n):\n sum = sum + (y_pre[i] - y[i]) ** 2\n result = (sum / n) ** 0.5\n\n return result\n\ndef square(x_train, x_test, a, B):\n # lecture08 Page50\n # square = 1/B + x_test.T @ np.linalg.inv(B * x_train @ x_train.T + alphaI) @ x_test\n x_transpose = np.transpose(x_train)\n x_test_transpose = np.transpose(x_test)\n B_xx = B * (x_train @ x_transpose)\n square = np.zeros((len(x_test_transpose), 1))\n aI = np.zeros((2, 2))\n for j in range(0, 2):\n aI[j][j] = a\n inverse = np.linalg.inv((aI + B_xx))\n for i in range(0, len(square)):\n x = x_test_transpose[i]\n x_t = np.transpose(x)\n square[i] = (1/B) + x @ inverse @ x_t\n\n\n\n return square\n\ndef Gaussian(mean, square, y_data):\n p = np.empty((len(mean), 1))\n for i in range(0, len(square)):\n p1 = 1 / math.sqrt(2 * math.pi * square[i])\n p2 = ((-1) * pow((y_data[i] - mean[i]), 2)) / (2 * square[i])\n p[i] = p1 * math.exp(p2)\n\n return p\n\ndef average_log_likelihood(p):\n for i in range(len(p)):\n if i == 0:\n sum_y = np.log(p[i])\n else:\n sum_y = sum_y + np.log(p[i])\n\n average = sum_y / len(p)\n return average\n\nif __name__ == '__main__':\n\n x_train, y_train = Xy(train_data)\n x_test, y_test = Xy(test_data)\n\n alpha = 0.01\n beta = 1 / (0.1 ** 2)\n ci = lambda_I(alpha, beta)\n w_posterior = parameter_posterior(x_train, y_train, ci)\n test_predicted_value = predicted_value(x_test, w_posterior)\n\n test_p = Gaussian(test_predicted_value, square(x_train, x_test, alpha, beta), y_test)\n log_l_test = average_log_likelihood(test_p)\n print(\"the log-likelihood of the test is\"+str(log_l_test))\n print(\"rmse test is\"+str(RMSE(test_predicted_value, y_test)))\n\n w_posterior_train = parameter_posterior(x_train, y_train, ci)\n train_predicted_value = predicted_value(x_train, w_posterior_train)\n train_p = Gaussian(train_predicted_value, square(x_train, x_train, alpha, beta), y_train)\n\n log_l_train = average_log_likelihood(train_p)\n print(\"the log-likelihood of the train is\"+str(log_l_train))\n print(\"rmse train is\" + str(RMSE(train_predicted_value, y_train)))\n\n x_ = np.linspace(np.min(x_train[0]), np.max(x_train[1]), num = 100).reshape(100, 1)\n x_ = np.concatenate([x_, np.ones(100).reshape(100, 1)], axis=1)\n y_ = predicted_value(x_.T, w_posterior)\n\n sig_ = square(x_.T, x_.T, alpha, beta)\n sig_ = np.sqrt(sig_)\n\n plt.scatter(x_.T[0], y_, c = 'blue', label = 'prediction')\n plt.scatter(x_train[0], y_train, c = 'black', label = 'original train data points')\n for i in range(3):\n plt.fill_between(x_.T[0], y_.reshape(100) + sig_.reshape(100) * (i+1),\n y_.reshape(100) - sig_.reshape(100) * (i+1),\n color = \"b\", alpha = 0.4)\n plt.title(\"Bayesian Linear Regression\")\n plt.xlabel('x')\n plt.ylabel('y')\n\n plt.legend\n plt.show()"
] |
[
[
"numpy.log",
"numpy.sqrt",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title",
"numpy.linalg.inv",
"numpy.min",
"numpy.matmul",
"numpy.ones",
"numpy.max",
"numpy.loadtxt",
"numpy.transpose",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"numpy.zeros",
"numpy.empty",
"matplotlib.pyplot.ylabel"
]
] |
sjtututu/QAStrategy
|
[
"ed6548d6bd2c4cf086ac021fc10f2107921950f0"
] |
[
"QAStrategy/qactabase.py"
] |
[
"import datetime\nimport json\nimport os\nimport re\nimport sys\nimport threading\nimport time\nimport copy\nimport uuid\n\nimport pandas as pd\nimport pymongo\nimport requests\nfrom qaenv import (eventmq_amqp, eventmq_ip, eventmq_password, eventmq_port,\n eventmq_username, mongo_ip, mongo_uri)\n\nimport QUANTAXIS as QA\nfrom QAPUBSUB.consumer import subscriber, subscriber_routing, subscriber_topic\nfrom QAPUBSUB.producer import publisher_routing\nfrom QAStrategy.util import QA_data_futuremin_resample\nfrom QIFIAccount import ORDER_DIRECTION, QIFI_Account\nfrom QUANTAXIS.QAARP import QA_Risk, QA_User\nfrom QUANTAXIS.QAEngine.QAThreadEngine import QA_Thread\nfrom QUANTAXIS.QAUtil.QAParameter import MARKET_TYPE, RUNNING_ENVIRONMENT\n\n\nclass QAStrategyCTABase():\n def __init__(self, code='rb1905', frequence='1min', strategy_id='QA_STRATEGY', risk_check_gap=1, portfolio='default',\n start='2019-01-01', end='2019-10-21', init_cash=1000000, send_wx=False,\n data_host=eventmq_ip, data_port=eventmq_port, data_user=eventmq_username, data_password=eventmq_password,\n trade_host=eventmq_ip, trade_port=eventmq_port, trade_user=eventmq_username, trade_password=eventmq_password,\n taskid=None, mongo_ip=mongo_ip):\n\n self.trade_host = trade_host\n\n self.code = code\n self.frequence = frequence\n self.strategy_id = strategy_id\n\n self.portfolio = portfolio\n\n self.data_host = data_host\n self.data_port = data_port\n self.data_user = data_user\n self.data_password = data_password\n self.trade_host = trade_host\n self.trade_port = trade_port\n self.trade_user = trade_user\n self.trade_password = trade_password\n\n self.start = start\n self.end = end\n self.init_cash = init_cash\n self.taskid = taskid\n\n self.running_time = ''\n\n self.market_preset = QA.QAARP.MARKET_PRESET()\n self._market_data = []\n self.risk_check_gap = risk_check_gap\n self.latest_price = {}\n\n self.isupdate = False\n self.new_data = {}\n self._systemvar = {}\n self._signal = []\n self.send_wx = send_wx\n self.last_order_towards = {'BUY': '', 'SELL': ''}\n self.dt = ''\n if isinstance(self.code, str):\n self.market_type = MARKET_TYPE.FUTURE_CN if re.search(\n r'[a-zA-z]+', self.code) else MARKET_TYPE.STOCK_CN\n else:\n self.market_type = MARKET_TYPE.FUTURE_CN if re.search(\n r'[a-zA-z]+', self.code[0]) else MARKET_TYPE.STOCK_CN\n\n self.bar_order = {'BUY_OPEN': 0, 'SELL_OPEN': 0,\n 'BUY_CLOSE': 0, 'SELL_CLOSE': 0}\n\n self._num_cached = 120 \n self._cached_data = [] \n\n @property\n def bar_id(self):\n return len(self._market_data)\n\n def _debug_sim(self):\n\n self.running_mode = 'sim'\n\n if self.frequence.endswith('min'):\n self._old_data = QA.QA_fetch_get_future_min('tdx', self.code.upper(), QA.QA_util_get_last_day(\n QA.QA_util_get_real_date(str(datetime.date.today()))), str(datetime.datetime.now()), self.frequence)[:-1].set_index(['datetime', 'code'])\n self._old_data = self._old_data.assign(volume=self._old_data.trade).loc[:, [\n 'open', 'high', 'low', 'close', 'volume']]\n else:\n self._old_data = pd.DataFrame()\n\n self.database = pymongo.MongoClient(mongo_ip).QAREALTIME\n\n self.client = self.database.account\n self.subscriber_client = self.database.subscribe\n\n self.acc = QIFI_Account(\n username=self.strategy_id, password=self.strategy_id, trade_host=mongo_ip, init_cash=self.init_cash)\n self.acc.initial()\n\n self.pub = publisher_routing(exchange='QAORDER_ROUTER', host=self.trade_host,\n port=self.trade_port, user=self.trade_user, password=self.trade_password)\n\n self.subscribe_data(self.code.lower(), self.frequence, self.data_host,\n self.data_port, self.data_user, self.data_password)\n\n self.database.strategy_schedule.job_control.update(\n {'strategy_id': self.strategy_id},\n {'strategy_id': self.strategy_id, 'taskid': self.taskid,\n 'filepath': os.path.abspath(__file__), 'status': 200}, upsert=True)\n\n def debug_sim(self):\n self._debug_sim()\n threading.Thread(target=self.sub.start, daemon=True).start()\n\n def run_sim(self):\n self._debug_sim()\n\n self.sub.start()\n\n def run_backtest(self):\n self.debug()\n self.acc.save()\n\n risk = QA_Risk(self.acc)\n risk.save()\n\n try:\n \"\"\"add rank flow if exist\n\n QARank是我们内部用于评价策略ELO的库 此处并不影响正常使用\n \"\"\"\n from QARank import QA_Rank\n QA_Rank(self.acc).send()\n except:\n pass\n\n def debug(self):\n self.running_mode = 'backtest'\n self.database = pymongo.MongoClient(mongo_ip).QUANTAXIS\n user = QA_User(username=\"admin\", password='admin')\n port = user.new_portfolio(self.portfolio)\n self.acc = port.new_accountpro(\n account_cookie=self.strategy_id, init_cash=self.init_cash, market_type=self.market_type)\n self.positions = self.acc.get_position(self.code)\n\n print(self.acc)\n\n print(self.acc.market_type)\n data = QA.QA_quotation(self.code.upper(), self.start, self.end, source=QA.DATASOURCE.MONGO,\n frequence=self.frequence, market=self.market_type, output=QA.OUTPUT_FORMAT.DATASTRUCT)\n\n def x1(item):\n # print(data)\n self.latest_price[item.name[1]] = item['close']\n if str(item.name[0])[0:10] != str(self.running_time)[0:10]:\n self.on_dailyclose()\n self.on_dailyopen()\n if self.market_type == QA.MARKET_TYPE.STOCK_CN:\n print('backtest: Settle!')\n self.acc.settle()\n self._on_1min_bar()\n self._market_data.append(item)\n self.running_time = str(item.name[0])\n self.on_bar(item)\n\n data.data.apply(x1, axis=1)\n\n def debug_t0(self):\n self.running_mode = 'backtest'\n self.database = pymongo.MongoClient(mongo_ip).QUANTAXIS\n user = QA_User(username=\"admin\", password='admin')\n port = user.new_portfolio(self.portfolio)\n self.acc = port.new_accountpro(\n account_cookie=self.strategy_id, init_cash=self.init_cash, init_hold={\n self.code: 100000},\n market_type=self.market_type, running_environment=RUNNING_ENVIRONMENT.TZERO)\n self.positions = self.acc.get_position(self.code)\n\n print(self.acc)\n\n print(self.acc.market_type)\n data = QA.QA_quotation(self.code.upper(), self.start, self.end, source=QA.DATASOURCE.MONGO,\n frequence=self.frequence, market=self.market_type, output=QA.OUTPUT_FORMAT.DATASTRUCT)\n\n def x1(item):\n # print(data)\n self.latest_price[item.name[1]] = item['close']\n if str(item.name[0])[0:10] != str(self.running_time)[0:10]:\n self.on_dailyclose()\n for order in self.acc.close_positions_order:\n order.trade('closebySys', order.price,\n order.amount, order.datetime)\n self.on_dailyopen()\n if self.market_type == QA.MARKET_TYPE.STOCK_CN:\n print('backtest: Settle!')\n self.acc.settle()\n self._on_1min_bar()\n self._market_data.append(item)\n self.running_time = str(item.name[0])\n self.on_bar(item)\n\n data.data.apply(x1, axis=1)\n\n def debug_currenttick(self, freq):\n data = QA.QA_fetch_get_future_transaction_realtime(\n 'tdx', self.code.upper())\n self.running_mode = 'backtest'\n self.database = pymongo.MongoClient(mongo_ip).QUANTAXIS\n user = QA_User(username=\"admin\", password='admin')\n port = user.new_portfolio(self.portfolio)\n self.strategy_id = self.strategy_id + 'currenttick_{}_{}'.format(str(datetime.date.today()), freq)\n self.acc = port.new_accountpro(\n account_cookie=self.strategy_id, init_cash=self.init_cash, market_type=self.market_type)\n self.positions = self.acc.get_position(self.code)\n data = data.assign(price=data.price/1000).loc[:, ['code', 'price', 'volume']].resample(\n freq).apply({'code': 'last', 'price': 'ohlc', 'volume': 'sum'}).dropna()\n data.columns = data.columns.droplevel(0)\n data = data.reset_index().set_index(['datetime', 'code'])\n\n def x1(item):\n self.latest_price[item.name[1]] = item['close']\n if str(item.name[0])[0:10] != str(self.running_time)[0:10]:\n self.on_dailyclose()\n self.on_dailyopen()\n self._on_1min_bar()\n self._market_data.append(item)\n self.running_time = str(item.name[0])\n self.on_bar(item)\n\n data.apply(x1, axis=1)\n\n def debug_histick(self, freq):\n data = QA.QA_fetch_get_future_transaction(\n 'tdx', self.code.upper(), self.start, self.end)\n self.running_mode = 'backtest'\n self.database = pymongo.MongoClient(mongo_ip).QUANTAXIS\n user = QA_User(username=\"admin\", password='admin')\n port = user.new_portfolio(self.portfolio)\n self.strategy_id = self.strategy_id + 'histick_{}_{}_{}'.format(self.start, self.end, freq)\n self.acc = port.new_accountpro(\n account_cookie=self.strategy_id, init_cash=self.init_cash, market_type=self.market_type)\n self.positions = self.acc.get_position(self.code)\n data = data.assign(price=data.price/1000).loc[:, ['code', 'price', 'volume']].resample(\n freq).apply({'code': 'last', 'price': 'ohlc', 'volume': 'sum'}).dropna()\n data.columns = data.columns.droplevel(0)\n data = data.reset_index().set_index(['datetime', 'code'])\n\n def x1(item):\n self.latest_price[item.name[1]] = item['close']\n if str(item.name[0])[0:10] != str(self.running_time)[0:10]:\n self.on_dailyclose()\n self.on_dailyopen()\n self._on_1min_bar()\n self._market_data.append(item)\n self.running_time = str(item.name[0])\n self.on_bar(item)\n\n data.apply(x1, axis=1)\n\n def subscribe_data(self, code, frequence, data_host, data_port, data_user, data_password):\n \"\"\"[summary]\n\n Arguments:\n code {[type]} -- [description]\n frequence {[type]} -- [description]\n \"\"\"\n\n if frequence.endswith('min'):\n\n self.sub = subscriber(exchange='realtime_{}_{}'.format(\n frequence, code), host=data_host, port=data_port, user=data_user, password=data_password)\n self.sub.callback = self.callback\n elif frequence.endswith('s'):\n\n \n import re\n self._num_cached = 2*int(re.findall(r'\\d+',self.frequence)[0])\n self.sub = subscriber_routing(exchange='CTPX', routing_key=code, host=data_host, port=data_port, user=data_user, password=data_password)\n self.sub.callback = self.second_callback\n elif frequence.endswith('tick'):\n self._num_cached = 1\n self.sub = subscriber_routing(exchange='CTPX', routing_key=code, host=data_host, port=data_port, user=data_user, password=data_password)\n self.sub.callback = self.tick_callback\n\n\n def subscribe_multi(self, codelist, frequence, data_host, data_port, data_user, data_password):\n\n self.sub = subscriber_topic(exchange='realtime_{}'.format(\n frequence), host=data_host, port=data_port, user=data_user, password=data_password)\n for item in codelist:\n self.sub.add_sub(exchange='realtime_{}'.format(\n frequence), routing_key=item)\n self.sub.callback = self.callback\n\n @property\n def old_data(self):\n return self._old_data\n\n def update(self):\n \"\"\"\n 此处是切换bar的时候的节点\n \"\"\"\n self._old_data = self._market_data\n self._on_1min_bar()\n\n @property\n def market_datetime(self):\n return self.market_data.index.levels[0]\n\n @property\n def market_data(self):\n\n if self.running_mode == 'sim':\n return self._market_data\n elif self.running_mode == 'backtest':\n return pd.concat(self._market_data[-100:], axis=1, sort=False).T\n\n def force_close(self):\n # 强平\n if self.positions.volume_long > 0:\n self.send_order('SELL', 'CLOSE', price=self.positions.last_price,\n volume=self.positions.volume_long)\n if self.positions.volume_short > 0:\n self.send_order('BUY', 'CLOSE', price=self.positions.last_price,\n volume=self.positions.volume_short)\n\n def upcoming_data(self, new_bar):\n \"\"\"upcoming_bar :\n\n Arguments:\n new_bar {json} -- [description]\n \"\"\"\n if len(self._old_data)> 0:\n self._market_data = pd.concat([self._old_data, new_bar])\n else:\n self._market_data = new_bar\n # QA.QA_util_log_info(self._market_data)\n\n if self.isupdate:\n self.update()\n self.isupdate = False\n\n self.update_account()\n self.positions.on_price_change(float(self.latest_price[self.code]))\n self.on_bar(json.loads(new_bar.to_json(orient='records'))[0])\n\n def ind2str(self, ind, ind_type):\n z = ind.tail(1).reset_index().to_dict(orient='records')[0]\n return json.dumps({'topic': ind_type, 'code': self.code, 'type': self.frequence, 'data': z})\n\n def second_callback(self, a, b, c, body):\n \"\"\"在strategy的callback中,我们需要的是\n\n 1. 更新数据\n 2. 更新bar\n 3. 更新策略状态\n 4. 推送事件\n\n Arguments:\n a {[type]} -- [description]\n b {[type]} -- [description]\n c {[type]} -- [description]\n body {[type]} -- [description]\n \n second ==> 2*second tick\n \n b'{\"ask_price_1\": 4145.0, \"ask_price_2\": 0, \"ask_price_3\": 0, \"ask_price_4\": 0, \"ask_price_5\": 0, \n \"ask_volume_1\": 69, \"ask_volume_2\": 0, \"ask_volume_3\": 0, \"ask_volume_4\": 0, \"ask_volume_5\": 0, \n \"average_price\": 61958.14258714826, \n \"bid_price_1\": 4143.0, \"bid_price_2\": 0, \"bid_price_3\": 0, \"bid_price_4\": 0, \"bid_price_5\": 0, \n \"bid_volume_1\": 30, \"bid_volume_2\": 0, \"bid_volume_3\": 0, \"bid_volume_4\": 0, \"bid_volume_5\": 0, \n \"datetime\": \"2019-11-20 01:57:08\", \"exchange\": \"SHFE\", \"gateway_name\": \"ctp\", \n \"high_price\": 4152.0, \"last_price\": 4144.0, \"last_volume\": 0,\n \"limit_down\": 3872.0, \"limit_up\": 4367.0, \"local_symbol\": \"ag1912.SHFE\", \n \"low_price\": 4105.0, \"name\": \"\", \"open_interest\": 277912.0, \"open_price\": 4140.0, \n \"preSettlementPrice\": 4120.0, \"pre_close\": 4155.0, \n \"symbol\": \"ag1912\", \n \"volume\": 114288}'\n\n\n tick 会基于热数据的量 self._num_cached 来判断更新/重采样\n \n \"\"\"\n\n self.new_data = json.loads(str(body, encoding='utf-8'))\n\n self._cached_data.append(self.new_data)\n self.latest_price[self.code] = self.new_data['last_price']\n\n\n # if len(self._cached_data) == self._num_cached:\n # self.isupdate = True\n\n\n\n if len(self._cached_data) > 3*self._num_cached:\n # 控制缓存数据量\n self._cached_data = self._cached_data[self._num_cached:]\n\n data= pd.DataFrame(self._cached_data).loc[:,['datetime','last_price', 'volume']]\n data = data.assign(datetime= pd.to_datetime(data.datetime)).set_index('datetime').resample(\n self.frequence).apply({'last_price': 'ohlc', 'volume': 'last'}).dropna()\n data.columns = data.columns.droplevel(0)\n\n data = data.assign(volume=data.volume.diff(), code=self.code)\n data = data.reset_index().set_index(['datetime', 'code'])\n\n self.acc.on_price_change(self.code, self.latest_price[self.code])\n # .loc[:, ['open', 'high', 'low', 'close', 'volume', 'tradetime']]\n now = datetime.datetime.now()\n if now.hour == 20 and now.minute == 59 and now.second < 10:\n self.daily_func()\n time.sleep(10)\n\n self.running_time = self.new_data['datetime']\n #print(data.iloc[-1].index[0])\n if self.dt != data.index[-1][0]:\n self.isupdate = True\n self.dt = data.index[-1][0]\n self.upcoming_data(data.tail(1))\n\n def tick_callback(self, a, b, c, body):\n pass\n\n\n def callback(self, a, b, c, body):\n \"\"\"在strategy的callback中,我们需要的是\n\n 1. 更新数据\n 2. 更新bar\n 3. 更新策略状态\n 4. 推送事件\n\n Arguments:\n a {[type]} -- [description]\n b {[type]} -- [description]\n c {[type]} -- [description]\n body {[type]} -- [description]\n \"\"\"\n\n self.new_data = json.loads(str(body, encoding='utf-8'))\n self.latest_price[self.code] = self.new_data['close']\n if self.dt != str(self.new_data['datetime'])[0:16]:\n # [0:16]是分钟线位数\n print('update!!!!!!!!!!!!')\n self.dt = str(self.new_data['datetime'])[0:16]\n self.isupdate = True\n\n self.acc.on_price_change(self.code, self.new_data['close'])\n # .loc[:, ['open', 'high', 'low', 'close', 'volume', 'tradetime']]\n bar = pd.DataFrame([self.new_data]).set_index(['datetime', 'code'])\n now = datetime.datetime.now()\n if now.hour == 20 and now.minute == 59 and now.second < 10:\n self.daily_func()\n time.sleep(10)\n\n # res = self.job_control.find_one(\n # {'strategy_id': self.strategy_id, 'strategy_id': self.strategy_id})\n # self.control_status(res)\n self.running_time = self.new_data['datetime']\n self.upcoming_data(bar)\n\n def control_status(self, res):\n print(res)\n\n def add_subscriber(self, qaproid):\n \"\"\"Add a subscriber\n 增加订阅者的QAPRO_ID\n\n \"\"\"\n self.subscriber_client.insert_one(\n {'strategy_id': self.strategy_id, 'user_id': qaproid})\n\n @property\n def subscriber_list(self):\n \"\"\"订阅者\n\n Returns:\n [type] -- [description]\n \"\"\"\n\n return list(set([item['user_id'] for item in self.subscriber_client.find({'strategy_id': self.strategy_id})]))\n\n def load_strategy(self):\n raise NotImplementedError\n\n def on_dailyopen(self):\n pass\n\n def on_dailyclose(self):\n pass\n\n def on_bar(self, bar):\n raise NotImplementedError\n\n def _on_1min_bar(self):\n #raise NotImplementedError\n if len(self._systemvar.keys()) > 0:\n self._signal.append(copy.deepcopy(self._systemvar))\n\n def on_1min_bar(self):\n raise NotImplementedError\n\n def on_5min_bar(self):\n raise NotImplementedError\n\n def on_15min_bar(self):\n raise NotImplementedError\n\n def on_30min_bar(self):\n raise NotImplementedError\n\n def order_handler(self):\n self._orders = {}\n\n def daily_func(self):\n QA.QA_util_log_info('DAILY FUNC')\n\n def risk_check(self):\n pass\n\n def plot(self, name, data, format):\n \"\"\" plot是可以存储你的临时信息的接口, 后期会接入可视化\n\n\n\n Arguments:\n name {[type]} -- [description]\n data {[type]} -- [description]\n format {[type]} -- [description]\n \"\"\"\n self._systemvar[name] = {'datetime': copy.deepcopy(str(\n self.running_time)), 'value': data, 'format': format}\n\n def check_order(self, direction, offset):\n \"\"\"[summary]\n 同方向不开仓 只对期货市场做限制\n\n buy - open\n sell - close\n \"\"\"\n if self.market_type == QA.MARKET_TYPE.FUTURE_CN:\n if self.last_order_towards[direction] == str(offset):\n return False\n else:\n return True\n else:\n return True\n\n def on_ordererror(self, direction, offset, price, volume):\n print('order Error ')\n\n def receive_simpledeal(self,\n code: str,\n trade_time,\n trade_amount,\n direction,\n offset,\n trade_price,\n message='sell_open'):\n self.send_order(direction=direction, offset=offset,\n volume=trade_amount, price=trade_price, order_id=QA.QA_util_random_with_topic(self.strategy_id))\n\n def send_order(self, direction='BUY', offset='OPEN', price=3925, volume=10, order_id='',):\n\n towards = eval('ORDER_DIRECTION.{}_{}'.format(direction, offset))\n order_id = str(uuid.uuid4()) if order_id == '' else order_id\n\n if isinstance(price, float):\n pass\n elif isinstance(price, pd.Series):\n price = price.values[0]\n\n if self.running_mode == 'sim':\n # 在此处拦截无法下单的订单\n if (direction == 'BUY' and self.latest_price[self.code] <= price) or (direction == 'SELL' and self.latest_price[self.code] >= price):\n QA.QA_util_log_info(\n '============ {} SEND ORDER =================='.format(order_id))\n QA.QA_util_log_info('direction{} offset {} price{} volume{}'.format(\n direction, offset, price, volume))\n\n if self.check_order(direction, offset):\n self.last_order_towards = {'BUY': '', 'SELL': ''}\n self.last_order_towards[direction] = offset\n now = str(datetime.datetime.now())\n\n order = self.acc.send_order(\n code=self.code, towards=towards, price=price, amount=volume, order_id=order_id)\n order['topic'] = 'send_order'\n self.pub.pub(\n json.dumps(order), routing_key=self.strategy_id)\n\n self.acc.make_deal(order)\n self.bar_order['{}_{}'.format(\n direction, offset)] = self.bar_id\n if self.send_wx:\n for user in self.subscriber_list:\n QA.QA_util_log_info(self.subscriber_list)\n try:\n requests.post('http://www.yutiansut.com/signal?user_id={}&template={}&strategy_id={}&realaccount={}&code={}&order_direction={}&order_offset={}&price={}&volume={}&order_time={}'.format(\n user, \"xiadan_report\", self.strategy_id, self.acc.user_id, self.code.lower(), direction, offset, price, volume, now))\n except Exception as e:\n QA.QA_util_log_info(e)\n\n else:\n QA.QA_util_log_info('failed in ORDER_CHECK')\n else:\n self.on_ordererror(direction, offset, price, volume)\n elif self.running_mode == 'backtest':\n\n self.bar_order['{}_{}'.format(direction, offset)] = self.bar_id\n\n if self.market_type == 'stock_cn':\n order = self.acc.send_order(\n code=self.code, amount=volume, time=self.running_time, towards=towards, price=price)\n order.trade(order.order_id, order.price,\n order.amount, order.datetime)\n else:\n self.acc.receive_simpledeal(\n code=self.code, trade_time=self.running_time, trade_towards=towards, trade_amount=volume, trade_price=price, order_id=order_id, realorder_id=order_id, trade_id=order_id)\n self.positions = self.acc.get_position(self.code)\n\n def update_account(self):\n if self.running_mode == 'sim':\n QA.QA_util_log_info('{} UPDATE ACCOUNT'.format(\n str(datetime.datetime.now())))\n\n self.accounts = self.acc.account_msg\n self.orders = self.acc.orders\n self.positions = self.acc.get_position(self.code)\n self.trades = self.acc.trades\n self.updatetime = self.acc.dtstr\n elif self.running_mode == 'backtest':\n self.positions = self.acc.get_position(self.code)\n\n def get_exchange(self, code):\n return self.market_preset.get_exchange(code)\n\n def get_positions(self, code):\n if self.running_mode == 'sim':\n self.update_account()\n return self.positions\n elif self.running_mode == 'backtest':\n return self.acc.get_position(code)\n\n def get_cash(self):\n if self.running_mode == 'sim':\n self.update_account()\n return self.accounts.get('available', '')\n elif self.running_mode == 'backtest':\n return self.acc.cash_available\n\n def run(self):\n\n while True:\n time.sleep(self.risk_check_gap)\n self.risk_check()\n\n\nif __name__ == '__main__':\n QAStrategyCTABase(code='RB2001').run()\n"
] |
[
[
"pandas.concat",
"pandas.to_datetime",
"pandas.DataFrame"
]
] |
mahuangxu/ray
|
[
"891648ea9ecd8e80921e075e05f8499cc323887f"
] |
[
"rllib/agents/dqn/dqn_tf_policy.py"
] |
[
"\"\"\"TensorFlow policy class used for DQN\"\"\"\n\nfrom typing import Dict\n\nimport gym\nimport numpy as np\nimport ray\nfrom ray.rllib.agents.dqn.distributional_q_tf_model import \\\n DistributionalQTFModel\nfrom ray.rllib.agents.dqn.simple_q_tf_policy import TargetNetworkMixin\nfrom ray.rllib.models import ModelCatalog\nfrom ray.rllib.models.modelv2 import ModelV2\nfrom ray.rllib.models.tf.tf_action_dist import Categorical\nfrom ray.rllib.policy.policy import Policy\nfrom ray.rllib.policy.sample_batch import SampleBatch\nfrom ray.rllib.policy.tf_policy import LearningRateSchedule\nfrom ray.rllib.policy.tf_policy_template import build_tf_policy\nfrom ray.rllib.utils.error import UnsupportedSpaceException\nfrom ray.rllib.utils.exploration import ParameterNoise\nfrom ray.rllib.utils.framework import try_import_tf\nfrom ray.rllib.utils.numpy import convert_to_numpy\nfrom ray.rllib.utils.tf_ops import (huber_loss, make_tf_callable,\n minimize_and_clip, reduce_mean_ignore_inf)\nfrom ray.rllib.utils.typing import (ModelGradients, TensorType,\n TrainerConfigDict)\n\ntf1, tf, tfv = try_import_tf()\n\nQ_SCOPE = \"q_func\"\nQ_TARGET_SCOPE = \"target_q_func\"\n\n# Importance sampling weights for prioritized replay\nPRIO_WEIGHTS = \"weights\"\n\n\nclass QLoss:\n def __init__(self,\n q_t_selected: TensorType,\n q_logits_t_selected: TensorType,\n q_tp1_best: TensorType,\n q_dist_tp1_best: TensorType,\n importance_weights: TensorType,\n rewards: TensorType,\n done_mask: TensorType,\n gamma: float = 0.99,\n n_step: int = 1,\n num_atoms: int = 1,\n v_min: float = -10.0,\n v_max: float = 10.0):\n\n if num_atoms > 1:\n # Distributional Q-learning which corresponds to an entropy loss\n\n z = tf.range(num_atoms, dtype=tf.float32)\n z = v_min + z * (v_max - v_min) / float(num_atoms - 1)\n\n # (batch_size, 1) * (1, num_atoms) = (batch_size, num_atoms)\n r_tau = tf.expand_dims(\n rewards, -1) + gamma**n_step * tf.expand_dims(\n 1.0 - done_mask, -1) * tf.expand_dims(z, 0)\n r_tau = tf.clip_by_value(r_tau, v_min, v_max)\n b = (r_tau - v_min) / ((v_max - v_min) / float(num_atoms - 1))\n lb = tf.floor(b)\n ub = tf.math.ceil(b)\n # indispensable judgement which is missed in most implementations\n # when b happens to be an integer, lb == ub, so pr_j(s', a*) will\n # be discarded because (ub-b) == (b-lb) == 0\n floor_equal_ceil = tf.cast(tf.less(ub - lb, 0.5), tf.float32)\n\n l_project = tf.one_hot(\n tf.cast(lb, dtype=tf.int32),\n num_atoms) # (batch_size, num_atoms, num_atoms)\n u_project = tf.one_hot(\n tf.cast(ub, dtype=tf.int32),\n num_atoms) # (batch_size, num_atoms, num_atoms)\n ml_delta = q_dist_tp1_best * (ub - b + floor_equal_ceil)\n mu_delta = q_dist_tp1_best * (b - lb)\n ml_delta = tf.reduce_sum(\n l_project * tf.expand_dims(ml_delta, -1), axis=1)\n mu_delta = tf.reduce_sum(\n u_project * tf.expand_dims(mu_delta, -1), axis=1)\n m = ml_delta + mu_delta\n\n # Rainbow paper claims that using this cross entropy loss for\n # priority is robust and insensitive to `prioritized_replay_alpha`\n self.td_error = tf.nn.softmax_cross_entropy_with_logits(\n labels=m, logits=q_logits_t_selected)\n self.loss = tf.reduce_mean(\n self.td_error * tf.cast(importance_weights, tf.float32))\n self.stats = {\n # TODO: better Q stats for dist dqn\n \"mean_td_error\": tf.reduce_mean(self.td_error),\n }\n else:\n q_tp1_best_masked = (1.0 - done_mask) * q_tp1_best\n\n # compute RHS of bellman equation\n q_t_selected_target = rewards + gamma**n_step * q_tp1_best_masked\n\n # compute the error (potentially clipped)\n self.td_error = (\n q_t_selected - tf.stop_gradient(q_t_selected_target))\n self.loss = tf.reduce_mean(\n tf.cast(importance_weights, tf.float32) * huber_loss(\n self.td_error))\n self.stats = {\n \"mean_q\": tf.reduce_mean(q_t_selected),\n \"min_q\": tf.reduce_min(q_t_selected),\n \"max_q\": tf.reduce_max(q_t_selected),\n \"mean_td_error\": tf.reduce_mean(self.td_error),\n }\n\n\nclass ComputeTDErrorMixin:\n \"\"\"Assign the `compute_td_error` method to the DQNTFPolicy\n\n This allows us to prioritize on the worker side.\n \"\"\"\n\n def __init__(self):\n @make_tf_callable(self.get_session(), dynamic_shape=True)\n def compute_td_error(obs_t, act_t, rew_t, obs_tp1, done_mask,\n importance_weights):\n # Do forward pass on loss to update td error attribute\n build_q_losses(\n self, self.model, None, {\n SampleBatch.CUR_OBS: tf.convert_to_tensor(obs_t),\n SampleBatch.ACTIONS: tf.convert_to_tensor(act_t),\n SampleBatch.REWARDS: tf.convert_to_tensor(rew_t),\n SampleBatch.NEXT_OBS: tf.convert_to_tensor(obs_tp1),\n SampleBatch.DONES: tf.convert_to_tensor(done_mask),\n PRIO_WEIGHTS: tf.convert_to_tensor(importance_weights),\n })\n\n return self.q_loss.td_error\n\n self.compute_td_error = compute_td_error\n\n\ndef build_q_model(policy: Policy, obs_space: gym.spaces.Space,\n action_space: gym.spaces.Space,\n config: TrainerConfigDict) -> ModelV2:\n \"\"\"Build q_model and target_q_model for DQN\n\n Args:\n policy (Policy): The Policy, which will use the model for optimization.\n obs_space (gym.spaces.Space): The policy's observation space.\n action_space (gym.spaces.Space): The policy's action space.\n config (TrainerConfigDict):\n\n Returns:\n ModelV2: The Model for the Policy to use.\n Note: The target q model will not be returned, just assigned to\n `policy.target_q_model`.\n \"\"\"\n if not isinstance(action_space, gym.spaces.Discrete):\n raise UnsupportedSpaceException(\n \"Action space {} is not supported for DQN.\".format(action_space))\n\n if config[\"hiddens\"]:\n # try to infer the last layer size, otherwise fall back to 256\n num_outputs = ([256] + list(config[\"model\"][\"fcnet_hiddens\"]))[-1]\n config[\"model\"][\"no_final_linear\"] = True\n else:\n num_outputs = action_space.n\n\n q_model = ModelCatalog.get_model_v2(\n obs_space=obs_space,\n action_space=action_space,\n num_outputs=num_outputs,\n model_config=config[\"model\"],\n framework=\"tf\",\n model_interface=DistributionalQTFModel,\n name=Q_SCOPE,\n num_atoms=config[\"num_atoms\"],\n dueling=config[\"dueling\"],\n q_hiddens=config[\"hiddens\"],\n use_noisy=config[\"noisy\"],\n v_min=config[\"v_min\"],\n v_max=config[\"v_max\"],\n sigma0=config[\"sigma0\"],\n # TODO(sven): Move option to add LayerNorm after each Dense\n # generically into ModelCatalog.\n add_layer_norm=isinstance(\n getattr(policy, \"exploration\", None), ParameterNoise)\n or config[\"exploration_config\"][\"type\"] == \"ParameterNoise\")\n\n policy.target_q_model = ModelCatalog.get_model_v2(\n obs_space=obs_space,\n action_space=action_space,\n num_outputs=num_outputs,\n model_config=config[\"model\"],\n framework=\"tf\",\n model_interface=DistributionalQTFModel,\n name=Q_TARGET_SCOPE,\n num_atoms=config[\"num_atoms\"],\n dueling=config[\"dueling\"],\n q_hiddens=config[\"hiddens\"],\n use_noisy=config[\"noisy\"],\n v_min=config[\"v_min\"],\n v_max=config[\"v_max\"],\n sigma0=config[\"sigma0\"],\n # TODO(sven): Move option to add LayerNorm after each Dense\n # generically into ModelCatalog.\n add_layer_norm=isinstance(\n getattr(policy, \"exploration\", None), ParameterNoise)\n or config[\"exploration_config\"][\"type\"] == \"ParameterNoise\")\n\n return q_model\n\n\ndef get_distribution_inputs_and_class(policy: Policy,\n model: ModelV2,\n obs_batch: TensorType,\n *,\n explore=True,\n **kwargs):\n q_vals = compute_q_values(\n policy, model, {\"obs\": obs_batch}, state_batches=None, explore=explore)\n q_vals = q_vals[0] if isinstance(q_vals, tuple) else q_vals\n\n policy.q_values = q_vals\n policy.q_func_vars = model.variables()\n return policy.q_values, Categorical, [] # state-out\n\n\ndef build_q_losses(policy: Policy, model, _,\n train_batch: SampleBatch) -> TensorType:\n \"\"\"Constructs the loss for DQNTFPolicy.\n\n Args:\n policy (Policy): The Policy to calculate the loss for.\n model (ModelV2): The Model to calculate the loss for.\n train_batch (SampleBatch): The training data.\n\n Returns:\n TensorType: A single loss tensor.\n \"\"\"\n config = policy.config\n # q network evaluation\n q_t, q_logits_t, q_dist_t, _ = compute_q_values(\n policy,\n model, {\"obs\": train_batch[SampleBatch.CUR_OBS]},\n state_batches=None,\n explore=False)\n\n # target q network evalution\n q_tp1, q_logits_tp1, q_dist_tp1, _ = compute_q_values(\n policy,\n policy.target_q_model, {\"obs\": train_batch[SampleBatch.NEXT_OBS]},\n state_batches=None,\n explore=False)\n if not hasattr(policy, \"target_q_func_vars\"):\n policy.target_q_func_vars = policy.target_q_model.variables()\n\n # q scores for actions which we know were selected in the given state.\n one_hot_selection = tf.one_hot(\n tf.cast(train_batch[SampleBatch.ACTIONS], tf.int32),\n policy.action_space.n)\n q_t_selected = tf.reduce_sum(q_t * one_hot_selection, 1)\n q_logits_t_selected = tf.reduce_sum(\n q_logits_t * tf.expand_dims(one_hot_selection, -1), 1)\n\n # compute estimate of best possible value starting from state at t + 1\n if config[\"double_q\"]:\n q_tp1_using_online_net, q_logits_tp1_using_online_net, \\\n q_dist_tp1_using_online_net, _ = compute_q_values(\n policy, model,\n {\"obs\": train_batch[SampleBatch.NEXT_OBS]},\n state_batches=None,\n explore=False)\n q_tp1_best_using_online_net = tf.argmax(q_tp1_using_online_net, 1)\n q_tp1_best_one_hot_selection = tf.one_hot(q_tp1_best_using_online_net,\n policy.action_space.n)\n q_tp1_best = tf.reduce_sum(q_tp1 * q_tp1_best_one_hot_selection, 1)\n q_dist_tp1_best = tf.reduce_sum(\n q_dist_tp1 * tf.expand_dims(q_tp1_best_one_hot_selection, -1), 1)\n else:\n q_tp1_best_one_hot_selection = tf.one_hot(\n tf.argmax(q_tp1, 1), policy.action_space.n)\n q_tp1_best = tf.reduce_sum(q_tp1 * q_tp1_best_one_hot_selection, 1)\n q_dist_tp1_best = tf.reduce_sum(\n q_dist_tp1 * tf.expand_dims(q_tp1_best_one_hot_selection, -1), 1)\n\n policy.q_loss = QLoss(\n q_t_selected, q_logits_t_selected, q_tp1_best, q_dist_tp1_best,\n train_batch[PRIO_WEIGHTS], train_batch[SampleBatch.REWARDS],\n tf.cast(train_batch[SampleBatch.DONES],\n tf.float32), config[\"gamma\"], config[\"n_step\"],\n config[\"num_atoms\"], config[\"v_min\"], config[\"v_max\"])\n\n return policy.q_loss.loss\n\n\ndef adam_optimizer(policy: Policy, config: TrainerConfigDict\n ) -> \"tf.keras.optimizers.Optimizer\":\n if policy.config[\"framework\"] in [\"tf2\", \"tfe\"]:\n return tf.keras.optimizers.Adam(\n learning_rate=policy.cur_lr, epsilon=config[\"adam_epsilon\"])\n else:\n return tf1.train.AdamOptimizer(\n learning_rate=policy.cur_lr, epsilon=config[\"adam_epsilon\"])\n\n\ndef clip_gradients(policy: Policy, optimizer: \"tf.keras.optimizers.Optimizer\",\n loss: TensorType) -> ModelGradients:\n return minimize_and_clip(\n optimizer,\n loss,\n var_list=policy.q_func_vars,\n clip_val=policy.config[\"grad_clip\"])\n\n\ndef build_q_stats(policy: Policy, batch) -> Dict[str, TensorType]:\n return dict({\n \"cur_lr\": tf.cast(policy.cur_lr, tf.float64),\n }, **policy.q_loss.stats)\n\n\ndef setup_mid_mixins(policy: Policy, obs_space, action_space, config) -> None:\n LearningRateSchedule.__init__(policy, config[\"lr\"], config[\"lr_schedule\"])\n ComputeTDErrorMixin.__init__(policy)\n\n\ndef setup_late_mixins(policy: Policy, obs_space: gym.spaces.Space,\n action_space: gym.spaces.Space,\n config: TrainerConfigDict) -> None:\n TargetNetworkMixin.__init__(policy, obs_space, action_space, config)\n\n\ndef compute_q_values(policy: Policy,\n model: ModelV2,\n input_dict,\n state_batches=None,\n seq_lens=None,\n explore=None,\n is_training: bool = False):\n\n config = policy.config\n\n input_dict[\"is_training\"] = policy._get_is_training_placeholder()\n model_out, state = model(input_dict, state_batches or [], seq_lens)\n\n if config[\"num_atoms\"] > 1:\n (action_scores, z, support_logits_per_action, logits,\n dist) = model.get_q_value_distributions(model_out)\n else:\n (action_scores, logits,\n dist) = model.get_q_value_distributions(model_out)\n\n if config[\"dueling\"]:\n state_score = model.get_state_value(model_out)\n if config[\"num_atoms\"] > 1:\n support_logits_per_action_mean = tf.reduce_mean(\n support_logits_per_action, 1)\n support_logits_per_action_centered = (\n support_logits_per_action - tf.expand_dims(\n support_logits_per_action_mean, 1))\n support_logits_per_action = tf.expand_dims(\n state_score, 1) + support_logits_per_action_centered\n support_prob_per_action = tf.nn.softmax(\n logits=support_logits_per_action)\n value = tf.reduce_sum(\n input_tensor=z * support_prob_per_action, axis=-1)\n logits = support_logits_per_action\n dist = support_prob_per_action\n else:\n action_scores_mean = reduce_mean_ignore_inf(action_scores, 1)\n action_scores_centered = action_scores - tf.expand_dims(\n action_scores_mean, 1)\n value = state_score + action_scores_centered\n else:\n value = action_scores\n\n return value, logits, dist, state\n\n\ndef _adjust_nstep(n_step, gamma, obs, actions, rewards, new_obs, dones):\n \"\"\"Rewrites the given trajectory fragments to encode n-step rewards.\n\n reward[i] = (\n reward[i] * gamma**0 +\n reward[i+1] * gamma**1 +\n ... +\n reward[i+n_step-1] * gamma**(n_step-1))\n\n The ith new_obs is also adjusted to point to the (i+n_step-1)'th new obs.\n\n At the end of the trajectory, n is truncated to fit in the traj length.\n \"\"\"\n\n assert not any(dones[:-1]), \"Unexpected done in middle of trajectory\"\n\n traj_length = len(rewards)\n for i in range(traj_length):\n for j in range(1, n_step):\n if i + j < traj_length:\n new_obs[i] = new_obs[i + j]\n dones[i] = dones[i + j]\n rewards[i] += gamma**j * rewards[i + j]\n\n\ndef postprocess_nstep_and_prio(policy: Policy,\n batch: SampleBatch,\n other_agent=None,\n episode=None) -> SampleBatch:\n # N-step Q adjustments.\n if policy.config[\"n_step\"] > 1:\n _adjust_nstep(policy.config[\"n_step\"], policy.config[\"gamma\"],\n batch[SampleBatch.CUR_OBS], batch[SampleBatch.ACTIONS],\n batch[SampleBatch.REWARDS], batch[SampleBatch.NEXT_OBS],\n batch[SampleBatch.DONES])\n\n if PRIO_WEIGHTS not in batch:\n batch[PRIO_WEIGHTS] = np.ones_like(batch[SampleBatch.REWARDS])\n\n # Prioritize on the worker side.\n if batch.count > 0 and policy.config[\"worker_side_prioritization\"]:\n td_errors = policy.compute_td_error(\n batch[SampleBatch.CUR_OBS], batch[SampleBatch.ACTIONS],\n batch[SampleBatch.REWARDS], batch[SampleBatch.NEXT_OBS],\n batch[SampleBatch.DONES], batch[PRIO_WEIGHTS])\n new_priorities = (np.abs(convert_to_numpy(td_errors)) +\n policy.config[\"prioritized_replay_eps\"])\n batch[PRIO_WEIGHTS] = new_priorities\n\n return batch\n\n\nDQNTFPolicy = build_tf_policy(\n name=\"DQNTFPolicy\",\n get_default_config=lambda: ray.rllib.agents.dqn.dqn.DEFAULT_CONFIG,\n make_model=build_q_model,\n action_distribution_fn=get_distribution_inputs_and_class,\n loss_fn=build_q_losses,\n stats_fn=build_q_stats,\n postprocess_fn=postprocess_nstep_and_prio,\n optimizer_fn=adam_optimizer,\n compute_gradients_fn=clip_gradients,\n extra_action_out_fn=lambda policy: {\"q_values\": policy.q_values},\n extra_learn_fetches_fn=lambda policy: {\"td_error\": policy.q_loss.td_error},\n before_loss_init=setup_mid_mixins,\n after_init=setup_late_mixins,\n mixins=[\n TargetNetworkMixin,\n ComputeTDErrorMixin,\n LearningRateSchedule,\n ])\n"
] |
[
[
"numpy.ones_like"
]
] |
salbertson/QUANTAXIS
|
[
"d701749c02fe2da0d78f19836a15843b8b811c67"
] |
[
"QUANTAXIS/QASU/save_tdx.py"
] |
[
"# coding:utf-8\n#\n# The MIT License (MIT)\n#\n# Copyright (c) 2016-2018 yutiansut/QUANTAXIS\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 concurrent\nimport datetime\nfrom concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor\nimport json\nimport pandas as pd\nimport pymongo\n\nfrom QUANTAXIS.QAFetch import QA_fetch_get_stock_block\nfrom QUANTAXIS.QAFetch.QATdx import (\n QA_fetch_get_option_day,\n QA_fetch_get_option_min,\n QA_fetch_get_index_day,\n QA_fetch_get_index_min,\n QA_fetch_get_stock_day,\n QA_fetch_get_stock_info,\n QA_fetch_get_stock_list,\n QA_fetch_get_future_list,\n QA_fetch_get_index_list,\n QA_fetch_get_future_day,\n QA_fetch_get_future_min,\n QA_fetch_get_stock_min,\n QA_fetch_get_stock_transaction,\n QA_fetch_get_stock_xdxr, select_best_ip)\nfrom QUANTAXIS.QAFetch.QATdx import (\n QA_fetch_get_50etf_option_contract_time_to_market,\n QA_fetch_get_commodity_option_CU_contract_time_to_market,\n QA_fetch_get_commodity_option_SR_contract_time_to_market,\n QA_fetch_get_commodity_option_M_contract_time_to_market,\n QA_fetch_get_50etf_option_contract_time_to_market,\n)\nfrom QUANTAXIS.QAUtil import (DATABASE, QA_util_get_next_day,\n QA_util_get_real_date, QA_util_log_info,\n QA_util_to_json_from_pandas, trade_date_sse)\n\n# ip=select_best_ip()\n\n\ndef now_time():\n return str(QA_util_get_real_date(str(datetime.date.today() - datetime.timedelta(days=1)), trade_date_sse, -1)) + \\\n ' 17:00:00' if datetime.datetime.now().hour < 15 else str(QA_util_get_real_date(\n str(datetime.date.today()), trade_date_sse, -1)) + ' 15:00:00'\n\n\ndef QA_SU_save_stock_day(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n save stock_day\n 保存日线数据\n :param client:\n :param ui_log: 给GUI qt 界面使用\n :param ui_progress: 给GUI qt 界面使用\n :param ui_progress_int_value: 给GUI qt 界面使用\n '''\n stock_list = QA_fetch_get_stock_list().code.unique().tolist()\n coll_stock_day = client.stock_day\n coll_stock_day.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll_stock_day):\n try:\n QA_util_log_info(\n '##JOB01 Now Saving STOCK_DAY==== {}'.format(str(code)), ui_log)\n\n # 首选查找数据库 是否 有 这个代码的数据\n ref = coll_stock_day.find({'code': str(code)[0:6]})\n end_date = str(now_time())[0:10]\n\n # 当前数据库已经包含了这个代码的数据, 继续增量更新\n # 加入这个判断的原因是因为如果股票是刚上市的 数据库会没有数据 所以会有负索引问题出现\n if ref.count() > 0:\n\n # 接着上次获取的日期继续更新\n start_date = ref[ref.count() - 1]['date']\n\n QA_util_log_info('UPDATE_STOCK_DAY \\n Trying updating {} from {} to {}'.format(\n code, start_date, end_date), ui_log)\n if start_date != end_date:\n coll_stock_day.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_day(str(code), QA_util_get_next_day(start_date), end_date, '00')))\n\n # 当前数据库中没有这个代码的股票数据, 从1990-01-01 开始下载所有的数据\n else:\n start_date = '1990-01-01'\n QA_util_log_info('UPDATE_STOCK_DAY \\n Trying updating {} from {} to {}'.format\n (code, start_date, end_date), ui_log)\n if start_date != end_date:\n coll_stock_day.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_day(str(code), start_date, end_date, '00')))\n except Exception as error0:\n print(error0)\n err.append(str(code))\n\n for item in range(len(stock_list)):\n QA_util_log_info('The {} of Total {}'.format\n (item, len(stock_list)))\n\n strProgressToLog = 'DOWNLOAD PROGRESS {} {}'.format(\n str(float(item / len(stock_list) * 100))[0:4] + '%', ui_log)\n intProgressToLog = int(float(item / len(stock_list) * 100))\n QA_util_log_info(strProgressToLog, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intProgressToLog)\n\n __saving_work(stock_list[item], coll_stock_day)\n\n if len(err) < 1:\n QA_util_log_info('SUCCESS save stock day ^_^', ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log)\n QA_util_log_info(err, ui_log)\n\n\ndef QA_SU_save_stock_week(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save stock_week\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n stock_list = QA_fetch_get_stock_list().code.unique().tolist()\n coll_stock_week = client.stock_week\n coll_stock_week.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll_stock_week):\n try:\n QA_util_log_info('##JOB01 Now Saving STOCK_WEEK==== {}'.format(\n str(code)), ui_log=ui_log)\n\n ref = coll_stock_week.find({'code': str(code)[0:6]})\n end_date = str(now_time())[0:10]\n if ref.count() > 0:\n # 加入这个判断的原因是因为如果股票是刚上市的 数据库会没有数据 所以会有负索引问题出现\n\n start_date = ref[ref.count() - 1]['date']\n\n QA_util_log_info('UPDATE_STOCK_WEEK \\n Trying updating {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n coll_stock_week.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_day(str(code), QA_util_get_next_day(start_date), end_date, '00', frequence='week')))\n else:\n start_date = '1990-01-01'\n QA_util_log_info('UPDATE_STOCK_WEEK \\n Trying updating {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n coll_stock_week.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_day(str(code), start_date, end_date, '00', frequence='week')))\n except:\n err.append(str(code))\n for item in range(len(stock_list)):\n QA_util_log_info('The {} of Total {}'.format\n (item, len(stock_list)), ui_log=ui_log)\n strProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(item / len(stock_list) * 100))[0:4] + '%')\n intProgress = int(float(item / len(stock_list) * 100))\n QA_util_log_info(strProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intProgress)\n\n __saving_work(stock_list[item], coll_stock_week)\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_stock_month(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save stock_month\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n stock_list = QA_fetch_get_stock_list().code.unique().tolist()\n coll_stock_month = client.stock_month\n coll_stock_month.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll_stock_month):\n try:\n QA_util_log_info('##JOB01 Now Saving STOCK_MONTH==== {}'.format(\n str(code)), ui_log=ui_log)\n\n ref = coll_stock_month.find({'code': str(code)[0:6]})\n end_date = str(now_time())[0:10]\n if ref.count() > 0:\n # 加入这个判断的原因是因为如果股票是刚上市的 数据库会没有数据 所以会有负索引问题出现\n\n start_date = ref[ref.count() - 1]['date']\n\n QA_util_log_info('UPDATE_STOCK_MONTH \\n Trying updating {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n coll_stock_month.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_day(str(code), QA_util_get_next_day(start_date), end_date, '00', frequence='month')))\n else:\n start_date = '1990-01-01'\n QA_util_log_info('UPDATE_STOCK_MONTH \\n Trying updating {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n coll_stock_month.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_day(str(code), start_date, end_date, '00', frequence='month')))\n except:\n err.append(str(code))\n for item in range(len(stock_list)):\n QA_util_log_info('The {} of Total {}'.format(\n item, len(stock_list)), ui_log=ui_log)\n strProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(item / len(stock_list) * 100))[0:4] + '%')\n intProgress = int(float(item / len(stock_list) * 100))\n QA_util_log_info(strProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intProgress)\n\n __saving_work(stock_list[item], coll_stock_month)\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info('ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_stock_year(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save stock_year\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n stock_list = QA_fetch_get_stock_list().code.unique().tolist()\n coll_stock_year = client.stock_year\n coll_stock_year.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll_stock_year):\n try:\n QA_util_log_info(\n '##JOB01 Now Saving STOCK_YEAR==== {}'.format(str(code)), ui_log=ui_log)\n\n ref = coll_stock_year.find({'code': str(code)[0:6]})\n end_date = str(now_time())[0:10]\n if ref.count() > 0:\n # 加入这个判断的原因是因为如果股票是刚上市的 数据库会没有数据 所以会有负索引问题出现\n\n start_date = ref[ref.count() - 1]['date']\n\n QA_util_log_info('UPDATE_STOCK_YEAR \\n Trying updating {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n coll_stock_year.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_day(str(code), QA_util_get_next_day(start_date), end_date, '00', frequence='year')))\n else:\n start_date = '1990-01-01'\n QA_util_log_info('UPDATE_STOCK_YEAR \\n Trying updating {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n coll_stock_year.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_day(str(code), start_date, end_date, '00', frequence='year')))\n except:\n err.append(str(code))\n for item in range(len(stock_list)):\n QA_util_log_info('The {} of Total {}'.format(\n item, len(stock_list)), ui_log=ui_log)\n\n strProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(item / len(stock_list) * 100))[0:4] + '%')\n intProgress = int(float(item / len(stock_list) * 100))\n QA_util_log_info(strProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intProgress)\n\n __saving_work(stock_list[item], coll_stock_year)\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_stock_xdxr(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"[summary]\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n stock_list = QA_fetch_get_stock_list().code.unique().tolist()\n # client.drop_collection('stock_xdxr')\n try:\n\n coll = client.stock_xdxr\n coll.create_index([('code', pymongo.ASCENDING),\n ('date', pymongo.ASCENDING)], unique=True)\n except:\n client.drop_collection('stock_xdxr')\n coll = client.stock_xdxr\n coll.create_index([('code', pymongo.ASCENDING),\n ('date', pymongo.ASCENDING)], unique=True)\n err = []\n\n def __saving_work(code, coll):\n QA_util_log_info('##JOB02 Now Saving XDXR INFO ==== {}'.format(\n str(code)), ui_log=ui_log)\n try:\n coll.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_xdxr(str(code))), ordered=False)\n\n except:\n\n err.append(str(code))\n for i_ in range(len(stock_list)):\n QA_util_log_info('The {} of Total {}'.format(\n i_, len(stock_list)), ui_log=ui_log)\n strLogInfo = 'DOWNLOAD PROGRESS {} '.format(\n str(float(i_ / len(stock_list) * 100))[0:4] + '%')\n intLogProgress = int(float(i_ / len(stock_list) * 100))\n QA_util_log_info(strLogInfo, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n __saving_work(stock_list[i_], coll)\n\n\ndef QA_SU_save_stock_min(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save stock_min\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n stock_list = QA_fetch_get_stock_list().code.unique().tolist()\n coll = client.stock_min\n coll.create_index([('code', pymongo.ASCENDING), ('time_stamp',\n pymongo.ASCENDING), ('date_stamp', pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll):\n QA_util_log_info(\n '##JOB03 Now Saving STOCK_MIN ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n for type in ['1min', '5min', '15min', '30min', '60min']:\n ref_ = coll.find(\n {'code': str(code)[0:6], 'type': type})\n end_time = str(now_time())[0:19]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['datetime']\n\n QA_util_log_info(\n '##JOB03.{} Now Saving {} from {} to {} =={} '.format(['1min', '5min', '15min', '30min', '60min'].index(type),\n str(code), start_time, end_time, type),\n ui_log=ui_log)\n if start_time != end_time:\n __data = QA_fetch_get_stock_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data)[1::])\n else:\n start_time = '2015-01-01'\n QA_util_log_info(\n '##JOB03.{} Now Saving {} from {} to {} =={} '.format(['1min', '5min', '15min', '30min', '60min'].index(type),\n str(code), start_time, end_time, type),\n ui_log=ui_log)\n if start_time != end_time:\n __data = QA_fetch_get_stock_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data))\n except Exception as e:\n QA_util_log_info(e, ui_log=ui_log)\n err.append(code)\n QA_util_log_info(err, ui_log=ui_log)\n\n executor = ThreadPoolExecutor(max_workers=4)\n #executor.map((__saving_work, stock_list[i_], coll),URLS)\n res = {executor.submit(\n __saving_work, stock_list[i_], coll) for i_ in range(len(stock_list))}\n count = 0\n for i_ in concurrent.futures.as_completed(res):\n QA_util_log_info('The {} of Total {}'.format(\n count, len(stock_list)), ui_log=ui_log)\n\n strProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(count / len(stock_list) * 100))[0:4] + '%')\n intProgress = int(count / len(stock_list) * 10000.0)\n QA_util_log_info(strProgress, ui_log, ui_progress=ui_progress,\n ui_progress_int_value=intProgress)\n count = count + 1\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_index_day(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save index_day\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n __index_list = QA_fetch_get_stock_list('index')\n coll = client.index_day\n coll.create_index([('code', pymongo.ASCENDING),\n ('date_stamp', pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll):\n\n try:\n ref_ = coll.find({'code': str(code)[0:6]})\n end_time = str(now_time())[0:10]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['date']\n\n QA_util_log_info('##JOB04 Now Saving INDEX_DAY==== \\n Trying updating {} from {} to {}'.format\n (code, start_time, end_time), ui_log=ui_log)\n\n if start_time != end_time:\n coll.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_index_day(str(code), QA_util_get_next_day(start_time), end_time)))\n else:\n try:\n start_time = '1990-01-01'\n QA_util_log_info('##JOB04 Now Saving INDEX_DAY==== \\n Trying updating {} from {} to {}'.format\n (code, start_time, end_time), ui_log=ui_log)\n coll.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_index_day(str(code), start_time, end_time)))\n except:\n start_time = '2009-01-01'\n QA_util_log_info('##JOB04 Now Saving INDEX_DAY==== \\n Trying updating {} from {} to {}'.format\n (code, start_time, end_time), ui_log=ui_log)\n coll.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_index_day(str(code), start_time, end_time)))\n except Exception as e:\n QA_util_log_info(e, ui_log=ui_log)\n err.append(str(code))\n QA_util_log_info(err, ui_log=ui_log)\n\n for i_ in range(len(__index_list)):\n # __saving_work('000001')\n QA_util_log_info('The {} of Total {}'.format(\n i_, len(__index_list)), ui_log=ui_log)\n\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(i_ / len(__index_list) * 100))[0:4] + '%')\n intLogProgress = int(float(i_ / len(__index_list) * 10000.0))\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n __saving_work(__index_list.index[i_][0], coll)\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_index_min(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save index_min\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n __index_list = QA_fetch_get_stock_list('index')\n coll = client.index_min\n coll.create_index([('code', pymongo.ASCENDING), ('time_stamp',\n pymongo.ASCENDING), ('date_stamp', pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll):\n\n QA_util_log_info(\n '##JOB05 Now Saving Index_MIN ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n\n for type in ['1min', '5min', '15min', '30min', '60min']:\n ref_ = coll.find(\n {'code': str(code)[0:6], 'type': type})\n end_time = str(now_time())[0:19]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['datetime']\n\n QA_util_log_info(\n '##JOB05.{} Now Saving {} from {} to {} =={} '.\n format(['1min', '5min', '15min', '30min', '60min'].\n index(type), str(code), start_time, end_time, type),\n ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_index_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data[1::]))\n else:\n start_time = '2015-01-01'\n\n QA_util_log_info(\n '##JOB05.{} Now Saving {} from {} to {} =={} '.\n format(['1min', '5min', '15min', '30min', '60min'].\n index(type), str(code), start_time, end_time, type),\n ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_index_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data))\n except:\n err.append(code)\n\n executor = ThreadPoolExecutor(max_workers=4)\n\n res = {executor.submit(\n __saving_work, __index_list.index[i_][0], coll) for i_ in range(len(__index_list))} # multi index ./.\n count = 0\n for i_ in concurrent.futures.as_completed(res):\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(count / len(__index_list) * 100))[0:4] + '%')\n intLogProgress = int(float(count / len(__index_list) * 10000.0))\n QA_util_log_info('The {} of Total {}'.format(\n count, len(__index_list)), ui_log=ui_log)\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n count = count + 1\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_etf_day(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save etf_day\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n __index_list = QA_fetch_get_stock_list('etf')\n coll = client.index_day\n coll.create_index([('code', pymongo.ASCENDING),\n ('date_stamp', pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll):\n\n try:\n\n ref_ = coll.find({'code': str(code)[0:6]})\n end_time = str(now_time())[0:10]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['date']\n\n QA_util_log_info('##JOB06 Now Saving ETF_DAY==== \\n Trying updating {} from {} to {}'.format\n (code, start_time, end_time), ui_log=ui_log)\n\n if start_time != end_time:\n coll.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_index_day(str(code), QA_util_get_next_day(start_time), end_time)))\n else:\n start_time = '1990-01-01'\n QA_util_log_info('##JOB06 Now Saving ETF_DAY==== \\n Trying updating {} from {} to {}'.format\n (code, start_time, end_time), ui_log=ui_log)\n\n if start_time != end_time:\n coll.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_index_day(str(code), start_time, end_time)))\n except:\n err.append(str(code))\n for i_ in range(len(__index_list)):\n # __saving_work('000001')\n QA_util_log_info('The {} of Total {}'.format(\n i_, len(__index_list)), ui_log=ui_log)\n\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(i_ / len(__index_list) * 100))[0:4] + '%')\n intLogProgress = int(float(i_ / len(__index_list) * 10000.0))\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n\n __saving_work(__index_list.index[i_][0], coll)\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_etf_min(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save etf_min\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n __index_list = QA_fetch_get_stock_list('etf')\n coll = client.index_min\n coll.create_index([('code', pymongo.ASCENDING), ('time_stamp',\n pymongo.ASCENDING), ('date_stamp', pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll):\n\n QA_util_log_info(\n '##JOB07 Now Saving ETF_MIN ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n\n for type in ['1min', '5min', '15min', '30min', '60min']:\n ref_ = coll.find(\n {'code': str(code)[0:6], 'type': type})\n end_time = str(now_time())[0:19]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['datetime']\n\n QA_util_log_info(\n '##JOB07.{} Now Saving {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type),\n ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_index_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data[1::]))\n else:\n start_time = '2015-01-01'\n\n QA_util_log_info(\n '##JOB07.{} Now Saving {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type), ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_index_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data))\n except:\n err.append(code)\n\n executor = ThreadPoolExecutor(max_workers=4)\n\n res = {executor.submit(\n __saving_work, __index_list.index[i_][0], coll) for i_ in range(len(__index_list))} # multi index ./.\n count = 0\n for i_ in concurrent.futures.as_completed(res):\n\n QA_util_log_info('The {} of Total {}'.format(\n count, len(__index_list)), ui_log=ui_log)\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(count / len(__index_list) * 100))[0:4] + '%')\n intLogProgress = int(float(count / len(__index_list) * 10000.0))\n\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n count = count + 1\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_stock_list(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save stock_list\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n client.drop_collection('stock_list')\n coll = client.stock_list\n coll.create_index('code')\n\n try:\n # 🛠todo 这个应该是第一个任务 JOB01, 先更新股票列表!!\n QA_util_log_info('##JOB08 Now Saving STOCK_LIST ====', ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=5000)\n stock_list_from_tdx = QA_fetch_get_stock_list()\n pandas_data = QA_util_to_json_from_pandas(stock_list_from_tdx)\n coll.insert_many(pandas_data)\n QA_util_log_info(\"完成股票列表获取\", ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=10000)\n except Exception as e:\n QA_util_log_info(e, ui_log=ui_log)\n print(\" Error save_tdx.QA_SU_save_stock_list exception!\")\n\n pass\n\n\ndef QA_SU_save_stock_block(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save stock_block\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n client.drop_collection('stock_block')\n coll = client.stock_block\n coll.create_index('code')\n\n try:\n QA_util_log_info('##JOB09 Now Saving STOCK_BlOCK ====', ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=5000)\n coll.insert_many(QA_util_to_json_from_pandas(\n QA_fetch_get_stock_block('tdx')))\n QA_util_log_info('tdx Block ====', ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=5000)\n\n # 🛠todo fixhere here 获取同花顺板块, 还是调用tdx的\n coll.insert_many(QA_util_to_json_from_pandas(\n QA_fetch_get_stock_block('ths')))\n QA_util_log_info('ths Block ====', ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=8000)\n\n QA_util_log_info('完成股票板块获取=', ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=10000)\n\n except Exception as e:\n QA_util_log_info(e, ui_log=ui_log)\n print(\" Error save_tdx.QA_SU_save_stock_block exception!\")\n pass\n\n\ndef QA_SU_save_stock_info(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save stock_info\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n client.drop_collection('stock_info')\n stock_list = QA_fetch_get_stock_list().code.unique().tolist()\n coll = client.stock_info\n coll.create_index('code')\n err = []\n\n def __saving_work(code, coll):\n QA_util_log_info(\n '##JOB010 Now Saving STOCK INFO ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n coll.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_stock_info(str(code))))\n\n except:\n err.append(str(code))\n for i_ in range(len(stock_list)):\n # __saving_work('000001')\n\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(i_ / len(stock_list) * 100))[0:4] + '%')\n intLogProgress = int(float(i_ / len(stock_list) * 10000.0))\n QA_util_log_info('The {} of Total {}'.format(i_, len(stock_list)))\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n\n __saving_work(stock_list[i_], coll)\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_stock_transaction(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save stock_transaction\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n stock_list = QA_fetch_get_stock_list().code.unique().tolist()\n coll = client.stock_transaction\n coll.create_index('code')\n err = []\n\n def __saving_work(code):\n QA_util_log_info(\n '##JOB11 Now Saving STOCK_TRANSACTION ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n coll.insert_many(\n QA_util_to_json_from_pandas(\n # 🛠todo str(stock_list[code]) 参数不对?\n QA_fetch_get_stock_transaction(str(code), '1990-01-01', str(now_time())[0:10])))\n except:\n err.append(str(code))\n for i_ in range(len(stock_list)):\n # __saving_work('000001')\n QA_util_log_info('The {} of Total {}'.format(\n i_, len(stock_list)), ui_log=ui_log)\n\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(i_ / len(stock_list) * 100))[0:4] + '%')\n intLogProgress = int(float(i_ / len(stock_list) * 10000.0))\n\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n __saving_work(stock_list[i_])\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef _save_option_commodity_sr_day(client=DATABASE, ui_log=None, ui_progress=None):\n ##################### sr 白糖 ############################################################################\n option_sr_contract_list = QA_fetch_get_commodity_option_SR_contract_time_to_market()\n coll_option_commodity_sr_day = client.option_commodity_sr_day\n coll_option_commodity_sr_day.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll_option_commodity_sr_day):\n try:\n QA_util_log_info('##JOB12 Now Saving OPTION_DAY_COMMODITY_SR 白糖 ==== {}'.format(\n str(code)), ui_log=ui_log)\n\n # 首选查找数据库 是否 有 这个代码的数据\n ref = coll_option_commodity_sr_day.find({'code': str(code)[0:8]})\n end_date = str(now_time())[0:10]\n\n # 当前数据库已经包含了这个代码的数据, 继续增量更新\n # 加入这个判断的原因是因为如果是刚上市的 数据库会没有数据 所以会有负索引问题出现\n if ref.count() > 0:\n\n # 接着上次获取的日期继续更新\n start_date = ref[ref.count() - 1]['date']\n QA_util_log_info(' 上次获取期权sr白糖日线数据的最后日期是 {}'.format(\n start_date), ui_log=ui_log)\n\n QA_util_log_info('UPDATE_OPTION_M_DAY \\n 从上一次下载数据开始继续 Trying update {} from {} to {}'.format(\n code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n\n start_date0 = QA_util_get_next_day(start_date)\n df0 = QA_fetch_get_option_day(code=code, start_date=start_date0, end_date=end_date,\n frequence='day', ip=None, port=None)\n retCount = df0.iloc[:, 0].size\n QA_util_log_info(\"日期从开始{}-结束{} , 合约代码{} , 返回了{}条记录 , 准备写入数据库\"\n .format(start_date0, end_date, code, retCount), ui_log=ui_log)\n coll_option_commodity_sr_day.insert_many(\n QA_util_to_json_from_pandas(df0))\n else:\n QA_util_log_info(\"^已经获取过这天的数据了^ {}\".format(\n start_date), ui_log=ui_log)\n\n else:\n start_date = '1990-01-01'\n QA_util_log_info('UPDATE_M_OPTION_DAY \\n 从新开始下载数据 Trying update {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n\n df0 = QA_fetch_get_option_day(code=code, start_date=start_date, end_date=end_date,\n frequence='day', ip=None, port=None)\n retCount = df0.iloc[:, 0].size\n QA_util_log_info(\"日期从开始{}-结束{} , 合约代码{} , 获取了{}条记录 , 准备写入数据库^_^ \"\n .format(start_date, end_date, code, retCount),\n ui_log=ui_log)\n\n coll_option_commodity_sr_day.insert_many(\n QA_util_to_json_from_pandas(df0))\n else:\n QA_util_log_info(\n \"*已经获取过这天的数据了* {}\".format(start_date), ui_log=ui_log)\n\n except Exception as error0:\n print(error0)\n err.append(str(code))\n\n for item in range(len(option_sr_contract_list)):\n QA_util_log_info('The {} of Total {}'.format(\n item, len(option_sr_contract_list)), ui_log=ui_log)\n\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(item / len(option_sr_contract_list) * 100))[0:4] + '%')\n intLogProgress = int(\n float(item / len(option_sr_contract_list) * 10000.0))\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n\n __saving_work(\n option_sr_contract_list[item].code, coll_option_commodity_sr_day)\n\n if len(err) < 1:\n QA_util_log_info('SUCCESS save option sr day ^_^ ', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef _save_option_commodity_m_day(client=DATABASE, ui_log=None, ui_progress=None):\n ##################### M 豆粕 ############################################################################\n option_m_contract_list = QA_fetch_get_commodity_option_M_contract_time_to_market()\n coll_option_commodity_m_day = client.option_commodity_m_day\n coll_option_commodity_m_day.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll_option_commodity_m_day):\n try:\n QA_util_log_info('##JOB12 Now Saving OPTION_DAY_COMMODITY_M 豆粕 ==== {}'.format(\n str(code)), ui_log=ui_log)\n\n # 首选查找数据库 是否 有 这个代码的数据\n # M XXXXXX 编码格式\n\n ref = coll_option_commodity_m_day.find({'code': str(code)[0:8]})\n end_date = str(now_time())[0:10]\n\n # 当前数据库已经包含了这个代码的数据, 继续增量更新\n # 加入这个判断的原因是因为如果是刚上市的 数据库会没有数据 所以会有负索引问题出现\n if ref.count() > 0:\n\n # 接着上次获取的日期继续更新\n start_date = ref[ref.count() - 1]['date']\n QA_util_log_info(' 上次获取期权M豆粕日线数据的最后日期是 {}'.format(\n start_date), ui_log=ui_log)\n\n QA_util_log_info('UPDATE_OPTION_M_DAY \\n 从上一次下载数据开始继续 Trying update {} from {} to {}'.format(\n code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n\n start_date0 = QA_util_get_next_day(start_date)\n df0 = QA_fetch_get_option_day(code=code, start_date=start_date0, end_date=end_date,\n frequence='day', ip=None, port=None)\n retCount = df0.iloc[:, 0].size\n QA_util_log_info(\"日期从开始{}-结束{} , 合约代码{} , 返回了{}条记录 , 准备写入数据库\"\n .format(start_date0, end_date, code, retCount), ui_log=ui_log)\n coll_option_commodity_m_day.insert_many(\n QA_util_to_json_from_pandas(df0))\n else:\n QA_util_log_info(\"^已经获取过这天的数据了^ {}\".format(\n start_date), ui_log=ui_log)\n\n else:\n start_date = '1990-01-01'\n QA_util_log_info('UPDATE_M_OPTION_DAY \\n 从新开始下载数据 Trying update {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n\n df0 = QA_fetch_get_option_day(code=code, start_date=start_date, end_date=end_date,\n frequence='day', ip=None, port=None)\n retCount = df0.iloc[:, 0].size\n QA_util_log_info(\"日期从开始{}-结束{} , 合约代码{} , 获取了{}条记录 , 准备写入数据库^_^ \"\n .format(start_date, end_date, code, retCount),\n ui_log=ui_log)\n\n coll_option_commodity_m_day.insert_many(\n QA_util_to_json_from_pandas(df0))\n else:\n QA_util_log_info(\n \"*已经获取过这天的数据了* {}\".format(start_date), ui_log=ui_log)\n\n except Exception as error0:\n print(error0)\n err.append(str(code))\n\n for item in range(len(option_m_contract_list)):\n QA_util_log_info('The {} of Total {}'.format(\n item, len(option_m_contract_list)), ui_log=ui_log)\n\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(item / len(option_m_contract_list) * 100))[0:4] + '%')\n intLogProgress = int(\n float(item / len(option_m_contract_list) * 10000.0))\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n\n __saving_work(\n option_m_contract_list[item].code, coll_option_commodity_m_day)\n\n if len(err) < 1:\n QA_util_log_info('SUCCESS save option m day ^_^ ', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef _save_option_commodity_cu_day(client=DATABASE, ui_log=None, ui_progress=None):\n ##################### CU 铜 ############################################################################\n option_cu_contract_list = QA_fetch_get_commodity_option_CU_contract_time_to_market()\n coll_option_commodity_cu_day = client.option_commodity_cu_day\n coll_option_commodity_cu_day.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll_option_commodity_cu_day):\n try:\n QA_util_log_info('##JOB12 Now Saving OPTION_DAY_COMMODITY_CU 铜 ==== {}'.format(\n str(code)), ui_log=ui_log)\n\n # 首选查找数据库 是否 有 这个代码的数据\n # 期权代码 从 10000001 开始编码 10001228\n ref = coll_option_commodity_cu_day.find({'code': str(code)[0:8]})\n end_date = str(now_time())[0:10]\n\n # 当前数据库已经包含了这个代码的数据, 继续增量更新\n # 加入这个判断的原因是因为如果是刚上市的 数据库会没有数据 所以会有负索引问题出现\n if ref.count() > 0:\n\n # 接着上次获取的日期继续更新\n start_date = ref[ref.count() - 1]['date']\n QA_util_log_info(' 上次获取期权CU日线数据的最后日期是 {}'.format(\n start_date), ui_log=ui_log)\n\n QA_util_log_info('UPDATE_OPTION_CU_DAY \\n 从上一次下载数据开始继续 Trying update {} from {} to {}'.format(\n code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n\n start_date0 = QA_util_get_next_day(start_date)\n df0 = QA_fetch_get_option_day(code=code, start_date=start_date0, end_date=end_date,\n frequence='day', ip=None, port=None)\n retCount = df0.iloc[:, 0].size\n QA_util_log_info(\"日期从开始{}-结束{} , 合约代码{} , 返回了{}条记录 , 准备写入数据库\"\n .format(start_date0, end_date, code, retCount), ui_log=ui_log)\n coll_option_commodity_cu_day.insert_many(\n QA_util_to_json_from_pandas(df0))\n else:\n QA_util_log_info(\"^已经获取过这天的数据了^ {}\".format(\n start_date), ui_log=ui_log)\n\n else:\n start_date = '1990-01-01'\n QA_util_log_info('UPDATE_CU_OPTION_DAY \\n 从新开始下载数据 Trying update {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n\n df0 = QA_fetch_get_option_day(code=code, start_date=start_date, end_date=end_date,\n frequence='day', ip=None, port=None)\n retCount = df0.iloc[:, 0].size\n QA_util_log_info(\"日期从开始{}-结束{} , 合约代码{} , 获取了{}条记录 , 准备写入数据库^_^ \"\n .format(start_date, end_date, code, retCount),\n ui_log=ui_log)\n\n coll_option_commodity_cu_day.insert_many(\n QA_util_to_json_from_pandas(df0))\n else:\n QA_util_log_info(\n \"*已经获取过这天的数据了* {}\".format(start_date), ui_log=ui_log)\n\n except Exception as error0:\n print(error0)\n err.append(str(code))\n\n for item in range(len(option_cu_contract_list)):\n QA_util_log_info('The {} of Total {}'.format(\n item, len(option_cu_contract_list)), ui_log=ui_log)\n\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(item / len(option_cu_contract_list) * 100))[0:4] + '%')\n intLogProgress = int(\n float(item / len(option_cu_contract_list) * 10000.0))\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n\n __saving_work(\n option_cu_contract_list[item].code, coll_option_commodity_cu_day)\n\n if len(err) < 1:\n QA_util_log_info('SUCCESS save option cu day ^_^ ', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_option_commodity_day(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n :param client:\n :return:\n '''\n _save_option_commodity_cu_day(\n client=client, ui_log=ui_log, ui_progress=ui_progress)\n _save_option_commodity_m_day(\n client=client, ui_log=ui_log, ui_progress=ui_progress)\n _save_option_commodity_sr_day(\n client=client, ui_log=ui_log, ui_progress=ui_progress)\n\n\ndef _save_option_commodity_cu_min(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n\n :param client:\n :param ui_log:\n :param ui_progress:\n :return:\n '''\n '''\n :param client:\n :return:\n '''\n option_contract_list = QA_fetch_get_commodity_option_CU_contract_time_to_market()\n coll_option_min = client.option_commodity_cu_min\n coll_option_min.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n # 索引 code\n\n err = []\n\n def __saving_work(code, coll):\n\n QA_util_log_info(\n '##JOB13 Now Saving Option CU 铜 MIN ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n\n for type in ['1min', '5min', '15min', '30min', '60min']:\n ref_ = coll.find({'code': str(code)[0:8], 'type': type})\n\n end_time = str(now_time())[0:19]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['datetime']\n\n QA_util_log_info(\n '##JOB13.{} Now Saving Option CU 铜 {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type),\n ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n QA_util_log_info(\n \" 写入 新增历史合约记录数 {} \".format(len(__data)))\n coll.insert_many(\n QA_util_to_json_from_pandas(__data[1::]))\n else:\n start_time = '2015-01-01'\n\n QA_util_log_info(\n '##JOB13.{} Now Option CU 铜 {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type), ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n QA_util_log_info(\n \" 写入 新增合约记录数 {} \".format(len(__data)))\n coll.insert_many(\n QA_util_to_json_from_pandas(__data))\n except:\n err.append(code)\n\n executor = ThreadPoolExecutor(max_workers=4)\n\n res = {executor.submit(\n __saving_work, option_contract_list[i_][\"code\"], coll_option_min) for i_ in\n range(len(option_contract_list))} # multi index ./.\n count = 0\n for i_ in concurrent.futures.as_completed(res):\n QA_util_log_info('The {} of Total {}'.format(\n count, len(option_contract_list)), ui_log=ui_log)\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(count / len(option_contract_list) * 100))[0:4] + '%')\n intLogProgress = int(\n float(count / len(option_contract_list) * 10000.0))\n\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n count = count + 1\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n pass\n\n\ndef _save_option_commodity_sr_min(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n\n :param client:\n :param ui_log:\n :param ui_progress:\n :return:\n '''\n '''\n :param client:\n :return:\n '''\n option_contract_list = QA_fetch_get_commodity_option_SR_contract_time_to_market()\n coll_option_min = client.option_commodity_sr_min\n coll_option_min.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n # 索引 code\n\n err = []\n\n def __saving_work(code, coll):\n\n QA_util_log_info(\n '##JOB13 Now Saving Option SR 白糖 ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n\n for type in ['1min', '5min', '15min', '30min', '60min']:\n ref_ = coll.find({'code': str(code)[0:8], 'type': type})\n\n end_time = str(now_time())[0:19]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['datetime']\n\n QA_util_log_info(\n '##JOB13.{} Now Saving Option SR 白糖 {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type),\n ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n QA_util_log_info(\n \" 写入 新增历史合约记录数 {} \".format(len(__data)))\n coll.insert_many(\n QA_util_to_json_from_pandas(__data[1::]))\n else:\n start_time = '2015-01-01'\n\n QA_util_log_info(\n '##JOB13.{} Now Option SR 白糖 {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type), ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n QA_util_log_info(\n \" 写入 新增合约记录数 {} \".format(len(__data)))\n coll.insert_many(\n QA_util_to_json_from_pandas(__data))\n except:\n err.append(code)\n\n executor = ThreadPoolExecutor(max_workers=4)\n\n res = {executor.submit(\n __saving_work, option_contract_list[i_][\"code\"], coll_option_min) for i_ in\n range(len(option_contract_list))} # multi index ./.\n count = 0\n for i_ in concurrent.futures.as_completed(res):\n QA_util_log_info('The {} of Total {}'.format(\n count, len(option_contract_list)), ui_log=ui_log)\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(count / len(option_contract_list) * 100))[0:4] + '%')\n intLogProgress = int(\n float(count / len(option_contract_list) * 10000.0))\n\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n count = count + 1\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n pass\n\n\ndef _save_option_commodity_m_min(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n\n :param client:\n :param ui_log:\n :param ui_progress:\n :return:\n '''\n\n option_contract_list = QA_fetch_get_commodity_option_M_contract_time_to_market()\n coll_option_min = client.option_commodity_m_min\n coll_option_min.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n # 索引 code\n\n err = []\n\n def __saving_work(code, coll):\n\n QA_util_log_info(\n '##JOB13 Now Saving Option M 豆粕 ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n\n for type in ['1min', '5min', '15min', '30min', '60min']:\n ref_ = coll.find({'code': str(code)[0:8], 'type': type})\n\n end_time = str(now_time())[0:19]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['datetime']\n\n QA_util_log_info(\n '##JOB13.{} Now Saving Option M 豆粕 {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type),\n ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n QA_util_log_info(\n \" 写入 新增历史合约记录数 {} \".format(len(__data)))\n coll.insert_many(\n QA_util_to_json_from_pandas(__data[1::]))\n else:\n start_time = '2015-01-01'\n\n QA_util_log_info(\n '##JOB13.{} Now Option M 豆粕 {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type), ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n QA_util_log_info(\n \" 写入 新增合约记录数 {} \".format(len(__data)))\n coll.insert_many(\n QA_util_to_json_from_pandas(__data))\n except:\n err.append(code)\n\n executor = ThreadPoolExecutor(max_workers=4)\n\n res = {executor.submit(\n __saving_work, option_contract_list[i_][\"code\"], coll_option_min) for i_ in\n range(len(option_contract_list))} # multi index ./.\n count = 0\n for i_ in concurrent.futures.as_completed(res):\n QA_util_log_info('The {} of Total {}'.format(\n count, len(option_contract_list)), ui_log=ui_log)\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(count / len(option_contract_list) * 100))[0:4] + '%')\n intLogProgress = int(\n float(count / len(option_contract_list) * 10000.0))\n\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n count = count + 1\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n pass\n\n\ndef QA_SU_save_option_commodity_min(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n :param client:\n :return:\n '''\n _save_option_commodity_cu_min(\n client=client, ui_log=ui_log, ui_progress=ui_progress)\n _save_option_commodity_sr_min(\n client=client, ui_log=ui_log, ui_progress=ui_progress)\n _save_option_commodity_m_min(\n client=client, ui_log=ui_log, ui_progress=ui_progress)\n\n\ndef QA_SU_save_option_min(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n :param client:\n :return:\n '''\n option_contract_list = QA_fetch_get_50etf_option_contract_time_to_market()\n coll_option_min = client.option_day_min\n coll_option_min.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n # 索引 code\n\n err = []\n\n def __saving_work(code, coll):\n\n QA_util_log_info(\n '##JOB13 Now Saving Option 50ETF MIN ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n\n for type in ['1min', '5min', '15min', '30min', '60min']:\n ref_ = coll.find({'code': str(code)[0:8], 'type': type})\n\n end_time = str(now_time())[0:19]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['datetime']\n\n QA_util_log_info(\n '##JOB13.{} Now Saving Option 50ETF {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type),\n ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n QA_util_log_info(\n \" 写入 新增历史合约记录数 {} \".format(len(__data)))\n coll.insert_many(\n QA_util_to_json_from_pandas(__data[1::]))\n else:\n start_time = '2015-01-01'\n\n QA_util_log_info(\n '##JOB13.{} Now Option 50ETF {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type), ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n QA_util_log_info(\n \" 写入 新增合约记录数 {} \".format(len(__data)))\n coll.insert_many(\n QA_util_to_json_from_pandas(__data))\n except:\n err.append(code)\n\n executor = ThreadPoolExecutor(max_workers=4)\n\n res = {executor.submit(\n __saving_work, option_contract_list[i_][\"code\"], coll_option_min) for i_ in range(len(option_contract_list))} # multi index ./.\n count = 0\n for i_ in concurrent.futures.as_completed(res):\n QA_util_log_info('The {} of Total {}'.format(\n count, len(option_contract_list)), ui_log=ui_log)\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(count / len(option_contract_list) * 100))[0:4] + '%')\n intLogProgress = int(\n float(count / len(option_contract_list) * 10000.0))\n\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n count = count + 1\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_option_day(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n :param client:\n :return:\n '''\n option_contract_list = QA_fetch_get_50etf_option_contract_time_to_market()\n coll_option_day = client.option_day\n coll_option_day.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n # 索引 code\n\n def __saving_work(code, coll_option_day):\n try:\n QA_util_log_info('##JOB12 Now Saving OPTION_DAY==== {}'.format(\n str(code)), ui_log=ui_log)\n\n # 首选查找数据库 是否 有 这个代码的数据\n # 期权代码 从 10000001 开始编码 10001228\n ref = coll_option_day.find({'code': str(code)[0:8]})\n end_date = str(now_time())[0:10]\n\n # 当前数据库已经包含了这个代码的数据, 继续增量更新\n # 加入这个判断的原因是因为如果是刚上市的 数据库会没有数据 所以会有负索引问题出现\n if ref.count() > 0:\n\n # 接着上次获取的日期继续更新\n start_date = ref[ref.count() - 1]['date']\n QA_util_log_info(' 上次获取期权日线数据的最后日期是 {}'.format(\n start_date), ui_log=ui_log)\n\n QA_util_log_info('UPDATE_OPTION_DAY \\n 从上一次下载数据开始继续 Trying update {} from {} to {}'.format(\n code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n\n start_date0 = QA_util_get_next_day(start_date)\n df0 = QA_fetch_get_option_day(code=code, start_date=start_date0, end_date=end_date,\n frequence='day', ip=None, port=None)\n retCount = df0.iloc[:, 0].size\n QA_util_log_info(\"日期从开始{}-结束{} , 合约代码{} , 返回了{}条记录 , 准备写入数据库\"\n .format(start_date0, end_date, code, retCount), ui_log=ui_log)\n coll_option_day.insert_many(\n QA_util_to_json_from_pandas(df0))\n else:\n QA_util_log_info(\"^已经获取过这天的数据了^ {}\".format(\n start_date), ui_log=ui_log)\n\n else:\n start_date = '1990-01-01'\n QA_util_log_info('UPDATE_OPTION_DAY \\n 从新开始下载数据 Trying update {} from {} to {}'.format\n (code, start_date, end_date), ui_log=ui_log)\n if start_date != end_date:\n\n df0 = QA_fetch_get_option_day(code=code, start_date=start_date, end_date=end_date,\n frequence='day', ip=None, port=None)\n retCount = df0.iloc[:, 0].size\n QA_util_log_info(\"日期从开始{}-结束{} , 合约代码{} , 获取了{}条记录 , 准备写入数据库^_^ \"\n .format(start_date, end_date, code, retCount),\n ui_log=ui_log)\n\n coll_option_day.insert_many(\n QA_util_to_json_from_pandas(df0))\n else:\n QA_util_log_info(\n \"*已经获取过这天的数据了* {}\".format(start_date), ui_log=ui_log)\n\n except Exception as error0:\n print(error0)\n err.append(str(code))\n\n for item in range(len(option_contract_list)):\n QA_util_log_info('The {} of Total {}'.format(\n item, len(option_contract_list)), ui_log=ui_log)\n\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(item / len(option_contract_list) * 100))[0:4] + '%')\n intLogProgress = int(float(item / len(option_contract_list) * 10000.0))\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n\n __saving_work(option_contract_list[item].code, coll_option_day)\n\n if len(err) < 1:\n QA_util_log_info('SUCCESS save option day ^_^ ', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_option_contract_list(client=DATABASE, ui_log=None, ui_progress=None):\n\n rows50etf = QA_fetch_get_50etf_option_contract_time_to_market()\n rows_cu = QA_fetch_get_commodity_option_CU_contract_time_to_market()\n rows_m = QA_fetch_get_commodity_option_M_contract_time_to_market()\n rows_sr = QA_fetch_get_commodity_option_SR_contract_time_to_market()\n\n try:\n # 🛠todo 这个应该是第一个任务 JOB01, 先更新股票列表!!\n QA_util_log_info('##JOB15 Now Saving OPTION_CONTRACT_LIST ====', ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=5000)\n\n coll = client.option_contract_list\n coll.create_index([('desc', pymongo.ASCENDING)], unique=True)\n\n # todo fixhere\n # from_items is deprecated. Please use DataFrame.from_dict(dict(items), ...) instead. DataFrame.from_dict\n\n try:\n\n df = pd.DataFrame.from_items([(s.desc, s) for s in rows50etf])\n df = (df.T)\n js = QA_util_to_json_from_pandas(df)\n result0 = coll.insert_many(js)\n\n except pymongo.errors.BulkWriteError as e:\n # https://ask.helplib.com/python/post_12740530\n panic = filter(lambda x: x['code'] !=\n 11000, e.details['writeErrors'])\n if len(panic) > 0:\n print\n \"really panic\"\n\n try:\n df = pd.DataFrame.from_items([(s.desc, s) for s in rows_cu])\n df = (df.T)\n js = QA_util_to_json_from_pandas(df)\n coll.insert_many(js)\n except pymongo.errors.BulkWriteError as e:\n # https://ask.helplib.com/python/post_12740530\n panic = filter(lambda x: x['code'] !=\n 11000, e.details['writeErrors'])\n if len(panic) > 0:\n print(\"really panic\")\n try:\n df = pd.DataFrame.from_items([(s.desc, s) for s in rows_m])\n df = (df.T)\n js = QA_util_to_json_from_pandas(df)\n coll.insert_many(js)\n except pymongo.errors.BulkWriteError as e:\n # https://ask.helplib.com/python/post_12740530\n panic = filter(lambda x: x['code'] !=\n 11000, e.details['writeErrors'])\n if len(panic) > 0:\n print(\"really panic\")\n\n try:\n df = pd.DataFrame.from_items([(s.desc, s) for s in rows_sr])\n df = (df.T)\n js = QA_util_to_json_from_pandas(df)\n coll.insert_many(js)\n\n except pymongo.errors.BulkWriteError as e:\n # https://ask.helplib.com/python/post_12740530\n panic = filter(lambda x: x['code'] !=\n 11000, e.details['writeErrors'])\n if len(panic) > 0:\n print(\"really panic\")\n\n QA_util_log_info(\"完成合约列表更新\", ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=10000)\n except Exception as e:\n QA_util_log_info(e, ui_log=ui_log)\n print(\" Error save_tdx.QA_SU_save_option_contract_list exception!\")\n\n\ndef QA_SU_save_future_list(client=DATABASE, ui_log=None, ui_progress=None):\n future_list = QA_fetch_get_future_list()\n coll_future_list = client.future_list\n coll_future_list.create_index(\"code\", unique=True)\n try:\n coll_future_list.insert_many(\n QA_util_to_json_from_pandas(future_list), ordered=False)\n except:\n pass\n\n\ndef QA_SU_save_index_list(client=DATABASE, ui_log=None, ui_progress=None):\n index_list = QA_fetch_get_index_list()\n coll_index_list = client.index_list\n coll_index_list.create_index(\"code\", unique=True)\n\n try:\n coll_index_list.insert_many(\n QA_util_to_json_from_pandas(index_list), ordered=False)\n except:\n pass\n\n\ndef QA_SU_save_future_day(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n save future_day\n 保存日线数据\n :param client:\n :param ui_log: 给GUI qt 界面使用\n :param ui_progress: 给GUI qt 界面使用\n :param ui_progress_int_value: 给GUI qt 界面使用\n :return:\n '''\n future_list = [item for item in QA_fetch_get_future_list(\n ).code.unique().tolist() if str(item)[-2:] in ['L8', 'L9']]\n coll_future_day = client.future_day\n coll_future_day.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll_future_day):\n try:\n QA_util_log_info(\n '##JOB12 Now Saving Future_DAY==== {}'.format(str(code)), ui_log)\n\n # 首选查找数据库 是否 有 这个代码的数据\n ref = coll_future_day.find({'code': str(code)[0:4]})\n end_date = str(now_time())[0:10]\n\n # 当前数据库已经包含了这个代码的数据, 继续增量更新\n # 加入这个判断的原因是因为如果股票是刚上市的 数据库会没有数据 所以会有负索引问题出现\n if ref.count() > 0:\n\n # 接着上次获取的日期继续更新\n start_date = ref[ref.count() - 1]['date']\n\n QA_util_log_info('UPDATE_Future_DAY \\n Trying updating {} from {} to {}'.format(\n code, start_date, end_date), ui_log)\n if start_date != end_date:\n coll_future_day.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_future_day(str(code), QA_util_get_next_day(start_date), end_date)))\n\n # 当前数据库中没有这个代码的股票数据, 从1990-01-01 开始下载所有的数据\n else:\n start_date = '2001-01-01'\n QA_util_log_info('UPDATE_Future_DAY \\n Trying updating {} from {} to {}'.format\n (code, start_date, end_date), ui_log)\n if start_date != end_date:\n coll_future_day.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_future_day(str(code), start_date, end_date)))\n except Exception as error0:\n print(error0)\n err.append(str(code))\n\n for item in range(len(future_list)):\n QA_util_log_info('The {} of Total {}'.format\n (item, len(future_list)))\n\n strProgressToLog = 'DOWNLOAD PROGRESS {} {}'.format(\n str(float(item / len(future_list) * 100))[0:4] + '%', ui_log)\n intProgressToLog = int(float(item / len(future_list) * 100))\n QA_util_log_info(strProgressToLog, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intProgressToLog)\n\n __saving_work(future_list[item], coll_future_day)\n\n if len(err) < 1:\n QA_util_log_info('SUCCESS save future day ^_^', ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log)\n QA_util_log_info(err, ui_log)\n\n\ndef QA_SU_save_future_day_all(client=DATABASE, ui_log=None, ui_progress=None):\n '''\n save future_day_all\n 保存日线数据(全部, 包含单月合约)\n :param client:\n :param ui_log: 给GUI qt 界面使用\n :param ui_progress: 给GUI qt 界面使用\n :param ui_progress_int_value: 给GUI qt 界面使用\n :return:\n '''\n future_list = QA_fetch_get_future_list().code.unique().tolist()\n coll_future_day = client.future_day\n coll_future_day.create_index(\n [(\"code\", pymongo.ASCENDING), (\"date_stamp\", pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll_future_day):\n try:\n QA_util_log_info(\n '##JOB12 Now Saving Future_DAY==== {}'.format(str(code)), ui_log)\n\n # 首选查找数据库 是否 有 这个代码的数据\n ref = coll_future_day.find({'code': str(code)[0:6]})\n end_date = str(now_time())[0:10]\n\n # 当前数据库已经包含了这个代码的数据, 继续增量更新\n # 加入这个判断的原因是因为如果股票是刚上市的 数据库会没有数据 所以会有负索引问题出现\n if ref.count() > 0:\n\n # 接着上次获取的日期继续更新\n start_date = ref[ref.count() - 1]['date']\n\n QA_util_log_info('UPDATE_Future_DAY \\n Trying updating {} from {} to {}'.format(\n code, start_date, end_date), ui_log)\n if start_date != end_date:\n coll_future_day.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_future_day(str(code), QA_util_get_next_day(start_date), end_date)))\n\n # 当前数据库中没有这个代码的股票数据, 从1990-01-01 开始下载所有的数据\n else:\n start_date = '2001-01-01'\n QA_util_log_info('UPDATE_Future_DAY \\n Trying updating {} from {} to {}'.format\n (code, start_date, end_date), ui_log)\n if start_date != end_date:\n coll_future_day.insert_many(\n QA_util_to_json_from_pandas(\n QA_fetch_get_future_day(str(code), start_date, end_date)))\n except Exception as error0:\n print(error0)\n err.append(str(code))\n\n for item in range(len(future_list)):\n QA_util_log_info('The {} of Total {}'.format\n (item, len(future_list)))\n\n strProgressToLog = 'DOWNLOAD PROGRESS {} {}'.format(\n str(float(item / len(future_list) * 100))[0:4] + '%', ui_log)\n intProgressToLog = int(float(item / len(future_list) * 100))\n QA_util_log_info(strProgressToLog, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intProgressToLog)\n\n __saving_work(future_list[item], coll_future_day)\n\n if len(err) < 1:\n QA_util_log_info('SUCCESS save future day ^_^', ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log)\n QA_util_log_info(err, ui_log)\n\n\ndef QA_SU_save_future_min(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save future_min\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n future_list = [item for item in QA_fetch_get_future_list(\n ).code.unique().tolist() if str(item)[-2:] in ['L8', 'L9']]\n coll = client.future_min\n coll.create_index([('code', pymongo.ASCENDING), ('time_stamp',\n pymongo.ASCENDING), ('date_stamp', pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll):\n\n QA_util_log_info(\n '##JOB13 Now Saving Future_MIN ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n\n for type in ['1min', '5min', '15min', '30min', '60min']:\n ref_ = coll.find(\n {'code': str(code)[0:6], 'type': type})\n end_time = str(now_time())[0:19]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['datetime']\n\n QA_util_log_info(\n '##JOB13.{} Now Saving Future {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type),\n ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data[1::]))\n else:\n start_time = '2015-01-01'\n\n QA_util_log_info(\n '##JOB13.{} Now Saving Future {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type), ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data))\n except:\n err.append(code)\n\n executor = ThreadPoolExecutor(max_workers=4)\n\n res = {executor.submit(\n __saving_work, future_list[i_], coll) for i_ in range(len(future_list))} # multi index ./.\n count = 0\n for i_ in concurrent.futures.as_completed(res):\n\n QA_util_log_info('The {} of Total {}'.format(\n count, len(future_list)), ui_log=ui_log)\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(count / len(future_list) * 100))[0:4] + '%')\n intLogProgress = int(float(count / len(future_list) * 10000.0))\n\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n count = count + 1\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\ndef QA_SU_save_future_min_all(client=DATABASE, ui_log=None, ui_progress=None):\n \"\"\"save future_min_all (全部, 包含单月合约)\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n \"\"\"\n\n future_list = QA_fetch_get_future_list().code.unique().tolist()\n coll = client.future_min\n coll.create_index([('code', pymongo.ASCENDING), ('time_stamp',\n pymongo.ASCENDING), ('date_stamp', pymongo.ASCENDING)])\n err = []\n\n def __saving_work(code, coll):\n\n QA_util_log_info(\n '##JOB13 Now Saving Future_MIN ==== {}'.format(str(code)), ui_log=ui_log)\n try:\n\n for type in ['1min', '5min', '15min', '30min', '60min']:\n ref_ = coll.find(\n {'code': str(code)[0:6], 'type': type})\n end_time = str(now_time())[0:19]\n if ref_.count() > 0:\n start_time = ref_[ref_.count() - 1]['datetime']\n\n QA_util_log_info(\n '##JOB13.{} Now Saving Future {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type),\n ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data[1::]))\n else:\n start_time = '2015-01-01'\n\n QA_util_log_info(\n '##JOB13.{} Now Saving Future {} from {} to {} =={} '\n .format(['1min', '5min', '15min', '30min', '60min']\n .index(type), str(code), start_time, end_time, type), ui_log=ui_log)\n\n if start_time != end_time:\n __data = QA_fetch_get_future_min(\n str(code), start_time, end_time, type)\n if len(__data) > 1:\n coll.insert_many(\n QA_util_to_json_from_pandas(__data))\n except:\n err.append(code)\n\n executor = ThreadPoolExecutor(max_workers=4)\n\n res = {executor.submit(\n __saving_work, future_list[i_], coll) for i_ in range(len(future_list))} # multi index ./.\n count = 0\n for i_ in concurrent.futures.as_completed(res):\n\n QA_util_log_info('The {} of Total {}'.format(\n count, len(future_list)), ui_log=ui_log)\n strLogProgress = 'DOWNLOAD PROGRESS {} '.format(\n str(float(count / len(future_list) * 100))[0:4] + '%')\n intLogProgress = int(float(count / len(future_list) * 10000.0))\n\n QA_util_log_info(strLogProgress, ui_log=ui_log,\n ui_progress=ui_progress, ui_progress_int_value=intLogProgress)\n count = count + 1\n if len(err) < 1:\n QA_util_log_info('SUCCESS', ui_log=ui_log)\n else:\n QA_util_log_info(' ERROR CODE \\n ', ui_log=ui_log)\n QA_util_log_info(err, ui_log=ui_log)\n\n\nif __name__ == '__main__':\n # QA_SU_save_stock_day()\n # QA_SU_save_stock_xdxr()\n # QA_SU_save_stock_min()\n # QA_SU_save_stock_transaction()\n # QA_SU_save_index_day()\n # QA_SU_save_stock_list()\n # QA_SU_save_index_min()\n # QA_SU_save_index_list()\n # QA_SU_save_future_list()\n\n QA_SU_save_future_day()\n\n QA_SU_save_future_min()\n"
] |
[
[
"pandas.DataFrame.from_items"
]
] |
airanmehr/Utils
|
[
"f97d704bb075b249d2b0dde5473327249f9deef4"
] |
[
"EE.py"
] |
[
"import numpy as np\nimport pandas as pd\ncomaleName = r'\\sc{Clear}'\nclass EE:\n @staticmethod\n def fx(x, s=0.0, h=0.5):\n Z=(1 + s) * x ** 2 + 2 * (1 + h * s) * x * (1 - x) + (1 - x) ** 2\n if Z>0:\n return ((1 + s) * x ** 2 + (1 + h * s) * x * (1 - x)) / (Z)\n else:\n return 0\n\n @staticmethod\n def sig(x): return 1. / (1 + np.exp(-x))\n\n @staticmethod\n def logit(p): return np.log(p) - np.log(1 - p)\n\n\n # def logit_(p): return T.log(p) - T.log(1 - p)\n\n\n # def sig_(x): return 1. / (1 + T.exp(-x))\n\n @staticmethod\n def Nu(s, t, nu0, theta, n=2000): return EE.Z(EE.sig(t * s / 2 + EE.logit(nu0)), n, theta)\n\n @staticmethod\n def forward(x0=0.005,h=0.5,s=1,t=150):\n def f(x,h=0.5,s=1): return ((1+s)*x*x + (1+h*s)*x*(1-x) )/((1+s)*x*x + 2*(1+h*s)*x*(1-x) +(1-x)**2)\n x=[x0]\n for i in range(t):\n x+=[f(x[-1],h,s)]\n return pd.Series(x)\n\n floatX = 'float64'\n\n @staticmethod\n def Z(nu, n, theta): return theta * (\n nu * ((nu + 1) / 2. - 1. / ((1 - nu) * n + 1)) + (1 - nu) * ((n + 1.) / (2 * n) - 1. / ((1 - nu) * n + 1)))\n"
] |
[
[
"numpy.log",
"numpy.exp",
"pandas.Series"
]
] |
DS1SQM/OPKR086_test4
|
[
"db60403de9fd5a80580b75fd852aea538d9fd83a"
] |
[
"selfdrive/car/hyundai/spdcontroller.py"
] |
[
"#this was initiated by atom(conan)\n#partially modified by opkr\nimport math\nimport numpy as np\n\nfrom cereal import log\nimport cereal.messaging as messaging\n\nfrom selfdrive.config import Conversions as CV\nfrom selfdrive.controls.lib.speed_smoother import speed_smoother\nfrom selfdrive.controls.lib.long_mpc import LongitudinalMpc\nfrom selfdrive.controls.lib.lane_planner import TRAJECTORY_SIZE\nfrom selfdrive.car.hyundai.values import Buttons\nfrom common.numpy_fast import clip, interp\nfrom common.params import Params\n\nfrom selfdrive.config import RADAR_TO_CAMERA\n\nimport common.log as trace1\nimport common.CTime1000 as tm\nimport common.MoveAvg as moveavg1\n\n\nMAX_SPEED = 255.0\nMIN_CURVE_SPEED = 30.\n\nLON_MPC_STEP = 0.2 # first step is 0.2s\nMAX_SPEED_ERROR = 2.0\nAWARENESS_DECEL = -0.2 # car smoothly decel at .2m/s^2 when user is distracted\n\n# lookup tables VS speed to determine min and max accels in cruise\n# make sure these accelerations are smaller than mpc limits\n_A_CRUISE_MIN_V = [-1.0, -.8, -.67, -.5, -.30]\n_A_CRUISE_MIN_BP = [0., 5., 10., 20., 40.]\n\n# need fast accel at very low speed for stop and go\n# make sure these accelerations are smaller than mpc limits\n_A_CRUISE_MAX_V = [1.2, 1.2, 0.65, .4]\n_A_CRUISE_MAX_V_FOLLOWING = [1.6, 1.6, 0.65, .4]\n_A_CRUISE_MAX_BP = [0., 6.4, 22.5, 40.]\n\n# Lookup table for turns\n_A_TOTAL_MAX_V = [1.7, 3.2]\n_A_TOTAL_MAX_BP = [20., 40.]\n\n# 75th percentile\nSPEED_PERCENTILE_IDX = 7\n\ndef limit_accel_in_turns(v_ego, angle_steers, a_target, steerRatio, wheelbase):\n \"\"\"\n This function returns a limited long acceleration allowed, depending on the existing lateral acceleration\n this should avoid accelerating when losing the target in turns\n \"\"\"\n\n a_total_max = interp(v_ego, _A_TOTAL_MAX_BP, _A_TOTAL_MAX_V)\n a_y = v_ego**2 * angle_steers * CV.DEG_TO_RAD / (steerRatio * wheelbase)\n a_x_allowed = math.sqrt(max(a_total_max**2 - a_y**2, 0.))\n\n return [a_target[0], min(a_target[1], a_x_allowed)]\n\n\nclass SpdController():\n def __init__(self, CP=None):\n self.long_control_state = 0 # initialized to off\n\n self.seq_step_debug = \"\"\n self.long_curv_timer = 0\n\n self.path_x = np.arange(192)\n\n self.traceSC = trace1.Loger(\"SPD_CTRL\")\n\n self.v_model = 0\n self.a_model = 0\n self.v_cruise = 0\n self.a_cruise = 0\n\n self.l_poly = []\n self.r_poly = []\n\n self.movAvg = moveavg1.MoveAvg()\n self.Timer1 = tm.CTime1000(\"SPD\")\n self.time_no_lean = 0\n\n self.wait_timer2 = 0\n\n self.cruise_set_speed_kph = 0\n self.curise_set_first = 0\n self.curise_sw_check = 0\n self.prev_clu_CruiseSwState = 0 \n\n self.prev_VSetDis = 0\n \n self.sc_clu_speed = 0\n self.btn_type = Buttons.NONE\n self.active_time = 0\n\n self.old_model_speed = 0\n self.old_model_init = 0\n\n self.curve_speed = 0\n self.curvature_gain = 1\n\n self.params = Params()\n self.cruise_set_mode = int(self.params.get(\"CruiseStatemodeSelInit\", encoding=\"utf8\"))\n self.map_spd_limit_offset = int(self.params.get(\"OpkrSpeedLimitOffset\", encoding=\"utf8\"))\n\n self.map_spd_enable = False\n self.map_spd_camera = 0\n self.map_enabled = False\n self.second = 0\n self.sm = messaging.SubMaster(['liveMapData'])\n\n def reset(self):\n self.v_model = 0\n self.a_model = 0\n self.v_cruise = 0\n self.a_cruise = 0\n\n def cal_curve_speed(self, sm, v_ego):\n md = sm['modelV2']\n if md is not None and len(md.position.x) == TRAJECTORY_SIZE and len(md.position.y) == TRAJECTORY_SIZE:\n x = md.position.x\n y = md.position.y\n dy = np.gradient(y, x)\n d2y = np.gradient(dy, x)\n curv = d2y / (1 + dy ** 2) ** 1.5\n curv = curv[5:TRAJECTORY_SIZE-10]\n a_y_max = 2.975 - v_ego * 0.0375 # ~1.85 @ 75mph, ~2.6 @ 25mph\n v_curvature = np.sqrt(a_y_max / np.clip(np.abs(curv), 1e-4, None))\n model_speed = np.mean(v_curvature) * 0.9 * self.curvature_gain\n self.curve_speed = float(max(model_speed, MIN_CURVE_SPEED * CV.KPH_TO_MS))\n # if model_speed < v_ego:\n # self.curve_speed = float(max(model_speed, MIN_CURVE_SPEED * CV.KPH_TO_MS))\n # else:\n # self.curve_speed = MAX_SPEED\n if np.isnan(self.curve_speed):\n self.curve_speed = MAX_SPEED\n else:\n self.curve_speed = MAX_SPEED\n\n return min(MAX_SPEED, self.curve_speed * CV.MS_TO_KPH)\n\n def calc_laneProb(self, prob, v_ego):\n if len(prob) > 1:\n path = list(prob)\n\n # TODO: compute max speed without using a list of points and without numpy\n y_p = 3 * path[0] * self.path_x**2 + \\\n 2 * path[1] * self.path_x + path[2]\n y_pp = 6 * path[0] * self.path_x + 2 * path[1]\n curv = y_pp / (1. + y_p**2)**1.5\n\n #print( 'curv = {}'.format( curv) )\n\n a_y_max = 2.975 - v_ego * 0.0375 # ~1.85 @ 75mph, ~2.6 @ 25mph\n v_curvature = np.sqrt(a_y_max / np.clip(np.abs(curv), 1e-4, None))\n model_speed = np.min(v_curvature)\n # Don't slow down below 20mph\n\n model_speed *= CV.MS_TO_KPH\n model_speed = max(MIN_CURVE_SPEED, model_speed)\n # print( 'v_curvature = {}'.format( v_curvature) )\n #print( 'model_speed = {} '.format( model_speed) )\n\n \n if model_speed > MAX_SPEED:\n model_speed = MAX_SPEED\n else:\n model_speed = MAX_SPEED\n \n\n return model_speed\n\n\n def cal_model_speed(self, sm, v_ego):\n md = sm['modelV2']\n #print('{}'.format( md ) )\n if len(md.path.poly):\n self.prob = list(md.path.poly)\n\n model_speed = self.calc_laneProb( self.prob, v_ego )\n \n delta_model = model_speed - self.old_model_speed\n if self.old_model_init < 10:\n self.old_model_init += 1\n self.old_model_speed = model_speed\n elif self.old_model_speed == model_speed:\n pass\n elif delta_model < -1:\n self.old_model_speed -= 0.5 #model_speed\n elif delta_model > 0:\n self.old_model_speed += 0.1\n\n else:\n self.old_model_speed = model_speed\n\n return self.old_model_speed\n\n\n def update_cruiseSW(self, CS):\n set_speed_kph = int(round(self.cruise_set_speed_kph))\n delta_vsetdis = 0\n if CS.acc_active:\n delta_vsetdis = abs(int(CS.VSetDis) - self.prev_VSetDis)\n if self.prev_clu_CruiseSwState != CS.cruise_buttons:\n if CS.cruise_buttons == Buttons.RES_ACCEL or CS.cruise_buttons == Buttons.SET_DECEL:\n self.prev_VSetDis = int(CS.VSetDis)\n elif CS.driverOverride:\n set_speed_kph = int(CS.VSetDis)\n elif self.prev_clu_CruiseSwState == Buttons.RES_ACCEL: # up \n if self.curise_set_first:\n self.curise_set_first = 0\n set_speed_kph = int(CS.VSetDis)\n elif delta_vsetdis > 0:\n set_speed_kph = int(CS.VSetDis)\n elif not self.curise_sw_check:\n set_speed_kph += 1\n elif self.prev_clu_CruiseSwState == Buttons.SET_DECEL: # dn\n if self.curise_set_first:\n self.curise_set_first = 0\n set_speed_kph = int(CS.VSetDis)\n elif delta_vsetdis > 0:\n set_speed_kph = int(CS.VSetDis)\n elif not self.curise_sw_check:\n set_speed_kph -= 1\n\n self.prev_clu_CruiseSwState = CS.cruise_buttons\n elif (CS.cruise_buttons == Buttons.RES_ACCEL or CS.cruise_buttons == Buttons.SET_DECEL) and delta_vsetdis > 0:\n self.curise_sw_check = True\n set_speed_kph = int(CS.VSetDis)\n else:\n self.curise_sw_check = False\n self.curise_set_first = 1\n self.prev_VSetDis = int(CS.VSetDis)\n set_speed_kph = int(CS.VSetDis)\n if self.prev_clu_CruiseSwState != CS.cruise_buttons: # MODE 전환.\n if CS.cruise_buttons == Buttons.GAP_DIST and not CS.acc_active and CS.out.cruiseState.available:\n self.cruise_set_mode += 1\n if self.cruise_set_mode > 4:\n self.cruise_set_mode = 0\n self.prev_clu_CruiseSwState = CS.cruise_buttons\n \n\n if set_speed_kph <= 30:\n set_speed_kph = 30\n\n self.cruise_set_speed_kph = set_speed_kph\n return self.cruise_set_mode, set_speed_kph\n\n\n @staticmethod\n def get_lead(sm):\n plan = sm['longitudinalPlan']\n if 0 < plan.dRel1 < 149:\n dRel = int(plan.dRel1) #EON Lead\n yRel = int(plan.yRel1) #EON Lead\n vRel = int(plan.vRel1 * 3.6 + 0.5) #EON Lead\n else:\n dRel = 150\n yRel = 0\n vRel = 0\n\n\n return dRel, yRel, vRel\n\n\n\n def get_tm_speed(self, CS, set_time, add_val, safety_dis=5):\n time = int(set_time)\n\n delta_speed = int(CS.VSetDis) - int(round(CS.clu_Vanz))\n set_speed = int(CS.VSetDis) + add_val\n \n if add_val > 0: # 증가\n if delta_speed > safety_dis:\n time = int(set_time)\n\n else:\n if delta_speed < -safety_dis:\n time = int(set_time)\n\n return time, set_speed\n\n # returns a \n def update_lead(self, c, can_strings):\n raise NotImplementedError\n\n def update_curv(self, CS, sm, curve_speed):\n raise NotImplementedError\n\n def update_log(self, CS, set_speed, target_set_speed, long_wait_cmd):\n str3 = 'M={:3.0f} DST={:3.0f} VSD={:.0f} DA={:.0f}/{:.0f}/{:.0f} DG={:s} DO={:.0f}'.format(\n CS.out.cruiseState.modeSel, target_set_speed, CS.VSetDis, CS.driverAcc_time, long_wait_cmd, self.long_curv_timer, self.seq_step_debug, CS.driverOverride )\n str4 = ' CS={:.1f}/{:.1f} '.format( CS.lead_distance, CS.lead_objspd )\n str5 = str3 + str4\n trace1.printf2( str5 )\n\n def lead_control(self, CS, sm, CC):\n dRel = CC.dRel\n yRel = CC.yRel\n vRel = CC.vRel\n active_time = 10\n btn_type = Buttons.NONE\n #lead_1 = sm['radarState'].leadOne\n long_wait_cmd = 500\n set_speed = int(round(self.cruise_set_speed_kph))\n\n if self.long_curv_timer < 600:\n self.long_curv_timer += 1\n\n\n # 선행 차량 거리유지\n lead_wait_cmd, lead_set_speed = self.update_lead( sm, CS, dRel, yRel, vRel, CC)\n\n # 커브 감속.\n curve_speed = CC.curve_speed #cal_curve_speed(sm, CS.out.vEgo)\n curv_wait_cmd, curv_set_speed = self.update_curv(CS, sm, curve_speed)\n\n if curv_wait_cmd != 0:\n if lead_set_speed > curv_set_speed:\n set_speed = curv_set_speed\n long_wait_cmd = curv_wait_cmd\n else:\n set_speed = lead_set_speed\n long_wait_cmd = lead_wait_cmd\n else:\n set_speed = lead_set_speed\n long_wait_cmd = lead_wait_cmd\n\n if set_speed >= int(round(self.cruise_set_speed_kph)):\n set_speed = int(round(self.cruise_set_speed_kph))\n elif set_speed <= 30:\n set_speed = 30\n\n # control process\n target_set_speed = set_speed\n delta = int(round(set_speed)) - int(CS.VSetDis)\n dec_step_cmd = 1\n\n self.second += 1\n if self.second > 200:\n self.map_enabled = Params().get_bool(\"OpkrMapEnable\")\n self.second = 0\n\n if self.map_enabled:\n self.sm.update(0)\n self.map_spd_camera = float(self.sm['liveMapData'].speedLimit)\n self.map_spd_enable = True if self.map_spd_camera > 29 else False\n else:\n self.map_spd_camera = CS.out.safetySign\n self.map_spd_enable = True if self.map_spd_camera > 29. else False\n\n if self.long_curv_timer < long_wait_cmd:\n pass\n elif delta > 0:\n if ((self.map_spd_camera+round(self.map_spd_camera*0.01*self.map_spd_limit_offset)) == int(CS.VSetDis)) and self.map_spd_enable:\n set_speed = int(CS.VSetDis) + 0\n btn_type = Buttons.NONE\n self.long_curv_timer = 0\n else:\n set_speed = int(CS.VSetDis) + dec_step_cmd\n btn_type = Buttons.RES_ACCEL\n self.long_curv_timer = 0\n elif delta < 0:\n set_speed = int(CS.VSetDis) - dec_step_cmd\n btn_type = Buttons.SET_DECEL\n self.long_curv_timer = 0\n if self.cruise_set_mode == 0:\n btn_type = Buttons.NONE\n\n\n self.update_log( CS, set_speed, target_set_speed, long_wait_cmd )\n\n\n return btn_type, set_speed, active_time\n\n\n\n def update(self, CS, sm, CC):\n self.cruise_set_mode = CS.out.cruiseState.modeSel\n #self.cruise_set_speed_kph = int(round(CS.out.cruiseState.speed * CV.MS_TO_KPH))\n self.cruise_set_speed_kph = int(round(CC.vCruiseSet))\n if CS.driverOverride == 2 or not CS.acc_active or CS.cruise_buttons == Buttons.RES_ACCEL or CS.cruise_buttons == Buttons.SET_DECEL:\n self.resume_cnt = 0\n self.btn_type = Buttons.NONE\n self.wait_timer2 = 10\n self.active_timer2 = 0\n elif self.wait_timer2:\n self.wait_timer2 -= 1\n else:\n btn_type, clu_speed, active_time = self.lead_control( CS, sm, CC ) # speed controller spdcontroller.py\n\n if (0 <= int(CS.clu_Vanz) <= 1 or 7 < int(CS.clu_Vanz) < 15) and CC.vRel <= 0:\n self.btn_type = Buttons.NONE\n elif self.btn_type != Buttons.NONE:\n pass\n elif btn_type != Buttons.NONE:\n self.resume_cnt = 0\n self.active_timer2 = 0\n self.btn_type = btn_type\n self.sc_clu_speed = clu_speed \n self.active_time = max( 5, active_time )\n\n if self.btn_type != Buttons.NONE:\n self.active_timer2 += 1\n if self.active_timer2 > self.active_time:\n self.wait_timer2 = 5\n self.resume_cnt = 0\n self.active_timer2 = 0\n self.btn_type = Buttons.NONE \n else:\n return 1\n return 0 "
] |
[
[
"numpy.abs",
"numpy.min",
"numpy.isnan",
"numpy.arange",
"numpy.gradient",
"numpy.mean"
]
] |
swaldtmann/squid_accel_log_analyzer
|
[
"c7dee8b633f90c8a7be2a29426f898a700d70e0d"
] |
[
"panda_parser.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport pandas as pd\n\nlog_data = open('./data/access.log', 'r')\nfields = ['ts', 'elapsed', 'remhost', 'status', 'bytes',\n 'method', 'url', 'rfc931', 'peerstatus', 'type']\nsplit_list = list()\n\n\nfor line in log_data:\n ls = line.split()\n l_type = ls[9]\n l_url = ls[6]\n # if l.type == \"text/html\":\n if l_type == \"application/vnd.apple.mpegurl\":\n # Group by Time Interval\n file = (l_url).split(\"/\")[-1]\n if file == \"playlist.m3u8\":\n # split_list.append(line.split())\n split_list.append([ls[0], ls[2], ls[6], file])\n\ndf = pd.DataFrame(split_list, columns=['ts', 'remhost', 'url', 'file'])\ndf.ts = pd.to_datetime(df.ts, unit='s')\nprint(df.dtypes)\nprint(df)\n\n\ndf_final = df.groupby(pd.Grouper(key='ts',freq='15min')).count()\n\n#df_final = df_grouped.sort_values('url', ascending=False)\nprint(df_final)\n#df_final.to_csv (r'./export_dataframe.csv', index = True, header=True)\nwith pd.ExcelWriter('./date/export_dataframe.xlsx') as writer:\n df_final.to_excel(writer)"
] |
[
[
"pandas.to_datetime",
"pandas.Grouper",
"pandas.DataFrame",
"pandas.ExcelWriter"
]
] |
SolomidHero/vcc20_baseline_cyclevae
|
[
"983f4852cefc525013b2168429934a5c46d45484"
] |
[
"baseline/src/parallel_wavegan/models/melgan.py"
] |
[
"# -*- coding: utf-8 -*-\n\n# Copyright 2020 Tomoki Hayashi\n# MIT License (https://opensource.org/licenses/MIT)\n\n\"\"\"MelGAN Modules.\"\"\"\n\nimport logging\n\nimport numpy as np\nimport torch\n\nfrom parallel_wavegan.layers import ResidualStack\n\n\nclass MelGANGenerator(torch.nn.Module):\n \"\"\"MelGAN generator module.\"\"\"\n\n def __init__(self,\n in_channels=80,\n out_channels=1,\n kernel_size=7,\n channels=512,\n bias=True,\n upsample_scales=[8, 8, 2, 2],\n stack_kernel_size=3,\n stacks=3,\n nonlinear_activation=\"LeakyReLU\",\n nonlinear_activation_params={\"negative_slope\": 0.2},\n pad=\"ReflectionPad1d\",\n pad_params={},\n use_final_nolinear_activation=True,\n use_weight_norm=True,\n use_causal_conv=False,\n ):\n \"\"\"Initialize MelGANGenerator module.\n\n Args:\n in_channels (int): Number of input channels.\n out_channels (int): Number of output channels.\n kernel_size (int): Kernel size of initial and final conv layer.\n channels (int): Initial number of channels for conv layer.\n bias (bool): Whether to add bias parameter in convolution layers.\n upsample_scales (list): List of upsampling scales.\n stack_kernel_size (int): Kernel size of dilated conv layers in residual stack.\n stacks (int): Number of stacks in a single residual stack.\n nonlinear_activation (str): Activation function module name.\n nonlinear_activation_params (dict): Hyperparameters for activation function.\n pad (str): Padding function module name before dilated convolution layer.\n pad_params (dict): Hyperparameters for padding function.\n use_final_nolinear_activation (torch.nn.Module): Activation function for the final layer.\n use_weight_norm (bool): Whether to use weight norm.\n If set to true, it will be applied to all of the conv layers.\n use_causal_conv (bool): Whether to use causal convolution.\n\n \"\"\"\n super(MelGANGenerator, self).__init__()\n\n # check hyper parameters is valid\n assert not use_causal_conv, \"Not supported yet.\"\n assert channels >= np.prod(upsample_scales)\n assert channels % (2 ** len(upsample_scales)) == 0\n\n # add initial layer\n layers = []\n layers += [\n getattr(torch.nn, pad)((kernel_size - 1) // 2, **pad_params),\n torch.nn.Conv1d(in_channels, channels, kernel_size, bias=bias),\n ]\n\n for i, upsample_scale in enumerate(upsample_scales):\n # add upsampling layer\n if upsample_scale == 1:\n layers += [\n getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params),\n torch.nn.Conv1d(\n in_channels=channels // (2 ** i),\n out_channels=channels // (2 ** (i + 1)),\n kernel_size=3,\n stride=1,\n padding=1,\n )\n ]\n else:\n layers += [\n getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params),\n torch.nn.ConvTranspose1d(\n in_channels=channels // (2 ** i),\n out_channels=channels // (2 ** (i + 1)),\n kernel_size=upsample_scale * 2,\n stride=upsample_scale,\n padding=upsample_scale // 2 + upsample_scale % 2,\n output_padding=upsample_scale % 2,\n )\n ]\n\n # add residual stack\n for j in range(stacks):\n layers += [\n ResidualStack(\n kernel_size=stack_kernel_size,\n channels=channels // (2 ** (i + 1)),\n dilation=stack_kernel_size ** j,\n bias=bias,\n nonlinear_activation=nonlinear_activation,\n nonlinear_activation_params=nonlinear_activation_params,\n pad=pad,\n pad_params=pad_params,\n use_causal_conv=use_causal_conv,\n )\n ]\n\n # add final layer\n layers += [\n getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params),\n getattr(torch.nn, pad)((kernel_size - 1) // 2, **pad_params),\n torch.nn.Conv1d(channels // (2 ** (i + 1)), out_channels, kernel_size, bias=bias),\n ]\n if use_final_nolinear_activation:\n layers += [torch.nn.Tanh()]\n\n self.melgan = torch.nn.Sequential(*layers)\n\n # apply weight norm\n if use_weight_norm:\n self.apply_weight_norm()\n\n # reset parameters\n self.reset_parameters()\n\n def forward(self, c):\n \"\"\"Calculate forward propagation.\n\n Args:\n c (Tensor): Input tensor (B, channels, T).\n\n Returns:\n Tensor: Output tensor (B, 1, T ** prod(upsample_scales)).\n\n \"\"\"\n return self.melgan(c)\n\n def remove_weight_norm(self):\n \"\"\"Remove weight normalization module from all of the layers.\"\"\"\n def _remove_weight_norm(m):\n try:\n logging.debug(f\"Weight norm is removed from {m}.\")\n torch.nn.utils.remove_weight_norm(m)\n except ValueError: # this module didn't have weight norm\n return\n\n self.apply(_remove_weight_norm)\n\n def apply_weight_norm(self):\n \"\"\"Apply weight normalization module from all of the layers.\"\"\"\n def _apply_weight_norm(m):\n if isinstance(m, torch.nn.Conv1d) or isinstance(m, torch.nn.ConvTranspose1d):\n torch.nn.utils.weight_norm(m)\n logging.debug(f\"Weight norm is applied to {m}.\")\n\n self.apply(_apply_weight_norm)\n\n def reset_parameters(self):\n \"\"\"Reset parameters.\n\n This initialization follows official implementation manner.\n https://github.com/descriptinc/melgan-neurips/blob/master/mel2wav/modules.py\n\n \"\"\"\n def _reset_parameters(m):\n if isinstance(m, torch.nn.Conv1d) or isinstance(m, torch.nn.ConvTranspose1d):\n m.weight.data.normal_(0.0, 0.02)\n logging.debug(f\"Reset parameters in {m}.\")\n\n self.apply(_reset_parameters)\n\n\nclass MelGANDiscriminator(torch.nn.Module):\n \"\"\"MelGAN discriminator module.\"\"\"\n\n def __init__(self,\n in_channels=1,\n out_channels=1,\n kernel_sizes=[5, 3],\n channels=16,\n max_downsample_channels=1024,\n bias=True,\n downsample_scales=[4, 4, 4, 4],\n nonlinear_activation=\"LeakyReLU\",\n nonlinear_activation_params={\"negative_slope\": 0.2},\n pad=\"ReflectionPad1d\",\n pad_params={},\n ):\n \"\"\"Initilize MelGAN discriminator module.\n\n Args:\n in_channels (int): Number of input channels.\n out_channels (int): Number of output channels.\n kernel_sizes (list): List of two kernel sizes. The prod will be used for the first conv layer,\n and the first and the second kernel sizes will be used for the last two layers.\n For example if kernel_sizes = [5, 3], the first layer kernel size will be 5 * 3 = 15,\n the last two layers' kernel size will be 5 and 3, respectively.\n channels (int): Initial number of channels for conv layer.\n max_downsample_channels (int): Maximum number of channels for downsampling layers.\n bias (bool): Whether to add bias parameter in convolution layers.\n downsample_scales (list): List of downsampling scales.\n nonlinear_activation (str): Activation function module name.\n nonlinear_activation_params (dict): Hyperparameters for activation function.\n pad (str): Padding function module name before dilated convolution layer.\n pad_params (dict): Hyperparameters for padding function.\n\n \"\"\"\n super(MelGANDiscriminator, self).__init__()\n self.layers = torch.nn.ModuleList()\n\n # check kernel size is valid\n assert len(kernel_sizes) == 2\n assert kernel_sizes[0] % 2 == 1\n assert kernel_sizes[1] % 2 == 1\n\n # add first layer\n self.layers += [\n torch.nn.Sequential(\n getattr(torch.nn, pad)((np.prod(kernel_sizes) - 1) // 2, **pad_params),\n torch.nn.Conv1d(in_channels, channels, np.prod(kernel_sizes), bias=bias),\n getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params),\n )\n ]\n\n # add downsample layers\n in_chs = channels\n for downsample_scale in downsample_scales:\n out_chs = min(in_chs * downsample_scale, max_downsample_channels)\n self.layers += [\n torch.nn.Sequential(\n torch.nn.Conv1d(\n in_chs, out_chs,\n kernel_size=downsample_scale * 10 + 1,\n stride=downsample_scale,\n padding=downsample_scale * 5,\n groups=in_chs // 4,\n bias=bias,\n ),\n getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params),\n )\n ]\n in_chs = out_chs\n\n # add final layers\n out_chs = min(in_chs * 2, max_downsample_channels)\n self.layers += [\n torch.nn.Sequential(\n torch.nn.Conv1d(\n in_chs, out_chs, kernel_sizes[0],\n padding=(kernel_sizes[0] - 1) // 2,\n bias=bias,\n ),\n getattr(torch.nn, nonlinear_activation)(**nonlinear_activation_params),\n )\n ]\n self.layers += [\n torch.nn.Conv1d(\n out_chs, out_channels, kernel_sizes[1],\n padding=(kernel_sizes[1] - 1) // 2,\n bias=bias,\n ),\n ]\n\n def forward(self, x):\n \"\"\"Calculate forward propagation.\n\n Args:\n x (Tensor): Input noise signal (B, 1, T).\n\n Returns:\n List: List of output tensors of each layer.\n\n \"\"\"\n outs = []\n for f in self.layers:\n x = f(x)\n outs += [x]\n\n return outs\n\n\nclass MelGANMultiScaleDiscriminator(torch.nn.Module):\n \"\"\"MelGAN multi-scale discriminator module.\"\"\"\n\n def __init__(self,\n in_channels=1,\n out_channels=1,\n scales=3,\n downsample_pooling=\"AvgPool1d\",\n # follow the official implementation setting\n downsample_pooling_params={\n \"kernel_size\": 4,\n \"stride\": 2,\n \"padding\": 1,\n \"count_include_pad\": False,\n },\n kernel_sizes=[5, 3],\n channels=16,\n max_downsample_channels=1024,\n bias=True,\n downsample_scales=[4, 4, 4, 4],\n nonlinear_activation=\"LeakyReLU\",\n nonlinear_activation_params={\"negative_slope\": 0.2},\n pad=\"ReflectionPad1d\",\n pad_params={},\n use_weight_norm=True,\n ):\n \"\"\"Initilize MelGAN multi-scale discriminator module.\n\n Args:\n in_channels (int): Number of input channels.\n out_channels (int): Number of output channels.\n downsample_pooling (str): Pooling module name for downsampling of the inputs.\n downsample_pooling_params (dict): Parameters for the above pooling module.\n kernel_sizes (list): List of two kernel sizes. The sum will be used for the first conv layer,\n and the first and the second kernel sizes will be used for the last two layers.\n channels (int): Initial number of channels for conv layer.\n max_downsample_channels (int): Maximum number of channels for downsampling layers.\n bias (bool): Whether to add bias parameter in convolution layers.\n downsample_scales (list): List of downsampling scales.\n nonlinear_activation (str): Activation function module name.\n nonlinear_activation_params (dict): Hyperparameters for activation function.\n pad (str): Padding function module name before dilated convolution layer.\n pad_params (dict): Hyperparameters for padding function.\n use_causal_conv (bool): Whether to use causal convolution.\n\n \"\"\"\n super(MelGANMultiScaleDiscriminator, self).__init__()\n self.discriminators = torch.nn.ModuleList()\n\n # add discriminators\n for _ in range(scales):\n self.discriminators += [\n MelGANDiscriminator(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_sizes=kernel_sizes,\n channels=channels,\n max_downsample_channels=max_downsample_channels,\n bias=bias,\n downsample_scales=downsample_scales,\n nonlinear_activation=nonlinear_activation,\n nonlinear_activation_params=nonlinear_activation_params,\n pad=pad,\n pad_params=pad_params,\n )\n ]\n self.pooling = getattr(torch.nn, downsample_pooling)(**downsample_pooling_params)\n\n # apply weight norm\n if use_weight_norm:\n self.apply_weight_norm()\n\n # reset parameters\n self.reset_parameters()\n\n def forward(self, x):\n \"\"\"Calculate forward propagation.\n\n Args:\n x (Tensor): Input noise signal (B, 1, T).\n\n Returns:\n List: List of list of each discriminator outputs, which consists of each layer output tensors.\n\n \"\"\"\n outs = []\n for f in self.discriminators:\n outs += [f(x)]\n x = self.pooling(x)\n\n return outs\n\n def remove_weight_norm(self):\n \"\"\"Remove weight normalization module from all of the layers.\"\"\"\n def _remove_weight_norm(m):\n try:\n logging.debug(f\"Weight norm is removed from {m}.\")\n torch.nn.utils.remove_weight_norm(m)\n except ValueError: # this module didn't have weight norm\n return\n\n self.apply(_remove_weight_norm)\n\n def apply_weight_norm(self):\n \"\"\"Apply weight normalization module from all of the layers.\"\"\"\n def _apply_weight_norm(m):\n if isinstance(m, torch.nn.Conv1d) or isinstance(m, torch.nn.ConvTranspose1d):\n torch.nn.utils.weight_norm(m)\n logging.debug(f\"Weight norm is applied to {m}.\")\n\n self.apply(_apply_weight_norm)\n\n def reset_parameters(self):\n \"\"\"Reset parameters.\n\n This initialization follows official implementation manner.\n https://github.com/descriptinc/melgan-neurips/blob/master/mel2wav/modules.py\n\n \"\"\"\n def _reset_parameters(m):\n if isinstance(m, torch.nn.Conv1d) or isinstance(m, torch.nn.ConvTranspose1d):\n m.weight.data.normal_(0.0, 0.02)\n logging.debug(f\"Reset parameters in {m}.\")\n\n self.apply(_reset_parameters)\n"
] |
[
[
"torch.nn.Sequential",
"torch.nn.utils.weight_norm",
"torch.nn.ModuleList",
"torch.nn.utils.remove_weight_norm",
"torch.nn.Tanh",
"numpy.prod",
"torch.nn.Conv1d",
"torch.nn.ConvTranspose1d"
]
] |
notha99y/Multimodal_human_actions
|
[
"6612b23aa8edeae9bf5a603552ccacf870d444ac"
] |
[
"src/show_videos.py"
] |
[
"'''\nScript to show the animation of the dataset\n\nParameters\n----------\n num: int\n TODO add in the action, subject, and trial\n\nReturns\n-------\n video of the choosen num\n'''\n\n\ndef show_depth_video(depth_info, frame_rate=50):\n '''\n Returns and animated video of the depth data\n\n Parameters\n ----------\n depth_info: array like\n The matrices of shape WxHxFrames\n frame_rate: int\n frame rate of the animation (in ms)\n\n Returns\n -------\n None\n Just output a matplotlib figure of the video\n '''\n\n from matplotlib import animation\n import matplotlib.pyplot as plt\n\n fig, ax = plt.subplots(1, figsize=(6, 6))\n\n ax = plt.axes()\n ax.set_axis_off()\n im = plt.imshow(depth_info[:, :, 0])\n\n def init():\n im.set_data(depth_info[:, :, 0])\n return [im]\n\n def animate(i):\n im.set_array(depth_info[:, :, i])\n return [im]\n\n ani = animation.FuncAnimation(\n fig, animate, init_func=init, frames=depth_info.shape[-1], interval=frame_rate, blit=True)\n plt.show()\n\n\ndef show_skeleton_video(skeleton_info, frame_rate=50):\n import numpy as np\n import matplotlib.pyplot as plt\n import mpl_toolkits.mplot3d.axes3d as p3\n from matplotlib import animation\n\n J = np.array([[1, 2, 3, 2, 5, 6, 7, 2, 9, 10, 11, 4, 13, 14, 15, 4, 17, 18, 19],\n [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]])\n J -= 1\n\n fig = plt.figure()\n ax = p3.Axes3D(fig)\n\n maxx = skeleton_info[:, 0, :].max()\n minx = skeleton_info[:, 0, :].min()\n maxy = skeleton_info[:, 1, :].max()\n miny = skeleton_info[:, 1, :].min()\n maxz = skeleton_info[:, 2, :].max()\n minz = skeleton_info[:, 2, :].min()\n\n # ax.set_xlabel('x axis')\n # ax.set_ylabel('z axis')\n # ax.set_zlabel('y axis')\n # ax.set_axis_off()\n\n ax.view_init(90, 0)\n ax.set_xlim3d(minx, maxx)\n ax.set_zlim3d(miny, maxy)\n ax.set_ylim3d(minz, maxz)\n\n ax.set_aspect('equal')\n\n joint = skeleton_info[:, :, 0]\n ln = []\n ln.append(ax.plot(joint[:, 0], joint[:, 2], joint[:, 1], 'o', c='b'))\n for i in range(len(J[0])):\n point1 = joint[J[0, i], :]\n point2 = joint[J[1, i], :]\n\n ln.append(ax.plot(xs=[point1[0], point2[0]], ys=[\n point1[2], point2[2]], zs=[point1[1], point2[1]], c='r'))\n\n def animate(i):\n tot_frames = skeleton_info.shape[-1]\n\n joint = skeleton_info[:, :, i]\n for j in range(len(ln)):\n\n if j == 0:\n ln[j][0].set_data(joint[:, 0], joint[:, 2])\n ln[j][0].set_3d_properties(joint[:, 1])\n else:\n point1 = joint[J[0, j-1], :]\n point2 = joint[J[1, j-1], :]\n ln[j][0].set_data([point1[0], point2[0]],\n [point1[2], point2[2]])\n ln[j][0].set_3d_properties([point1[1], point2[1]])\n ax.view_init(10, -1.2*i)\n ani = animation.FuncAnimation(\n fig, animate, frames=skeleton_info.shape[-1], interval=frame_rate, blit=False)\n ani.save('skeleton.gif', writer='imagemagick', fps=20)\n plt.show()\n\n\nif __name__ == \"__main__\":\n from utils import get_dataset\n import scipy.io as sio\n import os\n\n DATA_PATH = os.path.join(os.getcwd(), 'data')\n print(os.listdir(DATA_PATH))\n depth_paths, RGB_images_paths, inertial_paths, skeleton_paths, RGB_paths, depth_numpy_paths = get_dataset(\n DATA_PATH)\n\n # while True:\n # res = int(input(\"Choose a number from 0 - {}: \".format(len(depth_paths))))\n # depth_info = sio.loadmat(depth_paths[res])['d_depth']\n # show_depth_video(depth_info)\n\n skeleton_info = sio.loadmat(skeleton_paths[450])['d_skel']\n show_skeleton_video(skeleton_info)\n"
] |
[
[
"matplotlib.pyplot.imshow",
"scipy.io.loadmat",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.axes",
"matplotlib.animation.FuncAnimation",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
vikasverma1077/GraphNorm
|
[
"17723c2cc19795125c339dcc898039121d1fbdf2"
] |
[
"GraphNorm_ws/gnn_ws/gnn_example/model/Norm/norm.py"
] |
[
"import torch\r\nimport torch.nn as nn\r\nimport numpy as np\r\n\r\n\r\ndef get_norm(norm, ch, affine=True, twod=True):\r\n \"\"\"Get activation functions from the opt file.\"\"\"\r\n\r\n if norm == 'none':\r\n return nn.Identity()\r\n elif norm == 'batch':\r\n if twod:\r\n return nn.BatchNorm2d(ch, affine = affine)\r\n else:\r\n return nn.BatchNorm1d(ch, affine = affine)\r\n elif norm == 'group':\r\n return nn.GroupNorm(num_groups=min(ch // 4, 32), num_channels=ch, eps=1e-5, affine=affine)\r\n elif norm == 'layer':\r\n return nn.LayerNorm(normalized_shape=ch, eps=1e-5, elementwise_affine=affine)\r\n else:\r\n raise NotImplementedError('norm choice does not exist')\r\n\r\n\r\ndef default_init(scale=1.):\r\n \"\"\"The same initialization used in DDPM.\"\"\"\r\n scale = 1e-10 if scale == 0 else scale\r\n return variance_scaling(scale, 'fan_avg', 'uniform')\r\n\r\n\r\ndef variance_scaling(scale, mode, distribution,\r\n in_axis=1, out_axis=0,\r\n dtype=torch.float32,\r\n device='cpu'):\r\n \"\"\"Ported from JAX. \"\"\"\r\n\r\n def _compute_fans(shape, in_axis=1, out_axis=0):\r\n receptive_field_size = np.prod(shape) / shape[in_axis] / shape[out_axis]\r\n fan_in = shape[in_axis] * receptive_field_size\r\n fan_out = shape[out_axis] * receptive_field_size\r\n return fan_in, fan_out\r\n\r\n def init(shape, dtype=dtype, device=device):\r\n fan_in, fan_out = _compute_fans(shape, in_axis, out_axis)\r\n if mode == \"fan_in\":\r\n denominator = fan_in\r\n elif mode == \"fan_out\":\r\n denominator = fan_out\r\n elif mode == \"fan_avg\":\r\n denominator = (fan_in + fan_out) / 2\r\n else:\r\n raise ValueError(\r\n \"invalid mode for variance scaling initializer: {}\".format(mode))\r\n variance = scale / denominator\r\n if distribution == \"normal\":\r\n return torch.randn(*shape, dtype=dtype, device=device) * np.sqrt(variance)\r\n elif distribution == \"uniform\":\r\n return (torch.rand(*shape, dtype=dtype, device=device) * 2. - 1.) * np.sqrt(3 * variance)\r\n else:\r\n raise ValueError(\"invalid distribution for variance scaling initializer\")\r\n\r\n return init\r\n\r\n\r\nclass Norm(nn.Module):\r\n\r\n def __init__(self, norm_type, hidden_dim=64, print_info=None):\r\n super(Norm, self).__init__()\r\n # assert norm_type in ['bn', 'ln', 'gn', None]\r\n self.norm = None\r\n self.print_info = print_info\r\n if norm_type == 'bn':\r\n self.norm = nn.BatchNorm1d(hidden_dim)\r\n elif norm_type == 'gn':\r\n self.norm = norm_type\r\n self.weight = nn.Parameter(torch.ones(hidden_dim))\r\n self.bias = nn.Parameter(torch.zeros(hidden_dim))\r\n\r\n self.mean_scale = nn.Parameter(torch.ones(hidden_dim))\r\n\r\n def forward(self, graph, tensor, print_=False):\r\n if self.norm is not None and type(self.norm) != str:\r\n return self.norm(tensor)\r\n elif self.norm is None:\r\n return tensor\r\n\r\n batch_list = graph.batch_num_nodes\r\n batch_size = len(batch_list)\r\n batch_list = torch.Tensor(batch_list).long().to(tensor.device)\r\n batch_index = torch.arange(batch_size).to(tensor.device).repeat_interleave(batch_list)\r\n batch_index = batch_index.view((-1,) + (1,) * (tensor.dim() - 1)).expand_as(tensor)\r\n mean = torch.zeros(batch_size, *tensor.shape[1:]).to(tensor.device)\r\n mean = mean.scatter_add_(0, batch_index, tensor)\r\n mean = (mean.T / batch_list).T\r\n mean = mean.repeat_interleave(batch_list, dim=0)\r\n\r\n sub = tensor - mean * self.mean_scale\r\n\r\n std = torch.zeros(batch_size, *tensor.shape[1:]).to(tensor.device)\r\n std = std.scatter_add_(0, batch_index, sub.pow(2))\r\n std = ((std.T / batch_list).T + 1e-6).sqrt()\r\n std = std.repeat_interleave(batch_list, dim=0)\r\n return self.weight * sub / std + self.bias\r\n \r\n\r\nclass ContNorm(nn.Module):\r\n def __init__(self, act, norm, ch, emb_dim = None, spectral=False, no_act=False, twod=True):\r\n super(ContNorm, self).__init__()\r\n \r\n self.norm = norm\r\n self.act = act\r\n self.no_act = no_act or self.norm == 'evo' # we don't apply activation with evo-norm since it's part of it\r\n \r\n if emb_dim is not None:\r\n if spectral:\r\n self.Dense_0 = torch.nn.utils.spectral_norm(nn.Linear(emb_dim, 2*ch))\r\n else:\r\n self.Dense_0 = nn.Linear(emb_dim, 2*ch)\r\n self.Dense_0.weight.data = default_init()(self.Dense_0.weight.shape)\r\n nn.init.zeros_(self.Dense_0.bias)\r\n affine = False # We remove scale/intercept after normalization since we will learn it with [temb, yemb]\r\n else:\r\n affine = True\r\n\r\n self.Norm_0 = get_norm(norm, ch, affine, twod)\r\n \r\n def forward(self, graph, x, emb = None):\r\n if emb is not None:\r\n #emb = torch.cat([temb, yemb], dim=1) # Combine embeddings\r\n emb_out = self.Dense_0(emb)#[:, :, None, None] # Linear projection\r\n # ada-norm as in https://github.com/openai/guided-diffusion\r\n scale, shift = torch.chunk(emb_out, 2, dim=-1)\r\n \r\n node_per_graph = graph.batch_num_nodes\r\n node_per_graph = torch.Tensor(node_per_graph).long().to(x.device)\r\n scale = scale.repeat_interleave(node_per_graph, dim=0)\r\n shift = shift.repeat_interleave(node_per_graph, dim=0)\r\n #print(scale.size())\r\n #print(shift.size())\r\n #print(x.size())\r\n x = self.Norm_0(x) * (1 + scale) + shift\r\n else:\r\n x = self.Norm_0(x)\r\n if not self.no_act: # we don't apply activation with evo-norm since it's part of it\r\n x = self.act(x)\r\n return(x)"
] |
[
[
"torch.nn.BatchNorm1d",
"torch.ones",
"numpy.sqrt",
"torch.Tensor",
"torch.zeros",
"torch.randn",
"torch.arange",
"torch.nn.LayerNorm",
"torch.nn.Linear",
"torch.nn.Identity",
"torch.rand",
"numpy.prod",
"torch.nn.BatchNorm2d",
"torch.chunk",
"torch.nn.init.zeros_"
]
] |
ryoherisson/torch-classifier
|
[
"decf4dae0bc9e26cb5cda4ab85fad481e0b9331b"
] |
[
"dataloader/dataloader.py"
] |
[
"\"\"\"DataLoader class\"\"\"\nfrom typing import List\nfrom pathlib import Path\n\nimport pandas as pd\n\nimport torch.utils.data as data\n\nfrom dataloader.utils import make_data_list\nfrom dataloader.dataset import Dataset\nfrom dataloader.transform import DataTransform\n\nclass DataLoader:\n \"\"\"Data Loader class\"\"\"\n\n @staticmethod\n def load_data(dataroot: str, labelpath: str):\n \"\"\"load dataset from path\n\n Parameters\n ----------\n dataroot : str\n path to the image data directory e.g. './data/images/'\n labelpath : str\n path to the label csv e.g. './data/labels/train.csv'\n\n Returns\n -------\n Tuple of list\n img_list: e.g. ['./data/images/car1.png', './data/images/dog4.png', ...]\n lbl_list: e.g. [3, 5, ...]\n \"\"\"\n img_list, lbl_list = make_data_list(dataroot, labelpath)\n return (img_list, lbl_list)\n\n @staticmethod\n def preprocess_data(data_config: object, img_list: List, lbl_list: List, batch_size: int, mode: str):\n \"\"\"Preprocess dataset\n\n Parameters\n ----------\n data_config : object\n data configuration\n img_list : List\n a list of image paths\n lbl_list : List\n a list of labels\n batch_size : int\n batch_size\n mode : str\n 'train' or 'eval'\n\n Returns\n -------\n Object : \n DataLoader instance\n\n Raises\n ------\n ValueError\n raise value error if the mode is not 'train' or 'eval'\n \"\"\"\n # transform\n resize = (data_config.img_size[0], data_config.img_size[1])\n color_mean = tuple(data_config.color_mean)\n color_std = tuple(data_config.color_std)\n transform = DataTransform(resize, color_mean, color_std, mode)\n\n # dataset\n dataset = Dataset(img_list, lbl_list, transform)\n\n # dataloader\n if mode == 'train':\n return data.DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=2)\n elif mode == 'eval':\n return data.DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=2)\n else:\n raise ValueError('the mode should be train or eval. this mode is not supported')\n"
] |
[
[
"torch.utils.data.DataLoader"
]
] |
dongyan1024/overtime
|
[
"4f722a823585890026fe9584ba5985963b2a586c"
] |
[
"overtime/components/nodes.py"
] |
[
"\r\nimport math\r\nimport pandas as pd\r\n\r\n\r\n\r\nclass Node:\r\n \"\"\"\r\n A class to represent a node on a graph.\r\n\r\n Parameter(s):\r\n -------------\r\n label : String\r\n A label for the node.\r\n graph : Graph\r\n A valid Graph class/subclass.\r\n\r\n Object Propertie(s):\r\n --------------------\r\n label : String\r\n The label of the node.\r\n graph : Graph\r\n The graph of which the node belongs to.\r\n data : Dictionary\r\n A dictionary to be used for adding ambiguous data to a node.\r\n\r\n See also:\r\n ---------\r\n ForemostNode\r\n Nodes\r\n ForemostNodes\r\n \"\"\"\r\n\r\n def __init__(self, label, graph):\r\n self.label = str(label)\r\n self.graph = graph\r\n self.data = dict()\r\n\r\n\r\n def print(self):\r\n \"\"\"\r\n A method of Node.\r\n\r\n Returns:\r\n --------\r\n None, prints the label of the node.\r\n \"\"\"\r\n print(self.label)\r\n\r\n\r\n def node1of(self, time=None):\r\n \"\"\"\r\n A method of Node.\r\n\r\n Parameter(s):\r\n -------------\r\n time : Integer\r\n Time to check connectivity.\r\n\r\n Returns:\r\n --------\r\n edges : Edges\r\n An edges class/subclass object.\r\n The collection of edges returned each have the node1 property of this node (self).\r\n \"\"\"\r\n # if a time was specified.\r\n if time is not None:\r\n # get all graph edges that are active at this time.\r\n edges = self.graph.edges.get_active_edges(time)\r\n else:\r\n # no time was specified, get all the graph's edges.\r\n edges = self.graph.edges\r\n # return the edges that have this node as their 'node1' property.\r\n return edges.get_edge_by_node1(self.label)\r\n\r\n \r\n def sourceof(self, time=None):\r\n \"\"\"\r\n A method of Node.\r\n\r\n Parameter(s):\r\n -------------\r\n time : Integer\r\n Time to check connectivity.\r\n\r\n Returns:\r\n --------\r\n edges : Edges\r\n An edges class/subclass object.\r\n The collection of edges returned each have the sourceof property of this node (self).\r\n \"\"\"\r\n # return node1of (analogous property)\r\n return self.node1of(time)\r\n\r\n\r\n def node2of(self, time=None):\r\n \"\"\"\r\n A method of Node.\r\n\r\n Parameter(s):\r\n -------------\r\n time : Integer\r\n Time to check connectivity.\r\n\r\n Returns:\r\n --------\r\n edges : Edges\r\n An edges class/subclass object.\r\n The collection of edges returned each have the node2 property of this node (self).\r\n \"\"\"\r\n # if time was specified.\r\n if time is not None:\r\n # get all graph edges that are active at this time.\r\n edges = self.graph.edges.get_active_edges(time)\r\n else:\r\n # no time was specified, get all the graph's edges.\r\n edges = self.graph.edges\r\n # return the edges that have this node as their 'node2' property.\r\n return edges.get_edge_by_node2(self.label)\r\n\r\n \r\n def sinkof(self, time=None):\r\n \"\"\"\r\n A method of Node.\r\n\r\n Parameter(s):\r\n -------------\r\n time : Integer\r\n Time to check connectivity.\r\n\r\n Returns:\r\n --------\r\n edges : Edges\r\n An edges class/subclass object.\r\n The collection of edges returned each have the sinkof property of this node (self).\r\n \"\"\"\r\n # return node2of (analogous property)\r\n return self.node2of(time)\r\n\r\n\r\n def nodeof(self, time=None):\r\n \"\"\"\r\n A method of Node.\r\n\r\n Parameter(s):\r\n -------------\r\n time : Integer\r\n Time to check connectivity.\r\n\r\n Returns:\r\n --------\r\n edges : Edges\r\n An edges class/subclass object.\r\n The collection of edges returned each have the node1 or node2 property of this node (self).\r\n \"\"\"\r\n # if time was specified.\r\n if time is not None:\r\n # get all graph edges that are active at this time.\r\n edges = self.graph.edges.get_active_edges(time)\r\n else:\r\n # no time was specified, get all the graph's edges.\r\n edges = self.graph.edges\r\n # return the edges that have this node as their 'node1' or 'node2' property.\r\n return edges.get_edge_by_node(self.label)\r\n\r\n\r\n def neighbours(self, time=None):\r\n \"\"\"\r\n A method of Node.\r\n\r\n Parameter(s):\r\n -------------\r\n time : Integer\r\n Time to check connectivity.\r\n\r\n Returns:\r\n --------\r\n nodes : Nodes\r\n A nodes class/subclass object.\r\n The collection of nodes returned that are adjacent to this node (self).\r\n \"\"\"\r\n node1_edges = self.node1of(time) # edges that have this node as their 'node1' property.\r\n node2_edges = self.node2of(time) # edges that have this node as their 'node2' property.\r\n # create a new nodes collection.\r\n neighbours = self.graph.nodes.subset([])\r\n # for each edge in the node1 edges.\r\n for edge in node1_edges.set:\r\n # if the node has not already been added.\r\n if not neighbours.exists(edge.node2.label):\r\n # add the node as a neighbour.\r\n neighbours.add(edge.node2.label)\r\n # for each edge in the node2 edges.\r\n for edge in node2_edges.set:\r\n # if the node has not already been added.\r\n if not neighbours.exists(edge.node1.label):\r\n # add the node as a neighbour.\r\n neighbours.add(edge.node1.label)\r\n return neighbours\r\n\r\n\r\n\r\nclass ForemostNode(Node):\r\n \"\"\"\r\n A class to represent a node on a graph.\r\n\r\n Parameter(s):\r\n -------------\r\n label : String\r\n A label for the node.\r\n graph : Graph\r\n A valid Graph class/subclass.\r\n time : Integer\r\n A foremost time. Defaults to infinity (unreachable).\r\n\r\n Object Propertie(s):\r\n --------------------\r\n label : String\r\n Inherited from Node.\r\n graph : Graph\r\n Inherited from Node.\r\n data : Dictionary\r\n Inherited from Node.\r\n time : Integer\r\n The node's foremost time.\r\n\r\n See also:\r\n ---------\r\n Node\r\n Nodes\r\n ForemostNodes\r\n \"\"\"\r\n\r\n def __init__(self, label, graph, time=float('inf')):\r\n super().__init__(label, graph)\r\n self.time = time\r\n self.data['foremost_time'] = time\r\n\r\n\r\n def print(self):\r\n \"\"\"\r\n A method of ForemostNode.\r\n\r\n Returns:\r\n --------\r\n None, prints the label of the node and the foremost time.\r\n \"\"\"\r\n print(self.label, self.time)\r\n\r\n\r\n\r\nclass Nodes:\r\n \"\"\"\r\n A class to represent a collection of nodes on a graph.\r\n\r\n Parameter(s):\r\n -------------\r\n graph : Graph\r\n A valid Graph class/subclass.\r\n\r\n\r\n Object Propertie(s):\r\n --------------------\r\n set : Set\r\n The set of nodes.\r\n graph : Graph\r\n The graph of which the nodes collection belongs to.\r\n\r\n\r\n See also:\r\n ---------\r\n Node\r\n ForemostNode\r\n ForemostNodes\r\n \"\"\"\r\n def __init__(self, graph):\r\n self.set = set() # unorderd, unindexed, unique collection of node objects\r\n self.graph = graph\r\n\r\n\r\n def aslist(self):\r\n \"\"\"\r\n A method of Nodes.\r\n\r\n Returns:\r\n --------\r\n nodes : List\r\n A list of the nodes.\r\n \"\"\"\r\n return list(self.set)\r\n\r\n\r\n def as_ordered_list(self):\r\n \"\"\"\r\n A method of Nodes.\r\n\r\n Returns:\r\n --------\r\n nodes : List\r\n A list of the nodes, ordered by label.\r\n \"\"\"\r\n return sorted(list(self.set), key=lambda x:x.label, reverse=False)\r\n\r\n\r\n def add(self, label):\r\n \"\"\"\r\n A method of Nodes.\r\n\r\n Parameter(s):\r\n -------------\r\n label : String\r\n The label of the node to be added.\r\n\r\n Returns:\r\n --------\r\n node : Node\r\n The corresponding node object.\r\n \"\"\"\r\n # check if a node with this label already exists in the graph.\r\n if not self.exists(str(label)):\r\n # if it does not, add it (create a new node object).\r\n self.set.add(Node(label, self.graph))\r\n # return the node object (get or create).\r\n return self.get(label)\r\n\r\n\r\n def remove(self, label):\r\n \"\"\"\r\n A method of Nodes.\r\n\r\n Parameter(s):\r\n -------------\r\n label : String\r\n The label of the node to be removed.\r\n\r\n Returns:\r\n --------\r\n Result : Boolean\r\n Removes the node if it exists in the graph.\r\n \"\"\"\r\n # check if a node with this label already exists in the graph.\r\n if not self.exists(str(label)):\r\n print('Error: Node {} not found in graph {}.'.format(label, self.graph.label))\r\n return False\r\n else:\r\n self.set.remove(self.get(label))\r\n print('Node {} removed from graph {}.'.format(label, self.graph.label))\r\n return True\r\n\r\n\r\n def subset(self, alist):\r\n \"\"\"\r\n A method of Nodes.\r\n\r\n Parameter(s):\r\n -------------\r\n alist : List\r\n A list of node objects.\r\n\r\n Returns:\r\n --------\r\n subset : Nodes\r\n A nodes collection.\r\n \r\n \"\"\"\r\n # create a new nodes collection subset.\r\n subset = self.__class__(self.graph)\r\n # for each node in the specified list.\r\n for node in alist:\r\n # add the node to the subset.\r\n subset.set.add(node)\r\n # return the new collection of nodes.\r\n return subset\r\n\r\n\r\n def get(self, label):\r\n \"\"\"\r\n A method of Nodes.\r\n\r\n Parameter(s):\r\n -------------\r\n label : String\r\n The label of the node to be searched for.\r\n\r\n Returns:\r\n --------\r\n node : Node\r\n The node in the collection with label 'label' (if it exists).\r\n \r\n \"\"\"\r\n return next((node for node in self.set if node.label == label), None)\r\n\r\n\r\n def exists(self, label):\r\n \"\"\"\r\n A method of Nodes.\r\n\r\n Parameter(s):\r\n -------------\r\n label : String\r\n The label of the node to be checked for.\r\n\r\n Returns:\r\n --------\r\n exists : Boolean\r\n True/false depending of whether node with label 'label' exists in the collection.\r\n \r\n \"\"\"\r\n return True if self.get(label) is not None else False\r\n\r\n \r\n def count(self):\r\n \"\"\"\r\n A method of Nodes.\r\n\r\n Returns:\r\n --------\r\n count : Integer\r\n The number of nodes in the collection.\r\n \r\n \"\"\"\r\n return len(self.set)\r\n\r\n\r\n def labels(self):\r\n \"\"\"\r\n A method of Nodes.\r\n\r\n Returns:\r\n --------\r\n labels : List\r\n A list of node labels in the collection.\r\n \r\n \"\"\"\r\n return [node.label for node in self.set]\r\n\r\n\r\n def print(self):\r\n \"\"\"\r\n A method of Nodes.\r\n\r\n Returns:\r\n --------\r\n None, calls print for each node in the collection.\r\n \"\"\"\r\n print('Nodes:')\r\n for node in self.set:\r\n node.print()\r\n\r\n\r\n def add_data(self, csv_path):\r\n \"\"\"\r\n A method of Nodes.\r\n\r\n Parameter(s):\r\n -------------\r\n csv_path : String\r\n The path of the csv file.\r\n\r\n Returns:\r\n --------\r\n None, adds the data in the csv data frame to each node.\r\n The csv data must correspond to the nodes in the node collection.\r\n \"\"\"\r\n # create a data frame from the csv file.\r\n data_frame = pd.read_csv(csv_path)\r\n # for each row in the data frame.\r\n for index, row in data_frame.iterrows():\r\n # if a 'label' column exists.\r\n if self.exists(row['label']):\r\n # get the node corresponding to that 'label'.\r\n node = self.get(row['label'])\r\n # for each column, add the data to this node.\r\n for col in data_frame.columns:\r\n node.data[col] = row[col]\r\n\r\n\r\n\r\nclass ForemostNodes(Nodes):\r\n \"\"\"\r\n A class to represent a collection of foremost nodes on a tree.\r\n Inherits properties & methods from Nodes.\r\n\r\n Parameter(s):\r\n -------------\r\n graph : Graph\r\n A valid Graph class/subclass.\r\n\r\n Object Propertie(s):\r\n --------------------\r\n set : Set\r\n Inherited from Nodes.\r\n graph : Graph\r\n Inherited from Nodes.\r\n\r\n See also:\r\n ---------\r\n Node\r\n Nodes\r\n ForemostNodes\r\n \"\"\"\r\n\r\n def __init__(self, graph):\r\n super().__init__(graph)\r\n\r\n\r\n def add(self, label, time=float('inf')):\r\n \"\"\"\r\n A method of ForemostNodes.\r\n\r\n Parameter(s):\r\n -------------\r\n label : String\r\n The label of the node to be added.\r\n time : Integer\r\n A foremost time. Defaults to infinity (unreachable).\r\n\r\n Returns:\r\n --------\r\n node : Node\r\n The corresponding node object.\r\n \"\"\"\r\n # check if a node with this label already exists in the graph.\r\n if not self.exists(str(label)):\r\n # if it does not, add it (create a new node object).\r\n self.set.add(ForemostNode(label, self.graph, time))\r\n # return the node object (get or create).\r\n return self.get(label)\r\n\r\n\r\n def times(self):\r\n \"\"\"\r\n A method of ForemostNodes.\r\n\r\n Returns:\r\n --------\r\n times : List\r\n A list of node times in the collection.\r\n \"\"\"\r\n return [node.time for node in self.set]\r\n\r\n\r\n def get_reachable(self):\r\n \"\"\"\r\n A method of ForemostNodes.\r\n\r\n Returns:\r\n --------\r\n subset : ForemostNodes\r\n A subset of reachable nodes in the collection.\r\n \"\"\"\r\n return self.subset([node for node in self.set if not math.isinf(node.time)])\r\n"
] |
[
[
"pandas.read_csv"
]
] |
astrofrog/sunpy
|
[
"c658f7013a300b78e4cbf2146c2bcb98db32d788"
] |
[
"sunpy/gui/ui/mainwindow/widgets/figure_canvas.py"
] |
[
"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nPlot widgets for the PlotMan\nsubclassed from the matplotlib FigureCanvasQTAgg\n\nAuthor: Matt Earnshaw <matt@earnshaw.org.uk>\n\"\"\"\n\nimport sunpy\nimport matplotlib\nfrom PyQt4.QtGui import QSizePolicy\nfrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg\nfrom matplotlib.figure import Figure\n\nclass FigureCanvas(FigureCanvasQTAgg):\n \"\"\" General plot widget, resizes to fit window \"\"\"\n\n def __init__(self, map_, parent=None):\n self.parent = parent\n self.map = map_\n self.figure = Figure()\n self.map.plot(figure=self.figure)\n self.axes = self.figure.gca()\n\n # Code duplication from plotman.py!\n if self.map.norm() is not None:\n # If pre-normalised, get inital clips from the matplotlib norm\n self.vmin = self.map.norm().vmin\n self.vmax = self.map.norm().vmax\n else:\n # Otherwise, get initial clips from the map data directly.\n self.vmin = self.map.min()\n self.vmax = self.map.max()\n \n self.scaling = \"Linear\" # Shouldn't be a default.\n\n # Matplotlib kwargs\n self.params = {\n \"cmap\": self.map.cmap,\n \"norm\": self.map.norm(),\n }\n\n FigureCanvasQTAgg.__init__(self, self.figure)\n FigureCanvasQTAgg.setSizePolicy(self,\n QSizePolicy.Expanding,\n QSizePolicy.Expanding)\n FigureCanvasQTAgg.updateGeometry(self)\n\n def get_cmap(self, cmapname, gamma=None):\n \"\"\" Given a sunpy or matplotlib cmap name, returns the cmap. \"\"\"\n mpl_cmaps = sorted(m for m in matplotlib.pyplot.cm.datad\n if not m.endswith(\"_r\"))\n if cmapname in mpl_cmaps:\n return matplotlib.cm.get_cmap(cmapname)\n else:\n return sunpy.cm.get_cmap(cmapname)\n\n def get_norm(self):\n \"\"\" Return a matplotlib Normalize according to clip values and scale type \"\"\"\n if self.vmin < self.vmax:\n if self.scaling == \"Linear\": # This is not robust! \n return matplotlib.colors.Normalize(vmin=self.vmin,\n vmax=self.vmax)\n elif self.scaling == \"Logarithmic\":\n if self.vmin <= 0:\n # Cannot log scale 0 or negative data\n self.window().colorErrorLabel.setText(\"Cannot log scale zero or negative data!\")\n return self.params[\"norm\"]\n else:\n return matplotlib.colors.LogNorm(vmin=self.vmin,\n vmax=self.vmax)\n else:\n self.window().colorErrorLabel.setText(\"Min clip value must not exceed max clip value!\")\n return self.params[\"norm\"]\n\n\n def update_figure(self, cmapname=None, vmin=None, vmax=None, scaling=None):\n # Destroy any previous figures\n #matplotlib.pyplot.close()\n self.figure.clear()\n \n # Clear error messages\n self.window().colorErrorLabel.clear() \n\n if cmapname is not None:\n self.params.update({\"cmap\": self.get_cmap(cmapname)})\n elif vmax is not None:\n self.vmax = vmax\n self.params.update({\"norm\": self.get_norm()})\n elif vmin is not None:\n self.vmin = vmin\n self.params.update({\"norm\": self.get_norm()})\n elif scaling is not None:\n self.scaling = scaling\n self.params.update({\"norm\": self.get_norm()})\n\n #self.figure = Figure()\n self.map.plot(figure=self.figure, **self.params)\n self.axes = self.figure.gca()\n \n self.resize_figure() \n\n def reset_figure(self):\n self.figure = Figure()\n self.map.plot(figure=self.figure)\n self.axes = self.figure.gca()\n \n self.resize_figure()\n self.window().initialize_color_options()\n\n def resize_figure(self):\n self.updateGeometry()\n self.resize(1, 1) # It works, OK?\n self.draw()\n\n @property\n def cmap(self):\n return self.params[\"cmap\"]\n\n @property\n def norm(self):\n return self.params[\"norm\"]\n"
] |
[
[
"matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg.updateGeometry",
"matplotlib.colors.LogNorm",
"matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg.setSizePolicy",
"matplotlib.figure.Figure",
"matplotlib.colors.Normalize",
"matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg.__init__",
"matplotlib.cm.get_cmap"
]
] |
jaswinder9051998/zoofs
|
[
"63aa216248ac3677ee87df5172912cd73918f7cc"
] |
[
"zoofs/greywolfoptimization.py"
] |
[
"from zoofs.baseoptimizationalgorithm import BaseOptimizationAlgorithm\nimport numpy as np\nimport pandas as pd\nimport logging as log\nimport plotly.graph_objects as go\nimport scipy\nimport time\nimport warnings\n\n\nclass GreyWolfOptimization(BaseOptimizationAlgorithm):\n \"\"\" \n Attributes\n ----------\n best_feature_list : ndarray of shape (n_features)\n list of features with the best result of the entire run\n\n \"\"\"\n\n def __init__(self,\n objective_function,\n n_iteration: int = 1000,\n timeout: int = None,\n population_size=50,\n minimize=True):\n \"\"\"\n Parameters\n ----------\n objective_function : user made function of the signature 'func(model,X_train,y_train,X_test,y_test)'\n The function must return a value, that needs to be minimized/maximized.\n\n n_iteration : int, default=1000\n Number of time the Optimization algorithm will run\n\n timeout: int = None\n Stop operation after the given number of second(s).\n If this argument is set to None, the operation is executed without time limitation and n_iteration is followed\n\n population_size : int, default=50\n Total size of the population\n\n minimize : bool, default=True\n Defines if the objective value is to be maximized or minimized\n \"\"\"\n super().__init__(objective_function, n_iteration, timeout, population_size, minimize)\n\n def _check_params(self, model, x_train, y_train, x_valid, y_valid, method=1):\n super()._check_params(model, x_train, y_train, x_valid, y_valid)\n if method not in [1, 2]:\n raise ValueError(f\"method accepts only 1,2 \")\n\n def fit(self, model, X_train, y_train, X_valid, y_valid, method=1, verbose=True):\n \"\"\"\n Parameters\n ---------- \n model : machine learning model's object\n machine learning model's object\n\n X_train : pandas.core.frame.DataFrame of shape (n_samples, n_features)\n Training input samples to be used for machine learning model\n\n y_train : pandas.core.frame.DataFrame or pandas.core.series.Series of shape (n_samples)\n The target values (class labels in classification, real numbers in regression).\n\n X_valid : pandas.core.frame.DataFrame of shape (n_samples, n_features)\n Validation input samples\n\n y_valid : pandas.core.frame.DataFrame or pandas.core.series.Series of shape (n_samples)\n The target values (class labels in classification, real numbers in regression).\n\n method : {1, 2}, default=1\n Choose the between the two methods of grey wolf optimization\n\n verbose : bool,default=True\n Print results for iterations\n \"\"\"\n self._check_params(model, X_train, y_train, X_valid, y_valid, method)\n\n self.feature_score_hash = {}\n self.feature_list = np.array(list(X_train.columns))\n self.best_results_per_iteration = {}\n self.best_score = np.inf\n self.best_dim = np.ones(X_train.shape[1])\n\n self.initialize_population(X_train)\n\n self.best_score_dimension = np.ones(X_train.shape[1])\n\n self.alpha_wolf_dimension, self.alpha_wolf_fitness = np.ones(\n X_train.shape[1]), np.inf\n self.beta_wolf_dimension, self.beta_wolf_fitness = np.ones(\n X_train.shape[1]), np.inf\n self.delta_wolf_dimension, self.delta_wolf_fitness = np.ones(\n X_train.shape[1]), np.inf\n\n if (self.timeout is not None):\n timeout_upper_limit = time.time() + self.timeout\n else:\n timeout_upper_limit = time.time()\n for i in range(self.n_iteration):\n if (self.timeout is not None) & (time.time() > timeout_upper_limit):\n warnings.warn(\"Timeout occured\")\n break\n a = 2-2*((i+1)/self.n_iteration)\n\n self.fitness_scores = self._evaluate_fitness(\n model, X_train, y_train, X_valid, y_valid)\n\n self.iteration_objective_score_monitor(i)\n\n top_three_fitness_indexes = np.argsort(self.fitness_scores)[:3]\n\n for fit, dim in zip(np.array(self.fitness_scores)[top_three_fitness_indexes], self.individuals[top_three_fitness_indexes]):\n if fit < self.alpha_wolf_fitness:\n self.delta_wolf_fitness = self.beta_wolf_fitness\n self.beta_wolf_fitness = self.alpha_wolf_fitness\n self.alpha_wolf_fitness = fit\n\n self.delta_wolf_dimension = self.beta_wolf_dimension\n self.beta_wolf_dimension = self.alpha_wolf_dimension\n self.alpha_wolf_dimension = dim\n continue\n\n if ((fit > self.alpha_wolf_fitness) & (fit < self.beta_wolf_fitness)):\n self.delta_wolf_fitness = self.beta_wolf_fitness\n self.beta_wolf_fitness = fit\n\n self.delta_wolf_dimension = self.beta_wolf_dimension\n self.beta_wolf_dimension = dim\n continue\n\n if ((fit > self.beta_wolf_fitness) & (fit < self.delta_wolf_fitness)):\n self.delta_wolf_fitness = fit\n self.delta_wolf_dimension = dim\n\n if (method == 1) | (method == 2):\n C1 = 2 * \\\n np.random.random((self.population_size, X_train.shape[1]))\n A1 = 2*a * \\\n np.random.random(\n (self.population_size, X_train.shape[1]))-a\n d_alpha = abs(C1*self.alpha_wolf_dimension - self.individuals)\n\n C2 = 2 * \\\n np.random.random((self.population_size, X_train.shape[1]))\n A2 = 2*a * \\\n np.random.random(\n (self.population_size, X_train.shape[1]))-a\n d_beta = abs(C2*self.beta_wolf_dimension - self.individuals)\n\n C3 = 2 * \\\n np.random.random((self.population_size, X_train.shape[1]))\n A3 = 2*a * \\\n np.random.random(\n (self.population_size, X_train.shape[1]))-a\n d_delta = abs(C3*self.delta_wolf_dimension - self.individuals)\n\n if method == 2:\n X1 = abs(self.alpha_wolf_dimension - A1*d_alpha)\n X2 = abs(self.beta_wolf_dimension - A2*d_beta)\n X3 = abs(self.delta_wolf_dimension - A3*d_delta)\n self.individuals = np.where(np.random.uniform(size=(\n self.population_size, X_train.shape[1])) <= self.sigmoid((X1+X2+X3)/3), 1, 0)\n\n if method == 1:\n Y1 = np.where((self.alpha_wolf_dimension + np.where(self.sigmoid(A1*d_alpha) >\n np.random.uniform(size=(self.population_size, X_train.shape[1])), 1, 0)) >= 1, 1, 0)\n Y2 = np.where((self.beta_wolf_dimension + np.where(self.sigmoid(A1*d_beta) >\n np.random.uniform(size=(self.population_size, X_train.shape[1])), 1, 0)) >= 1, 1, 0)\n Y3 = np.where((self.delta_wolf_dimension + np.where(self.sigmoid(A1*d_delta) >\n np.random.uniform(size=(self.population_size, X_train.shape[1])), 1, 0)) >= 1, 1, 0)\n r = np.random.uniform(\n size=(self.population_size, X_train.shape[1]))\n self.individuals[r < (1/3)] = Y1[r < (1/3)]\n self.individuals[(r >= (1/3)) & (r < (2/3))\n ] = Y2[(r >= (1/3)) & (r < (2/3))]\n self.individuals[r >= (2/3)] = Y3[r >= (2/3)]\n\n self.verbose_results(verbose, i)\n self.best_feature_list = list(\n self.feature_list[np.where(self.best_dim)[0]])\n return self.best_feature_list\n\n"
] |
[
[
"numpy.random.random",
"numpy.ones",
"numpy.random.uniform",
"numpy.argsort",
"numpy.array",
"numpy.where"
]
] |
mingo-x/tensorpack
|
[
"0ab28b75e54ab1a807b8d047d3c3414017242eed"
] |
[
"examples/FasterRCNN/basemodel.py"
] |
[
"# -*- coding: utf-8 -*-\n# File: basemodel.py\n\nfrom contextlib import contextmanager, ExitStack\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.framework import add_model_variable\n\nfrom tensorpack.tfutils import argscope\nfrom tensorpack.tfutils.scope_utils import auto_reuse_variable_scope\nfrom tensorpack.tfutils.varreplace import custom_getter_scope, freeze_variables\nfrom tensorpack.models import (\n Conv2D, MaxPooling, BatchNorm, layer_register)\n\nfrom config import config as cfg\n\n\n@layer_register(log_shape=True)\ndef GroupNorm(x, group=32, gamma_initializer=tf.constant_initializer(1.)):\n shape = x.get_shape().as_list()\n ndims = len(shape)\n assert ndims == 4, shape\n chan = shape[1]\n assert chan % group == 0, chan\n group_size = chan // group\n\n orig_shape = tf.shape(x)\n h, w = orig_shape[2], orig_shape[3]\n\n x = tf.reshape(x, tf.stack([-1, group, group_size, h, w]))\n\n mean, var = tf.nn.moments(x, [2, 3, 4], keep_dims=True)\n\n new_shape = [1, group, group_size, 1, 1]\n\n beta = tf.get_variable('beta', [chan], initializer=tf.constant_initializer())\n beta = tf.reshape(beta, new_shape)\n\n gamma = tf.get_variable('gamma', [chan], initializer=gamma_initializer)\n gamma = tf.reshape(gamma, new_shape)\n\n out = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-5, name='output')\n return tf.reshape(out, orig_shape, name='output')\n\n\ndef freeze_affine_getter(getter, *args, **kwargs):\n # custom getter to freeze affine params inside bn\n name = args[0] if len(args) else kwargs.get('name')\n if name.endswith('/gamma') or name.endswith('/beta'):\n kwargs['trainable'] = False\n ret = getter(*args, **kwargs)\n add_model_variable(ret)\n else:\n ret = getter(*args, **kwargs)\n return ret\n\n\ndef maybe_reverse_pad(topleft, bottomright):\n if cfg.BACKBONE.TF_PAD_MODE:\n return [topleft, bottomright]\n return [bottomright, topleft]\n\n\n@contextmanager\ndef backbone_scope(freeze):\n \"\"\"\n Args:\n freeze (bool): whether to freeze all the variables under the scope\n \"\"\"\n def nonlin(x):\n x = get_norm()(x)\n return tf.nn.relu(x)\n\n with argscope([Conv2D, MaxPooling, BatchNorm], data_format='channels_first'), \\\n argscope(Conv2D, use_bias=False, activation=nonlin,\n kernel_initializer=tf.variance_scaling_initializer(\n scale=2.0, mode='fan_out')), \\\n ExitStack() as stack:\n if cfg.BACKBONE.NORM in ['FreezeBN', 'SyncBN']:\n if freeze or cfg.BACKBONE.NORM == 'FreezeBN':\n stack.enter_context(argscope(BatchNorm, training=False))\n else:\n stack.enter_context(argscope(\n BatchNorm, sync_statistics='nccl' if cfg.TRAINER == 'replicated' else 'horovod'))\n\n if freeze:\n stack.enter_context(freeze_variables(stop_gradient=False, skip_collection=True))\n else:\n # the layers are not completely freezed, but we may want to only freeze the affine\n if cfg.BACKBONE.FREEZE_AFFINE:\n stack.enter_context(custom_getter_scope(freeze_affine_getter))\n yield\n\n\ndef image_preprocess(image, bgr=True):\n with tf.name_scope('image_preprocess'):\n if image.dtype.base_dtype != tf.float32:\n image = tf.cast(image, tf.float32)\n\n mean = cfg.PREPROC.PIXEL_MEAN\n std = np.asarray(cfg.PREPROC.PIXEL_STD)\n if bgr:\n mean = mean[::-1]\n std = std[::-1]\n image_mean = tf.constant(mean, dtype=tf.float32)\n image_invstd = tf.constant(1.0 / std, dtype=tf.float32)\n image = (image - image_mean) * image_invstd\n return image\n\n\ndef get_norm(zero_init=False):\n if cfg.BACKBONE.NORM == 'GN':\n Norm = GroupNorm\n layer_name = 'gn'\n else:\n Norm = BatchNorm\n layer_name = 'bn'\n return lambda x: Norm(layer_name, x, gamma_initializer=tf.zeros_initializer() if zero_init else None)\n\n\ndef resnet_shortcut(l, n_out, stride, activation=tf.identity):\n n_in = l.shape[1]\n if n_in != n_out: # change dimension when channel is not the same\n # TF's SAME mode output ceil(x/stride), which is NOT what we want when x is odd and stride is 2\n # In FPN mode, the images are pre-padded already.\n if not cfg.MODE_FPN and stride == 2:\n l = l[:, :, :-1, :-1]\n return Conv2D('convshortcut', l, n_out, 1,\n strides=stride, activation=activation)\n else:\n return l\n\n\ndef resnet_bottleneck(l, ch_out, stride):\n shortcut = l\n if cfg.BACKBONE.STRIDE_1X1:\n if stride == 2:\n l = l[:, :, :-1, :-1]\n l = Conv2D('conv1', l, ch_out, 1, strides=stride)\n l = Conv2D('conv2', l, ch_out, 3, strides=1)\n else:\n l = Conv2D('conv1', l, ch_out, 1, strides=1)\n if stride == 2:\n l = tf.pad(l, [[0, 0], [0, 0], maybe_reverse_pad(0, 1), maybe_reverse_pad(0, 1)])\n l = Conv2D('conv2', l, ch_out, 3, strides=2, padding='VALID')\n else:\n l = Conv2D('conv2', l, ch_out, 3, strides=stride)\n l = Conv2D('conv3', l, ch_out * 4, 1, activation=get_norm(zero_init=True))\n ret = l + resnet_shortcut(shortcut, ch_out * 4, stride, activation=get_norm(zero_init=False))\n return tf.nn.relu(ret, name='output')\n\n\ndef resnet_group(name, l, block_func, features, count, stride):\n with tf.variable_scope(name):\n for i in range(0, count):\n with tf.variable_scope('block{}'.format(i)):\n l = block_func(l, features, stride if i == 0 else 1)\n return l\n\n\ndef resnet_c4_backbone(image, num_blocks):\n assert len(num_blocks) == 3\n freeze_at = cfg.BACKBONE.FREEZE_AT\n with backbone_scope(freeze=freeze_at > 0):\n l = tf.pad(image, [[0, 0], [0, 0], maybe_reverse_pad(2, 3), maybe_reverse_pad(2, 3)])\n l = Conv2D('conv0', l, 64, 7, strides=2, padding='VALID')\n l = tf.pad(l, [[0, 0], [0, 0], maybe_reverse_pad(0, 1), maybe_reverse_pad(0, 1)])\n l = MaxPooling('pool0', l, 3, strides=2, padding='VALID')\n\n with backbone_scope(freeze=freeze_at > 1):\n c2 = resnet_group('group0', l, resnet_bottleneck, 64, num_blocks[0], 1)\n with backbone_scope(freeze=False):\n c3 = resnet_group('group1', c2, resnet_bottleneck, 128, num_blocks[1], 2)\n c4 = resnet_group('group2', c3, resnet_bottleneck, 256, num_blocks[2], 2)\n # 16x downsampling up to now\n return c4\n\n\n@auto_reuse_variable_scope\ndef resnet_conv5(image, num_block):\n with backbone_scope(freeze=False):\n l = resnet_group('group3', image, resnet_bottleneck, 512, num_block, 2)\n return l\n\n\ndef resnet_fpn_backbone(image, num_blocks):\n freeze_at = cfg.BACKBONE.FREEZE_AT\n shape2d = tf.shape(image)[2:]\n mult = float(cfg.FPN.RESOLUTION_REQUIREMENT)\n new_shape2d = tf.to_int32(tf.ceil(tf.to_float(shape2d) / mult) * mult)\n pad_shape2d = new_shape2d - shape2d\n assert len(num_blocks) == 4, num_blocks\n with backbone_scope(freeze=freeze_at > 0):\n chan = image.shape[1]\n pad_base = maybe_reverse_pad(2, 3)\n l = tf.pad(image, tf.stack(\n [[0, 0], [0, 0],\n [pad_base[0], pad_base[1] + pad_shape2d[0]],\n [pad_base[0], pad_base[1] + pad_shape2d[1]]]))\n l.set_shape([None, chan, None, None])\n l = Conv2D('conv0', l, 64, 7, strides=2, padding='VALID')\n l = tf.pad(l, [[0, 0], [0, 0], maybe_reverse_pad(0, 1), maybe_reverse_pad(0, 1)])\n l = MaxPooling('pool0', l, 3, strides=2, padding='VALID')\n with backbone_scope(freeze=freeze_at > 1):\n c2 = resnet_group('group0', l, resnet_bottleneck, 64, num_blocks[0], 1)\n with backbone_scope(freeze=False):\n c3 = resnet_group('group1', c2, resnet_bottleneck, 128, num_blocks[1], 2)\n c4 = resnet_group('group2', c3, resnet_bottleneck, 256, num_blocks[2], 2)\n c5 = resnet_group('group3', c4, resnet_bottleneck, 512, num_blocks[3], 2)\n # 32x downsampling up to now\n # size of c5: ceil(input/32)\n return c2, c3, c4, c5\n"
] |
[
[
"tensorflow.nn.relu",
"tensorflow.get_variable",
"tensorflow.nn.batch_normalization",
"tensorflow.constant",
"tensorflow.shape",
"numpy.asarray",
"tensorflow.stack",
"tensorflow.nn.moments",
"tensorflow.reshape",
"tensorflow.contrib.framework.add_model_variable",
"tensorflow.cast",
"tensorflow.zeros_initializer",
"tensorflow.constant_initializer",
"tensorflow.variance_scaling_initializer",
"tensorflow.name_scope",
"tensorflow.to_float",
"tensorflow.variable_scope"
]
] |
rkube/fourier_neural_operator
|
[
"14c1f870ce8b2033883a22c4d45cea7d12cce69f"
] |
[
"scripts/eval.py"
] |
[
"import torch\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nfrom utilities3 import *\nimport operator\nfrom functools import reduce\nfrom functools import partial\n\nfrom timeit import default_timer\nimport scipy.io\n\ntorch.manual_seed(0)\nnp.random.seed(0)\n\ndef compl_mul3d(a, b):\n # (batch, in_channel, x,y,t ), (in_channel, out_channel, x,y,t) -> (batch, out_channel, x,y,t)\n op = partial(torch.einsum, \"bixyz,ioxyz->boxyz\")\n return torch.stack([\n op(a[..., 0], b[..., 0]) - op(a[..., 1], b[..., 1]),\n op(a[..., 1], b[..., 0]) + op(a[..., 0], b[..., 1])\n ], dim=-1)\n\nclass SpectralConv3d_fast(nn.Module):\n def __init__(self, in_channels, out_channels, modes1, modes2, modes3):\n super(SpectralConv3d_fast, self).__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.modes1 = modes1 #Number of Fourier modes to multiply, at most floor(N/2) + 1\n self.modes2 = modes2\n self.modes3 = modes3\n\n self.scale = (1 / (in_channels * out_channels))\n self.weights1 = nn.Parameter(self.scale * torch.rand(in_channels, out_channels, self.modes1, self.modes2, self.modes3, 2))\n self.weights2 = nn.Parameter(self.scale * torch.rand(in_channels, out_channels, self.modes1, self.modes2, self.modes3, 2))\n self.weights3 = nn.Parameter(self.scale * torch.rand(in_channels, out_channels, self.modes1, self.modes2, self.modes3, 2))\n self.weights4 = nn.Parameter(self.scale * torch.rand(in_channels, out_channels, self.modes1, self.modes2, self.modes3, 2))\n\n def forward(self, x):\n batchsize = x.shape[0]\n #Compute Fourier coeffcients up to factor of e^(- something constant)\n x_ft = torch.rfft(x, 3, normalized=True, onesided=True)\n\n # Multiply relevant Fourier modes\n out_ft = torch.zeros(batchsize, self.in_channels, x.size(-3), x.size(-2), x.size(-1)//2 + 1, 2, device=x.device)\n out_ft[:, :, :self.modes1, :self.modes2, :self.modes3] = \\\n compl_mul3d(x_ft[:, :, :self.modes1, :self.modes2, :self.modes3], self.weights1)\n out_ft[:, :, -self.modes1:, :self.modes2, :self.modes3] = \\\n compl_mul3d(x_ft[:, :, -self.modes1:, :self.modes2, :self.modes3], self.weights2)\n out_ft[:, :, :self.modes1, -self.modes2:, :self.modes3] = \\\n compl_mul3d(x_ft[:, :, :self.modes1, -self.modes2:, :self.modes3], self.weights3)\n out_ft[:, :, -self.modes1:, -self.modes2:, :self.modes3] = \\\n compl_mul3d(x_ft[:, :, -self.modes1:, -self.modes2:, :self.modes3], self.weights4)\n\n #Return to physical space\n x = torch.irfft(out_ft, 3, normalized=True, onesided=True, signal_sizes=(x.size(-3), x.size(-2), x.size(-1)))\n return x\n\nclass SimpleBlock2d(nn.Module):\n def __init__(self, modes1, modes2, modes3, width):\n super(SimpleBlock2d, self).__init__()\n\n self.modes1 = modes1\n self.modes2 = modes2\n self.modes3 = modes3\n self.width = width\n self.fc0 = nn.Linear(13, self.width)\n\n self.conv0 = SpectralConv3d_fast(self.width, self.width, self.modes1, self.modes2, self.modes3)\n self.conv1 = SpectralConv3d_fast(self.width, self.width, self.modes1, self.modes2, self.modes3)\n self.conv2 = SpectralConv3d_fast(self.width, self.width, self.modes1, self.modes2, self.modes3)\n self.conv3 = SpectralConv3d_fast(self.width, self.width, self.modes1, self.modes2, self.modes3)\n self.w0 = nn.Conv1d(self.width, self.width, 1)\n self.w1 = nn.Conv1d(self.width, self.width, 1)\n self.w2 = nn.Conv1d(self.width, self.width, 1)\n self.w3 = nn.Conv1d(self.width, self.width, 1)\n self.bn0 = torch.nn.BatchNorm3d(self.width)\n self.bn1 = torch.nn.BatchNorm3d(self.width)\n self.bn2 = torch.nn.BatchNorm3d(self.width)\n self.bn3 = torch.nn.BatchNorm3d(self.width)\n\n\n self.fc1 = nn.Linear(self.width, 128)\n self.fc2 = nn.Linear(128, 1)\n\n def forward(self, x):\n batchsize = x.shape[0]\n size_x, size_y, size_z = x.shape[1], x.shape[2], x.shape[3]\n\n x = self.fc0(x)\n x = x.permute(0, 4, 1, 2, 3)\n\n x1 = self.conv0(x)\n x2 = self.w0(x.view(batchsize, self.width, -1)).view(batchsize, self.width, size_x, size_y, size_z)\n x = self.bn0(x1 + x2)\n x = F.relu(x)\n x1 = self.conv1(x)\n x2 = self.w1(x.view(batchsize, self.width, -1)).view(batchsize, self.width, size_x, size_y, size_z)\n x = self.bn1(x1 + x2)\n x = F.relu(x)\n x1 = self.conv2(x)\n x2 = self.w2(x.view(batchsize, self.width, -1)).view(batchsize, self.width, size_x, size_y, size_z)\n x = self.bn2(x1 + x2)\n x = F.relu(x)\n x1 = self.conv3(x)\n x2 = self.w3(x.view(batchsize, self.width, -1)).view(batchsize, self.width, size_x, size_y, size_z)\n x = self.bn3(x1 + x2)\n\n x = x.permute(0, 2, 3, 4, 1)\n x = self.fc1(x)\n x = F.relu(x)\n x = self.fc2(x)\n return x\n\nclass Net2d(nn.Module):\n def __init__(self, modes, width):\n super(Net2d, self).__init__()\n self.conv1 = SimpleBlock2d(modes, modes, 6, width)\n\n def forward(self, x):\n x = self.conv1(x)\n return x.squeeze()\n\n def count_params(self):\n c = 0\n for p in self.parameters():\n c += reduce(operator.mul, list(p.size()))\n\n return c\n\n\nt1 = default_timer()\n\nTEST_PATH = 'data/ns_data_V1e-4_N20_T50_R256test.mat'\n\n\nntest = 20\n\nsub = 4\nsub_t = 4\nS = 64\nT_in = 10\nT = 20\n\nindent = 3\n\n# load data\nreader = MatReader(TEST_PATH)\ntest_a = reader.read_field('u')[:,::sub,::sub, indent:T_in*4:4] #([0, T_in])\ntest_u = reader.read_field('u')[:,::sub,::sub, indent+T_in*4:indent+(T+T_in)*4:sub_t] #([T_in, T_in + T])\n\nprint(test_a.shape, test_u.shape)\n\n# pad the location information (s,t)\nS = S * (4//sub)\nT = T * (4//sub_t)\n\ntest_a = test_a.reshape(ntest,S,S,1,T_in).repeat([1,1,1,T,1])\n\ngridx = torch.tensor(np.linspace(0, 1, S), dtype=torch.float)\ngridx = gridx.reshape(1, S, 1, 1, 1).repeat([1, 1, S, T, 1])\ngridy = torch.tensor(np.linspace(0, 1, S), dtype=torch.float)\ngridy = gridy.reshape(1, 1, S, 1, 1).repeat([1, S, 1, T, 1])\ngridt = torch.tensor(np.linspace(0, 1, T+1)[1:], dtype=torch.float)\ngridt = gridt.reshape(1, 1, 1, T, 1).repeat([1, S, S, 1, 1])\n\ntest_a = torch.cat((gridx.repeat([ntest,1,1,1,1]), gridy.repeat([ntest,1,1,1,1]),\n gridt.repeat([ntest,1,1,1,1]), test_a), dim=-1)\n\nt2 = default_timer()\nprint('preprocessing finished, time used:', t2-t1)\ndevice = torch.device('cuda')\n\n# load model\nmodel = torch.load('model/ns_fourier_V1e-4_T20_N9800_ep200_m12_w32')\n\nprint(model.count_params())\n\n# test\ntest_loader = torch.utils.data.DataLoader(torch.utils.data.TensorDataset(test_a, test_u), batch_size=1, shuffle=False)\nmyloss = LpLoss(size_average=False)\npred = torch.zeros(test_u.shape)\nindex = 0\nwith torch.no_grad():\n test_l2 = 0\n for x, y in test_loader:\n x, y = x.cuda(), y.cuda()\n\n out = model(x)\n pred[index] = out\n loss = myloss(out.view(1, -1), y.view(1, -1)).item()\n test_l2 += loss\n print(index, loss)\n index = index + 1\nprint(test_l2/ntest)\n\npath = 'eval'\nscipy.io.savemat('pred/'+path+'.mat', mdict={'pred': pred.cpu().numpy(), 'u': test_u.cpu().numpy()})\n\n\n\n\n\n"
] |
[
[
"numpy.random.seed",
"torch.zeros",
"torch.load",
"torch.manual_seed",
"numpy.linspace",
"torch.utils.data.TensorDataset",
"torch.rfft",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.no_grad",
"torch.rand",
"torch.nn.Conv1d",
"torch.device",
"torch.nn.BatchNorm3d"
]
] |
jatervon/ultra-short-cognitive-load-detection
|
[
"b3abc35d353bd7ba63d4412e3a066294fc8467ba"
] |
[
"xgb_hyperopt.py"
] |
[
"import os\nimport numpy as np\nimport pickle\nimport argparse\nfrom statsmodels.stats.weightstats import DescrStatsW\n\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import accuracy_score\nfrom xgboost import XGBClassifier\n\nfrom utils import personal_normalisation, cv_indices_nfolds\nfrom data import read_features\n\nimport csv\nfrom hyperopt import STATUS_OK\nfrom hyperopt import hp\nfrom hyperopt import tpe\nfrom hyperopt import Trials\nfrom hyperopt import fmin\nfrom timeit import default_timer as timer\n\nMODALITIES = ['gsr', 'hr', 'rr', 'temp']\nTEST_SUBJECTS = ['3caqi', '6frz4', 'bd47a', 'f1gjp', 'iz3x1']\nUSE_TEST_SUBJECTS = False\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--wlen', action='store', default='30', choices=['5', '10', '15', '20', '25', '30'],\n help=\"Window length in seconds\")\nparser.add_argument('--overlap', action='store', default='15', choices=['2.5', '5', '7.5', '10', '12.5', '15'],\n help=\"Overlap in seconds\")\nparser.add_argument('--data_path', action='store', default='./data/', help=\"Path to feature data\")\nparser.add_argument('--results_path', action='store', default='./results/', help=\"Path to results folder\")\n# opts = parser.parse_args('--wlen 30 --overlap 15'.split(' '))\nopts = parser.parse_args()\n\n\nif not os.path.exists(opts.results_path):\n os.makedirs(opts.results_path)\n\nITERATION = 0\n\noverl_str = str(opts.overlap).replace('.', '')\nidentifier = f'{opts.wlen}s_{overl_str}s'\n\nFILENAME = f'./{opts.results_path}/xgb_bayes_opt_{identifier}.csv'\nTRIALS_NAME = f'./{opts.results_path}/xgb_bayes_trials_{identifier}.pickle'\nMAX_EVALS = 50\nSEED = 36147\n\nprint(opts)\n\n\ndef objective(params):\n \"\"\"Objective function for XGB Hyperparameter Optimization\"\"\"\n\n # Keep track of evals\n global ITERATION\n\n ITERATION += 1\n\n start = timer()\n\n # check that two params are integers\n params['n_estimators'] = int(params['n_estimators'])\n params['max_depth'] = int(params['max_depth'])\n # params['n_estimators'] = 2\n # params['max_depth'] = 1\n\n # define estimator\n xgb = XGBClassifier(random_state=SEED, **params)\n # xgb.set_params(**params)\n\n # Perform n_folds cross validation\n scores_list = list()\n avg_score = list()\n avg_std_score = list()\n n_test_users = list()\n test_scores = list()\n for tr, te in cv:\n # break\n x_train_i = X_train.iloc[tr]\n x_train_i = x_train_i.reset_index(drop=True)\n y_tr_i = y_train.iloc[tr].values\n\n # inner cv indeces\n # data = train.iloc[tr].reset_index(drop=True)\n # kwargs = {'seed': SEED, 'nfolds': 5}\n\n tr_i, val_i, ntest_i = cv_indices_nfolds(train.iloc[tr].reset_index(drop=True), seed=SEED, nfolds=10)\n # print(ntest_i)\n\n # cross-validate\n scores = cross_val_score(xgb, x_train_i, y_tr_i, scoring='accuracy', cv=zip(tr_i, val_i), n_jobs=-1)\n wstat = DescrStatsW(scores, weights=ntest_i, ddof=1)\n avg = wstat.mean\n avg_std = wstat.std\n\n scores_list.append(scores)\n avg_score.append(avg)\n avg_std_score.append(avg_std)\n n_test_users.append(ntest_i)\n\n # monitor test scores\n xgb.fit(x_train_i, y_tr_i)\n te_pred = xgb.predict(X_train.iloc[te])\n test_scores.append(accuracy_score(y_train.iloc[te].values, te_pred))\n\n # acc = np.mean(scores_list, axis=1).mean() # validation acc - unweighted\n wstat = DescrStatsW(avg_score, weights=len(train.subject.unique()) - np.array(ntest), ddof=1)\n val_acc = wstat.mean # validation acc\n val_acc_std = wstat.std # std of avg score\n # val_acc_std = np.average(avg_std_score, weights=len(train.subject.unique()) - np.array(ntest)) # validation acc\n wstat = DescrStatsW(test_scores, weights=ntest, ddof=1)\n test_val_acc = wstat.mean # mean test score\n test_val_acc_std = wstat.std # std of test score\n\n run_time = timer() - start\n\n # Loss must be minimized\n loss = 1 - val_acc\n\n # Write to the csv file\n out_file = os.getcwd() + os.sep + FILENAME\n of_connection = open(out_file, 'a')\n writer = csv.writer(of_connection)\n if USE_TEST_SUBJECTS:\n xgb.fit(X_train, y_train)\n test_acc = accuracy_score(y_test, xgb.predict(X_test)) # monitor test acc just for fun\n writer.writerow([val_acc, val_acc_std, test_val_acc, test_acc, params, ITERATION, run_time])\n else:\n test_acc = np.nan\n writer.writerow([val_acc, val_acc_std, test_val_acc, test_val_acc_std, test_acc, params, ITERATION, run_time])\n of_connection.close()\n\n # Dictionary with information for evaluation\n return {'loss': loss, 'params': params, 'iteration': ITERATION,\n 'train_time': run_time, 'status': STATUS_OK}\n\n\nif __name__ == '__main__':\n # get feature data and normalise\n df = read_features(opts.wlen, opts.overlap, opts.data_path, True)\n df = df.drop(['task', 'level', 'win'], axis=1)\n df = df.drop([c for c in df.columns if 'TLX' in c], axis=1)\n df = personal_normalisation(df)\n\n # split into training/validation and testing\n if USE_TEST_SUBJECTS:\n inds = [i for i in range(len(df)) if df.subject.iloc[i] in TEST_SUBJECTS]\n test = df.iloc[inds]\n train = df.drop(inds)\n train = train.reset_index(drop=True)\n test = test.reset_index(drop=True)\n\n X_train = train.drop(['subject', 'y'], axis=1)\n y_train = train.y\n\n X_test = test.drop(['subject', 'y'], axis=1)\n y_test = test.y\n else:\n train = df.reset_index(drop=True)\n X_train = train.drop(['subject', 'y'], axis=1)\n y_train = train.y\n\n # obtain outer cv indeces\n # trainind, testind = cv_leave_three_out(train, seed=SEED)\n trainind, testind, ntest = cv_indices_nfolds(train, seed=SEED, nfolds=11)\n cv = list(zip(trainind, testind))\n\n # define search space\n space = {\n # 'boosting': hp.choice('boosting', ['gbtree', 'gblinear', 'dart']),\n 'n_estimators': hp.quniform('n_estimators-xg', 20, 250, 10),\n 'max_depth': hp.quniform('max_depth-xg', 2, 12, 1),\n 'learning_rate': hp.uniform('learning_rate-xg', 0.01, 0.5),\n 'gamma': hp.choice('gamma', [0, hp.uniform('gamma-xg', 0, 0.05)]),\n 'subsample': hp.choice('subsample', [1, hp.uniform('subsample-xg', 0.7, 1)]),\n 'colsample_bytree': hp.choice('colsample_bytree', [1, hp.uniform('colsample_bytree-xg', 0.7, 1)]),\n 'colsample_bynode': hp.choice('colsample_bynode', [1, hp.uniform('colsample_bynode-xg', 0.7, 1)]),\n 'colsample_bylevel': hp.choice('colsample_bylevel', [1, hp.uniform('colsample_bylevel-xg', 0.7, 1)]),\n 'reg_alpha': hp.uniform('reg_alpha-xg', 0, 1),\n 'reg_lambda': hp.uniform('reg_lambda-xg', 0, 1)}\n\n # from hyperopt.pyll.stochastic import sample\n # params = sample(space)\n\n tpe_algorithm = tpe.suggest\n trials_obj = TRIALS_NAME\n multip = 1\n if os.path.isfile(trials_obj):\n print(\"Reading in old trials file\")\n with open(trials_obj, 'rb') as fp:\n bayes_trials = pickle.load(fp)\n iters = bayes_trials.results[-1]['iteration']\n MAX_EVALS += iters\n ITERATION += iters\n else:\n bayes_trials = Trials()\n\n # File to save results\n out_file = os.getcwd() + os.sep + FILENAME\n if not os.path.isfile(out_file):\n of_connection = open(out_file, 'w')\n writer = csv.writer(of_connection)\n\n # Write the headers to the file\n writer.writerow(['val_acc', 'val_acc_std', 'test_val_acc', 'test_val_acc_std', 'test_acc', 'params',\n 'iteration', 'validation_time'])\n of_connection.close()\n else:\n print(\"Appending to old results file\")\n\n # Run optimization\n try:\n best = fmin(fn=objective, space=space, algo=tpe.suggest,\n max_evals=MAX_EVALS, trials=bayes_trials)\n except KeyboardInterrupt:\n with open(trials_obj, 'wb') as fp:\n pickle.dump(bayes_trials, fp)\n\n with open(trials_obj, 'wb') as fp:\n pickle.dump(bayes_trials, fp)\n\n\n# import pandas as pd\n# res = pd.read_csv('./results/xgb_bayes_opt_30s_15s.csv')\n# res.sort_values('acc')\n"
] |
[
[
"numpy.array",
"sklearn.metrics.accuracy_score"
]
] |
dribnet/glow
|
[
"853b0fa8eb521392a661e1cdfa13378db3aa05ab"
] |
[
"model.py"
] |
[
"import tensorflow as tf\n\nimport tfops as Z\nimport optim\nimport numpy as np\nfrom tensorflow.contrib.framework.python.ops import add_arg_scope\ntry:\n import horovod.tensorflow as hvd\nexcept ImportError:\n from train import hvd\n\n\n'''\nf_loss: function with as input the (x,y,reuse=False), and as output a list/tuple whose first element is the loss.\n'''\n\n\ndef abstract_model_xy(sess, hps, feeds, train_iterator, test_iterator, data_init, lr, f_loss):\n\n # == Create class with static fields and methods\n class m(object):\n pass\n m.sess = sess\n m.feeds = feeds\n m.lr = lr\n\n # === Loss and optimizer\n loss_train, stats_train = f_loss(train_iterator, True)\n all_params = tf.trainable_variables()\n if hps.gradient_checkpointing == 1:\n from memory_saving_gradients import gradients\n gs = gradients(loss_train, all_params)\n else:\n gs = tf.gradients(loss_train, all_params)\n\n optimizer = {'adam': optim.adam, 'adamax': optim.adamax,\n 'adam2': optim.adam2}[hps.optimizer]\n\n train_op, polyak_swap_op, ema = optimizer(\n all_params, gs, alpha=lr, hps=hps)\n if hps.direct_iterator:\n m.train = lambda _lr: sess.run([train_op, stats_train], {lr: _lr})[1]\n else:\n def _train(_lr):\n _x, _y = train_iterator()\n return sess.run([train_op, stats_train], {feeds['x']: _x,\n feeds['y']: _y, lr: _lr})[1]\n m.train = _train\n\n m.polyak_swap = lambda: sess.run(polyak_swap_op)\n\n # === Testing\n loss_test, stats_test = f_loss(test_iterator, False, reuse=True)\n if hps.direct_iterator:\n m.test = lambda: sess.run(stats_test)\n else:\n def _test():\n _x, _y = test_iterator()\n return sess.run(stats_test, {feeds['x']: _x,\n feeds['y']: _y})\n m.test = _test\n\n # === Saving and restoring\n saver = tf.train.Saver()\n saver_ema = tf.train.Saver(ema.variables_to_restore())\n m.save_ema = lambda path: saver_ema.save(\n sess, path, write_meta_graph=False)\n m.save = lambda path: saver.save(sess, path, write_meta_graph=False)\n m.restore = lambda path: saver.restore(sess, path)\n\n # === Initialize the parameters\n if hps.restore_path != '':\n m.restore(hps.restore_path)\n else:\n with Z.arg_scope([Z.get_variable_ddi, Z.actnorm], init=True):\n results_init = f_loss(None, True, reuse=True)\n sess.run(tf.global_variables_initializer())\n sess.run(results_init, {feeds['x']: data_init['x'],\n feeds['y']: data_init['y']})\n sess.run(hvd.broadcast_global_variables(0))\n\n return m\n\n\ndef codec(hps):\n\n def encoder(z, objective):\n eps = []\n for i in range(hps.n_levels):\n z, objective = revnet2d(str(i), z, objective, hps)\n if i < hps.n_levels-1:\n z, objective, _eps = split2d(\"pool\"+str(i), z, objective=objective)\n eps.append(_eps)\n return z, objective, eps\n\n def decoder(z, eps=[None]*hps.n_levels, eps_std=None):\n for i in reversed(range(hps.n_levels)):\n if i < hps.n_levels-1:\n z = split2d_reverse(\"pool\"+str(i), z, eps=eps[i], eps_std=eps_std)\n z, _ = revnet2d(str(i), z, 0, hps, reverse=True)\n\n return z\n\n return encoder, decoder\n\n\ndef prior(name, y_onehot, hps):\n\n with tf.variable_scope(name):\n n_z = hps.top_shape[-1]\n\n h = tf.zeros([tf.shape(y_onehot)[0]]+hps.top_shape[:2]+[2*n_z])\n if hps.learntop:\n h = Z.conv2d_zeros('p', h, 2*n_z)\n if hps.ycond:\n h += tf.reshape(Z.linear_zeros(\"y_emb\", y_onehot,\n 2*n_z), [-1, 1, 1, 2 * n_z])\n\n pz = Z.gaussian_diag(h[:, :, :, :n_z], h[:, :, :, n_z:])\n\n def logp(z1):\n objective = pz.logp(z1)\n return objective\n\n def sample(eps=None, eps_std=None):\n if eps is not None:\n # Already sampled eps. Don't use eps_std\n z = pz.sample2(eps)\n elif eps_std is not None:\n # Sample with given eps_std\n z = pz.sample2(pz.eps * tf.reshape(eps_std, [-1, 1, 1, 1]))\n else:\n # Sample normally\n z = pz.sample\n\n return z\n\n def eps(z1):\n return pz.get_eps(z1)\n\n return logp, sample, eps\n\n\ndef model(sess, hps, train_iterator, test_iterator, data_init):\n\n # Only for decoding/init, rest use iterators directly\n with tf.name_scope('input'):\n X = tf.placeholder(\n tf.uint8, [None, hps.image_size, hps.image_size, 3], name='image')\n Y = tf.placeholder(tf.int32, [None], name='label')\n lr = tf.placeholder(tf.float32, None, name='learning_rate')\n\n encoder, decoder = codec(hps)\n hps.n_bins = 2. ** hps.n_bits_x\n\n def preprocess(x):\n x = tf.cast(x, 'float32')\n if hps.n_bits_x < 8:\n x = tf.floor(x / 2 ** (8 - hps.n_bits_x))\n x = x / hps.n_bins - .5\n return x\n\n def postprocess(x):\n return tf.cast(tf.clip_by_value(tf.floor((x + .5)*hps.n_bins)*(256./hps.n_bins), 0, 255), 'uint8')\n\n def _f_loss(x, y, is_training, reuse=False):\n\n with tf.variable_scope('model', reuse=reuse):\n y_onehot = tf.cast(tf.one_hot(y, hps.n_y, 1, 0), 'float32')\n\n # Discrete -> Continuous\n objective = tf.zeros_like(x, dtype='float32')[:, 0, 0, 0]\n z = preprocess(x)\n z = z + tf.random_uniform(tf.shape(z), 0, 1./hps.n_bins)\n objective += - np.log(hps.n_bins) * np.prod(Z.int_shape(z)[1:])\n\n # Encode\n z = Z.squeeze2d(z, 2) # > 16x16x12\n z, objective, _ = encoder(z, objective)\n\n # Prior\n hps.top_shape = Z.int_shape(z)[1:]\n logp, _, _ = prior(\"prior\", y_onehot, hps)\n objective += logp(z)\n\n # Generative loss\n nobj = - objective\n bits_x = nobj / (np.log(2.) * int(x.get_shape()[1]) * int(\n x.get_shape()[2]) * int(x.get_shape()[3])) # bits per subpixel\n\n # Predictive loss\n if hps.weight_y > 0 and hps.ycond:\n\n # Classification loss\n h_y = tf.reduce_mean(z, axis=[1, 2])\n y_logits = Z.linear_zeros(\"classifier\", h_y, hps.n_y)\n bits_y = tf.nn.softmax_cross_entropy_with_logits_v2(\n labels=y_onehot, logits=y_logits) / np.log(2.)\n\n # Classification accuracy\n y_predicted = tf.argmax(y_logits, 1, output_type=tf.int32)\n classification_error = 1 - \\\n tf.cast(tf.equal(y_predicted, y), tf.float32)\n else:\n bits_y = tf.zeros_like(bits_x)\n classification_error = tf.ones_like(bits_x)\n\n return bits_x, bits_y, classification_error\n\n def f_loss(iterator, is_training, reuse=False):\n if hps.direct_iterator and iterator is not None:\n x, y = iterator.get_next()\n else:\n x, y = X, Y\n\n bits_x, bits_y, pred_loss = _f_loss(x, y, is_training, reuse)\n local_loss = bits_x + hps.weight_y * bits_y\n stats = [local_loss, bits_x, bits_y, pred_loss]\n global_stats = Z.allreduce_mean(\n tf.stack([tf.reduce_mean(i) for i in stats]))\n\n return tf.reduce_mean(local_loss), global_stats\n\n feeds = {'x': X, 'y': Y}\n m = abstract_model_xy(sess, hps, feeds, train_iterator,\n test_iterator, data_init, lr, f_loss)\n\n # === Sampling function\n def f_sample(y, eps_std):\n with tf.variable_scope('model', reuse=True):\n y_onehot = tf.cast(tf.one_hot(y, hps.n_y, 1, 0), 'float32')\n\n _, sample, _ = prior(\"prior\", y_onehot, hps)\n z = sample(eps_std=eps_std)\n z = decoder(z, eps_std=eps_std)\n z = Z.unsqueeze2d(z, 2) # 8x8x12 -> 16x16x3\n x = postprocess(z)\n\n return x\n\n m.eps_std = tf.placeholder(tf.float32, [None], name='eps_std')\n x_sampled = f_sample(Y, m.eps_std)\n\n def sample(_y, _eps_std):\n return m.sess.run(x_sampled, {Y: _y, m.eps_std: _eps_std})\n m.sample = sample\n\n if hps.inference:\n # === Encoder-Decoder functions\n def f_encode(x, y, reuse=True):\n with tf.variable_scope('model', reuse=reuse):\n y_onehot = tf.cast(tf.one_hot(y, hps.n_y, 1, 0), 'float32')\n\n # Discrete -> Continuous\n objective = tf.zeros_like(x, dtype='float32')[:, 0, 0, 0]\n z = preprocess(x)\n z = z + tf.random_uniform(tf.shape(z), 0, 1. / hps.n_bins)\n objective += - np.log(hps.n_bins) * np.prod(Z.int_shape(z)[1:])\n\n # Encode\n z = Z.squeeze2d(z, 2) # > 16x16x12\n z, objective, eps = encoder(z, objective)\n\n # Prior\n hps.top_shape = Z.int_shape(z)[1:]\n logp, _, _eps = prior(\"prior\", y_onehot, hps)\n objective += logp(z)\n eps.append(_eps(z))\n\n return eps\n\n def f_decode(y, eps, reuse=True):\n with tf.variable_scope('model', reuse=reuse):\n y_onehot = tf.cast(tf.one_hot(y, hps.n_y, 1, 0), 'float32')\n\n _, sample, _ = prior(\"prior\", y_onehot, hps)\n z = sample(eps=eps[-1])\n z = decoder(z, eps=eps[:-1])\n z = Z.unsqueeze2d(z, 2) # 8x8x12 -> 16x16x3\n x = postprocess(z)\n\n return x\n\n enc_eps = f_encode(X, Y)\n dec_eps = []\n print(enc_eps)\n for i, _eps in enumerate(enc_eps):\n print(_eps)\n dec_eps.append(tf.placeholder(tf.float32, _eps.get_shape().as_list(), name=\"dec_eps_\" + str(i)))\n dec_x = f_decode(Y, dec_eps)\n\n eps_shapes = [_eps.get_shape().as_list()[1:] for _eps in enc_eps]\n\n def flatten_eps(eps):\n # [BS, eps_size]\n return np.concatenate([np.reshape(e, (e.shape[0], -1)) for e in eps], axis=-1)\n\n def unflatten_eps(feps):\n index = 0\n eps = []\n bs = feps.shape[0]\n for shape in eps_shapes:\n eps.append(np.reshape(feps[:, index: index+np.prod(shape)], (bs, *shape)))\n index += np.prod(shape)\n return eps\n\n # If model is uncondtional, always pass y = np.zeros([bs], dtype=np.int32)\n def encode(x, y):\n return flatten_eps(sess.run(enc_eps, {X: x, Y: y}))\n\n def decode(y, feps):\n eps = unflatten_eps(feps)\n feed_dict = {Y: y}\n for i in range(len(dec_eps)):\n feed_dict[dec_eps[i]] = eps[i]\n return sess.run(dec_x, feed_dict)\n\n m.encode = encode\n m.decode = decode\n\n return m\n\n\ndef checkpoint(z, logdet):\n zshape = Z.int_shape(z)\n z = tf.reshape(z, [-1, zshape[1]*zshape[2]*zshape[3]])\n logdet = tf.reshape(logdet, [-1, 1])\n combined = tf.concat([z, logdet], axis=1)\n tf.add_to_collection('checkpoints', combined)\n logdet = combined[:, -1]\n z = tf.reshape(combined[:, :-1], [-1, zshape[1], zshape[2], zshape[3]])\n return z, logdet\n\n\n@add_arg_scope\ndef revnet2d(name, z, logdet, hps, reverse=False):\n with tf.variable_scope(name):\n if not reverse:\n for i in range(hps.depth):\n z, logdet = checkpoint(z, logdet)\n z, logdet = revnet2d_step(str(i), z, logdet, hps, reverse)\n z, logdet = checkpoint(z, logdet)\n else:\n for i in reversed(range(hps.depth)):\n z, logdet = revnet2d_step(str(i), z, logdet, hps, reverse)\n return z, logdet\n\n# Simpler, new version\n@add_arg_scope\ndef revnet2d_step(name, z, logdet, hps, reverse):\n with tf.variable_scope(name):\n\n shape = Z.int_shape(z)\n n_z = shape[3]\n assert n_z % 2 == 0\n\n if not reverse:\n\n z, logdet = Z.actnorm(\"actnorm\", z, logdet=logdet)\n\n if hps.flow_permutation == 0:\n z = Z.reverse_features(\"reverse\", z)\n elif hps.flow_permutation == 1:\n z = Z.shuffle_features(\"shuffle\", z)\n elif hps.flow_permutation == 2:\n z, logdet = invertible_1x1_conv(\"invconv\", z, logdet)\n else:\n raise Exception()\n\n z1 = z[:, :, :, :n_z // 2]\n z2 = z[:, :, :, n_z // 2:]\n\n if hps.flow_coupling == 0:\n z2 += f(\"f1\", z1, hps.width)\n elif hps.flow_coupling == 1:\n h = f(\"f1\", z1, hps.width, n_z)\n shift = h[:, :, :, 0::2]\n # scale = tf.exp(h[:, :, :, 1::2])\n scale = tf.nn.sigmoid(h[:, :, :, 1::2] + 2.)\n z2 += shift\n z2 *= scale\n logdet += tf.reduce_sum(tf.log(scale), axis=[1, 2, 3])\n else:\n raise Exception()\n\n z = tf.concat([z1, z2], 3)\n\n else:\n\n z1 = z[:, :, :, :n_z // 2]\n z2 = z[:, :, :, n_z // 2:]\n\n if hps.flow_coupling == 0:\n z2 -= f(\"f1\", z1, hps.width)\n elif hps.flow_coupling == 1:\n h = f(\"f1\", z1, hps.width, n_z)\n shift = h[:, :, :, 0::2]\n # scale = tf.exp(h[:, :, :, 1::2])\n scale = tf.nn.sigmoid(h[:, :, :, 1::2] + 2.)\n z2 /= scale\n z2 -= shift\n logdet -= tf.reduce_sum(tf.log(scale), axis=[1, 2, 3])\n else:\n raise Exception()\n\n z = tf.concat([z1, z2], 3)\n\n if hps.flow_permutation == 0:\n z = Z.reverse_features(\"reverse\", z, reverse=True)\n elif hps.flow_permutation == 1:\n z = Z.shuffle_features(\"shuffle\", z, reverse=True)\n elif hps.flow_permutation == 2:\n z, logdet = invertible_1x1_conv(\n \"invconv\", z, logdet, reverse=True)\n else:\n raise Exception()\n\n z, logdet = Z.actnorm(\"actnorm\", z, logdet=logdet, reverse=True)\n\n return z, logdet\n\n\ndef f(name, h, width, n_out=None):\n n_out = n_out or int(h.get_shape()[3])\n with tf.variable_scope(name):\n h = tf.nn.relu(Z.conv2d(\"l_1\", h, width))\n h = tf.nn.relu(Z.conv2d(\"l_2\", h, width, filter_size=[1, 1]))\n h = Z.conv2d_zeros(\"l_last\", h, n_out)\n return h\n\n\ndef f_resnet(name, h, width, n_out=None):\n n_out = n_out or int(h.get_shape()[3])\n with tf.variable_scope(name):\n h = tf.nn.relu(Z.conv2d(\"l_1\", h, width))\n h = Z.conv2d_zeros(\"l_2\", h, n_out)\n return h\n\n# Invertible 1x1 conv\n@add_arg_scope\ndef invertible_1x1_conv(name, z, logdet, reverse=False):\n\n if True: # Set to \"False\" to use the LU-decomposed version\n\n with tf.variable_scope(name):\n\n shape = Z.int_shape(z)\n w_shape = [shape[3], shape[3]]\n\n # Sample a random orthogonal matrix:\n w_init = np.linalg.qr(np.random.randn(\n *w_shape))[0].astype('float32')\n\n w = tf.get_variable(\"W\", dtype=tf.float32, initializer=w_init)\n\n # dlogdet = tf.linalg.LinearOperator(w).log_abs_determinant() * shape[1]*shape[2]\n dlogdet = tf.cast(tf.log(abs(tf.matrix_determinant(\n tf.cast(w, 'float64')))), 'float32') * shape[1]*shape[2]\n\n if not reverse:\n\n _w = tf.reshape(w, [1, 1] + w_shape)\n z = tf.nn.conv2d(z, _w, [1, 1, 1, 1],\n 'SAME', data_format='NHWC')\n logdet += dlogdet\n\n return z, logdet\n else:\n\n _w = tf.matrix_inverse(w)\n _w = tf.reshape(_w, [1, 1]+w_shape)\n z = tf.nn.conv2d(z, _w, [1, 1, 1, 1],\n 'SAME', data_format='NHWC')\n logdet -= dlogdet\n\n return z, logdet\n\n else:\n\n # LU-decomposed version\n shape = Z.int_shape(z)\n with tf.variable_scope(name):\n\n dtype = 'float64'\n\n # Random orthogonal matrix:\n import scipy\n np_w = scipy.linalg.qr(np.random.randn(shape[3], shape[3]))[\n 0].astype('float32')\n\n np_p, np_l, np_u = scipy.linalg.lu(np_w)\n np_s = np.diag(np_u)\n np_sign_s = np.sign(np_s)\n np_log_s = np.log(abs(np_s))\n np_u = np.triu(np_u, k=1)\n\n p = tf.get_variable(\"P\", initializer=np_p, trainable=False)\n l = tf.get_variable(\"L\", initializer=np_l)\n sign_s = tf.get_variable(\n \"sign_S\", initializer=np_sign_s, trainable=False)\n log_s = tf.get_variable(\"log_S\", initializer=np_log_s)\n # S = tf.get_variable(\"S\", initializer=np_s)\n u = tf.get_variable(\"U\", initializer=np_u)\n\n p = tf.cast(p, dtype)\n l = tf.cast(l, dtype)\n sign_s = tf.cast(sign_s, dtype)\n log_s = tf.cast(log_s, dtype)\n u = tf.cast(u, dtype)\n\n w_shape = [shape[3], shape[3]]\n\n l_mask = np.tril(np.ones(w_shape, dtype=dtype), -1)\n l = l * l_mask + tf.eye(*w_shape, dtype=dtype)\n u = u * np.transpose(l_mask) + tf.diag(sign_s * tf.exp(log_s))\n w = tf.matmul(p, tf.matmul(l, u))\n\n if True:\n u_inv = tf.matrix_inverse(u)\n l_inv = tf.matrix_inverse(l)\n p_inv = tf.matrix_inverse(p)\n w_inv = tf.matmul(u_inv, tf.matmul(l_inv, p_inv))\n else:\n w_inv = tf.matrix_inverse(w)\n\n w = tf.cast(w, tf.float32)\n w_inv = tf.cast(w_inv, tf.float32)\n log_s = tf.cast(log_s, tf.float32)\n\n if not reverse:\n\n w = tf.reshape(w, [1, 1] + w_shape)\n z = tf.nn.conv2d(z, w, [1, 1, 1, 1],\n 'SAME', data_format='NHWC')\n logdet += tf.reduce_sum(log_s) * (shape[1]*shape[2])\n\n return z, logdet\n else:\n\n w_inv = tf.reshape(w_inv, [1, 1]+w_shape)\n z = tf.nn.conv2d(\n z, w_inv, [1, 1, 1, 1], 'SAME', data_format='NHWC')\n logdet -= tf.reduce_sum(log_s) * (shape[1]*shape[2])\n\n return z, logdet\n\n\n@add_arg_scope\ndef split2d(name, z, objective=0.):\n with tf.variable_scope(name):\n n_z = Z.int_shape(z)[3]\n z1 = z[:, :, :, :n_z // 2]\n z2 = z[:, :, :, n_z // 2:]\n pz = split2d_prior(z1)\n objective += pz.logp(z2)\n z1 = Z.squeeze2d(z1)\n eps = pz.get_eps(z2)\n return z1, objective, eps\n\n\n@add_arg_scope\ndef split2d_reverse(name, z, eps, eps_std):\n with tf.variable_scope(name):\n z1 = Z.unsqueeze2d(z)\n pz = split2d_prior(z1)\n if eps is not None:\n # Already sampled eps\n z2 = pz.sample2(eps)\n elif eps_std is not None:\n # Sample with given eps_std\n z2 = pz.sample2(pz.eps * tf.reshape(eps_std, [-1, 1, 1, 1]))\n else:\n # Sample normally\n z2 = pz.sample\n z = tf.concat([z1, z2], 3)\n return z\n\n\n@add_arg_scope\ndef split2d_prior(z):\n n_z2 = int(z.get_shape()[3])\n n_z1 = n_z2\n h = Z.conv2d_zeros(\"conv\", z, 2 * n_z1)\n\n mean = h[:, :, :, 0::2]\n logs = h[:, :, :, 1::2]\n return Z.gaussian_diag(mean, logs)\n"
] |
[
[
"numpy.diag",
"tensorflow.get_variable",
"tensorflow.concat",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.equal",
"numpy.random.randn",
"tensorflow.nn.conv2d",
"numpy.reshape",
"tensorflow.floor",
"tensorflow.gradients",
"tensorflow.name_scope",
"tensorflow.trainable_variables",
"tensorflow.train.Saver",
"numpy.triu",
"tensorflow.argmax",
"tensorflow.matmul",
"numpy.log",
"tensorflow.nn.sigmoid",
"tensorflow.shape",
"tensorflow.placeholder",
"tensorflow.exp",
"tensorflow.global_variables_initializer",
"tensorflow.zeros_like",
"tensorflow.one_hot",
"numpy.transpose",
"tensorflow.add_to_collection",
"tensorflow.reduce_mean",
"tensorflow.matrix_inverse",
"tensorflow.reshape",
"tensorflow.ones_like",
"tensorflow.eye",
"scipy.linalg.lu",
"numpy.sign",
"numpy.ones",
"tensorflow.log",
"numpy.prod",
"tensorflow.nn.softmax_cross_entropy_with_logits_v2",
"tensorflow.variable_scope"
]
] |
srvasude/jax
|
[
"fcb05915b5a106dbfad5162eb11064a9a5e430a2",
"fcb05915b5a106dbfad5162eb11064a9a5e430a2"
] |
[
"tests/pmap_test.py",
"tests/sharded_jit_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\nfrom concurrent.futures import ThreadPoolExecutor\nfrom functools import partial\nimport os\nfrom random import shuffle\nfrom unittest import SkipTest\n\nimport numpy as np\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n\nimport jax\nimport jax.numpy as jnp\nfrom jax import test_util as jtu\nfrom jax import tree_util\nfrom jax import lax\nfrom jax import random\nfrom jax.abstract_arrays import ShapedArray\nfrom jax.api import (pmap, soft_pmap, jit, vmap, jvp, grad, make_jaxpr,\n linearize, device_put)\nfrom jax.lib import xla_bridge\nfrom jax.util import prod\nfrom jax.interpreters import pxla\nfrom jax.interpreters import xla\n\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n\nprev_xla_flags = None\n\n# Run all tests with 8 CPU devices.\ndef setUpModule():\n global prev_xla_flags\n prev_xla_flags = os.getenv(\"XLA_FLAGS\")\n flags_str = prev_xla_flags or \"\"\n # Don't override user-specified device count, or other XLA flags.\n if \"xla_force_host_platform_device_count\" not in flags_str:\n os.environ[\"XLA_FLAGS\"] = (flags_str +\n \" --xla_force_host_platform_device_count=8\")\n # Clear any cached backends so new CPU backend will pick up the env var.\n xla_bridge.get_backend.cache_clear()\n\n# Reset to previous configuration in case other test modules will be run.\ndef tearDownModule():\n if prev_xla_flags is None:\n del os.environ[\"XLA_FLAGS\"]\n else:\n os.environ[\"XLA_FLAGS\"] = prev_xla_flags\n xla_bridge.get_backend.cache_clear()\n\nignore_soft_pmap_warning = partial(\n jtu.ignore_warning, message=\"soft_pmap is an experimental.*\")\n\n\nclass PmapTest(jtu.JaxTestCase):\n def _getMeshShape(self, device_mesh_shape):\n device_count = xla_bridge.device_count()\n if any(size == -1 for size in device_mesh_shape):\n try:\n return np.arange(device_count).reshape(device_mesh_shape).shape\n except ValueError as err:\n msg = \"device mesh shape {} not compatible with device count {}\"\n raise SkipTest(msg.format(device_mesh_shape, device_count)) from err\n else:\n if device_count % prod(device_mesh_shape):\n msg = \"device mesh size {} does not divide available device count {}\"\n raise SkipTest(msg.format(prod(device_mesh_shape), device_count))\n else:\n return device_mesh_shape\n\n def testBasic(self):\n f = pmap(lambda x: x - lax.psum(x, 'i'), axis_name='i')\n\n shape = (xla_bridge.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n expected = x - np.sum(x, 0)\n\n ans = f(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testMean(self):\n f = pmap(lambda x: x - lax.pmean(x, 'i'), axis_name='i')\n\n shape = (xla_bridge.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n expected = x - np.broadcast_to(np.mean(x, 0), x.shape)\n\n ans = f(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testGather(self):\n f = pmap(lambda x: lax.all_gather(x, 'i'), axis_name='i')\n\n shape = (xla_bridge.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n expected = np.array([x] * xla_bridge.device_count())\n ans = f(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testTrees(self):\n ptranspose = lambda x, axis_name: lax.all_to_all(x, axis_name, 0, 0)\n def protate(x, axis_name):\n n = lax.psum(1, axis_name)\n return lax.ppermute(x, axis_name, [(i, (i + 1) % n) for i in range(n)])\n\n tree_f = lambda f: partial(tree_util.tree_map, f)\n jax_f = lambda p: pmap(lambda x: p(x, 'i'), 'i')\n np_f = lambda p: tree_f(lambda x: np.broadcast_to(p(x, 0), x.shape))\n np_transpose = tree_f(np.transpose)\n np_rotate = tree_f(lambda x: np.concatenate([x[-1:], x[:-1]]))\n\n n = xla_bridge.device_count()\n x = {'a': np.arange(1 * n * n, 2 * n * n).reshape([n, n]),\n 'b': np.arange(2 * n * n, 3 * n * n).reshape([n, n]),\n 'c': np.arange(4 * n * n, 5 * n * n).reshape([n, n])}\n\n assert_allclose = partial(tree_util.tree_multimap,\n partial(self.assertAllClose, check_dtypes=False))\n assert_allclose(jax_f(lax.pmax)(x), np_f(np.max)(x))\n assert_allclose(jax_f(lax.pmin)(x), np_f(np.min)(x))\n assert_allclose(jax_f(lax.psum)(x), np_f(np.sum)(x))\n assert_allclose(jax_f(lax.pmean)(x), np_f(np.mean)(x))\n if jtu.device_under_test() not in (\"cpu\", \"gpu\"):\n # NOTE: all-to-all and ppermute only supported on TPU.\n assert_allclose(jax_f(ptranspose)(x), np_transpose(x))\n assert_allclose(jax_f(protate)(x), np_rotate(x))\n\n def testCollectivesWithTreesOfDifferentDtypes(self):\n n = len(jax.devices())\n x = {'a': np.arange(1 * n * n, 2 * n * n, dtype=np.float32).reshape([n, n]),\n 'b': np.arange(2 * n * n, 3 * n * n, dtype=np.int32).reshape([n, n]),\n 'c': np.arange(4 * n * n, 5 * n * n, dtype=np.float32).reshape([n, n]),\n 'd': np.arange(6 * n * n, 7 * n * n, dtype=np.int32).reshape([n, n])}\n tree_f = lambda f: partial(tree_util.tree_map, f)\n jax_f = lambda p: pmap(lambda x: p(x, 'i'), 'i')\n np_f = lambda p: tree_f(lambda x: np.broadcast_to(p(x, 0), x.shape))\n assert_allclose = partial(tree_util.tree_multimap,\n partial(self.assertAllClose, check_dtypes=False))\n assert_allclose(jax_f(lax.pmax)(x), np_f(np.max)(x))\n assert_allclose(jax_f(lax.pmin)(x), np_f(np.min)(x))\n assert_allclose(jax_f(lax.psum)(x), np_f(np.sum)(x))\n assert_allclose(jax_f(lax.pmean)(x), np_f(np.mean)(x))\n\n def testComplexPsum(self):\n f = pmap(lambda x: x - lax.psum(x, 'i'), axis_name='i')\n\n shape = (xla_bridge.device_count(), 4 * 2)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape).view(np.complex64)\n expected = x - np.sum(x, 0)\n\n ans = f(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n\n def testNestedBasic(self):\n f = lambda x: lax.psum(lax.psum(x, 'i'), 'j')\n f = pmap(pmap(f, 'i'), 'j')\n\n def sum_and_broadcast(x, axis):\n return np.repeat(np.sum(x, axis, keepdims=True), x.shape[axis], axis)\n\n shape = (xla_bridge.device_count(), 1, 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n\n ans = f(x)\n expected = sum_and_broadcast(sum_and_broadcast(x, 0), 1)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testMismatchedAxisSizes(self):\n n = xla_bridge.device_count()\n f = pmap(lambda x, y: x + y)\n self.assertRaisesRegex(\n ValueError,\n \"pmap got inconsistent sizes for array axes to be mapped\",\n lambda: f(np.random.randn(n), np.random.randn(n - 1)))\n\n @parameterized.named_parameters(\n {\"testcase_name\": \"_mesh={}\".format(device_mesh_shape).replace(\" \", \"\"),\n \"device_mesh_shape\": device_mesh_shape}\n for device_mesh_shape in [(1, 1), (2, -1), (-1, 2)])\n def testNestedShardingAndStacking(self, device_mesh_shape):\n mesh_shape = self._getMeshShape(device_mesh_shape)\n\n f = lambda x: x\n f = pmap(pmap(f, 'i'), 'j')\n\n shape = mesh_shape + (4,)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n\n ans = f(x)\n expected = x\n self.assertEqual(ans.shape, expected.shape)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testPartiallyMapped(self):\n f = pmap(lambda x, y: x, in_axes=(None, 0))\n g = pmap(lambda x, y: x - lax.psum(y, 'i'), axis_name='i', in_axes=(None, 0))\n\n mesh_shape = (xla_bridge.device_count(),)\n shape = mesh_shape + (4,)\n x = np.array(3., dtype=np.float32)\n y = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n\n f_expected = np.broadcast_to(x, mesh_shape)\n f_ans = f(x, y)\n self.assertAllClose(f_ans, f_expected)\n self.assertIsInstance(f_ans, pxla.ShardedDeviceArray)\n # the output is actually replicated (has the same values in each device buffer)\n # but out_axes is implicitly 0, so we shouldn't have replication in the\n # sharding spec.\n self.assertEmpty(f_ans.sharding_spec.replication_factors)\n\n g_expected = np.broadcast_to(x - np.sum(y, 0, keepdims=True), shape)\n g_ans = g(x, y)\n self.assertAllClose(g_ans, g_expected)\n self.assertIsInstance(g_ans, pxla.ShardedDeviceArray)\n self.assertEmpty(g_ans.sharding_spec.replication_factors)\n\n @parameterized.named_parameters(\n {\"testcase_name\": \"_mesh={}\".format(device_mesh_shape).replace(\" \", \"\"),\n \"device_mesh_shape\": device_mesh_shape}\n for device_mesh_shape in [(1, 1), (2, -1), (-1, 2)])\n def testPartiallyMappedNested(self, device_mesh_shape):\n mesh_shape = self._getMeshShape(device_mesh_shape)\n\n f = pmap(lambda x, y: x - lax.psum(y, 'i'), axis_name='i', in_axes=(None, 0))\n f = pmap(f, axis_name='j', in_axes=(None, 0))\n\n x = 3.\n y = np.arange(prod(mesh_shape), dtype=np.float32).reshape(mesh_shape)\n expected = np.broadcast_to(x - np.sum(y, 1, keepdims=True), mesh_shape)\n\n ans = f(x, y)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testJvpAndPartialEval(self):\n @partial(pmap, axis_name='i')\n def f(x):\n return jnp.sin(x)\n\n def splitjvp(x):\n _, jvp = linearize(f, x)\n return jvp(jnp.ones_like(x))\n\n shape = (xla_bridge.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n expected = np.cos(x)\n\n ans = splitjvp(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n make_jaxpr(splitjvp)(x) # doesn't crash\n\n def testGradBasic(self):\n @partial(pmap, axis_name='i')\n def f(x):\n return jnp.sin(x)\n\n shape = (xla_bridge.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n\n ans = grad(lambda x: jnp.sum(jnp.sin(x)))(x)\n expected = grad(lambda x: jnp.sum(f(x)))(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testGradOfPsum(self):\n @partial(pmap, axis_name='i')\n def f(x):\n return lax.psum(x, axis_name='i')\n\n shape = (jax.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n jtu.check_grads(f, (x,), 2, [\"fwd\", \"rev\"], 1e-2, 1e-2, eps=1.)\n\n def testGradOfJvp(self):\n @partial(pmap, axis_name='i')\n def f(x):\n return jnp.sin(x)\n\n def splitjvp(x):\n _, jvp = linearize(f, x)\n return jvp(jnp.ones_like(x))\n\n fun = lambda x: jnp.sum(jvp(jnp.sin, (x,), (jnp.ones_like(x),))[1])\n\n shape = (xla_bridge.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n\n ans = grad(lambda x: jnp.sum(splitjvp(x)))(x)\n expected = grad(fun)(x)\n self.assertAllClose(ans, expected)\n\n def testTwoArgsGrad(self):\n def f(x, y):\n return lax.psum(5. * jnp.cos(x) * jnp.sin(y), 'i')\n f = pmap(f, 'i')\n\n def g(x, y):\n tot = jnp.sum(5. * jnp.cos(x) * jnp.sin(y))\n return tot * jnp.ones_like(x) # broadcast to map like pjit does\n\n shape = (xla_bridge.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n y = 4 + x\n ans = grad(lambda x, y: jnp.sum(g(x, y)))(x, y)\n expected = grad(lambda x, y: jnp.sum(g(x, y)))(x, y)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @parameterized.named_parameters(\n {\"testcase_name\": \"_mesh={}\".format(device_mesh_shape).replace(\" \", \"\"),\n \"device_mesh_shape\": device_mesh_shape}\n for device_mesh_shape in [(1, 1), (2, -1), (-1, 2)])\n def testNestedWithClosure(self, device_mesh_shape):\n mesh_shape = self._getMeshShape(device_mesh_shape)\n\n @partial(pmap, axis_name='i')\n def test_fun(x):\n y = jnp.sum(jnp.sin(x))\n\n @partial(pmap, axis_name='j')\n def g(z):\n return 3. * jnp.exp(jnp.sin(x).sum() * jnp.cos(y) * jnp.tan(z))\n\n return grad(lambda w: jnp.sum(g(w)))(x)\n\n @vmap\n def baseline_fun(x):\n y = jnp.sum(jnp.sin(x))\n\n @vmap\n def g(z):\n return 3. * jnp.exp(jnp.sin(x).sum() * jnp.cos(y) * jnp.tan(z))\n\n return grad(lambda w: jnp.sum(g(w)))(x)\n\n shape = mesh_shape + (4,)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n\n ans = grad(lambda x: jnp.sum(test_fun(x)))(x)\n expected = grad(lambda x: jnp.sum(baseline_fun(x)))(x)\n self.assertAllClose(ans, expected, atol=1e-3)\n\n def testShardedDeviceArrays(self):\n f = lambda x: 2 * x\n f = pmap(f, axis_name='i')\n\n shape = (xla_bridge.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n\n # test that we can pass in and out ShardedDeviceArrays\n y = f(x)\n self.assertIsInstance(y, jnp.ndarray)\n self.assertIsInstance(y, pxla.ShardedDeviceArray)\n self.assertAllClose(y, 2 * x, check_dtypes=False)\n z = f(y)\n self.assertIsInstance(z, pxla.ShardedDeviceArray)\n self.assertAllClose(z, 2 * 2 * x, check_dtypes=False)\n\n # test that we can pass in a regular DeviceArray\n y = f(device_put(x))\n self.assertIsInstance(y, pxla.ShardedDeviceArray)\n self.assertAllClose(y, 2 * x, check_dtypes=False)\n\n # test that we can pass a ShardedDeviceArray to a regular jit computation\n z = y + y\n self.assertAllClose(z, 2 * 2 * x, check_dtypes=False)\n\n # test that we can handle device movement on dispatch\n y.device_buffers = y.device_buffers[::-1]\n z = f(y)\n self.assertAllClose(z, 2 * 2 * x[::-1], check_dtypes=False)\n\n # test that the repr doesn't crash\n repr(z)\n\n # Tests edge cases in lax._reshape_sharded_device_array\n @parameterized.named_parameters(\n {\"testcase_name\": \"_in={}_out={}\".format(in_shape, out_shape)\n .replace(\" \", \"\"),\n \"in_shape\": in_shape, \"out_shape\": out_shape}\n for in_shape, out_shape in [\n [(1,1), (1,)], [(1,), (1,1)], [(1,), ()], [(4,7), (2,2,7)]\n ])\n def testShardedDeviceArrayReshape(self, in_shape, out_shape):\n if xla_bridge.device_count() < max(in_shape[:1] + out_shape[:1]):\n raise SkipTest(\"not enough devices\")\n\n x = np.arange(prod(in_shape)).reshape(in_shape)\n sharded_x = pmap(lambda x: x)(x)\n self.assertAllClose(sharded_x.reshape(out_shape), x.reshape(out_shape),\n check_dtypes=False)\n\n def testPsumMultiple(self):\n f = lambda x: lax.psum(x, ('i', 'j'))\n f = pmap(pmap(f, 'i'), 'j')\n\n def sum_and_broadcast(x, axis):\n return np.repeat(np.sum(x, axis, keepdims=True), x.shape[axis], axis)\n\n device_count = xla_bridge.device_count()\n num_pairs, ragged = divmod(device_count, 2)\n if num_pairs > 1 and not ragged:\n shape = (num_pairs, 2, 4)\n else:\n shape = (device_count, 1, 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n\n ans = f(x)\n expected = sum_and_broadcast(sum_and_broadcast(x, 0), 1)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testPsumReplicaGroups(self):\n replicas = xla_bridge.device_count()\n if replicas % 2 != 0:\n raise SkipTest\n axis_index_groups = np.arange(replicas).reshape(\n 2, replicas // 2).tolist()\n f = lambda x: x - lax.psum(x, 'i', axis_index_groups=axis_index_groups)\n f = pmap(f, 'i')\n\n shape = (replicas, 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n def sum_helper(a):\n return np.broadcast_to(a.sum(0, keepdims=True),\n (replicas // 2, x.shape[1]))\n expected_psum_1 = sum_helper(x[:replicas // 2])\n expected_psum_2 = sum_helper(x[replicas // 2:])\n expected_psum = np.concatenate([expected_psum_1, expected_psum_2], 0)\n expected = x - expected_psum\n\n ans = f(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testNestedPmapReplicaGroups(self):\n replicas = xla_bridge.device_count()\n if replicas % 4 != 0:\n raise SkipTest\n axis_index_groups = np.arange(replicas // 2).reshape(\n 2, replicas // 4).tolist()\n f = lambda x: x - lax.psum(x, 'i', axis_index_groups=axis_index_groups)\n f1 = pmap(pmap(f, 'i'), 'j')\n f2 = pmap(lambda x: pmap(f, 'i')(x) + 1., 'j') # \"imperfectly nested\" case\n f3 = pmap(pmap(f, 'j'), 'i')\n\n shape = (2, replicas // 2, 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n def sum_helper_f1(a):\n return np.broadcast_to(a.sum(1, keepdims=True),\n (shape[0], shape[1] // 2, shape[2]))\n expected_psum_1 = sum_helper_f1(x[:, :replicas // 4])\n expected_psum_2 = sum_helper_f1(x[:, replicas // 4:])\n expected_psum = np.concatenate([expected_psum_1, expected_psum_2], 1)\n expected = x - expected_psum\n ans = f1(x)\n self.assertAllClose(ans, expected)\n\n expected = x - expected_psum + 1.\n ans = f2(x)\n self.assertAllClose(ans, expected)\n\n shape = (replicas // 2, 2, 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n def sum_helper_f3(a):\n return np.broadcast_to(a.sum(0, keepdims=True),\n (shape[0] // 2, shape[1], shape[2]))\n expected_psum_1 = sum_helper_f3(x[:replicas // 4])\n expected_psum_2 = sum_helper_f3(x[replicas // 4:])\n expected_psum = np.concatenate([expected_psum_1, expected_psum_2], 0)\n expected = x - expected_psum\n ans = f3(x)\n self.assertAllClose(ans, expected)\n\n def testAxisGroups(self):\n axis_env = xla.AxisEnv(8, ('i', 'j'), (4, 2))\n groups = xla.axis_groups(axis_env, 'i')\n self.assertEqual(groups, ((0, 2, 4, 6), (1, 3, 5, 7)))\n\n groups = xla.axis_groups(axis_env, 'j')\n self.assertEqual(groups, ((0, 1), (2, 3), (4, 5), (6, 7)))\n\n groups = xla.axis_groups(axis_env, ('i', 'j'))\n self.assertEqual(groups, ((0, 1, 2, 3, 4, 5, 6, 7,),))\n\n groups = xla.axis_groups(axis_env, ('j', 'i'))\n self.assertEqual(len(groups), 1)\n self.assertEqual((tuple(sorted(groups[0])),),\n ((0, 1, 2, 3, 4, 5, 6, 7,),)) # order doesn't matter\n\n @jtu.skip_on_devices(\"cpu\", \"gpu\")\n def testCollectivePermute(self):\n device_count = xla_bridge.device_count()\n rotation = [(i, (i + 1) % device_count) for i in range(device_count)]\n f = lambda x: lax.ppermute(x, perm=rotation, axis_name='i')\n f = pmap(f, 'i')\n\n x = jnp.arange(4 * device_count).reshape((device_count, 4))\n ans = f(x)\n expected = np.roll(x, shift=1, axis=0)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @jtu.skip_on_devices(\"cpu\", \"gpu\")\n def testCollectivePermuteGrad(self):\n device_count = xla_bridge.device_count()\n shift_right = [(i, (i + 1)) for i in range(device_count - 1)]\n f = lambda x: lax.ppermute(x, perm=shift_right, axis_name='i')\n y = np.pi + np.arange(device_count, dtype=np.float32)\n g = lambda x: jnp.sum(y * pmap(f, 'i')(x))\n\n x = np.arange(device_count, dtype=np.float32)\n ans = grad(g)(x)\n expected = np.concatenate([np.pi + np.arange(1, device_count), [0]])\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @jtu.skip_on_devices(\"cpu\", \"gpu\")\n def testCollectivePermuteCyclicGrad(self):\n device_count = xla_bridge.device_count()\n shift_right = [(i, (i + 1) % device_count) for i in range(device_count)]\n f = lambda x: lax.ppermute(x, perm=shift_right, axis_name='i')\n y = np.pi + np.arange(device_count, dtype=np.float32)\n g = lambda x: jnp.sum(y * pmap(f, 'i')(x))\n\n x = np.arange(device_count, dtype=np.float32)\n ans = grad(g)(x)\n expected = np.roll(np.pi + np.arange(device_count), 1)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @jtu.skip_on_devices(\"cpu\")\n def testCollectivePermuteCyclicWithPShuffle(self):\n device_count = xla_bridge.device_count()\n values = np.arange(device_count)\n shift_right = [(i - 1) % device_count for i in range(device_count)]\n f = lambda x: lax.pshuffle(x, perm=shift_right, axis_name='i')\n expected = np.roll(values, -1)\n ans = np.asarray(pmap(f, \"i\")(values))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @jtu.skip_on_devices(\"cpu\")\n def testPShuffleWithBadPerm(self):\n device_count = xla_bridge.device_count()\n bad_perm = list(range(device_count))\n bad_perm[0] = 1\n f = lambda x: lax.pshuffle(x, perm=bad_perm, axis_name='i')\n g = lambda: pmap(f, \"i\")(np.arange(device_count))\n self.assertRaisesRegex(\n AssertionError,\n \"Given `perm` does not represent a real permutation: \\\\[1.*\\\\]\", g)\n\n @jtu.skip_on_devices(\"cpu\", \"gpu\")\n def testPpermuteWithZipObject(self):\n # https://github.com/google/jax/issues/1703\n num_devices = xla_bridge.device_count()\n perm = [num_devices - 1] + list(range(num_devices - 1))\n f = pmap(\n lambda x: lax.ppermute(x, \"i\", zip(range(num_devices), perm)), \"i\")\n result = f(jnp.arange(num_devices, dtype=jnp.float32))\n expected = jnp.asarray(perm, dtype=jnp.float32)\n self.assertAllClose(result, expected)\n\n @jtu.skip_on_devices(\"cpu\", \"gpu\")\n def testRule30(self):\n # This is a test of collective_permute implementing a simple halo exchange\n # to run a rule 30 simulation: https://en.wikipedia.org/wiki/Rule_30\n # Halo exchange should be useful in spatially-sharded convolutions and in\n # other simulations.\n device_count = xla_bridge.device_count()\n\n def send_right(x, axis_name):\n left_perm = [(i, (i + 1) % device_count) for i in range(device_count)]\n return lax.ppermute(x, perm=left_perm, axis_name=axis_name)\n\n def send_left(x, axis_name):\n left_perm = [((i + 1) % device_count, i) for i in range(device_count)]\n return lax.ppermute(x, perm=left_perm, axis_name=axis_name)\n\n def update_board(board):\n left = board[:-2]\n right = board[2:]\n center = board[1:-1]\n return lax.bitwise_xor(left, lax.bitwise_or(center, right))\n\n @partial(pmap, axis_name='i')\n def step(board_slice):\n left, right = board_slice[:1], board_slice[-1:]\n right, left = send_left(left, 'i'), send_right(right, 'i')\n enlarged_board_slice = jnp.concatenate([left, board_slice, right])\n return update_board(enlarged_board_slice)\n\n board = np.zeros(40, dtype=bool)\n board[board.shape[0] // 2] = True\n reshaped_board = board.reshape((device_count, -1))\n\n boards = []\n def print_board(board):\n boards.append(''.join('*' if x else ' ' for x in board.ravel()))\n\n print_board(reshaped_board)\n for _ in range(20):\n reshaped_board = step(reshaped_board)\n print_board(reshaped_board)\n\n ans = '\\n'.join(boards)\n expected = '\\n'.join((\n ' * ',\n ' *** ',\n ' ** * ',\n ' ** **** ',\n ' ** * * ',\n ' ** **** *** ',\n ' ** * * * ',\n ' ** **** ****** ',\n ' ** * *** * ',\n ' ** **** ** * *** ',\n ' ** * * **** ** * ',\n ' ** **** ** * * **** ',\n ' ** * *** ** ** * * ',\n ' ** **** ** *** *** ** *** ',\n ' ** * * *** * *** * * ',\n ' ** **** ** * * ***** ******* ',\n ' ** * *** **** * *** * ',\n ' ** **** ** *** ** ** * *** ',\n ' ** * * *** * ** *** **** ** * ',\n ' ** **** ** * ****** * * *** ****',\n ' * * *** **** **** *** ** * ',\n ))\n\n print(ans)\n self.assertEqual(ans, expected)\n\n @jtu.skip_on_devices(\"cpu\", \"gpu\")\n def testReduceMax(self):\n f = pmap(lambda x: x - lax.pmax(x, 'i'), axis_name='i')\n\n shape = (xla_bridge.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n expected = x - np.max(x, 0)\n\n ans = f(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @jtu.skip_on_devices(\"cpu\", \"gpu\")\n def testReduceMin(self):\n f = pmap(lambda x: x - lax.pmin(x, 'i'), axis_name='i')\n\n shape = (xla_bridge.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n expected = x - np.min(x, 0)\n\n ans = f(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testDeviceCountError(self):\n device_count = xla_bridge.device_count()\n\n f = pmap(lambda x: x)\n x = jnp.arange(device_count + 1)\n self.assertRaisesRegex(ValueError, \".*requires.*replicas\", lambda: f(x))\n\n f = pmap(lambda x: x)\n x = np.ones((device_count + 1, 10))\n self.assertRaisesRegex(ValueError, \".*requires.*replicas\", lambda: f(x))\n\n f = pmap(lambda x: pmap(lambda x: x)(x))\n x = np.ones((device_count, 2, 10))\n self.assertRaisesRegex(ValueError, \".*requires.*replicas\", lambda: f(x))\n\n def testPmapConstant(self):\n device_count = xla_bridge.device_count()\n f = pmap(lambda x: 3)\n x = jnp.arange(device_count)\n with jtu.count_jit_and_pmap_compiles() as count:\n ans = f(x)\n self.assertEqual(count[0], 0)\n expected = np.repeat(3, device_count)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n f = pmap(lambda x: (x, 3))\n x = np.arange(device_count)\n with jtu.count_jit_and_pmap_compiles() as count:\n _, ans = f(x)\n self.assertEqual(count[0], 1)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testPmapConstantDevices(self):\n if xla_bridge.device_count() == 1:\n raise SkipTest(\"this test requires multiple devices\")\n\n devices = xla_bridge.devices()[:-1]\n shuffle(devices)\n f = pmap(lambda x: 3, devices=devices)\n x = jnp.arange(len(devices))\n with jtu.count_jit_and_pmap_compiles() as count:\n ans = f(x)\n self.assertEqual(count[0], 0)\n expected = np.repeat(3, len(devices))\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n # Test that 'ans' was properly replicated across devices.\n self.assertEqual([b.device() for b in ans.device_buffers], devices)\n\n def testPmapConstantError(self):\n device_count = xla_bridge.device_count()\n f = pmap(lambda x: 3)\n x = jnp.arange(device_count + 1)\n self.assertRaisesRegex(\n ValueError, r\"Cannot replicate across \\d+ replicas because only \\d+ \"\n r\"local devices are available.\", lambda: f(x))\n\n f = pmap(lambda x: 3, devices=[xla_bridge.devices()[0]])\n x = jnp.arange(2)\n self.assertRaisesRegex(\n ValueError, \"Cannot replicate across 2 replicas because only 1 \"\n \"local devices are available.\", lambda: f(x))\n\n def testNestedPmapConstant(self):\n if xla_bridge.device_count() == 1:\n raise SkipTest(\"this test requires multiple devices\")\n\n f = pmap(pmap(lambda x: 3))\n shape = (2, xla_bridge.device_count() // 2, 3)\n x = jnp.arange(prod(shape)).reshape(shape)\n with jtu.count_jit_and_pmap_compiles() as count:\n ans = f(x)\n self.assertEqual(count[0], 0)\n expected = 3 * np.ones(shape[:2])\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n # Test that 'ans' was properly replicated across devices.\n expected_sharded = pmap(pmap(lambda x: x))(expected)\n self.assertEqual([b.device() for b in ans.device_buffers],\n [b.device() for b in expected_sharded.device_buffers])\n\n f = pmap(pmap(lambda x: (x, 3)))\n x_sharded, ans = f(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n self.assertEqual([b.device() for b in ans.device_buffers],\n [b.device() for b in x_sharded.device_buffers])\n\n\n def testNestedPmapConstantDevices(self):\n raise SkipTest(\"Nested pmaps with devices not yet implemented\")\n\n if xla_bridge.device_count() < 6:\n raise SkipTest(\"this test requires >= 6 devices\")\n\n devices = xla_bridge.devices()[:-2]\n shuffle(devices)\n f = pmap(pmap(lambda x: 3), devices=devices)\n shape = (2, len(devices) // 2, 3)\n x = jnp.arange(prod(shape)).reshape(shape)\n with jtu.count_jit_and_pmap_compiles() as count:\n ans = f(x)\n self.assertEqual(count[0], 0)\n expected = 3 * np.ones(shape[:2])\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n # Test that 'ans' was properly replicated across devices.\n expected_sharded = pmap(pmap(lambda x: x), devices=devices)(expected)\n self.assertEqual([b.device() for b in ans.device_buffers],\n [b.device() for b in expected_sharded.device_buffers])\n\n def testNestedPmapConstantError(self):\n f = pmap(pmap(lambda x: 3))\n shape = (2, xla_bridge.device_count() // 2 + 1, 3)\n x = jnp.arange(prod(shape)).reshape(shape)\n self.assertRaisesRegex(\n ValueError, r\"Cannot replicate across \\d+ replicas because only \\d+ \"\n r\"local devices are available.\", lambda: f(x))\n\n if xla_bridge.device_count() > 1:\n f = pmap(pmap(lambda x: 3), devices=xla_bridge.devices()[:-1])\n shape = (2, xla_bridge.device_count() // 2, 3)\n x = jnp.arange(prod(shape)).reshape(shape)\n self.assertRaisesRegex(\n ValueError, r\"Cannot replicate across \\d+ replicas because only \\d+ \"\n r\"local devices are available.\", lambda: f(x))\n\n def testCollectiveConstant(self):\n device_count = xla_bridge.device_count()\n f = pmap(lambda x: lax.psum(1, 'i'), 'i')\n x = jnp.arange(device_count)\n ans = f(x)\n expected = np.repeat(device_count, device_count)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testCollectiveConstantNested(self):\n device_count = xla_bridge.device_count()\n\n @partial(pmap, axis_name='i')\n def f(x):\n @partial(pmap, axis_name='j')\n def g(y):\n a = lax.psum(1, 'i')\n b = lax.psum(1, 'j')\n c = lax.psum(1, ('i', 'j'))\n return a, b, c\n return g(x)\n\n shape = (device_count, 1, 4)\n x = jnp.arange(prod(shape)).reshape(shape)\n a, b, c = f(x)\n\n self.assertEqual(a.shape, shape[:-1])\n self.assertEqual(b.shape, shape[:-1])\n self.assertEqual(c.shape, shape[:-1])\n\n self.assertEqual(a.ravel()[0], device_count)\n self.assertEqual(b.ravel()[0], 1)\n self.assertEqual(c.ravel()[0], device_count * 1)\n\n def testAxisIndex(self):\n device_count = xla_bridge.device_count()\n f = pmap(lambda x: x + pxla.axis_index('i'), 'i')\n x = jnp.ones(device_count)\n ans = f(x)\n expected = 1 + np.arange(device_count)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testVmapOfPmap(self):\n device_count = xla_bridge.device_count()\n f0 = lambda x: x\n f1 = pmap(f0, axis_name='i')\n ax = np.random.randn(2, device_count, 50, 60)\n bx = vmap(f1)(ax)\n self.assertAllClose(ax, bx, check_dtypes=False)\n\n def testVmapOfPmap2(self):\n N_DEVICES = xla_bridge.device_count()\n keys = random.split(random.PRNGKey(1), 13) # [13, 2]\n\n @pmap\n def g(key):\n _ = random.normal(key, ())\n return 0.\n\n @vmap\n def s(keys):\n keys = jnp.broadcast_to(keys, (N_DEVICES,) + keys.shape)\n return g(keys)\n\n ans = s(keys) # doesn't crash\n self.assertEqual(ans.shape, (13, N_DEVICES))\n\n def testVmapOfPmapNonLeadingAxis(self):\n device_count = xla_bridge.device_count()\n f0 = lambda x: x\n f1 = pmap(f0, axis_name='i')\n ax = np.random.randn(device_count, 2, 50, 60)\n bx = vmap(f1, in_axes=2, out_axes=2)(ax)\n self.assertAllClose(ax, bx, check_dtypes=False)\n\n def testVmapOfPmapTuple(self):\n device_count = xla_bridge.device_count()\n f0 = lambda *x: x\n f1 = pmap(f0, axis_name='i')\n\n ax = np.random.randn(device_count, 2, 50, 60)\n ay = np.random.randn(device_count, 30, 2)\n az1 = np.random.randn(device_count, 20)\n az2 = np.random.randn(2, device_count, 20)\n\n bx, by, bz = vmap(f1, in_axes=(1, 2, (None, 0)), out_axes=(1, 2, 0))(ax, ay, (az1, az2))\n\n self.assertAllClose(ax, bx, check_dtypes=False)\n self.assertAllClose(ay, by, check_dtypes=False)\n\n bz1, bz2 = bz\n expected_bz1 = np.broadcast_to(az1, (2,) + az1.shape)\n self.assertAllClose(expected_bz1, bz1, check_dtypes=False)\n self.assertAllClose(bz2, bz2, check_dtypes=False)\n\n @jtu.skip_on_devices(\"gpu\")\n def testPswapaxes(self):\n device_count = xla_bridge.device_count()\n # TODO: AllToAll not yet implemented on XLA:CPU\n if jtu.device_under_test() == \"cpu\":\n device_count = 1\n shape = (device_count, 3, device_count, 5)\n x = np.arange(prod(shape)).reshape(shape)\n\n ans = pmap(lambda x: lax.pswapaxes(x, 'i', 1), axis_name='i')(x)\n expected = np.swapaxes(x, 0, 2)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testReshardInput(self):\n if xla_bridge.device_count() < 6:\n raise SkipTest(\"testReshardInput requires 6 devices\")\n # Manually construct a ShardedDeviceArray with the wrong sharding for the\n # subsequent pmap\n shard_shape = (3,2)\n shard = jnp.arange(jnp.prod(shard_shape)).reshape(shard_shape)\n bufs = [xla.device_put(shard, d) for d in xla_bridge.devices()[:4]]\n aval = ShapedArray((6,4), shard.dtype)\n sharding_spec = pxla.ShardingSpec(\n shards_per_axis=(2, 2),\n is_axis_materialized=(True, True),\n replication_factors=[])\n arr = pxla.ShardedDeviceArray(aval, sharding_spec, bufs)\n\n r = pmap(lambda x: x + 1)(arr)\n self.assertAllClose(r, arr + 1)\n self.assertEqual(len(r.device_buffers), 6)\n\n @ignore_soft_pmap_warning()\n def testSoftPmapPsum(self):\n n = 4 * xla_bridge.device_count()\n def f(x):\n return x / lax.psum(x, 'i')\n ans = soft_pmap(f, 'i')(jnp.ones(n))\n expected = np.ones(n) / n\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @ignore_soft_pmap_warning()\n def testSoftPmapAxisIndex(self):\n n = 4 * xla_bridge.device_count()\n def f(x):\n return x * lax.axis_index('i')\n ans = soft_pmap(f, 'i')(2 * jnp.ones(n))\n expected = 2 * np.arange(n)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @ignore_soft_pmap_warning()\n def testSoftPmapOfJit(self):\n n = 4 * xla_bridge.device_count()\n def f(x):\n return 3 * x\n ans = soft_pmap(jit(f), 'i')(np.arange(n))\n expected = 3 * np.arange(n)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @ignore_soft_pmap_warning()\n def testSoftPmapNested(self):\n n = 4 * xla_bridge.device_count()\n\n @partial(soft_pmap, axis_name='i')\n @partial(soft_pmap, axis_name='j')\n def f(x):\n i_size = lax.psum(1, 'i')\n return x + lax.axis_index('i') + i_size * lax.axis_index('j')\n\n ans = f(jnp.zeros((n, n)))\n expected = np.arange(n ** 2).reshape(n, n).T\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @ignore_soft_pmap_warning()\n def testGradOfSoftPmap(self):\n n = 4 * xla_bridge.device_count()\n\n @partial(soft_pmap, axis_name='i')\n def f(x):\n return x * lax.axis_index('i')\n\n ans = grad(lambda x: jnp.sum(f(x)))(jnp.zeros((n, n)))\n expected = np.repeat(np.arange(n)[:, None], n, axis=1)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n @ignore_soft_pmap_warning()\n def testSoftPmapDevicePersistence(self):\n device_count = xla_bridge.device_count()\n shape = (2 * 2 * device_count, 2, 3)\n\n # check that we can maintain device persistence across calls\n x = np.arange(prod(shape)).reshape(shape)\n x = soft_pmap(lambda x: x)(x)\n self.assertIsInstance(x, pxla.ShardedDeviceArray)\n x._npy_value = np.float32(np.nan) # can't be coerced to ndarray for xfer\n x = soft_pmap(lambda x: x)(x) # doesn't crash\n self.assertIsInstance(x, pxla.ShardedDeviceArray)\n\n # check that we don't crash when we can't maintain device persistence\n x = np.arange(prod(shape)).reshape(shape)\n x = soft_pmap(lambda x: x)(x)\n self.assertIsInstance(x, pxla.ShardedDeviceArray)\n y = x.reshape(device_count, -1)\n self.assertIsInstance(y, xla.DeviceArray) # should have forced collection\n soft_pmap(lambda x: x)(y) # doesn't crash\n z = x + 2\n self.assertIsInstance(z, xla.DeviceArray) # should have forced collection\n x._npy_value = np.float32(np.nan) # can't be coerced to ndarray for xfer\n self.assertRaisesRegex(\n RuntimeError,\n '.*does not match host shape or layout of computation parameter 0.*',\n lambda: x + 2)\n\n # check that different axis merges aren't a problem\n x = np.arange(prod(shape)).reshape(shape)\n x = soft_pmap(lambda x: x)(x)\n self.assertIsInstance(x, pxla.ShardedDeviceArray)\n x = x.reshape(2 * device_count, 2, 2, 3) # axis merge of the wrong size\n self.assertIsInstance(x, xla.DeviceArray) # should have forced collection\n\n def testSoftPmapAllToAll(self):\n raise SkipTest(\"the underlying code here is broken\") # TODO(mattjj)\n n = 4 * xla_bridge.device_count()\n def f(x):\n return lax.all_to_all(x, 'i', 0, 0)\n ans = soft_pmap(f, 'i')(jnp.arange(n ** 2).reshape(n, n))\n expected = np.arange(n ** 2).reshape(n, n).T\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testShardedDeviceArrayBlockUntilReady(self):\n x = np.arange(xla_bridge.device_count())\n x = pmap(lambda x: x)(x)\n x.block_until_ready() # doesn't crash\n\n def testJitPmapComposition(self):\n f = lambda x: x - lax.psum(x, 'i')\n\n shape = (xla_bridge.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n expected = x - np.sum(x, 0)\n\n ans = jit(pmap(f, 'i'))(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n ans = pmap(jit(f), 'i')(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testMakeJaxprOfOpenSpmd(self):\n f = lambda x: x - lax.psum(x, 'i')\n shape = (xla_bridge.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n make_jaxpr(f)(x) # doesn't crash\n\n def testCompositionWithJitTwice(self):\n @jit\n def f(x):\n y = 2 * x\n\n @jit\n def g(z):\n return pmap(lambda x: x * y)(z)\n\n return g(x)\n\n f(np.arange(1.).reshape((1, 1))) # doesn't crash\n\n def testIssue1065(self):\n # from https://github.com/google/jax/issues/1065\n device_count = xla_bridge.device_count()\n\n def multi_step_pmap(state, count):\n @partial(pmap, axis_name='x')\n @jit\n def exchange_and_multi_step(state):\n return state\n\n @jit\n def time_evolution(state):\n return lax.fori_loop(0, count, lambda i, s: exchange_and_multi_step(s), state)\n\n return time_evolution(state)\n\n multi_step_pmap(jnp.zeros((device_count,)), count=1)\n\n def testShardedDeviceArrayGetItem(self):\n f = lambda x: 2 * x\n f = pmap(f, axis_name='i')\n\n shape = (xla_bridge.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n\n y = f(x)\n self.assertIsInstance(y, jnp.ndarray)\n self.assertIsInstance(y, pxla.ShardedDeviceArray)\n\n z = y[0] # doesn't crash\n self.assertAllClose(z, 2 * x[0], check_dtypes=False)\n\n def testPostProcessMap(self):\n # TODO(mattjj): this fails with multiple devices (unless we add a jit)\n # because we assume eager ops (like scan here) can't require more than 1\n # replica.\n raise SkipTest(\"need eager multi-replica support\")\n # test came from https://github.com/google/jax/issues/1369\n nrep = xla_bridge.device_count()\n\n def pmvm(a, b):\n a = a.reshape((nrep, -1, a.shape[1]))\n func = pmap(lambda z: jnp.dot(z, b))\n return func(a).reshape(b.shape)\n\n n = nrep * 2\n rng = np.random.RandomState(0)\n a = rng.randn(n, n)\n b = rng.randn(n)\n\n iters = jnp.arange(5)\n def body(carry, i):\n return pmvm(a, carry), i\n ans, _ = lax.scan(body, b, iters)\n\n expected = np.linalg.matrix_power(a, 5).dot(b)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testManyArgs(self):\n @pmap\n def f(args_list):\n return sum(args_list)\n\n vals = list(range(500))\n ndevices = xla_bridge.device_count()\n self.assertAllClose(f(jnp.array([vals] * ndevices)),\n jnp.array([sum(vals)] * ndevices))\n\n def testPostProcessMap2(self):\n # code from https://github.com/google/jax/issues/2787\n def vv(x, y):\n \"\"\"Vector-vector multiply\"\"\"\n return jnp.dot(x, y)\n\n def distributed_matrix_vector(x, y):\n \"\"\"Matrix vector multiply. First batch it and then row by row\"\"\"\n fv = lambda z: lax.map(lambda j: vv(j, y), z)\n res = pmap(fv)(x.reshape((jax.device_count(), -1) + tuple(x.shape[1:])))\n res = res.reshape(res.shape[0] * res.shape[1], *res.shape[2:])\n return res\n\n key = random.PRNGKey(1)\n x = random.normal(key, (80, 50))\n batched_mvm = vmap(lambda b: distributed_matrix_vector(x, b), in_axes=0)\n y = random.normal(key, (10, 50, 1))\n result = batched_mvm(y)\n expected = jnp.einsum('ij,njk->nik', x, y)\n tol = 1e-1 if jtu.device_under_test() == \"tpu\" else 1e-3\n self.assertAllClose(result, expected, check_dtypes=False, atol=tol, rtol=tol)\n\n def testAxisIndexRemat(self):\n # https://github.com/google/jax/issues/2716\n n = len(jax.devices())\n\n def f(key):\n key = random.fold_in(key, jax.lax.axis_index('i'))\n return random.bernoulli(key, p=0.5)\n\n keys = random.split(random.PRNGKey(0), n)\n jax.pmap(jax.remat(f), axis_name='i')(keys)\n\n def testPmapMapVmapCombinations(self):\n # https://github.com/google/jax/issues/2822\n def vv(x, y):\n \"\"\"Vector-vector multiply\"\"\"\n return jnp.dot(x, y)\n\n def matrix_vector(x, y, parallel=True):\n \"\"\"Matrix vector multiply. First batch it and then row by row\"\"\"\n fv = lambda z: lax.map(lambda j: vv(j, y), z)\n if parallel:\n # split leading axis in two\n new_x = x.reshape((jax.device_count(), -1, *x.shape[1:]))\n # apply map\n new_res = pmap(fv)(new_x)\n # reshape back out\n res = new_res.reshape(x.shape[0], *new_res.shape[2:])\n else:\n res = fv(x)\n return res\n\n x = random.normal(random.PRNGKey(1), (80, 5))\n y = random.normal(random.PRNGKey(1), (10, 5))\n\n result1 = vmap(lambda b: matrix_vector(x, b, True))(y) # vmap + pmap\n result2 = lax.map(lambda b: matrix_vector(x, b, False), y) # map + map\n result3 = lax.map(lambda b: matrix_vector(x, b, True), y) # map + pmap\n result4 = jnp.stack([matrix_vector(x, b, False) for b in y]) # none + map\n\n self.assertAllClose(result1, result2, check_dtypes=False, atol=1e-3, rtol=1e-3)\n self.assertAllClose(result1, result3, check_dtypes=False, atol=1e-3, rtol=1e-3)\n self.assertAllClose(result1, result4, check_dtypes=False, atol=1e-3, rtol=1e-3)\n\n def testPmapAxisNameError(self):\n # https://github.com/google/jax/issues/3120\n a = np.arange(4)[np.newaxis,:]\n def test(x):\n return jax.lax.psum(x, axis_name='batch')\n\n with self.assertRaisesRegex(NameError, \"unbound axis name: batch\"):\n jax.pmap(test)(a)\n\n def testPsumOnBooleanDtype(self):\n # https://github.com/google/jax/issues/3123\n n = xla_bridge.device_count()\n if n > 1:\n x = jnp.array([True, False])\n\n out = pmap(lambda x: jax.lax.psum(x, 'i'), 'i')(x)\n self.assertEqual(list(out), [1, 1])\n\n out = pmap(lambda x: jax.lax.pmean(x, 'i'), 'i')(x)\n self.assertEqual(list(out), [1/2, 1/2])\n else:\n x = jnp.array([True])\n\n out = pmap(lambda x: jax.lax.psum(x, 'i'), 'i')(x)\n self.assertEqual(list(out), [1])\n\n out = pmap(lambda x: jax.lax.pmean(x, 'i'), 'i')(x)\n self.assertEqual(list(out), [1])\n\n\nclass PmapWithDevicesTest(jtu.JaxTestCase):\n\n def testAllDevices(self):\n f = pmap(lambda x: x - lax.psum(x, 'i'), axis_name='i',\n devices=xla_bridge.devices())\n shape = (xla_bridge.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n expected = x - np.sum(x, 0)\n ans = f(x)\n self.assertAllClose(ans, expected)\n\n def testOneDevice(self):\n if xla_bridge.device_count() == 1:\n raise SkipTest(\"this test requires multiple devices\")\n\n d0 = xla_bridge.devices()[0]\n d1 = xla_bridge.devices()[1]\n f = lambda x: jnp.dot(x, x.T)\n f0 = pmap(f, devices=[d0])\n f1 = pmap(f, devices=[d1])\n x = np.random.rand(1, 1000, 1000)\n r0 = f0(x)\n r1 = f1(x)\n expected = np.expand_dims(np.dot(x.squeeze(), x.squeeze().T), 0)\n self.assertAllClose(r0, expected, atol=1e-6, rtol=1e-3)\n self.assertAllClose(r1, expected, atol=1e-6, rtol=1e-3)\n\n def testNoDevicesError(self):\n f = pmap(lambda x: x - lax.psum(x, 'i'), axis_name='i', devices=[])\n shape = (xla_bridge.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n with self.assertRaisesRegex(\n ValueError, \"'devices' argument to pmap must be non-empty, or None.\"):\n f(x)\n\n def testBadAxisSizeError(self):\n if xla_bridge.device_count() == 1:\n raise SkipTest(\"this test requires multiple devices\")\n\n f = pmap(lambda x: lax.psum(x, 'i'), axis_name='i',\n devices=xla_bridge.devices())\n with self.assertRaisesRegex(\n ValueError, r\"Leading axis size of input to pmapped function must \"\n r\"equal the number of local devices passed to pmap. Got axis_size=1, \"\n r\"num_local_devices=\\d.\"):\n f(jnp.ones(1))\n\n with self.assertRaisesRegex(\n ValueError, r\"Leading axis size of input to pmapped function must \"\n r\"equal the number of local devices passed to pmap. Got axis_size=\\d, \"\n r\"num_local_devices=\\d.\"):\n f(jnp.ones(xla_bridge.device_count() + 1))\n\n def testNestedPmapsError(self):\n # Devices specified in outer pmap\n @partial(pmap, axis_name='i', devices=xla_bridge.devices())\n def foo(x):\n @partial(pmap, axis_name='j')\n def bar(y):\n return lax.psum(y, 'j')\n return bar(x)\n\n with self.assertRaisesRegex(\n ValueError,\n \"Nested pmaps with explicit devices argument.\"):\n foo(jnp.ones((xla_bridge.device_count(), 1)))\n\n # Devices specified in inner pmap\n @partial(pmap, axis_name='i')\n def foo(x):\n @partial(pmap, axis_name='j', devices=xla_bridge.devices())\n def bar(y):\n return lax.psum(y, 'j')\n return bar(x)\n\n with self.assertRaisesRegex(\n ValueError,\n \"Nested pmaps with explicit devices argument.\"):\n foo(jnp.ones((xla_bridge.device_count(), 1)))\n\n def testJitInPmap(self):\n @partial(pmap, axis_name='i', devices=xla_bridge.devices())\n def foo(x):\n @jit\n def bar(y):\n return y + 1\n return lax.psum(bar(x), 'i')\n\n ndevices = xla_bridge.device_count()\n ans = foo(jnp.ones((ndevices, 1)))\n expected = np.ones((ndevices, 1), dtype=jnp.float_) * ndevices * 2\n self.assertAllClose(ans, expected)\n\n def testPmapInJit(self):\n @jit\n def foo(x):\n @partial(pmap, axis_name='i', devices=xla_bridge.devices())\n def bar(y):\n return lax.psum(y, 'i')\n return bar(x)\n\n ndevices = xla_bridge.device_count()\n ans = foo(jnp.ones((ndevices, 1)))\n expected = np.ones((ndevices, 1), dtype=jnp.float_) * ndevices\n self.assertAllClose(ans, expected)\n\n def testGradBasic(self):\n @partial(pmap, axis_name='i', devices=xla_bridge.devices())\n def f(x):\n return jnp.sin(x)\n\n shape = (xla_bridge.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n\n ans = grad(lambda x: jnp.sum(jnp.sin(x)))(x)\n expected = grad(lambda x: jnp.sum(f(x)))(x)\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n def testPmapStaticArgnums(self):\n @partial(pmap, axis_name='i', static_broadcasted_argnums=1)\n def f(x, y):\n return jnp.sin(x + y)\n shape = (xla_bridge.device_count(), 4)\n x = np.arange(prod(shape), dtype=np.float32).reshape(shape)\n y = np.arange(4, dtype=np.float32)\n\n ans = f(x, y)\n expected = np.sin(x + y[None])\n self.assertAllClose(ans, expected, check_dtypes=False)\n\n\nclass ShardedDeviceArrayTest(jtu.JaxTestCase):\n\n def testThreadsafeIndexing(self):\n # NOTE(skye): I picked these values to be big enough to cause interesting\n # execution overlap, but small enough to not use too much memory. YMMV.\n shape = (8, 8000, 1000)\n\n if jax.device_count() < shape[0]:\n raise SkipTest(f\"requires {shape[0]} devices\")\n\n x = jnp.arange(jnp.prod(shape)).reshape(shape)\n sharded_x = pmap(lambda x: x)(x)\n\n num_threads = 10\n futures = []\n expected = []\n with ThreadPoolExecutor(max_workers=num_threads) as executor:\n for i in range(num_threads):\n idx = i % shape[0]\n # Mix together different kinds of indices\n if i % 2 == 0:\n idx = slice(idx, idx + 1)\n # Use the \"kwarg trick\" to work around late-binding closures. See\n # https://docs.python-guide.org/writing/gotchas/#late-binding-closures.\n futures.append(executor.submit(\n lambda idx=idx: [sharded_x[idx] for _ in range(10)][0]))\n expected.append(x[idx])\n actual = [f.result() for f in futures]\n self.assertAllClose(actual, expected, check_dtypes=False)\n\n\nclass SpecToIndicesTest(jtu.JaxTestCase):\n\n def testShardsPerAxis(self):\n shape = (4, 8)\n spec = pxla.ShardingSpec(shards_per_axis=(2, 2),\n is_axis_materialized=(True, True),\n replication_factors=[])\n self.assertEqual(pxla.spec_to_indices(shape, spec),\n ((slice(0,2), slice(0,4)),\n (slice(0,2), slice(4,8)),\n (slice(2,4), slice(0,4)),\n (slice(2,4), slice(4,8))))\n\n def testUnshardedAxis(self):\n shape = (4, 8)\n spec = pxla.ShardingSpec(shards_per_axis=(2, 1),\n is_axis_materialized=(True, True),\n replication_factors=[])\n self.assertEqual(pxla.spec_to_indices(shape, spec),\n (slice(0,2), (slice(2,4))))\n\n def testNoSharding(self):\n shape = (4, 8)\n spec = pxla.ShardingSpec(shards_per_axis=(1, 1),\n is_axis_materialized=(True, True),\n replication_factors=[])\n self.assertEqual(pxla.spec_to_indices(shape, spec),\n (slice(None),))\n\n def testUnmaterializedAxis(self):\n shape = (4, 8)\n spec = pxla.ShardingSpec(shards_per_axis=(4, 1),\n is_axis_materialized=(False, True),\n replication_factors=[])\n self.assertEqual(pxla.spec_to_indices(shape, spec),\n (0, 1, 2, 3))\n\n shape = (2, 2)\n spec = pxla.ShardingSpec(shards_per_axis=(1, 2),\n is_axis_materialized=(True, False),\n replication_factors=[])\n self.assertEqual(pxla.spec_to_indices(shape, spec),\n ((slice(None), 0),\n (slice(None), 1)))\n\n def testReplicationAfterUnsharded(self):\n shape = (2, 8)\n spec = pxla.ShardingSpec(shards_per_axis=(2, 1),\n is_axis_materialized=(False, True),\n replication_factors=[(3, 2)])\n self.assertEqual(pxla.spec_to_indices(shape, spec),\n (0, 0, 0, 1, 1, 1))\n\n def testReplicationPosition2(self):\n shape = (2, 8)\n spec = pxla.ShardingSpec(shards_per_axis=(2, 2),\n is_axis_materialized=(False, True),\n replication_factors=[(3, 2)])\n self.assertEqual(pxla.spec_to_indices(shape, spec),\n ((0, slice(0, 4)), (0, slice(0, 4)), (0, slice(0, 4)),\n (0, slice(4, 8)), (0, slice(4, 8)), (0, slice(4, 8)),\n (1, slice(0, 4)), (1, slice(0, 4)), (1, slice(0, 4)),\n (1, slice(4, 8)), (1, slice(4, 8)), (1, slice(4, 8))))\n\n def testReplicationPosition1(self):\n shape = (2, 8)\n spec = pxla.ShardingSpec(shards_per_axis=(2, 2),\n is_axis_materialized=(False, True),\n replication_factors=[(3, 1)])\n self.assertEqual(pxla.spec_to_indices(shape, spec),\n ((0, slice(0, 4)), (0, slice(4, 8)),\n (0, slice(0, 4)), (0, slice(4, 8)),\n (0, slice(0, 4)), (0, slice(4, 8)),\n (1, slice(0, 4)), (1, slice(4, 8)),\n (1, slice(0, 4)), (1, slice(4, 8)),\n (1, slice(0, 4)), (1, slice(4, 8))))\n\n def testReplicationPosition0(self):\n shape = (2, 8)\n spec = pxla.ShardingSpec(shards_per_axis=(2, 1),\n is_axis_materialized=(False, True),\n replication_factors=[(3, 0)])\n self.assertEqual(pxla.spec_to_indices(shape, spec),\n (0, 1, 0, 1, 0, 1))\n\n def testMultipleReplications(self):\n shape = (2, 7, 4)\n spec = pxla.ShardingSpec(shards_per_axis=(2, 1, 2),\n is_axis_materialized=(False, True, True),\n replication_factors=[(3, 0), (2, 0), (2, 2)])\n self.assertEqual(\n pxla.spec_to_indices(shape, spec),\n ((0, slice(None), slice(0, 2)), (0, slice(None), slice(2, 4)),\n (0, slice(None), slice(0, 2)), (0, slice(None), slice(2, 4)),\n (1, slice(None), slice(0, 2)), (1, slice(None), slice(2, 4)),\n (1, slice(None), slice(0, 2)), (1, slice(None), slice(2, 4))) * 3 * 2)\n\n def testReplicatedScalar(self):\n shape = ()\n spec = pxla.ShardingSpec(shards_per_axis=(),\n is_axis_materialized=(),\n replication_factors=[(3, 0)])\n self.assertEqual(pxla.spec_to_indices(shape, spec),\n ((), (), ()))\n\n\ndef _spec_str(spec):\n return (f\"({spec.shards_per_axis},\"\n f\"{spec.is_axis_materialized},\"\n f\"{spec.replication_factors})\")\n\n\nclass ShardArgsTest(jtu.JaxTestCase):\n\n def numpy_array(x):\n return x\n\n def device_array(x):\n return jax.device_put(x)\n\n # TODO(skye): add coverage for ShardedDeviceArrays\n\n @parameterized.named_parameters(\n {\"testcase_name\":\n f\"_shape={shape}_spec={_spec_str(spec)}_arg={make_arg.__name__}\"\n .replace(\" \", \"\"),\n \"shape\": shape, \"spec\": spec, \"make_arg\": make_arg}\n for make_arg in [numpy_array, device_array]\n for shape, spec in [\n # pmap(in_axes=0)\n [(4, 8), pxla.ShardingSpec(shards_per_axis=(4, 1),\n is_axis_materialized=(False, True),\n replication_factors=[])],\n # pmap(in_axes=1)\n [(2, 2), pxla.ShardingSpec(shards_per_axis=(1, 2),\n is_axis_materialized=(True, False),\n replication_factors=[])],\n # unsharded\n [(4, 8), pxla.ShardingSpec(shards_per_axis=(1, 1),\n is_axis_materialized=(True, True),\n replication_factors=[])],\n # partitioned, 1 axis\n [(4, 8), pxla.ShardingSpec(shards_per_axis=(2, 1),\n is_axis_materialized=(True, True),\n replication_factors=[])],\n # partitioned, 2 axes\n [(4, 8), pxla.ShardingSpec(shards_per_axis=(2, 2),\n is_axis_materialized=(True, True),\n replication_factors=[])],\n # partitioned + sharding\n [(2, 8), pxla.ShardingSpec(shards_per_axis=(2, 2),\n is_axis_materialized=(False, True),\n replication_factors=[])],\n # replication + sharding\n [(2, 8), pxla.ShardingSpec(shards_per_axis=(2, 1),\n is_axis_materialized=(False, True),\n replication_factors=[(3, 2)])],\n # replication, no sharding\n [(2, 8), pxla.ShardingSpec(shards_per_axis=(1, 1),\n is_axis_materialized=(True, True),\n replication_factors=[(3, 2)])],\n # multiple replicated axes\n [(1, 8), pxla.ShardingSpec(shards_per_axis=(1, 2),\n is_axis_materialized=(False, True),\n replication_factors=[(2, 0), (2, 1)])],\n # replicated scalar\n [(), pxla.ShardingSpec(shards_per_axis=(),\n is_axis_materialized=(),\n replication_factors=[(2, 0), (3, 0)])]\n ])\n def testShardArgs(self, shape, spec, make_arg):\n indices = pxla.spec_to_indices(shape, spec)\n nshards = len(indices)\n if jax.device_count() < nshards:\n raise SkipTest\n x = np.arange(np.prod(shape)).reshape(shape)\n arg = make_arg(x)\n bufs = pxla.shard_args(jax.devices()[:nshards],\n [indices], [arg])\n self.assertEqual(len(bufs), nshards)\n for buf, idx in zip(bufs, indices):\n self.assertEqual(len(buf), 1)\n self.assertAllClose(buf[0].to_py(), x[idx], check_dtypes=False)\n\nif __name__ == '__main__':\n absltest.main()\n",
"# Copyright 2020 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\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom functools import partial\nfrom unittest import SkipTest\n\nimport numpy as np\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n\nimport jax\nfrom jax import jit, pmap, vjp\nfrom jax import lax\nfrom jax import test_util as jtu\nfrom jax import tree_util\nfrom jax.interpreters import pxla\nfrom jax.interpreters.sharded_jit import sharded_jit, with_sharding_constraint\nfrom jax.interpreters.sharded_jit import PartitionSpec as P\nimport jax.numpy as jnp\n\nfrom jax.config import config\nconfig.parse_flags_with_absl()\n\n\nclass ShardedJitTest(jtu.JaxTestCase):\n\n def setUp(self):\n super(ShardedJitTest, self).setUp()\n if jtu.device_under_test() != \"tpu\":\n raise SkipTest\n\n def testBasic(self):\n if jax.device_count() < 2:\n raise SkipTest\n\n @partial(sharded_jit, in_parts=(P(2, 1), P(2, 1)), out_parts=None)\n def f(x, y):\n return x + y\n\n shape = (8, 8)\n x = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)\n actual = f(x, x + 1)\n expected = x + (x + 1)\n self.assertAllClose(actual, expected, check_dtypes=False)\n self.assertIsInstance(actual, pxla.ShardedDeviceArray)\n self.assertLen(actual.device_buffers, 2)\n self.assertAllClose(actual.device_buffers[0].to_py(), expected,\n check_dtypes=False)\n\n def testPyTreeArgs(self):\n if jax.device_count() < 2:\n raise SkipTest\n\n def f(a, b, c):\n a1, a2 = a\n c1, (c2, c3) = c\n return a1 + a2 + b + c1 + c2 + c3\n\n def _make_arg(*shape):\n return np.arange(np.prod(shape)).reshape(shape)\n\n a = (_make_arg(4, 4), 1)\n b = _make_arg(4, 4)\n c = [2, (_make_arg(4, 4), _make_arg(4, 4))]\n\n in_parts = (None, P(2, 1), [None, P(2, 1)])\n out_parts = P(2, 1)\n\n result = sharded_jit(f, in_parts, out_parts)(a, b, c)\n expected = f(a, b, c)\n\n self.assertAllClose(result, expected, check_dtypes=False)\n self.assertIsInstance(result, pxla.ShardedDeviceArray)\n self.assertLen(result.device_buffers, 2)\n\n in_parts = None\n result = sharded_jit(f, in_parts, out_parts)(a, b, c)\n self.assertAllClose(result, expected, check_dtypes=False)\n self.assertIsInstance(result, pxla.ShardedDeviceArray)\n self.assertLen(result.device_buffers, 2)\n\n def testPyTreeOutputs(self):\n if jax.device_count() < 2:\n raise SkipTest\n\n def f(x):\n return x + 1, ((x + 2, x + 3), x + 4)\n\n shape = (4, 4)\n x = np.arange(np.prod(shape)).reshape(shape)\n in_parts = (P(2, 1),)\n out_parts = (P(2, 1), ((P(1, 2), None), P(2, 1)))\n\n result = sharded_jit(f, in_parts, out_parts)(x)\n expected = f(x)\n self.assertAllClose(result, expected, check_dtypes=False)\n\n out_parts = None\n result = sharded_jit(f, in_parts, out_parts)(x)\n self.assertAllClose(result, expected, check_dtypes=False)\n\n def testAllArgsOutputsReplicated(self):\n @partial(sharded_jit, in_parts=None, out_parts=None)\n def f(x):\n return x + 1\n\n result = f(1.)\n self.assertEqual(result, 2.)\n self.assertIsInstance(result, pxla.ShardedDeviceArray)\n self.assertLen(result.device_buffers, 1)\n\n def testShardingConstraint(self):\n if jax.local_device_count() < 2:\n raise SkipTest(\"requires 2 devices\")\n\n def f(x):\n y = x + 1\n y = with_sharding_constraint(y, P(1,2))\n return y * 2\n\n shape = (8, 8)\n x = np.arange(np.prod(shape)).reshape(shape)\n expected = (x + 1) * 2\n\n # Matching sharded_jit partitions\n actual = sharded_jit(f, in_parts=P(2,1), out_parts=P(2,1))(x)\n self.assertAllClose(actual, expected, check_dtypes=False)\n self.assertLen(actual.device_buffers, 2)\n self.assertEqual(actual.device_buffers[0].shape().dimensions(), (4,8))\n self.assertEqual(actual.device_buffers[1].shape().dimensions(), (4,8))\n\n # Mismatched sharded_jit partitions\n with self.assertRaisesRegex(\n ValueError,\n r\"with_sharding_constraint with partitions=PartitionSpec\\(1, 2\\) \"\n r\"\\(total partitions: 2\\) doesn't match expected number of partitions: \"\n r\"4. If these partitions look right, check outer sharded_jit and/or \"\n r\"other with_sharding_constraint calls.\"):\n sharded_jit(f, in_parts=P(2,2), out_parts=P(2,2))(x)\n\n # Replicated sharded_jit\n actual = sharded_jit(f, in_parts=None, out_parts=None)(x)\n self.assertAllClose(actual, expected, check_dtypes=False)\n self.assertLen(actual.device_buffers, 2)\n self.assertAllClose(actual.device_buffers[0].to_py(),\n actual.device_buffers[1].to_py(),\n check_dtypes=False)\n\n def testNestedShardingConstraint(self):\n if jax.local_device_count() < 2:\n raise SkipTest(\"requires 2 devices\")\n\n shape = (8, 8)\n\n @jit\n def f(x):\n return lax.while_loop(lambda i: i[0,0] < 10.,\n lambda i: with_sharding_constraint(i + 1., P(2, 1)),\n x)\n\n x = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)\n expected = x + 10.\n actual = sharded_jit(f, in_parts=None, out_parts=None)(x)\n self.assertAllClose(actual, expected, check_dtypes=False)\n self.assertLen(actual.device_buffers, 2)\n\n def testGradOfShardingConstraint(self):\n if jax.local_device_count() < 4:\n raise SkipTest(\"requires 4 devices\")\n\n @partial(sharded_jit, in_parts=P(4,1), out_parts=None)\n def f(x):\n y = x + 1\n p, vjp_f = vjp(lambda z: jnp.sin(with_sharding_constraint(z, P(2,2))), y)\n return vjp_f(p)\n\n def expected_f(x):\n y = x + 1\n p, vjp_f = vjp(lambda z: jnp.sin(z), y)\n return vjp_f(p)\n\n shape = (4, 4)\n x = jnp.arange(jnp.prod(shape), dtype=jnp.float32).reshape(shape)\n actual = f(x)\n expected = expected_f(x)\n self.assertAllClose(actual, expected, check_dtypes=False)\n\n @parameterized.named_parameters({\n \"testcase_name\": f\"_partition_input={partition_input}\",\n \"partition_input\": partition_input\n } for partition_input in [True, False])\n def testInfeed(self, partition_input):\n if jax.local_device_count() % 2 != 0:\n raise SkipTest\n\n shape = (jax.local_device_count() * 2, 4)\n # Run computation across all devices so we know which devices to feed.\n parts = P(jax.local_device_count(), 1)\n in_parts = parts if partition_input else None\n infeed_shapes = (jax.ShapedArray(shape, np.float32),\n jax.ShapedArray((1,), np.float32))\n infeed_parts = (parts, None)\n\n @partial(sharded_jit, in_parts=in_parts, out_parts=None)\n def f(x):\n token = lax.create_token(x)\n (y, z), token = lax.infeed(token, infeed_shapes, partitions=infeed_parts)\n return x @ y.T + z\n\n x = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)\n y = x + 1\n shard_size = shape[0] // jax.local_device_count()\n y_shards = [y[i:i+shard_size] for i in range(0, shape[0], shard_size)]\n z = jnp.array([3.], dtype=np.float32)\n\n result = f(x)\n assert len(jax.local_devices()) == len(y_shards)\n for device, y_shard in zip(jax.local_devices(), y_shards):\n device.transfer_to_infeed((y_shard, z))\n\n expected = x @ y.T + z\n self.assertAllClose(result, expected, check_dtypes=False)\n\n\n# TODO(skye): add more error tests\nclass ShardedJitErrorsTest(jtu.JaxTestCase):\n\n def setUp(self):\n super(ShardedJitErrorsTest, self).setUp()\n if jtu.device_under_test() != \"tpu\":\n raise SkipTest\n\n def testNotEnoughDevices(self):\n ndevices = jax.local_device_count()\n\n @partial(sharded_jit, in_parts=P(ndevices + 1), out_parts=None)\n def f(x):\n return x + x\n\n with self.assertRaisesRegex(\n ValueError,\n f\"sharded_jit computation requires {ndevices + 1} devices, \"\n f\"but only {ndevices} devices are available.\"):\n f(np.ones(ndevices + 1))\n\n\n# Tests that don't need a TPU to run.\nclass ShardedJitTestNoTpu(jtu.JaxTestCase):\n\n def testTranslationRule(self):\n @partial(sharded_jit, in_parts=(P(2, 1), P(2, 1)), out_parts=None)\n def f(x, y):\n return x + y\n\n # Test that the translation rule runs without error and produces the\n # OpShardings we expect somewhere.\n shape = (8, 8)\n hlo = jax.xla_computation(f)(np.ones(shape), np.ones(shape))\n self.assertIn(\"sharding={devices=[2,1]0,1}\", hlo.as_hlo_text())\n self.assertIn(\"sharding={replicated}\", hlo.as_hlo_text())\n\n def testShardingConstraintAnnotation(self):\n @partial(sharded_jit, in_parts=None, out_parts=None)\n def f(x):\n y = x + 1\n y = with_sharding_constraint(y, P(2,1))\n return y * 2\n\n shape = (8, 8)\n hlo = jax.xla_computation(f)(np.ones(shape))\n # Annotation from with_sharding_constraint\n self.assertIn(\"sharding={devices=[2,1]0,1}\", hlo.as_hlo_text())\n # Annotation from sharded_jit\n self.assertIn(\"sharding={replicated}\", hlo.as_hlo_text())\n\nclass PmapOfShardedJitTest(jtu.JaxTestCase):\n\n def setUp(self):\n super(PmapOfShardedJitTest, self).setUp()\n if jtu.device_under_test() != \"tpu\":\n raise SkipTest\n\n # TODO(skye): make a similar version for ShardedJitTest and run the same tests\n def _runTest(self, f, in_partitions, out_partitions, dtype=np.float32):\n \"\"\"Compares pmap(sharded_jit(f, ...)) to pmap(f)\"\"\"\n shape = (2, 4, 4)\n num_shards = shape[0] * np.prod(in_partitions[0])\n if num_shards > jax.local_device_count():\n raise SkipTest(\"requires %d devices\" % num_shards)\n\n x = np.arange(np.prod(shape, dtype=dtype)).reshape(shape)\n y = x + 1\n result = pmap(\n sharded_jit(f, in_parts=in_partitions, out_parts=out_partitions))(x, y)\n expected = pmap(f)(x, y)\n self.assertAllClose(result, expected, check_dtypes=False)\n\n flat_result = tree_util.tree_flatten(result)[0]\n for r in flat_result:\n self.assertTrue(isinstance(r, pxla.ShardedDeviceArray))\n self.assertEqual(len(r.device_buffers), num_shards)\n\n\n @parameterized.named_parameters({\n \"testcase_name\":\n \"_in_parts={}_out_parts={}\".format(in_partitions,\n out_partitions).replace(\" \", \"\"),\n \"in_partitions\":\n in_partitions,\n \"out_partitions\":\n out_partitions\n } for in_partitions in [\n (P(2, 1), P(2, 1)),\n (P(2, 1), P(1, 2)),\n (P(2, 2), P(2, 2)),\n (P(4, 1), P(2, 2)),\n ] for out_partitions in [in_partitions[0], None])\n def testBasic(self, in_partitions, out_partitions):\n\n def f(x, y):\n return lax.dot(x, y)\n\n self._runTest(f, in_partitions, out_partitions)\n\n @parameterized.named_parameters({\n \"testcase_name\":\n \"_in_parts={}_out_parts={}\".format(in_partitions,\n out_partitions).replace(\" \", \"\"),\n \"in_partitions\":\n in_partitions,\n \"out_partitions\":\n out_partitions\n } for in_partitions in [\n (P(2, 1), P(2, 1)),\n (P(2, 1), P(1, 2)),\n (P(4, 1), P(2, 2))\n ] for out_partitions in [(in_partitions[1], in_partitions[0], None),\n (None, None, None)])\n def testMultipleOutputs(self, in_partitions, out_partitions):\n\n def f(x, y):\n a = lax.dot(x, y)\n # TODO(skye): use these more interesting outputs once returning constants\n # works\n # return a, a + 1, 3\n return a, a + x, x + y\n\n self._runTest(f, in_partitions, out_partitions)\n\n @parameterized.named_parameters({\n \"testcase_name\":\n \"_in_parts={}_out_parts={}\".format(in_partitions,\n out_partitions).replace(\" \", \"\"),\n \"in_partitions\":\n in_partitions,\n \"out_partitions\":\n out_partitions\n } for in_partitions in [\n (P(2, 1), P(2, 1)),\n (P(2, 1), P(1, 2)),\n (P(4, 1), P(2, 2))\n ] for out_partitions in [in_partitions[0], None])\n def testArrayConstants(self, in_partitions, out_partitions):\n\n def f(x, y):\n a = lax.dot(x, y)\n b = a + jnp.ones(a.shape)\n c = b + jnp.ones(a.shape[0])\n return c\n\n self._runTest(f, in_partitions, out_partitions)\n\n def testPyTreeArgs(self):\n if jax.local_device_count() < 4:\n raise SkipTest(\"requires 4 devices\")\n\n def f(a, b, c):\n a1, a2 = a\n c1, (c2, c3) = c\n return a1 + a2 + b + c1 + c2 + c3\n\n def _make_arg(*shape):\n return np.arange(np.prod(shape)).reshape(shape)\n\n a = (_make_arg(2, 4, 4), _make_arg(2))\n b = _make_arg(2, 4, 4)\n c = (_make_arg(2), (_make_arg(2, 4, 4), _make_arg(2, 4, 4)))\n\n in_parts = (None, P(2, 1), (None, P(2, 1)))\n out_parts = P(2, 1)\n\n result = pmap(sharded_jit(f, in_parts=in_parts, out_parts=out_parts))(a, b, c)\n expected = pmap(f)(a, b, c)\n\n self.assertAllClose(result, expected, check_dtypes=False)\n self.assertTrue(isinstance(result, pxla.ShardedDeviceArray))\n self.assertEqual(len(result.device_buffers), 4)\n\n def testPyTreeOutputs(self):\n if jax.local_device_count() < 4:\n raise SkipTest(\"requires 4 devices\")\n\n def f(x):\n return x + 1, ((x + 2, x + 3), x + 4)\n\n shape = (2, 4, 4)\n x = np.arange(np.prod(shape)).reshape(shape)\n in_parts = (P(2, 1),)\n out_parts = (P(2, 1), ((P(1, 2), None), P(2, 1)))\n\n result = pmap(sharded_jit(f, in_parts=in_parts, out_parts=out_parts))(x)\n expected = pmap(f)(x)\n\n self.assertAllClose(result, expected, check_dtypes=False)\n\n def testManyArgs(self):\n if jax.local_device_count() < 4:\n raise SkipTest(\"requires 4 devices\")\n\n num_args = 200\n\n def f(*args):\n return jnp.sum(args)\n\n shape = (2, 4, 4)\n args = [np.arange(np.prod(shape)).reshape(shape)] * num_args\n in_partitions = (P(2, 1),) * num_args\n out_partitions = None\n result = pmap(sharded_jit(\n f, in_parts=in_partitions, out_parts=out_partitions))(*args)\n expected = pmap(f)(*args)\n\n self.assertAllClose(result, expected, check_dtypes=False)\n self.assertTrue(isinstance(result, pxla.ShardedDeviceArray))\n self.assertEqual(len(result.device_buffers), 4)\n\n def testShardingConstraint(self):\n if jax.local_device_count() < 4:\n raise SkipTest(\"requires 4 devices\")\n\n @partial(sharded_jit, in_parts=None, out_parts=None)\n def f(x):\n y = jnp.dot(x, x)\n y = with_sharding_constraint(y, P(2,1))\n return y * 2\n\n def expected_f(x):\n return jnp.dot(x, x) * 2\n\n shape = (2, 8, 8)\n x = np.arange(np.prod(shape)).reshape(shape)\n result = pmap(f)(x)\n expected = pmap(expected_f)(x)\n\n self.assertAllClose(result, expected, check_dtypes=False)\n self.assertIsInstance(result, pxla.ShardedDeviceArray)\n self.assertLen(result.device_buffers, 4)\n\n def testInAxesNone(self):\n shape = (4, 4)\n replicas = 2\n in_partitions = (P(2, 1), None, None)\n out_partitions = P(2, 1)\n in_axes = (None, None, 0)\n x = y = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)\n dummy = np.arange(replicas, dtype=np.float32) + 1\n num_shards = replicas * np.prod(in_partitions[0])\n if num_shards > jax.local_device_count():\n raise SkipTest(\"requires %d devices\" % num_shards)\n\n def f(x, y, _):\n return x @ y\n\n result = pmap(\n sharded_jit(f, in_parts=in_partitions, out_parts=out_partitions),\n in_axes=in_axes)(x, y, dummy)\n expected = pmap(f, in_axes=in_axes)(x, y, dummy)\n self.assertAllClose(result, expected, check_dtypes=True)\n\n\nif __name__ == \"__main__\":\n absltest.main()\n"
] |
[
[
"numpy.linalg.matrix_power",
"numpy.concatenate",
"numpy.max",
"numpy.random.randn",
"numpy.mean",
"numpy.roll",
"numpy.swapaxes",
"numpy.arange",
"numpy.sin",
"numpy.float32",
"numpy.repeat",
"numpy.zeros",
"numpy.min",
"numpy.random.rand",
"numpy.array",
"numpy.random.RandomState",
"numpy.sum",
"numpy.cos",
"numpy.ones",
"numpy.broadcast_to",
"numpy.prod"
],
[
"numpy.arange",
"numpy.prod",
"numpy.ones"
]
] |
CITlabRostock/citlab-article-separation-new
|
[
"814364bf81552eefbe0ce60bbb9ec9e8ca63baf4"
] |
[
"article_separation/image_segmentation/net_post_processing/textblock_net_post_processor_old.py"
] |
[
"import logging\nimport os\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom python_util.geometry.rectangle import Rectangle\nfrom python_util.image_processing.image_stats import get_rotation_angle\nfrom scipy.ndimage import interpolation as inter\n\nlogger = logging.getLogger(\"TextBlockNetPostProcessor\")\n# logging.basicConfig(level=logging.WARNING)\nlogging.basicConfig(level=logging.INFO)\n\nMIN_PIXEL_SEPARATOR_DISTANCE_FACTOR = 0.003\nMAX_RECURSION_DEPTH = 4\n\n\nclass TextBlockNetPostProcessor(object):\n \"\"\"Comments / Workflow:\n 1.) the original image is used to calculate the rotation angle of the image -> better way to do this?\n 2.) the text block channel of the net output is used to calculate white runs in the image, i.e. separator\n 3.) the separator channel of the net output is used to extract visible separator from the image\n 4.) 2.) & 3.) are combined to provide a first partition into coarse regions (the number of columns should be visible)\n 5.) Iterate over the regions from the last step and use the separator and text block channel to provide more horizontal separator\n 6.) The resulting grid-like image can be used to divide the Page into text regions\n\n won't work well for pages with\n - images, since no image detection is provided for now -> coming\n - complex layout, e.g. many advertisments -> check\n\n \"\"\"\n\n def __init__(self, original_image, text_block_outline, text_block, separator):\n self.images = {'original_image': original_image, 'text_block_outline': text_block_outline,\n 'text_block': text_block, 'separator': separator,\n 'binarized_image': self.binarize_image(original_image),\n 'empty_image': np.zeros(original_image.shape, dtype=np.uint8)}\n if not self.check_dimensions(*self.images.values()):\n raise RuntimeError(\"Image shapes don't match.\")\n self.image_height, self.image_width = self.images['original_image'].shape\n\n @staticmethod\n def binarize_net_output(image, threshold):\n return np.array((image > threshold), np.int32)\n\n @staticmethod\n def binarize_image(image, gaussian_blur=True):\n if gaussian_blur:\n res = cv2.GaussianBlur(image, (5, 5), 0)\n else:\n res = image\n _, res = cv2.threshold(res, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n return res\n\n def get_best_rotation_angle(self):\n rotation_angle_binarized_image = get_rotation_angle(self.images['binarized_image'])[1]\n rotation_angle_textblock_image = get_rotation_angle(self.images[\"text_block\"])[1]\n print(f\"Rotation angle determined by the binarized image: {rotation_angle_binarized_image}\")\n print(f\"Rotation angle determined by the text block image: {rotation_angle_textblock_image}\")\n return rotation_angle_binarized_image\n # return get_rotation_angle(self.images['binarized_image'])[1]\n\n @staticmethod\n def check_dimensions(*images):\n return all(image.shape == images[0].shape for image in images)\n\n def rotate_images(self, angle):\n logger.info(f\"Rotate images by {angle} degrees.\")\n for img_name, img in self.images.items():\n self.images[img_name] = inter.rotate(img, angle, reshape=False, order=0)\n\n @staticmethod\n def get_separators(image, mode='horizontal', threshold=0.1):\n \"\"\" This function looks for separators in an image ``image``. By default it looks for white runs in the image by\n adding up the pixel values across the x or y dimension depending on the ``mode`` parameter and check if it exceeds\n a given threshold given by the parameter ``threshold``. If you're looking for black runs, just invert the image.\n\n :param image: input image\n :param mode: can be one of 'horizontal' (0) or 'vertical' (1)\n :param threshold: the value the sum of the pixels must exceed to be defined as a white run\n :return: A list of tuples containing the row/column where a white run is present together with its relative score value.\n \"\"\"\n if type(mode) == str:\n if mode.lower() == 'horizontal':\n mode = 0\n elif mode.lower() == 'vertical':\n mode = 1\n if mode not in [0, 1]:\n raise ValueError(\"Provide a proper mode, possible options are 'horizontal' (0) or 'vertical' (1).\")\n\n image_height, image_width = image.shape[:2]\n\n separators = None\n if mode == 0:\n profiles = np.sum(image, axis=1) / 255\n separators = [(i, hp / image_width) for i, hp in enumerate(profiles) if hp / image_width > threshold]\n elif mode == 1:\n profiles = np.sum(image, axis=0) / 255\n separators = [(i, vp / image_height) for i, vp in enumerate(profiles) if vp / image_height > threshold]\n\n return separators\n\n # def get_separators(self, threshold_horizontal=0.1, threshold_vertical=0.5):\n #\n # height, width = self.images['text_block'].shape\n #\n # horizontal_profiles = np.sum(self.images['text_block'], axis=1) / 255\n # vertical_profiles = np.sum(self.images['text_block'], axis=0) / 255\n #\n # # We check for '<', because we search for blackruns in the textblock netoutput!\n # horizontal_separators = [(i, hp / width) for i, hp in enumerate(horizontal_profiles) if\n # hp / width < threshold_horizontal]\n # vertical_separators = [(i, vp / height) for i, vp in enumerate(vertical_profiles) if\n # vp / height < threshold_vertical]\n #\n # print(len(horizontal_separators))\n # print(horizontal_separators)\n # print(len(vertical_separators))\n # print(vertical_separators)\n #\n # return horizontal_separators, vertical_separators\n\n def run_recursion(self, region_rectangle: Rectangle, max_recursion_depth=MAX_RECURSION_DEPTH, mode=\"horizontal\", threshold=0.9):\n \"\"\" Run recursion to determine the text regions. Make sure to alternate between horizontal and vertical\n separator detection. The ``mode`` parameter determines with which subdivision to start, defaults to 'horizontal'.\n\n :param region_rectangle: determines the region in the original text block image\n :param threshold: relative number of white pixels that should be reached to be defined as a white run.\n :param mode: same parameter as in method ``get_separators``, 'horizontal' or 'vertical'.\n :param max_recursion_depth: maximal number of times to run the recursion\n :return: a mask that can be applied to the baseline detection output to get a division into text regions\n \"\"\"\n print(MAX_RECURSION_DEPTH - max_recursion_depth)\n\n if max_recursion_depth == 0:\n return\n\n image = self.images[\"text_block\"]\n\n image = image[region_rectangle.x: region_rectangle.x + region_rectangle.width][\n region_rectangle.y: region_rectangle.y + region_rectangle.height]\n\n # The min_pixel_separator_distance determines up to which (pixel)distance neighboring white runs get merged!\n min_pixel_separator_distance = int(self.image_height * MIN_PIXEL_SEPARATOR_DISTANCE_FACTOR)\n print(f\"min_pixel_separator_distance = {min_pixel_separator_distance}\")\n\n # profile_list = self.get_separators(255 - self.images['text_block'], mode, threshold)\n profile_list = self.get_separators(255 - image, mode, threshold)\n index_separators = [i for i, _ in profile_list]\n if not index_separators:\n return\n\n index_separators_new = []\n if index_separators[0] > min_pixel_separator_distance:\n index_separators_new.append((0, index_separators[0]))\n\n for i in range(len(index_separators) - 1):\n if index_separators[i + 1] - index_separators[i] > min_pixel_separator_distance:\n index_separators_new.append((index_separators[i] + 1, index_separators[i + 1]))\n if mode == 'horizontal':\n if (self.image_height - 1) - index_separators[-1] > min_pixel_separator_distance:\n index_separators_new.append((index_separators[-1], self.image_height - 1))\n elif mode == 'vertical':\n if (self.image_width - 1) - index_separators[-1] > min_pixel_separator_distance:\n index_separators_new.append((index_separators[-1], self.image_width - 1))\n # print(index_separators)\n # print(index_separators_new)\n\n new_mode = None\n if mode == \"horizontal\":\n new_mode = \"vertical\"\n elif mode == \"vertical\":\n new_mode = \"horizontal\"\n\n new_region_rectangle = None\n for image_range in index_separators_new:\n # image_range is a tuple with x coordinate from\n # new_region_rectangle = None\n if mode == \"horizontal\":\n # update the y-coordinates and keep the x-coordinates\n new_y = image_range[0] + region_rectangle.y\n new_height = image_range[1] - image_range[0]\n new_region_rectangle = Rectangle(region_rectangle.x, new_y, region_rectangle.width, new_height)\n elif mode == \"vertical\":\n # update the x-coordinates and keep the y-coordinates\n new_x = image_range[0] + region_rectangle.x\n new_width = image_range[1] - image_range[0]\n new_region_rectangle = Rectangle(new_x, region_rectangle.y, new_width, region_rectangle.height)\n print(\"REGION RECTANGLE COORD: \", new_region_rectangle.get_vertices())\n cv2.rectangle(self.images[\"empty_image\"], new_region_rectangle.get_vertices()[0], new_region_rectangle.get_vertices()[2], (255, 0, 0), 1)\n # self.get_separators(self.images[\"text_block\"][image_range[0]:image_range[1]], new_mode, threshold)\n self.run_recursion(new_region_rectangle, max_recursion_depth - 1, new_mode, max(0.9*threshold, 0.65))\n\n return new_region_rectangle\n\n def run(self):\n rotation_angle = round(self.get_best_rotation_angle(), 4)\n self.rotate_images(rotation_angle)\n\n region_rectangle_image = Rectangle(0, 0, self.image_width, self.image_height)\n self.run_recursion(region_rectangle_image, threshold=0.9)\n\n plt.set_cmap('gray')\n plt.subplot(1, 3, 1)\n plt.imshow(self.images[\"empty_image\"])\n plt.subplot(1, 3, 2)\n plt.imshow(self.images[\"text_block\"])\n plt.subplot(1, 3, 3)\n plt.imshow(self.images[\"original_image\"])\n\n plt.show()\n\n\n\nif __name__ == '__main__':\n path_to_image_folder = '/home/max/devel/projects/python/article_separation/data/test_post_processing/textblock/'\n path_to_orig_image = os.path.join(path_to_image_folder, 'ONB_aze_19110701_004.jpg')\n path_to_tb_outline = os.path.join(path_to_image_folder, 'ONB_aze_19110701_004_OUT0.jpg')\n path_to_tb = os.path.join(path_to_image_folder, 'ONB_aze_19110701_004_OUT1.jpg')\n path_to_separator = os.path.join(path_to_image_folder, 'ONB_aze_19110701_004_OUT2.jpg')\n\n orig_image = cv2.imread(path_to_orig_image, cv2.IMREAD_UNCHANGED)\n tb_outline_image = cv2.imread(path_to_tb_outline, cv2.IMREAD_UNCHANGED)\n tb_image = cv2.imread(path_to_tb, cv2.IMREAD_UNCHANGED)\n separator_image = cv2.imread(path_to_separator, cv2.IMREAD_UNCHANGED)\n\n orig_image = cv2.resize(orig_image, None, fx=0.4, fy=0.4)\n # orig_image_gb = cv2.GaussianBlur(orig_image, (5, 5), 0)\n orig_image_gb = orig_image\n _, orig_image_gb_bin = cv2.threshold(orig_image_gb, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n\n tb_pp = TextBlockNetPostProcessor(orig_image_gb_bin, tb_outline_image, tb_image, separator_image)\n\n region_rectangle_image = Rectangle(0, 0, orig_image.shape[1], orig_image.shape[0])\n # tb_pp.run_recursion(region_rectangle_image)\n #\n # text_block_rgb = cv2.cvtColor(tb_pp.images[\"text_block\"], cv2.COLOR_BGR2RGB)\n # # text_block_rgb = tb_pp.images[\"text_block\"]\n # plt.imshow(text_block_rgb)\n # plt.show()\n\n tb_pp.run()\n\n # # CONTOURS TEST\n # original_image_rgb = cv2.cvtColor(tb_pp.images[\"original_image\"], cv2.COLOR_BGR2RGB)\n # text_block_image_rgb = cv2.cvtColor(tb_pp.images[\"text_block\"], cv2.COLOR_BGR2RGB)\n # plt.subplot(1, 2, 1)\n # plt.imshow(text_block_image_rgb)\n # contours, _ = cv2.findContours(tb_pp.images[\"text_block\"], cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)\n # contour_image = cv2.drawContours(text_block_image_rgb, contours, -1, (0, 255, 0), 3)\n # plt.subplot(1, 2, 2)\n # plt.imshow(text_block_image_rgb)\n # plt.show()\n\n # rotation_angle = round(tb_pp.get_best_rotation_angle(), 4)\n # tb_pp.rotate_images(rotation_angle)\n #\n # horizontal_profile_list, vertical_profile_list = tb_pp.get_separators()\n #\n # index_horizontal = [i for i, _ in horizontal_profile_list]\n # index_vertical = [i for i, _ in vertical_profile_list]\n #\n # white_sep = np.zeros(orig_image.shape, dtype=np.uint8)\n # white_sep[:, index_vertical] = 255\n # white_sep[index_horizontal, :] = 255\n # # white_sep = cv2.resize(white_sep, None, fx=0.5, fy=0.5)\n #\n # # separator_image = cv2.resize(separator_image, None, fx=0.5, fy=0.5)\n # separator_image = np.array((separator_image > 0.2), np.uint8)\n # print(separator_image, separator_image.dtype)\n # separator_image *= 255\n #\n # print(separator_image, separator_image.dtype)\n # print(white_sep, white_sep.dtype)\n #\n # add_condition = np.not_equal(white_sep, separator_image)\n # black_white_separator = np.copy(white_sep)\n # black_white_separator[add_condition] += separator_image[add_condition]\n #\n # kernel = np.ones((5, 5), np.uint8)\n # black_white_separator = cv2.morphologyEx(black_white_separator, cv2.MORPH_CLOSE, kernel)\n #\n # plt.set_cmap(\"gray\")\n # plt.subplot(1, 4, 1)\n # plt.imshow(white_sep)\n # plt.subplot(1, 4, 2)\n # plt.imshow(separator_image)\n # plt.subplot(1, 4, 3)\n # plt.imshow(black_white_separator)\n # plt.subplot(1, 4, 4)\n # plt.imshow(orig_image)\n # plt.show()\n #\n # # cv2.imshow('white separator', white_sep)\n # # cv2.imshow('black separator net', separator_image)\n # # cv2.imshow('black white separator', black_white_separator)\n # # cv2.waitKey(0)\n # # cv2.destroyAllWindows()\n #\n # vertical_profile = np.sum(black_white_separator, axis=0)\n # horizontal_profile = np.sum(black_white_separator, axis=1)\n #\n # horizontal = [(i, hp / orig_image.shape[1] / 255) for i, hp in enumerate(horizontal_profile) if\n # hp / orig_image.shape[1] / 255 < 0.2]\n # vertical = [(i, vp / orig_image.shape[0] / 255) for i, vp in enumerate(vertical_profile) if\n # vp / orig_image.shape[0] / 255 < 0.2]\n #\n # horizontal_index = [i for i, _ in horizontal]\n # vertical_index = [i for i, _ in vertical]\n #\n # print(horizontal_index)\n # print(vertical_index)\n #\n #\n # def convert_to_ranges(index_list):\n # range_list = []\n # skip = False\n # for i in range(len(index_list) - 1):\n # if not skip:\n # begin = index_list[i]\n # if index_list[i + 1] - index_list[i] < 3:\n # skip = True\n # continue\n # skip = False\n # end = index_list[i]\n # range_list.append((begin, end))\n # return range_list\n #\n #\n # print(convert_to_ranges(horizontal_index))\n # print(convert_to_ranges(vertical_index))\n #\n # # tb_image_binarized = np.array((tb_image > 0.8), np.uint8) * 255\n # # print(tb_image_binarized)\n # # # erosion_kernel = np.array([[0, 1, 0], [0, 1, 0], [0, 1, 0]], dtype=np.uint8)\n # # erosion_kernel = np.ones([8, 8], dtype=np.uint8)\n # # print(erosion_kernel)\n # # tb_image_erosion = cv2.erode(tb_image_binarized, erosion_kernel, iterations=1)\n # # tb_image_erosion = cv2.resize(tb_image_erosion, None, fx=0.4, fy=0.4)\n # # print(tb_image_erosion)\n # # cv2.imshow(\"erosion image textblock\", tb_image_erosion)\n # # cv2.waitKey(0)\n # # cv2.destroyAllWindows()\n # # exit(1)\n"
] |
[
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.set_cmap",
"scipy.ndimage.interpolation.rotate",
"matplotlib.pyplot.subplot",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"matplotlib.pyplot.show"
]
] |
MelleStarke/MAS_B06
|
[
"fbedc7459006c0915428f0122d923dd41b57b51e"
] |
[
"src/agents/util/mathstuffs.py"
] |
[
"import pandas as pd\nimport numpy as np\n\ndef perform_TOPSIS(df, supplier_names):\n score = []\n nn = []\n pp = []\n\n # Hard-coded weights and impact for now.\n # weights = [0.2125, 0.1802, 0.0868, 0.1048, 0.0462, 0.0745, 0.0389, 0.0722, 0.0518, 0.0411, 0.0562, 0.035]\n a = pd.read_csv(\"../agents/util/q.csv\", index_col=\"Unnamed: 0\")\n impact = ['pos', 'pos', 'pos', 'pos', 'pos', 'pos', 'pos', 'pos', 'neg', 'neg', 'pos', 'pos']\n\n # Now we Calculate the Normalized Matrix and weighted Normalize matrix\n cols = len(df.columns)\n # making a copy of dataframe to use it later\n temp_df = df.copy()\n temp_df.iloc[:, 1:] = temp_df[temp_df.columns[1:]].astype(float)\n # Normalizing the supplier data\n b = temp_df.iloc[:, 1:].to_numpy()\n norm = np.linalg.norm(b)\n b = b / norm\n temp_df.iloc[:, 1:] = b\n # Normalizing the comparision matrix\n a = a.to_numpy()\n norm = np.linalg.norm(a)\n norm_a = a / norm\n # Construct the weighted normalized decision matrix by\n # multiplying the normalized decision matrix by its\n # associated weights.\n norm_weight_mat = np.matmul(b, norm_a)\n temp_df.iloc[:, 1:] = norm_weight_mat\n\n # # After creating a normalised matrix, We then multiply each value in a column with the corresponding weight given.\n # for i in range(1, cols):\n # temp = 0\n # for j in range(len(temp_df)):\n # temp = temp + temp_df.iloc[j, i] ** 2\n # temp = temp ** 0.5\n # for j in range(len(temp_df)):\n # temp_df.iat[j, i] = (temp_df.iloc[j, i] / temp) * weights[i - 1]\n\n # Now we calculate Ideal Best and Ideal worst and Euclidean distance for each row from ideal worst and ideal best value\n # Here we need to see the impact, i.e. is it ‘positive’ or ‘negative‘ impact.\n p_sln = (temp_df.max().values)[1:]\n n_sln = (temp_df.min().values)[1:]\n for i in range(1, cols):\n if impact[i - 1] == 'neg':\n p_sln[i - 1], n_sln[i - 1] = n_sln[i - 1], p_sln[i - 1]\n\n # now we calculate the distances and topsis scores now\n\n for i in range(len(temp_df)):\n temp_p, temp_n = 0, 0\n for j in range(1, cols):\n temp_p = temp_p + (p_sln[j - 1] - temp_df.iloc[i, j]) ** 2\n temp_n = temp_n + (n_sln[j - 1] - temp_df.iloc[i, j]) ** 2\n temp_p, temp_n = temp_p * 0.5, temp_n * 0.5\n score.append(temp_n / (temp_p + temp_n))\n nn.append(temp_n)\n pp.append(temp_p)\n\n # now we append the created lists into the original dataframe to rank it\n df['distance positive'] = pp\n df['distance negative'] = nn\n df['Topsis Score'] = score\n\n df['Rank'] = (df['Topsis Score'].rank(method='max', ascending=False))\n df = df.astype({\"Rank\": int})\n rankings = df[\"Rank\"].to_dict()\n rankings = {name: rank for (name, rank) in zip(supplier_names, rankings.values())}\n sorted_rankings = [rankings[k] for k in sorted(rankings)]\n return sorted_rankings\n \n\ndef order_perms(D, Ns):\n \"\"\"\n Computes the permutations of the order allocations.\n i.e. every way to distribute the order across the suppliers.\n \n D: demand, i.e. the order.\n Ns: nr. of suppliers.\n \"\"\"\n \n def div_perms(n, r, ans=None):\n \"\"\"\n Recursively calculates the permutations of one product order over the suppliers.\n\n n: amount of the product.\n r: nr. of suppliers (i.e. range)\n ans: result of the function\n \"\"\"\n if ans is None:\n ans = [[0 for x in range(r)]]\n \n if n == 0:\n return ans\n \n new_ans = list()\n for a in ans:\n for ri in range(r):\n new_ans.append([ x+1 if i == ri else x for (i, x) in enumerate(a)])\n \n return div_perms(n-1, r, new_ans)\n \n \n def comb_perms(div_perms, ans=None):\n \"\"\"\n Computes the permutations of the results of div_perms, resulting in every legal order division.\n \n div_perms: list of div_perms result for all products.\n ans: result of the function.\n \"\"\"\n\n if len(div_perms) == 0:\n return ans\n \n if ans is None:\n #print(div_perms)\n dp = div_perms.pop(0)\n return comb_perms(div_perms, [[x] for x in dp])\n \n dp = div_perms.pop(0)\n new_ans = [ [] for x in range(len(ans) * len(dp))]\n \n i = 0\n for a in ans:\n for p in dp:\n x = a + [p]\n new_ans[i] = x\n i += 1\n \n return comb_perms(div_perms, new_ans)\n \n \n div_ps = [div_perms(d, Ns) for d in D]\n\n return(comb_perms(div_ps))\n\n\n\n\n\n\n\n\n"
] |
[
[
"pandas.read_csv",
"numpy.matmul",
"numpy.linalg.norm"
]
] |
callat-qcd/project_fkfpi
|
[
"364bc40cf936261b5d2a84374f51327646e60d41"
] |
[
"fit_fkfpi.py"
] |
[
"#!/usr/bin/env python3\n# python libraries\nimport os, sys, shutil, copy\nimport matplotlib.pyplot as plt\nimport numpy as np\n# Peter Lepage's libraries\nimport gvar as gv\nimport lsqfit\n\n# FK / Fpi libraries\nsys.path.append('utils')\nimport io_utils\nimport chipt\nimport analysis\nimport plotting\n\n''' Write description\n'''\n\n''' useful for changing matplotlib.plt.show behavior and accessing results\n from main() if run interactively in iPython\n'''\ndef run_from_ipython():\n try:\n __IPYTHON__\n return True\n except NameError:\n return False\n\ndef main():\n print(\"python version:\", sys.version)\n import input_params as ip\n # Load input params\n switches = ip.switches\n priors = ip.priors\n phys_point = ip.phys_point\n check_fit = ip.check_fit\n\n # if check_fit: - add support\n if switches['check_fit']:\n models = analysis.sys_models(switches)\n print('DEBUGGING FIT FUNCTION')\n print('p')\n for k in check_fit['p']:\n print(\"%7s\" %k,check_fit['p'][k])\n print('x')\n for k in check_fit['x']:\n print(\"%7s\" %k,check_fit['x'][k])\n for model in models:\n print('===============================================================')\n print('DEBUGGING Terms in ',model)\n print('---------------------------------------------------------------')\n model_list, FF, fv = analysis.gather_model_elements(model)\n debug_fit_function(check_fit, model_list, FF, fv)\n sys.exit()\n if switches['print_Li']:\n li_rho = r'$10^3L_i(m_\\rho)$& '\n li_mu0 = r'$10^3L_i(\\mu_0)$& '\n for Li in ['L1','L2','L3','L4','L5','L6','L7','L8']:\n li_rho += str(ip.Li_mrho[Li])+'& '\n li_mu0 += str(1e3*ip.priors[Li])+'& '\n print(li_rho)\n print(li_mu0)\n sys.exit('Exiting after printing L_i values')\n\n if switches['save_fits']:\n if not os.path.exists('pickled_fits'):\n os.makedirs('pickled_fits')\n\n # load data\n gv_data = io_utils.format_h5_data('data/FK_Fpi_data.h5',switches)\n\n models = analysis.sys_models(switches)\n if switches['prior_search']:\n print('Performing Prior Width Scan')\n print(r'%33s & nnlo_x & nnlo_a & n3lo_x & n3lo_a & logGBF_max' %'model')\n print('======================================================================================')\n for model in models:\n model_list, FF, fv = analysis.gather_model_elements(model)\n fit_model = chipt.FitModel(model_list, _fv=fv, _FF=FF)\n fitEnv = FitEnv(gv_data, fit_model, switches)\n analysis.prior_width_scan(model, fitEnv, fit_model, priors, switches)\n else: # do analysis\n fit_results = dict()\n plt.ion()\n for model in models:\n print('===============================================================')\n print(model)\n model_list, FF, fv = analysis.gather_model_elements(model)\n fit_model = chipt.FitModel(model_list, _fv=fv, _FF=FF)\n fitEnv = FitEnv(gv_data, fit_model, switches)\n\n do_fit = False\n pickled_fit = 'pickled_fits/'+model+'_n2lo'+str(ip.nnlo_x)+'_n3lo'+str(ip.n3lo_x)+'.p'\n if switches['save_fits'] or switches['debug_save_fit']:\n if os.path.exists(pickled_fit):\n print('reading %s' %pickled_fit)\n fit_result = gv.load(pickled_fit)\n check_pickled_fit(fit_result,switches,priors)\n else:\n do_fit = True\n else:\n do_fit = True\n if do_fit or switches['debug_save_fit']:\n tmp_result = fitEnv.fit_data(priors)\n tmp_result.phys_point = dict()\n tmp_result.phys_point.update({k:v for k,v in phys_point['p'].items() if ('Lchi' in k) or k in ['mpi','mk','mkp']})\n if switches['debug_save_fit']:\n print('live fit')\n report_phys_point(tmp_result, phys_point, model_list, FF, report=True)\n analysis.uncertainty_breakdown(tmp_result,'FKFpi',print_error=True)\n print('pickled fit')\n if not os.path.exists(pickled_fit):\n gv.dump(tmp_result, pickled_fit, add_dependencies=True)\n fit_result = gv.load(pickled_fit)\n report_phys_point(fit_result, phys_point, model_list, FF, report=True)\n analysis.uncertainty_breakdown(fit_result,'FKFpi',print_error=True)\n if do_fit:\n fit_result = tmp_result\n\n if switches['print_fit']:\n print(fit_result.format(maxline=True))\n fit_result.phys_point.update({k:v for k,v in phys_point['p'].items() if ('Lchi' in k) or k in ['mpi','mk','mkp']})\n fit_result.ensembles_fit = switches['ensembles_fit']\n report_phys_point(fit_result, phys_point, model_list, FF, report=switches['report_phys'])\n if switches['report_Li']:\n for Li in ['L1','L2','L3','L4','L5','L6','L7','L8']:\n if Li in fit_result.p:\n Li_mu0 = fit_result.p[Li]\n Li_rho = Li_mu0 - ip.gamma_i[Li]/(4*np.pi)**2 * np.log(770 / (4*np.pi*80))\n print(\"%s %10s %10s\" %(Li, 1e3*Li_mu0, 1e3*Li_rho))\n for k in ['k_4', 'p_4', 'kp_6', 'k_6', 'p_6']:\n if k in fit_result.p:\n print(\"%4s %s\" %(k,fit_result.p[k]))\n fit_results[model] = fit_result\n if switches['save_fits']:\n gv.dump(fit_result, pickled_fit, add_dependencies=True)\n\n if switches['debug_phys_point'] and not do_fit:\n report_phys_point(fit_result, phys_point, model_list, FF)\n if switches['make_extrap'] or switches['make_fv']:\n plots = plotting.ExtrapolationPlots(model, model_list, fitEnv, fit_result, switches)\n if switches['make_extrap']:\n if 'alphaS' not in model and 'ma' not in model:\n plots.plot_vs_eps_asq(phys_point)\n if 'ma' not in model:\n plots.plot_vs_eps_pi(phys_point)\n if switches['make_fv']:\n if 'xpt' in model and 'FV' in model and 'PP' in model:\n plots.plot_vs_ml()\n\n if switches['model_avg']:\n model_avg = analysis.BayesModelAvg(fit_results)\n model_avg.print_weighted_models()\n model_avg.bayes_model_avg()\n if switches['make_hist']:\n model_avg.plot_bma_hist('FF',save_fig=switches['save_figs'])\n model_avg.plot_bma_hist('FF_xpt',save_fig=switches['save_figs'])\n model_avg.plot_bma_hist('ratio',save_fig=switches['save_figs'])\n model_avg.plot_bma_hist('ct',save_fig=switches['save_figs'])\n\n plt.ioff()\n if run_from_ipython():\n plt.show(block=False)\n return fit_results\n else:\n plt.show()\n\n return fit_results\n\n'''\n This is the main class that runs a given fit specified by a model\n'''\nclass FitEnv:\n # xyp_dict is a dictionary with keys 'x', 'y', 'p'\n # 'y' value is a dict{ensemble : yval},\n # 'x' value is a dict{ensemble : {<all the x variables which are not priors>}\n # 'p' value is a dict{(ensemble, pKey) : aPal} for all the\n # ensemble-specific priors like meson masses as well as teh LECs\n def __init__(self, xyp_dict, model, switches):\n self.switches = switches\n self.ensembles = switches['ensembles_fit']\n self.x = xyp_dict['x']\n self.pruned_x = {ens : { k : v for k, v in xyp_dict['x'][ens].items()}\n for ens in self.ensembles}\n self.y = xyp_dict['y']\n self.pruned_y = {ens : xyp_dict['y'][ens] for ens in self.ensembles}\n required_params = model.get_required_parameters()\n self.p = xyp_dict['p']\n self.pruned_p = {(ens, k) : v for (ens, k), v in xyp_dict['p'].items()\n if k in required_params and ens in self.ensembles}\n self.model = model\n\n # create a callable function that acts on a single x and p (not all ensembles)\n @classmethod\n def _fit_function(cls, a_model, x, p):\n return a_model(x,p)\n\n def fit_function(self, x, p):\n a_result = dict()\n for ens in x.keys():\n p_ens = dict()\n for k, v in p.items():\n if type(k) == tuple and k[0] == ens:\n p_ens[k[1]] = v # the x-params which are priors\n else:\n p_ens[k] = v # the LECs of the fit\n model = self.model\n a_result[ens] = FitEnv._fit_function(model, x[ens], p_ens)\n return a_result\n\n def fit_data(self, lec_priors):\n required_params = self.model.get_required_parameters()\n # add the LEC priors to our list of priors for the fit\n self.pruned_p.update({ k:v for k,v in lec_priors.items() if k in required_params})\n x = self.pruned_x\n y = self.pruned_y\n p = self.pruned_p\n if self.switches['scipy']:\n fitter='scipy_least_squares'\n else:\n fitter='gsl_multifit'\n return lsqfit.nonlinear_fit(data=(x,y), prior=p, fcn=self.fit_function, fitter=fitter, debug=True)\n\ndef report_phys_point(fit_result, phys_point_params, model_list, FF, report=False):\n phys_data = copy.deepcopy(phys_point_params)\n if 'ma' in model_list[0]:\n model_list[0] = model_list[0].replace('ma','xpt')\n fit_model = chipt.FitModel(model_list, _fv=False, _FF=FF)\n for k in fit_result.p:\n if isinstance(k,str):\n phys_data['p'][k] = fit_result.p[k]\n fit_result.phys = dict()\n fit_result.phys['FKFpi'] = FitEnv._fit_function(fit_model, phys_data['x'], phys_data['p'])\n fit_result.phys['dF_iso_xpt'] = chipt.dFKFpi_iso(phys_data, FF)\n fit_result.phys['dF_iso_xpt2'] = chipt.dFKFpi_iso_2(phys_data, FF, fit_result.phys['FKFpi'])\n if report:\n print(' chi2/dof [dof] = %.2f [%d] Q=%.3f logGBF = %.3f' \\\n %(fit_result.chi2/fit_result.dof, fit_result.dof, fit_result.Q, fit_result.logGBF))\n print(' FK/Fpi = %s' %fit_result.phys['FKFpi'])\n print(' dF_iso_xpt = %s' %chipt.dFKFpi_iso(phys_data, FF))\n print(' dF_iso_xpt2 = %s' %chipt.dFKFpi_iso_2(phys_data, FF, fit_result.phys['FKFpi']))\n print(' dF_iso_vincenzo = %s' %chipt.dFKFpi_vincenzo(phys_data, FF))\n print(' dF_iso_vincenzo2 = %s' %chipt.dFKFpi_vincenzo_2(phys_data, FF, fit_result.phys['FKFpi']))\n\ndef debug_fit_function(check_fit, model_list, FF, fv):\n x = check_fit['x']\n p = check_fit['p']\n fit_model = chipt.FitModel(model_list, _fv=False, _FF=FF)\n cP = chipt.ConvenienceDict(fit_model, x, p)\n result = 0.\n result_FV = 0.\n if fv:\n fit_model_fv = chipt.FitModel(model_list, _fv=True, _FF=FF)\n cP_FV = chipt.ConvenienceDict(fit_model_fv, x, p)\n for term in model_list:\n if '_nlo' in term:\n t_FV = getattr(chipt.FitModel, term)(fit_model_fv, x, p, cP_FV)\n t = getattr(chipt.FitModel, term)(fit_model, x, p, cP)\n result += t\n result_FV += t_FV\n print('%16s ' %(term+'_FV'), t_FV)\n print('%16s ' %(term), t)\n else:\n t = getattr(chipt.FitModel, term)(fit_model, x, p, cP)\n result_FV += t\n result += t\n print('%16s ' %(term), t)\n else:\n for term in model_list:\n t = getattr(chipt.FitModel, term)(fit_model, x, p, cP)\n result += t\n print('%16s ' %(term), t)\n print('---------------------------------------')\n if fv:\n print('%16s %f' %('total_FV', result_FV))\n print('%16s %f' %('total', result))\n\ndef check_pickled_fit(fit,switches,priors):\n ''' make sure the pickled data is consistent with choices in switches '''\n if not set(fit.ensembles_fit) == set(switches['ensembles_fit']):\n sys.exit('ensembles_fit from the pickled fit does not match ensembles_fit from input_params')\n for p in priors:\n if p in fit.prior:\n if priors[p].mean != fit.prior[p].mean or priors[p].sdev != fit.prior[p].sdev:\n sys.exit('prior %s from fit, %s, does not match from input_params %s' \\\n %(p,fit.prior[p],priors[p]))\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"matplotlib.pyplot.ioff",
"numpy.log",
"matplotlib.pyplot.ion",
"matplotlib.pyplot.show"
]
] |
dy-Doing/FAE
|
[
"8b03941106a0f0f3c21ccfef1dc959a54115c6ee"
] |
[
"FAE/FeatureAnalysis/FeatureSelector.py"
] |
[
"from abc import ABCMeta,abstractmethod\nimport numpy as np\nfrom copy import deepcopy\nimport pandas as pd\nfrom random import randrange,seed\nimport os\nimport numbers\nimport csv\n\nfrom sklearn.feature_selection import SelectKBest, f_classif, RFE\nfrom sklearn.decomposition import PCA\nimport pymrmr\nfrom sklearn.svm import SVC\n\nfrom FAE.FeatureAnalysis.ReliefF import ReliefF\nfrom FAE.DataContainer.DataContainer import DataContainer\nfrom FAE.HyperParameterConfig.HyperParamManager import HyperParameterManager\n\n\ndef SaveSelectInfo(data_container, store_path, is_merge=False):\n info = {}\n info['feature_number'] = len(data_container.GetFeatureName())\n if not is_merge:\n info['selected_feature'] = data_container.GetFeatureName()\n\n write_info = []\n for key in info.keys():\n temp_list = []\n temp_list.append(key)\n if isinstance(info[key], (numbers.Number, str)):\n temp_list.append(info[key])\n else:\n temp_list.extend(info[key])\n write_info.append(temp_list)\n\n with open(os.path.join(store_path), 'w', newline='') as csvfile:\n writer = csv.writer(csvfile, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n writer.writerows(write_info)\n\nclass FeatureSelector:\n def __init__(self):\n self.__selector = None\n\n def SelectFeatureByIndex(self, data_container, selected_list, is_replace=False, store_path=''):\n new_data = data_container.GetArray()[:, selected_list]\n new_feature = [data_container.GetFeatureName()[t] for t in selected_list]\n\n if is_replace:\n data_container.SetArray(new_data)\n data_container.SetFeatureName(new_feature)\n data_container.UpdateFrameByData()\n new_data_container = deepcopy(data_container)\n else:\n new_data_container = deepcopy(data_container)\n new_data_container.SetArray(new_data)\n new_data_container.SetFeatureName(new_feature)\n new_data_container.UpdateFrameByData()\n if store_path:\n new_data_container.Save(store_path)\n\n return new_data_container\n\n def SelectFeatureByName(self, data_container, selected_feature_name, is_replace=False, store_path=''):\n new_data = data_container.GetFrame()[selected_feature_name].values\n\n if is_replace:\n data_container.SetArray(new_data)\n data_container.SetFeatureName(selected_feature_name)\n data_container.UpdateFrameByData()\n new_data_container = deepcopy(data_container)\n else:\n new_data_container = deepcopy(data_container)\n new_data_container.SetArray(new_data)\n new_data_container.SetFeatureName(selected_feature_name)\n new_data_container.UpdateFrameByData()\n if store_path:\n new_data_container.Save(store_path)\n\n return new_data_container\n\n def GetDescription(self):\n text = \"Since the number of features is not too high, we did not apply any feature selection method here. \" \\\n \"All features were used to build the final model. \"\n return text\n\n __metaclass__ = ABCMeta\n @abstractmethod\n def Run(self, data_container, store_folder):\n pass\n\n\n#################################################################\n\nclass RemoveNonNumericFeature(FeatureSelector):\n def __init__(self):\n super(RemoveNonNumericFeature, self).__init__()\n\n def Run(self, data_container, store_folder=''):\n temp_frame = data_container.GetFrame().select_dtypes(include=None, exclude=['object'])\n new_data_container = DataContainer()\n new_data_container.SetFrame(temp_frame)\n if store_folder and os.path.isdir(store_folder):\n feature_store_path = os.path.join(store_folder, 'numeric_feature.csv')\n featureinfo_store_path = os.path.join(store_folder, 'feature_select_info.csv')\n\n new_data_container.Save(feature_store_path)\n SaveSelectInfo(new_data_container, featureinfo_store_path, is_merge=False)\n\n return new_data_container\n\nclass RemoveSameFeatures(FeatureSelector):\n def __init__(self):\n super(RemoveSameFeatures, self).__init__()\n\n def GetSelectedFeatureIndex(self, data_container):\n data = data_container.GetArray()\n feature_list = []\n for feature_index in range(data.shape[1]):\n feature = data[:, feature_index]\n unique, counts = np.unique(feature, return_counts=True)\n if np.max(counts) / np.sum(counts) < 0.9: # This is arbitrarily\n feature_list.append(feature_index)\n return feature_list\n\n def Run(self, data_container, store_folder=''):\n new_data_container = self.SelectFeatureByIndex(data_container, self.GetSelectedFeatureIndex(data_container), is_replace=False)\n if store_folder and os.path.isdir(store_folder):\n feature_store_path = os.path.join(store_folder, 'selected_feature.csv')\n featureinfo_store_path = os.path.join(store_folder, 'feature_select_info.csv')\n\n new_data_container.Save(feature_store_path)\n SaveSelectInfo(new_data_container, featureinfo_store_path, is_merge=False)\n\n return new_data_container\n\nclass FeatureSelectBySubName(FeatureSelector):\n def __init__(self, sub_name_list):\n super(FeatureSelectBySubName, self).__init__()\n if isinstance(sub_name_list, str):\n sub_name_list = [sub_name_list]\n\n self.__sub_name_list = sub_name_list\n\n def GetSelectFeaturedNameBySubName(self, data_container):\n all_feature_name = data_container.GetFeatureName()\n selected_feature_name_list = []\n for selected_sub_name in self.__sub_name_list:\n for feature_name in all_feature_name:\n if selected_sub_name in feature_name:\n selected_feature_name_list.append(feature_name)\n\n selected_feature_name_list = list(sorted(set(selected_feature_name_list)))\n return selected_feature_name_list\n\n def Run(self, data_container, store_folder=''):\n new_data_container = self.SelectFeatureByName(data_container, self.GetSelectFeaturedNameBySubName(data_container), is_replace=False)\n if store_folder and os.path.isdir(store_folder):\n feature_store_path = os.path.join(store_folder, 'selected_feature.csv')\n featureinfo_store_path = os.path.join(store_folder, 'feature_select_info.csv')\n\n new_data_container.Save(feature_store_path)\n SaveSelectInfo(new_data_container, featureinfo_store_path, is_merge=False)\n \n return new_data_container\n\n#################################################################\nclass FeatureSelectByAnalysis(FeatureSelector):\n def __init__(self, selected_feature_number=0):\n super(FeatureSelectByAnalysis, self).__init__()\n self.__selected_feature_number = selected_feature_number\n\n def SetSelectedFeatureNumber(self, selected_feature_number):\n self.__selected_feature_number = selected_feature_number\n\n def GetSelectedFeatureNumber(self):\n return self.__selected_feature_number\n\n __metaclass__ = ABCMeta\n @abstractmethod\n def Run(self, data_container, store_folder):\n pass\n\n @abstractmethod\n def GetName(self):\n pass\n\n\nclass FeatureSelectByANOVA(FeatureSelectByAnalysis):\n def __init__(self, selected_feature_number=1):\n super(FeatureSelectByANOVA, self).__init__(selected_feature_number)\n\n def GetSelectedFeatureIndex(self, data_container):\n data = data_container.GetArray()\n data /= np.linalg.norm(data, ord=2, axis=0)\n label = data_container.GetLabel()\n\n if data.shape[1] < self.GetSelectedFeatureNumber():\n print('ANOVA: The number of features {:d} in data container is smaller than the required number {:d}'.format(\n data.shape[1], self.GetSelectedFeatureNumber()))\n self.SetSelectedFeatureNumber(data.shape[1])\n\n fs = SelectKBest(f_classif, k=self.GetSelectedFeatureNumber())\n fs.fit(data, label)\n feature_index = fs.get_support(True)\n f_value, p_value = f_classif(data, label)\n return feature_index.tolist(), f_value, p_value\n\n def GetName(self):\n return 'ANOVA'\n\n def GetDescription(self):\n text = \"Before build the model, we used analysis of variance (ANOVA) to select features. ANOVA was a common method \" \\\n \"to explore the significant features corresponding to the labels. F-value was calculated to evaluate the relationship \" \\\n \"between features and the label. We sorted features according to the corresponding F-value and selected sepcific \" \\\n \"number of features to build the model. \"\n return text\n\n def Run(self, data_container, store_folder=''):\n selected_index, f_value, p_value = self.GetSelectedFeatureIndex(data_container)\n new_data_container = self.SelectFeatureByIndex(data_container, selected_index, is_replace=False)\n if store_folder and os.path.isdir(store_folder):\n feature_store_path = os.path.join(store_folder, 'selected_feature.csv')\n featureinfo_store_path = os.path.join(store_folder, 'feature_select_info.csv')\n\n new_data_container.Save(feature_store_path)\n SaveSelectInfo(new_data_container, featureinfo_store_path, is_merge=False)\n\n anova_sort_path = os.path.join(store_folder, 'anova_sort.csv')\n df = pd.DataFrame(data=np.stack((f_value, p_value), axis=1), index=data_container.GetFeatureName(), columns=['F', 'P'])\n df.to_csv(anova_sort_path)\n\n return new_data_container\n\nclass FeatureSelectByRelief(FeatureSelectByAnalysis):\n def __init__(self, selected_feature_number=1, iter_ratio=1):\n super(FeatureSelectByRelief, self).__init__(selected_feature_number)\n self.__iter_radio = iter_ratio\n self._weight = None\n\n def __SortByValue(self, feature_score):\n feature_list = []\n sorted_feature_number_list = []\n for feature_index in range(len(feature_score)):\n feature_list_unit = []\n feature_list_unit.append(feature_score[feature_index])\n feature_list_unit.append(feature_index)\n feature_list.append(feature_list_unit)\n sorted_feature_list = sorted(feature_list, key=lambda x: abs(x[0]), reverse=True)\n for feature_index in range(len(sorted_feature_list)):\n sorted_feature_number_list.append(sorted_feature_list[feature_index][1])\n\n return sorted_feature_number_list\n\n def __DistanceNorm(self, Norm, D_value):\n # initialization\n\n # Norm for distance\n if Norm == '1':\n counter = np.absolute(D_value)\n counter = np.sum(counter)\n elif Norm == '2':\n counter = np.power(D_value, 2)\n counter = np.sum(counter)\n counter = np.sqrt(counter)\n elif Norm == 'Infinity':\n counter = np.absolute(D_value)\n counter = np.max(counter)\n else:\n raise Exception('We will program this later......')\n\n return counter\n\n def __SortByRelief(self, data_container):\n data = data_container.GetArray()\n data /= np.linalg.norm(data, ord=2, axis=0)\n label = data_container.GetLabel()\n\n # initialization\n (n_samples, n_features) = np.shape(data)\n distance = np.zeros((n_samples, n_samples))\n weight = np.zeros(n_features)\n\n if self.__iter_radio >= 0.5:\n # compute distance\n for index_i in range(n_samples):\n for index_j in range(index_i + 1, n_samples):\n D_value = data[index_i] - data[index_j]\n distance[index_i, index_j] = self.__DistanceNorm('2', D_value)\n distance += distance.T\n else:\n pass\n\n # start iteration\n\n for iter_num in range(int(self.__iter_radio * n_samples)):\n # print iter_num;\n # initialization\n nearHit = list()\n nearMiss = list()\n distance_sort = list()\n\n # random extract a sample\n index_i = iter_num\n self_features = data[index_i]\n\n # search for nearHit and nearMiss\n if self.__iter_radio >= 0.5:\n distance[index_i, index_i] = np.max(distance[index_i]) # filter self-distance\n for index in range(n_samples):\n distance_sort.append([distance[index_i, index], index, label[index]])\n else:\n # compute distance respectively\n distance = np.zeros(n_samples)\n for index_j in range(n_samples):\n D_value = data[index_i] - data[index_j]\n distance[index_j] = self.__DistanceNorm('2', D_value)\n distance[index_i] = np.max(distance) # filter self-distance\n for index in range(n_samples):\n distance_sort.append([distance[index], index, label[index]])\n distance_sort.sort(key=lambda x: x[0])\n for index in range(n_samples):\n if nearHit == [] and distance_sort[index][2] == label[index_i]:\n # nearHit = distance_sort[index][1];\n nearHit = data[distance_sort[index][1]]\n elif nearMiss == [] and distance_sort[index][2] != label[index_i]:\n # nearMiss = distance_sort[index][1]\n nearMiss = data[distance_sort[index][1]]\n elif nearHit != [] and nearMiss != []:\n break\n else:\n continue\n\n # update weight\n weight = weight - np.power(self_features - nearHit, 2) + np.power(self_features - nearMiss, 2)\n result = self.__SortByValue(weight / (self.__iter_radio * n_samples))\n self._weight = weight\n return result\n\n def GetSelectedFeatureIndex(self, data_container):\n feature_sort_list = self.__SortByRelief(data_container)\n if len(feature_sort_list) < self.GetSelectedFeatureNumber():\n print('Relief: The number of features {:d} in data container is smaller than the required number {:d}'.format(len(feature_sort_list), self.GetSelectedFeatureNumber()))\n self.SetSelectedFeatureNumber(len(feature_sort_list))\n selected_feature_index = feature_sort_list[:self.GetSelectedFeatureNumber()]\n return selected_feature_index\n\n def GetName(self):\n return 'Relief'\n\n def GetDescription(self):\n text = \"Before build the model, we used Relief to select features. Relief selects sub data set and find the \" \\\n \"relative features according to the label recursively. \"\n return text\n\n def Run(self, data_container, store_folder=''):\n new_data_container = self.SelectFeatureByIndex(data_container, self.GetSelectedFeatureIndex(data_container), is_replace=False)\n if store_folder and os.path.isdir(store_folder):\n feature_store_path = os.path.join(store_folder, 'selected_feature.csv')\n featureinfo_store_path = os.path.join(store_folder, 'feature_select_info.csv')\n\n relief_sort_path = os.path.join(store_folder, 'Relief_sort.csv')\n df = pd.DataFrame(data=self._weight, index=data_container.GetFeatureName(), columns=['weight'])\n df.to_csv(relief_sort_path)\n\n new_data_container.Save(feature_store_path)\n SaveSelectInfo(new_data_container, featureinfo_store_path, is_merge=False)\n return new_data_container\n\nclass FeatureSelectByRFE(FeatureSelectByAnalysis):\n def __init__(self, selected_feature_number=1, classifier=SVC(kernel='linear')):\n super(FeatureSelectByRFE, self).__init__(selected_feature_number)\n self.__classifier = classifier\n\n def GetDescription(self):\n text = \"Before build the model, we used recursive feature elimination (RFE) to select features. The goal of RFE \" \\\n \"is to select features based on a classifier by recursively considering smaller set of the features. \"\n return text\n\n def GetSelectedFeatureIndex(self, data_container):\n data = data_container.GetArray()\n data /= np.linalg.norm(data, ord=2, axis=0)\n label = data_container.GetLabel()\n\n if data.shape[1] < self.GetSelectedFeatureNumber():\n print('RFE: The number of features {:d} in data container is smaller than the required number {:d}'.format(\n data.shape[1], self.GetSelectedFeatureNumber()))\n self.SetSelectedFeatureNumber(data.shape[1])\n\n fs = RFE(self.__classifier, self.GetSelectedFeatureNumber(), step=0.05)\n fs.fit(data, label)\n feature_index = fs.get_support(True)\n ranks = fs.ranking_\n\n return feature_index.tolist(), ranks\n\n def GetName(self):\n return 'RFE'\n\n def Run(self, data_container, store_folder=''):\n selected_index, rank = self.GetSelectedFeatureIndex(data_container)\n new_data_container = self.SelectFeatureByIndex(data_container, selected_index, is_replace=False)\n if store_folder and os.path.isdir(store_folder):\n feature_store_path = os.path.join(store_folder, 'selected_feature.csv')\n featureinfo_store_path = os.path.join(store_folder, 'feature_select_info.csv')\n\n new_data_container.Save(feature_store_path)\n SaveSelectInfo(new_data_container, featureinfo_store_path, is_merge=False)\n\n rfe_sort_path = os.path.join(store_folder, 'RFE_sort.csv')\n df = pd.DataFrame(data=rank, index=data_container.GetFeatureName(), columns=['rank'])\n df.to_csv(rfe_sort_path)\n\n return new_data_container\n\nclass FeatureSelectByMrmr(FeatureSelectByAnalysis):\n def __init__(self, selected_feature_number=1):\n super(FeatureSelectByMrmr, self).__init__(selected_feature_number)\n self._hyper_parameter_manager = HyperParameterManager()\n\n def GetDescription(self):\n text = \"Before build the model, we used minimum-Redundancy-Maximum-Relevance (mRMR) to select features. The goal of mRMR \" \\\n \"is to select a feature subset set that best characterizes the statistical property of a target classification variable,\" \\\n \"subject to the constraint that these features are mutually as dissimilar to each other as possible, but marginally as similar to the classification variable as possible.\"\n return text\n\n def GetSelectedFeatureIndex(self, data_container):\n data = data_container.GetArray()\n data /= np.linalg.norm(data, ord=2, axis=0)\n label = data_container.GetLabel()\n\n if data.shape[1] < self.GetSelectedFeatureNumber():\n print('mMRM: The number of features {:d} in data container is smaller than the required number {:d}'.format(\n data.shape[1], self.GetSelectedFeatureNumber()))\n self.SetSelectedFeatureNumber(data.shape[1])\n\n feature_list = ['class'] + data_container.GetFeatureName()\n feature_index = []\n pd_label = pd.DataFrame(label)\n pd_data = pd.DataFrame(data)\n mRMR_input = pd.concat([pd_label, pd_data], axis=1)\n mRMR_input.columns = feature_list\n parameter_list = self.LoadFeatureSelectorParameterList(relative_path=r'HyperParameters\\FeatureSelector')\n feature_name = pymrmr.mRMR(mRMR_input, parameter_list[0]['mutual_information'], self.GetSelectedFeatureNumber())\n feature_list.remove('class')\n\n rank = []\n for index, item in enumerate(feature_name):\n feature_index.append(feature_list.index(item))\n rank.append(index)\n return feature_index, rank, feature_name\n\n def GetName(self):\n return 'mRMR'\n\n def LoadFeatureSelectorParameterList(self, relative_path=os.path.join('HyperParameters', 'FeatureSelector')):\n self._hyper_parameter_manager.LoadSpecificConfig(self.GetName(), relative_path=relative_path)\n parameter_list = self._hyper_parameter_manager.GetParameterSetting()\n return parameter_list\n\n def Run(self, data_container, store_folder=''):\n selected_index, rank, feature_name = self.GetSelectedFeatureIndex(data_container)\n new_data_container = self.SelectFeatureByIndex(data_container, selected_index, is_replace=False)\n if store_folder and os.path.isdir(store_folder):\n feature_store_path = os.path.join(store_folder, 'selected_feature.csv')\n featureinfo_store_path = os.path.join(store_folder, 'feature_select_info.csv')\n\n new_data_container.Save(feature_store_path)\n SaveSelectInfo(new_data_container, featureinfo_store_path, is_merge=False)\n\n mrmr_sort_path = os.path.join(store_folder, 'mMRM_sort.csv')\n df = pd.DataFrame(data=rank, index=feature_name, columns=['rank'])\n df.to_csv(mrmr_sort_path)\n\n return new_data_container\n\n################################################################\n\nclass FeatureSelectPipeline(FeatureSelector):\n def __init__(self, selector, selected_feature_number=0):\n if isinstance(selector, FeatureSelector):\n selector = [selector]\n self.__selector_list = selector\n self.__selected_feature_number = selected_feature_number\n\n def SetSelectedFeatureNumber(self, selected_feature_number):\n self.__selected_feature_number = selected_feature_number\n try:\n self.__selector_list[-1].SetSelectedFeatureNumber(selected_feature_number)\n except:\n print('The last selector does not have method SetSelectedFeatureNumber')\n\n def GetSelectedFeatureNumber(self):\n return self.__selected_feature_number\n\n def GetName(self):\n try:\n return self.__selector_list[-1].GetName()\n except:\n print('The last selector does not have method GetName')\n\n #TODO: Add verbose parameter to show the removed feature name in each selector\n def Run(self, data_container, store_folder=''):\n input_data_container = data_container\n for fs in self.__selector_list:\n output = fs.Run(input_data_container, store_folder)\n input_data_container = output\n return output\n\n################################################################\n\nif __name__ == '__main__':\n import os\n print(os.getcwd())\n from FAE.DataContainer.DataContainer import DataContainer\n data_container = DataContainer()\n print(os.path.abspath(r'..\\..\\Example\\numeric_feature.csv'))\n data_container.Load(r'..\\..\\Example\\numeric_feature.csv')\n # data_container.UsualNormalize()\n\n print(data_container.GetArray().shape)\n print(data_container.GetFeatureName())\n\n fs = FeatureSelectBySubName(['shape', 'ADC'])\n\n output = fs.Run(data_container)\n print(output.GetFeatureName())\n\n # fs1 = RemoveNonNumericFeature()\n # fs1.SetDataContainer(data_container)\n # non_number_data_container = fs1.Run()\n #\n # fs2 = FeatureSelectByANOVA(10)\n # fs2.SetDataContainer(non_number_data_container)\n # output = fs2.Run()\n\n # feature_selector_list = [RemoveNonNumericFeature(), RemoveCosSimilarityFeatures(), FeatureSelectByANOVA(5)]\n # feature_selector_pipeline = FeatureSelectPipeline(feature_selector_list)\n # feature_selector_pipeline.SetDataContainer(data_container)\n # output = feature_selector_pipeline.Run()\n\n print(output.GetArray().shape)\n"
] |
[
[
"pandas.concat",
"numpy.absolute",
"numpy.sqrt",
"sklearn.feature_selection.f_classif",
"numpy.unique",
"numpy.power",
"numpy.linalg.norm",
"pandas.DataFrame",
"numpy.stack",
"numpy.max",
"numpy.shape",
"sklearn.svm.SVC",
"numpy.zeros",
"numpy.sum"
]
] |
cdyangzhenyu/X2Paddle
|
[
"6d6d18e576bdea941180f29d30ca1a702192496d"
] |
[
"x2paddle/decoder/tf_decoder.py"
] |
[
"# Copyright (c) 2019 PaddlePaddle 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\nfrom x2paddle.core.graph import GraphNode, Graph\nfrom x2paddle.core.fluid_code import FluidCode\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.core.framework import attr_value_pb2\nimport tensorflow as tf\nimport copy as cp\nimport numpy\nimport sys\n\n\nclass TFGraphNode(GraphNode):\n def __init__(self, layer, layer_name=None, data_format=\"NHWC\"):\n if layer_name is None:\n super(TFGraphNode, self).__init__(\n layer,\n layer.name.replace('/', '_').replace('-', '_').replace('^', ''))\n else:\n super(TFGraphNode, self).__init__(\n layer,\n layer_name.replace('/', '_').replace('-', '_').replace('^', ''))\n\n self.layer_type = layer.op\n self.tf_data_format = data_format\n self.pd_data_format = \"NCHW\"\n self.fluid_code = FluidCode()\n\n self.dtype_map = {\n 1: \"float32\",\n 3: \"int32\",\n 4: \"uint8\",\n 9: \"int64\",\n 10: \"bool\"\n }\n\n @property\n def out_shapes(self):\n if self.layer_type == \"OneShotIterator\":\n values = self.layer.attr[\"output_shapes\"].list.shape\n else:\n values = self.layer.attr[\"_output_shapes\"].list.shape\n out_shapes = list()\n for value in values:\n shape = [dim.size for dim in value.dim]\n out_shapes.append(shape)\n return out_shapes\n\n @property\n def dtype(self):\n keys = ['dtype', 'Tidx', 'T', 'DstT']\n for k in keys:\n dtype = self.layer.attr[k].type\n if dtype > 0:\n break\n if dtype == 0:\n dtype = self.layer.attr['output_types'].list.type[0]\n if dtype not in self.dtype_map:\n raise Exception(\"Dtype[{}] not in dtype_map\".format(dtype))\n return self.dtype_map[dtype]\n\n @property\n def raw_dtype(self):\n keys = ['dtype', 'Tidx', 'T', 'DstT']\n for k in keys:\n dtype = self.layer.attr[k].type\n if dtype > 0:\n break\n return dtype\n\n @property\n def value(self):\n assert self.layer_type == \"Const\", \"Only Const node has value.\"\n\n attr = self.layer.attr['value']\n field = getattr(attr, attr.WhichOneof('value'))\n return tensor_util.MakeNdarray(field)\n\n def get_attr(self, name):\n if name not in self.layer.attr:\n return None\n attr = self.layer.attr[name]\n field = attr.WhichOneof('value')\n value = getattr(attr, field) if field else None\n\n if isinstance(value, attr_value_pb2.AttrValue.ListValue):\n result = list(value.ListFields()[0][1])\n for i in range(len(result)):\n if isinstance(result[i], int):\n result[i] = int(result[i])\n try:\n if isinstance(result[i], long):\n result[i] = int(result[i])\n except:\n pass\n return result\n else:\n return value\n\n\nclass TFGraph(Graph):\n def __init__(self, model, data_format=\"NHWC\"):\n super(TFGraph, self).__init__(model)\n self.identity_map = dict()\n self.multi_out_ops = ['Split', 'SplitV']\n self.tf_data_format = data_format\n\n def build(self):\n for layer in self.model.node:\n self.node_map[layer.name.replace('/', '_').replace(\n '-', '_')] = TFGraphNode(layer, data_format=self.tf_data_format)\n\n for layer_name, node in self.node_map.items():\n for in_node in node.layer.input:\n in_node = in_node.replace('/',\n '_').replace('-',\n '_').replace('^', '')\n if in_node not in self.node_map:\n if in_node.strip().split(':')[0] in self.node_map:\n self.connect(in_node.strip().split(':')[0], layer_name)\n else:\n raise Exception(\n 'input[{}] of node[{}] does not exist in node_map'.\n format(in_node, layer_name))\n else:\n self.connect(in_node, layer_name)\n\n super(TFGraph, self).build()\n\n # tensorflow graph optimize\n self._remove_isolated_node()\n self._optimize_dialiation_conv()\n self._remove_identity_node()\n self._remove_cast_node()\n\n def get_node(self, node_name, copy=False):\n items = node_name.strip().split(':')\n items[0] = items[0].replace('/', '_').replace('-', '_')\n if items[0] in self.identity_map:\n items[0] = self.identity_map[items[0]]\n new_node_name = \":\".join(items)\n node = super(TFGraph, self).get_node(new_node_name, copy)\n if node is None:\n return None\n if node.layer_type == \"Switch\":\n if hasattr(node, 'index'):\n del node.index\n if len(items) == 1 and node.layer_type in self.multi_out_ops:\n node.index = 0\n return node\n\n def remove_node(self, node_name):\n if node_name not in self.node_map:\n raise Exception(\"Node[{}] not in graph\".format(node_name))\n inputs = self.node_map[node_name].inputs\n outputs = self.node_map[node_name].outputs\n # assert len(inputs) == 1\n input_node = self.node_map[inputs[0]]\n idx = input_node.outputs.index(node_name)\n del input_node.outputs[idx]\n for output in outputs:\n node = self.node_map[output]\n idx = node.inputs.index(node_name)\n node.inputs[idx] = inputs[0]\n input_node.outputs.append(output)\n\n del self.node_map[node_name]\n\n idx = self.topo_sort.index(node_name)\n del self.topo_sort[idx]\n\n def _optimize_dialiation_conv(self):\n for name in list(self.node_map.keys()):\n node = self.node_map[name]\n if node.layer_type == \"SpaceToBatchND\":\n is_dilation = True\n out_node0 = self.node_map[node.outputs[0]]\n if out_node0.layer_type != 'ExpandDims':\n is_dilation = False\n continue\n out_node1 = self.node_map[out_node0.outputs[0]]\n if out_node1.layer_type != 'Conv2D':\n is_dilation = False\n continue\n out_node2 = self.node_map[out_node1.outputs[0]]\n if out_node2.layer_type != 'Squeeze':\n is_dilation = False\n continue\n out_node3 = self.node_map[out_node2.outputs[0]]\n if out_node3.layer_type != 'BatchToSpaceND':\n is_dilation = False\n continue\n\n if is_dilation:\n node.skip = True\n out_node3.skip = True\n block_shape = self.node_map[node.inputs[1]]\n out_node1.dilation = block_shape.value.tolist()\n\n def _remove_isolated_node(self):\n # delete isolated nodes\n isolated_nodes = list()\n for node_name in self.node_map.keys():\n if len(self.get_node(node_name).inputs) == 0 and len(\n self.get_node(node_name).outputs) == 0:\n isolated_nodes.append(node_name)\n\n for node_name in isolated_nodes:\n del self.node_map[node_name]\n if node_name in self.input_nodes:\n idx = self.input_nodes.index(node_name)\n del self.input_nodes[idx]\n if node_name in self.output_nodes:\n idx = self.output_nodes.index(node_name)\n del self.output_nodes[idx]\n idx = self.topo_sort.index(node_name)\n del self.topo_sort[idx]\n\n def _remove_identity_node(self):\n identity_ops = [\n 'Identity', 'StopGradient', 'Switch', 'Merge',\n 'PlaceholderWithDefault', 'IteratorGetNext'\n ]\n identity_node = list()\n for node_name, node in self.node_map.items():\n if node.layer_type in identity_ops:\n identity_node.append(node_name)\n\n for node_name in identity_node:\n node = self.get_node(node_name)\n input_node = self.get_node(node.inputs[0])\n self.remove_node(node_name)\n\n self.identity_map[node_name] = input_node.layer_name\n\n if node_name in self.output_nodes:\n idx = self.output_nodes.index(node_name)\n self.output_nodes[idx] = input_node.layer_name\n\n def _remove_cast_node(self):\n cast_node = list()\n for node_name, node in self.node_map.items():\n if node.layer_type == \"Cast\":\n input = self.get_node(node.inputs[0])\n if input.layer_type != \"Placeholder\" or len(input.outputs) != 1:\n continue\n cast_node.append(node_name)\n\n for node_name in cast_node:\n node = self.get_node(node_name)\n input_node = self.get_node(node.inputs[0])\n input_node.layer.attr[\"dtype\"].type = node.raw_dtype\n self.remove_node(node_name)\n\n self.identity_map[node_name] = input_node.layer_name\n\n if node_name in self.output_nodes:\n idx = self.output_nodes.index(node_name)\n self.output_nodes[idx] = input_node.layer_name\n\n def data_format_propagation(self, node):\n current_node = self.node_map[node.layer_name]\n current_node = node.tf_data_format\n outputs = current_node.outputs\n if len(outputs) == 0:\n return\n for out in outputs:\n next_node = self.node_map[out]\n next_node.tf_data_format = node.tf_data_format\n self.data_format_propagation(next_node)\n\n\nclass TFDecoder(object):\n def __init__(self, pb_model, data_format=\"NHWC\", define_input_shape=False):\n try:\n self.sess = tf.compat.v1.Session()\n except:\n self.sess = tf.Session()\n self.input_info = dict()\n self.define_input_shape = define_input_shape\n with open(pb_model, 'rb') as f:\n try:\n graph_def = tf.compat.v1.GraphDef()\n except:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n input_map = self._check_input_shape(graph_def)\n self._fix_output_shape(graph_def)\n self.sess.graph.as_default()\n tf.import_graph_def(graph_def, name='', input_map=input_map)\n\n try:\n initializer = tf.compat.v1.global_variables_initializer()\n except:\n initializer = tf.global_variables_initializer()\n self.sess.run(initializer)\n\n self.tf_graph = TFGraph(\n self.sess.graph._as_graph_def(add_shapes=True)[0], data_format)\n self.tf_graph.build()\n\n def _fix_output_shape(self, graph):\n for i in range(len(graph.node)):\n node = graph.node[i]\n if node.op == \"swish_f32\":\n graph.node[i].attr['_disable_call_shape_inference'].b = False\n\n def _check_input_shape(self, graph_def):\n numpy.random.seed(13)\n graph_def = cp.deepcopy(graph_def)\n input_map = dict()\n for layer in graph_def.node:\n if layer.op != \"Placeholder\" and layer.op != \"OneShotIterator\":\n continue\n graph_node = TFGraphNode(layer)\n dtype = graph_node.layer.attr['dtype'].type\n\n need_define_shape = 0\n if self.define_input_shape:\n need_define_shape = 3\n elif graph_node.layer.attr[\n 'shape'].shape.unknown_rank or not graph_node.get_attr(\n \"shape\"):\n need_define_shape = 1\n else:\n value = graph_node.layer.attr[\"shape\"].shape\n shape = [dim.size for dim in value.dim]\n if shape.count(-1) > 1:\n need_define_shape = 2\n\n if need_define_shape == 1:\n try:\n shape = graph_node.out_shapes[0]\n if len(shape) > 0 and shape.count(-1) < 2:\n need_define_shape = 0\n except:\n pass\n\n if need_define_shape > 0:\n shape = None\n if graph_node.get_attr(\"shape\"):\n value = value = graph_node.layer.attr[\"shape\"].shape\n shape = [dim.size for dim in value.dim]\n if need_define_shape == 1:\n print(\"Unknown shape for input tensor[tensor name: \\\"{}\\\"]\".\n format(layer.name))\n elif need_define_shape == 2:\n print(\n \"\\nShape[now is {}] for input tensor[tensor name: \\\"{}\\\"] not support yet\"\n .format(shape, layer.name))\n else:\n print(\n \"Define shape[now is {}] for input tensor[tensor name: \\\"{}\\']\"\n .format(shape, layer.name))\n print(\n \"Use your keyboard type the shape of input tensor below :)\")\n\n right_shape_been_input = False\n while not right_shape_been_input:\n try:\n shape = raw_input(\n \"Shape of Input(e.g. None,224,224,3): \")\n except:\n shape = input(\"Shape of Input(e.g. None,224,224,3): \")\n if shape.count(\"None\") > 1:\n print(\"Only 1 dimension can be None, type again:)\")\n else:\n right_shape_been_input = True\n\n shape = [\n None if dim == \"None\" else int(dim)\n for dim in shape.strip().split(',')\n ]\n assert shape.count(None) <= 1, \"Only one dimension can be None\"\n try:\n x2paddle_input = tf.compat.v1.placeholder(\n dtype=dtype,\n shape=shape,\n name=\"x2paddle_{}\".format(layer.name))\n except:\n x2paddle_input = tf.placeholder(dtype=dtype,\n shape=shape,\n name=\"x2paddle_{}\".format(\n layer.name))\n\n input_map[\"{}:0\".format(layer.name)] = x2paddle_input\n if shape.count(None) > 0:\n shape[shape.index(None)] = -1\n self.input_info[\"x2paddle_{}\".format(layer.name)] = (shape,\n dtype)\n else:\n value = graph_node.layer.attr[\"shape\"].shape\n shape = [dim.size for dim in value.dim]\n self.input_info[graph_node.layer_name] = (shape, dtype)\n\n return input_map\n\n # trick method\n # should be removed after PaddlePaddle V1.6 been released\n def infer_tensor(self, graph_node):\n if hasattr(graph_node, \"index\"):\n tensor_name = graph_node.layer.name + \":{}\".format(graph_node.index)\n else:\n tensor_name = graph_node.layer.name + \":0\"\n feed = dict()\n for input_name, info in self.input_info.items():\n (shape, dtype) = cp.deepcopy(info)\n input_tensor = self.sess.graph.get_tensor_by_name(input_name + \":0\")\n if shape.count(-1) > 0:\n shape[shape.index(-1)] = 2\n feed[input_tensor] = numpy.random.random_sample(shape)\n output_tensor = self.sess.graph.get_tensor_by_name(tensor_name)\n return self.sess.run([output_tensor], feed)[0]\n\n def infer_shape_tensor(self, graph_node, out_shape=None):\n if hasattr(graph_node, \"index\"):\n tensor_name = graph_node.layer.name + \":{}\".format(graph_node.index)\n else:\n tensor_name = graph_node.layer.name + \":0\"\n feed = dict()\n batch_size = [2, 3, 5]\n results = list()\n for b in batch_size:\n for input_name, info in self.input_info.items():\n (shape, dtype) = cp.deepcopy(info)\n input_tensor = self.sess.graph.get_tensor_by_name(input_name +\n \":0\")\n if shape.count(-1) > 0:\n shape[shape.index(-1)] = b\n feed[input_tensor] = numpy.random.random_sample(shape)\n output_tensor = self.sess.graph.get_tensor_by_name(tensor_name)\n results.append(self.sess.run([output_tensor], feed)[0].flatten())\n\n compare01 = (results[0] == results[1])\n compare12 = (results[1] == results[2])\n\n if compare01.all() and compare12.all():\n return results[0].tolist()\n\n if (compare01 == compare12).all():\n index = numpy.argwhere(compare01 == False).flatten()\n if index.shape[0] != 1:\n raise Exception(\"There's not only one unstable dimension\")\n results[0][index[0]] = -1\n\n index = numpy.argwhere(results[0] < 0).flatten()\n if index.shape[0] > 2:\n print(\"Warning: More than two dimension less than zero\")\n if index.shape[0] == 2 and out_shape is not None:\n if out_shape[index[1]] > 0:\n results[0][index[1]] = out_shape[index[1]]\n else:\n results[0][index[0]] = out_shape[index[0]]\n return results[0].tolist()\n else:\n raise Exception(\"Couldn't infer a stable shape shape tensor value\")\n\n def infer_tensor_shape(self, graph_node):\n if hasattr(graph_node, \"index\"):\n tensor_name = graph_node.layer.name + \":{}\".format(graph_node.index)\n else:\n tensor_name = graph_node.layer.name + \":0\"\n feed = dict()\n batch_size = [2, 3, 5]\n shapes = list()\n for b in batch_size:\n for input_name, info in self.input_info.items():\n (shape, dtype) = cp.deepcopy(info)\n input_tensor = self.sess.graph.get_tensor_by_name(input_name +\n \":0\")\n if shape.count(-1) > 0:\n shape[shape.index(-1)] = b\n feed[input_tensor] = numpy.random.random_sample(shape)\n output_tensor = self.sess.graph.get_tensor_by_name(tensor_name)\n shape = self.sess.run([output_tensor], feed)[0].shape\n shapes.append(numpy.array(shape))\n\n compare01 = (shapes[0] == shapes[1])\n compare12 = (shapes[1] == shapes[2])\n\n if compare01.all() and compare12.all():\n return shape[0].tolist()\n\n if (compare01 == compare12).all():\n index = numpy.argwhere(compare01 == False).flatten()\n if index.shape[0] != 1:\n raise Exception(\"There's not only one unstable dimension\")\n if index[0] != 0:\n raise Exception(\"Batch size not in the first dimension\")\n shapes[0][0] = -1\n return shapes[0].tolist()\n"
] |
[
[
"tensorflow.python.framework.tensor_util.MakeNdarray",
"tensorflow.import_graph_def",
"numpy.random.seed",
"numpy.random.random_sample",
"tensorflow.compat.v1.global_variables_initializer",
"tensorflow.compat.v1.Session",
"tensorflow.global_variables_initializer",
"numpy.argwhere",
"tensorflow.Session",
"tensorflow.compat.v1.GraphDef",
"tensorflow.GraphDef",
"numpy.array"
]
] |
dsanno/chainer-neural-style
|
[
"2424ff10d7fd3fb8d838874df6f706ab1fb41edb"
] |
[
"src/image_analogy.py"
] |
[
"import argparse\nimport numpy as np\nfrom scipy import linalg\nfrom PIL import Image\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Transfer image using Image Analogy color transfer')\n parser.add_argument('style_image', type=str, help='Style image file path')\n parser.add_argument('content_image', type=str, help='Content image file path')\n parser.add_argument('output_image', type=str, help='Output image file path')\n args = parser.parse_args()\n\n xs = np.asarray(Image.open(args.style_image).convert('RGB'), dtype=np.float32)\n xc = np.asarray(Image.open(args.content_image).convert('RGB'), dtype=np.float32)\n style_shape = xs.shape\n\n xs = xs.reshape((-1, 3)).transpose((1, 0))\n xs_mean = np.mean(xs, axis=1, keepdims=True)\n xs_var = np.cov(xs)\n d, v = linalg.eig(xs_var)\n sigma_style_inv = v.dot(np.diag(d ** (-0.5))).dot(v.T)\n\n xc = xc.reshape((-1, 3)).transpose((1, 0))\n xc_mean = np.mean(xc, axis=1, keepdims=True)\n xc_var = np.cov(xc)\n d, v = linalg.eig(xc_var)\n sigma_content = v.dot(np.diag(d ** 0.5)).dot(v.T)\n\n a = sigma_content.dot(sigma_style_inv)\n b = xc_mean - a.dot(xs_mean)\n xs2 = a.dot(xs) + b\n xs2 = xs2.transpose((1, 0)).reshape(style_shape).real.clip(0, 255).astype(np.uint8)\n\n Image.fromarray(xs2).save(args.output_image)\n"
] |
[
[
"numpy.diag",
"numpy.cov",
"numpy.mean",
"scipy.linalg.eig"
]
] |
ZhaomingXie/RLAlg
|
[
"dff9fc9be9417797ded428fc706cd779e638f7bf"
] |
[
"model.py"
] |
[
"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport torch.multiprocessing as mp\nfrom torch.distributions import Normal, Categorical\nimport math\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nclass ActorCriticNet(nn.Module):\n def __init__(self, num_inputs, num_outputs, hidden_layer=[64, 64], num_contact=0):\n super(ActorCriticNet, self).__init__()\n self.num_outputs = num_outputs\n self.hidden_layer = hidden_layer\n self.p_fcs = nn.ModuleList()\n self.v_fcs = nn.ModuleList()\n self.hidden_layer_v = [256, 256, 256, 256, 256, 256]\n if (len(hidden_layer) > 0):\n p_fc = nn.Linear(num_inputs, self.hidden_layer[0])\n v_fc = nn.Linear(num_inputs, self.hidden_layer_v[0])\n self.p_fcs.append(p_fc)\n self.v_fcs.append(v_fc)\n for i in range(len(self.hidden_layer)-1):\n p_fc = nn.Linear(self.hidden_layer[i], self.hidden_layer[i+1])\n v_fc = nn.Linear(self.hidden_layer_v[i], self.hidden_layer_v[i+1])\n self.p_fcs.append(p_fc)\n self.v_fcs.append(v_fc)\n self.mu = nn.Linear(self.hidden_layer[-1], num_outputs)\n else:\n #p_fc = nn.Linear(num_inputs, num_outputs)\n #self.p_fcs.append(p_fc)\n self.mu = nn.Linear(num_inputs, num_outputs)\n self.log_std = nn.Parameter(torch.zeros(num_outputs),requires_grad=True)\n self.v = nn.Linear(self.hidden_layer_v[-1],1)\n self.noise = 0\n #self.train()\n\n def forward(self, inputs):\n # actor\n if len(self.hidden_layer) > 0:\n x = F.relu(self.p_fcs[0](inputs))\n for i in range(len(self.hidden_layer)-1):\n x = F.relu(self.p_fcs[i+1](x))\n mu = torch.tanh(self.mu(x))\n else:\n mu = torch.tanh(self.mu(inputs))\n log_std = Variable(self.noise*torch.ones(self.num_outputs)).unsqueeze(0).expand_as(mu)\n\n # critic\n x = F.relu(self.v_fcs[0](inputs))\n for i in range(len(self.hidden_layer)-1):\n x = F.relu(self.v_fcs[i+1](x))\n v = self.v(x)\n #print(mu)\n return mu, log_std, v\n\n def get_log_stds(self, actions):\n return Variable(torch.Tensor(self.noise)*torch.ones(self.num_outputs)).unsqueeze(0).expand_as(actions)\n #return self.log_std.unsqueeze(0).expand_as(actions)\n\n def sample_best_actions(self, inputs):\n x = F.relu(self.p_fcs[0](inputs))\n for i in range(len(self.hidden_layer)-1):\n x = F.relu(self.p_fcs[i+1](x))\n mu = F.tanh(self.mu(x))\n return mu\n\n def sample_actions(self, inputs):\n mu = self.sample_best_actions(inputs)\n log_std = self.get_log_stds(mu)\n #std = torch.exp(log_std)\n eps = torch.randn(mu.size())\n actions = torch.clamp(mu + log_std.exp()*(eps), -1, 1)\n return actions\n\n def set_noise(self, noise):\n self.noise = noise\n\n def get_action(self, inputs):\n x = F.relu(self.p_fcs[0](inputs))\n for i in range(len(self.hidden_layer)-1):\n x = F.relu(self.p_fcs[i+1](x))\n mu = F.tanh(self.mu(x))\n log_std = Variable(self.noise*torch.ones(self.num_outputs)).unsqueeze(0).expand_as(mu)\n return mu, log_std\n\n def get_value(self, inputs, device=\"cpu\"):\n x = F.relu(self.v_fcs[0](inputs))\n for i in range(len(self.hidden_layer)-1):\n x = F.relu(self.v_fcs[i+1](x))\n v = self.v(x)\n return v\n def calculate_prob_gpu(self, inputs, actions):\n log_stds = self.get_log_stds(actions).to(device)\n #print(log_stds.shape)\n mean_actions = self.sample_best_actions(inputs)\n #print(mean_actions.shape)\n #w = self.get_w(inputs).to(device)\n numer = ((actions - mean_actions) / (log_stds.exp())).pow(2)\n log_probs = (-0.5 * numer).sum(dim=-1) - log_stds.sum(dim=-1)\n #print(log_probs)\n #probs = (log_probs.exp() * w.t()).sum(dim=0).log()\n #print(probs)\n return log_probs\n\n def calculate_prob(self, inputs, actions):\n log_stds = self.get_log_stds(actions)\n #print(log_stds.shape)\n mean_actions = self.sample_best_actions(inputs)\n #print(mean_actions.shape)\n #w = self.get_w(inputs).to(device)\n numer = ((actions - mean_actions) / (log_stds.exp())).pow(2)\n log_probs = (-0.5 * numer).sum(dim=-1) - log_stds.sum(dim=-1)\n #print(log_probs)\n #probs = (log_probs.exp() * w.t()).sum(dim=0).log()\n #print(probs)\n return log_probs\n\nclass ActorCriticNetMixtureExpert(nn.Module):\n def __init__(self, num_inputs, num_outputs, hidden_layer=[64, 64], v_hidden_layer=[256, 256], w_hidden_layer=[256, 256], num_expert=1, num_contact=0):\n super(ActorCriticNetMixtureExpert, self).__init__()\n self.num_outputs = num_outputs\n self.num_inputs = num_inputs\n self.num_expert = num_expert\n self.hidden_layer = hidden_layer\n self.v_hidden_layer = v_hidden_layer\n self.w_hidden_layer = w_hidden_layer\n self.experts = nn.ModuleList()\n for i in range(num_expert):\n expert_i = ActorCriticNet(num_inputs, num_outputs, hidden_layer)\n self.experts.append(expert_i)\n\n # self.v_fcs = nn.ModuleList()\n # v_fc = nn.Linear(num_inputs, self.v_hidden_layer[0])\n # self.v_fcs.append(v_fc)\n # for i in range(len(self.v_hidden_layer)-1):\n # v_fc = nn.Linear(self.v_hidden_layer[i], self.v_hidden_layer[i+1])\n # self.v_fcs.append(v_fc)\n # self.v = nn.Linear(self.v_hidden_layer[-1],1)\n\n self.w_fcs = nn.ModuleList()\n w_fc = nn.Linear(num_inputs, self.w_hidden_layer[0])\n self.w_fcs.append(w_fc)\n for i in range(len(self.w_hidden_layer)-1):\n w_fc = nn.Linear(self.w_hidden_layer[i], self.w_hidden_layer[i+1])\n self.w_fcs.append(w_fc)\n self.w = nn.Linear(self.w_hidden_layer[-1], num_expert)\n self.noise = -1\n self.log_std = nn.Parameter(torch.zeros(num_outputs),requires_grad=True)\n\n def get_value(self, inputs, device=\"cpu\"):\n values = []\n for i in range(self.num_expert):\n value = self.experts[i].get_value(inputs)\n values.append(value)\n w = self.get_w(inputs)\n categorical = Categorical(w)\n pis = list(categorical.sample().data)\n return_v = torch.zeros(inputs.shape[0], 1)\n for i, j in enumerate(pis):\n return_v[i] = (values[j][i])\n return return_v.to(device)\n\n def forward(self, inputs):\n actions = self.get_mean_actions(inputs)\n \n # critic\n v = self.get_value(inputs)\n\n # w\n w = self.get_w(inputs)\n return actions, v, w\n\n def get_mean_actions(self, inputs):\n actions = []\n for i in range(self.num_expert):\n a = self.experts[i].get_action(inputs)[0]\n actions.append(a)\n #print(actions[0].shape)\n return actions\n\n def get_w(self, inputs):\n x = F.relu(self.w_fcs[0](inputs))\n for i in range(len(self.w_hidden_layer)-1):\n x = F.relu(self.w_fcs[i+1](x))\n w = self.w(x)\n #w = torch.ones(inputs.size()[0], self.num_expert)\n w = F.softmax(w, dim=-1)\n #print(w)\n return w\n\n def sample_actions(self, inputs):\n actions = self.get_mean_actions(inputs)\n #print(\"list\", actions)\n w = self.get_w(inputs)\n categorical = Categorical(w)\n pis = list(categorical.sample().data)\n #print(pis)\n log_std = self.get_log_stds(actions[0])#Variable(self.noise*torch.ones(self.num_outputs)).unsqueeze(0).expand_as(actions[0])\n #print(log_std)\n std = torch.exp(log_std)\n sample = Variable(std.data.new(std.size(0), std.size(1)).normal_())\n for i, j in enumerate(pis):\n sample[i] = sample[i].mul(std[i]).add(actions[j][i])\n #sample[:, 0:3] *= 0\n #sample[:, 11:17] *= 0\n #print(\"sample\", sample) \n return sample\n\n def sample_best_actions(self, inputs):\n actions = self.get_mean_actions(inputs)\n w = self.get_w(inputs)\n log_std = self.get_log_stds(actions[0])#log_stds = self.noise * torch.ones(self.num_outputs).expand_as(actions[0])\n #print(log_std)\n eps = torch.randn(actions[0].size())\n values, indices = torch.max(w, 1)\n #print(values ,indices)\n return actions[indices]# + eps * log_stds.exp()\n\n def calculate_prob(self, inputs, actions):\n log_stds = self.get_log_stds(actions)\n #print(log_stds.shape)\n mean_actions = torch.stack(self.get_mean_actions(inputs))\n #print(mean_actions.shape)\n w = self.get_w(inputs)\n numer = ((actions - mean_actions) / (log_stds.exp())).pow(2)\n log_probs = (-0.5 * numer).sum(dim=-1) - log_stds.sum(dim=-1)\n #print(log_probs)\n probs = (log_probs.exp() * w.t()).sum(dim=0).log()\n #probs = log_probs.sum(dim=0)\n return probs\n\n def calculate_prob_gpu(self, inputs, actions):\n log_stds = self.get_log_stds(actions).to(device)\n #print(log_stds.shape)\n mean_actions = torch.stack(self.get_mean_actions(inputs))\n #print(mean_actions.shape)\n w = self.get_w(inputs).to(device)\n numer = ((actions - mean_actions) / (log_stds.exp())).pow(2)\n log_probs = (-0.5 * numer).sum(dim=-1) - log_stds.sum(dim=-1)\n #print(log_probs)\n probs = (log_probs.exp() * w.t()).sum(dim=0).log()\n return probs\n\n def get_log_stds(self, actions):\n return Variable(torch.Tensor(self.noise)*torch.ones(self.num_outputs)).unsqueeze(0).expand_as(actions)\n\n #return self.log_std.unsqueeze(0).expand_as(actions)\n\n def get_actions_difference(self, inputs):\n actions = self.get_mean_actions(inputs)\n difference_matrix = torch.zeros(self.num_expert, self.num_expert)\n for i in range(self.num_expert):\n for j in range(self.num_expert):\n difference_matrix[i, j] = torch.max((actions[i]-actions[j])**2)\n return difference_matrix\n\n def set_noise(self, noise):\n self.noise = noise\n\nclass ActorCriticNetWithContact(ActorCriticNetMixtureExpert):\n def __init__(self, num_inputs, num_outputs, hidden_layer=[64, 64], v_hidden_layer=[256, 256], w_hidden_layer=[256, 256], num_contact=1):\n self.num_contact = num_contact\n num_expert = self.num_contact**2\n super().__init__(num_inputs, num_outputs, hidden_layer=hidden_layer, v_hidden_layer=v_hidden_layer, w_hidden_layer=w_hidden_layer, num_expert=num_expert)\n def get_w(self, inputs):\n # x = F.relu(self.w_fcs[0](inputs))\n # for i in range(len(self.w_hidden_layer)-1):\n # x = F.relu(self.w_fcs[i+1](x))\n # w = self.w(x)\n # #w = torch.ones(inputs.size()[0], self.num_expert)\n # w = F.softmax(w, dim=-1)\n #print(w)\n w = torch.ones(inputs.size()[0], self.num_expert)\n #print(w.shape)\n if self.num_expert == 2:\n w[:, 0] = (inputs[:, -1] > 0.1)\n w[:, 1] = (inputs[:, -1] < 0.1)\n elif self.num_expert == 4:\n #print(inputs[:, -1].shape)\n w[:, 0] = ((inputs[:, -1] > 0.1) & (inputs[:, -2] > 0.1))\n w[:, 1] = ((inputs[:, -1] > 0.1) & (inputs[:, -2] < 0.1))\n w[:, 2] = ((inputs[:, -1] < 0.1) & (inputs[:, -2] > 0.1))\n w[:, 3] = ((inputs[:, -1] < 0.1) & (inputs[:, -2] < 0.1))\n w.float()\n return w\n\n\nclass ActorNet(nn.Module):\n def __init__(self, num_inputs, num_outputs, hidden_layer=[64, 64]):\n super(ActorNet, self).__init__()\n self.num_outputs = num_outputs\n self.hidden_layer = hidden_layer\n self.p_fcs = nn.ModuleList()\n self.log_stds = nn.ModuleList()\n p_fc = nn.Linear(num_inputs, self.hidden_layer[0])\n log_std = nn.Linear(num_inputs, self.hidden_layer[0])\n self.p_fcs.append(p_fc)\n self.log_stds.append(log_std)\n for i in range(len(self.hidden_layer)-1):\n p_fc = nn.Linear(self.hidden_layer[i], self.hidden_layer[i+1])\n log_std = nn.Linear(self.hidden_layer[i], self.hidden_layer[i+1])\n self.p_fcs.append(p_fc)\n self.log_stds.append(log_std)\n self.mu = nn.Linear(self.hidden_layer[-1], num_outputs)\n self.log_std = nn.Parameter(torch.zeros(num_outputs),requires_grad=True)\n self.noise = -2.0\n self.noises = torch.Tensor(num_outputs)\n self.log_std_linear = nn.Linear(num_inputs, num_outputs)\n def forward(self, inputs):\n # actor\n x = F.relu(self.p_fcs[0](inputs))\n #log_std = F.relu(self.log_stds[0](inputs))\n for i in range(len(self.hidden_layer)-1):\n x = F.relu(self.p_fcs[i+1](x))\n #log_std = F.relu(self.log_stds[i+1](log_std))\n #print(self.mu(x))\n mu = F.softsign(self.mu(x))\n #print(mu)\n log_std = Variable(self.noise * torch.ones(self.num_outputs)).unsqueeze(0).expand_as(mu)\n #log_std.to(device)\n #log_std = torch.tanh((self.log_std_linear(inputs)))\n #log_std = torch.clamp(log_std, min=-2, max=2)\n return mu, log_std\n def sample_gpu(self, inputs):\n mean, log_std = self.forward(inputs)\n #mean.to(device)\n std = log_std.exp().to(device)\n eps = torch.randn(mean.shape).to(device)\n normal = Normal(mean, std)\n #action = normal.rsample()\n action = (mean + (std * eps).clamp(-0.5, 0.5)).clamp(-1.0, 1.0)#torch.clamp(normal.rsample(), -1.0, 1.0)\n return (action), 0, (mean), 0\n def sample(self, inputs):\n mean, log_std = self.forward(inputs)\n #mean.to(device)\n std = log_std.exp()\n eps = torch.randn(mean.shape)\n normal = Normal(mean, std)\n #action = normal.rsample()\n action = (mean + (std * eps).clamp(-0.5, 0.5)).clamp(-1.0, 1.0)#torch.clamp(normal.rsample(), -1.0, 1.0)\n return (action), 0, (mean), 0\n def set_noise(self, noise):\n self.noise = noise\n\nclass ValueNet(nn.Module):\n def __init__(self, num_inputs, hidden_layer=[64, 64]):\n super(ValueNet, self).__init__()\n self.hidden_layer = hidden_layer\n self.v_fcs = nn.ModuleList()\n v_fc = nn.Linear(num_inputs, self.hidden_layer[0])\n self.v_fcs.append(v_fc)\n for i in range(len(self.hidden_layer)-1):\n v_fc = nn.Linear(self.hidden_layer[i], self.hidden_layer[i+1])\n self.v_fcs.append(v_fc)\n self.v = nn.Linear(self.hidden_layer[-1],1)\n def forward(self, inputs):\n # critic\n x = F.relu(self.v_fcs[0](inputs))\n for i in range(len(self.hidden_layer)-1):\n x = F.relu(self.v_fcs[i+1](x))\n v = self.v(x)\n #print(mu)\n return v\n\nclass QNet(nn.Module):\n def __init__(self, num_inputs, num_outputs, hidden_layer=[64, 64]):\n super(QNet, self).__init__()\n self.hidden_layer = hidden_layer\n self.num_outputs = num_outputs\n self.q_fcs1 = nn.ModuleList()\n self.q_fcs2 = nn.ModuleList()\n q_fc1 = nn.Linear(num_inputs + num_outputs, self.hidden_layer[0])\n q_fc2 = nn.Linear(num_inputs + num_outputs, self.hidden_layer[0])\n self.q_fcs1.append(q_fc1)\n self.q_fcs2.append(q_fc2)\n for i in range(len(self.hidden_layer)-1):\n q_fc1 = nn.Linear(self.hidden_layer[i], self.hidden_layer[i+1])\n q_fc2 = nn.Linear(self.hidden_layer[i], self.hidden_layer[i+1])\n self.q_fcs1.append(q_fc1)\n self.q_fcs2.append(q_fc2)\n self.q_1 = nn.Linear(self.hidden_layer[-1],1)\n self.q_2 = nn.Linear(self.hidden_layer[-1],1)\n def forward(self, states, actions):\n inputs = torch.cat([states, actions], 1)\n q1 = F.relu(self.q_fcs1[0](inputs))\n q2 = F.relu(self.q_fcs2[0](inputs))\n for i in range(len(self.hidden_layer)-1):\n q1 = F.relu(self.q_fcs1[i+1](q1))\n q2 = F.relu(self.q_fcs2[i+1](q2))\n q1 = (self.q_1(q1))\n q2 = (self.q_2(q2))\n return q1, q2\n\n\nclass Shared_grad_buffers():\n def __init__(self, model):\n self.grads = {}\n for name, p in model.named_parameters():\n self.grads[name+'_grad'] = torch.ones(p.size()).share_memory_()\n\n def add_gradient(self, model):\n for name, p in model.named_parameters():\n self.grads[name+'_grad'] += p.grad.data\n\n def reset(self):\n for name,grad in self.grads.items():\n self.grads[name].fill_(0)\n\nclass Shared_obs_stats():\n def __init__(self, num_inputs):\n self.n = torch.zeros(num_inputs).share_memory_()\n self.mean = torch.zeros(num_inputs).share_memory_()\n self.mean_diff = torch.zeros(num_inputs).share_memory_()\n self.std = torch.ones(num_inputs).share_memory_()\n self.num_inputs = num_inputs\n self.sum = torch.zeros(num_inputs).share_memory_()\n self.sum_sqr = torch.zeros(num_inputs).share_memory_()\n\n def observes(self, obs):\n # observation mean var updates\n x = obs.data.squeeze()\n if True:\n self.n += 1.\n last_mean = self.mean.clone()\n self.sum = self.sum + x\n self.sum_sqr += x.pow(2)\n self.mean = self.sum / self.n\n self.std = (self.sum_sqr / self.n - self.mean.pow(2)).clamp(1e-2,1e9).sqrt()\n self.mean = self.mean.float()\n self.std = self.std.float()\n #self.mean = (self.mean * self.n + x) / self.\n #self.mean += (x-self.mean)/self.n\n #self.mean_diff += (x-last_mean)*(x-self.mean)\n #self.var = torch.clamp(self.mean_diff/self.n, min=1e-2)\n\n def normalize(self, inputs):\n #if (inputs.shape[1]) > self.num_inputs:\n # inputs = inputs[:, 0:self.num_inputs]\n obs_mean = Variable(self.mean.unsqueeze(0).expand_as(inputs[:, 0:self.num_inputs]))\n obs_std = Variable(self.std.unsqueeze(0).expand_as(inputs[:, 0:self.num_inputs]))\n obs_mean = ((inputs[:, 0:self.num_inputs] - obs_mean) / obs_std)\n if (inputs.shape[1]) > self.num_inputs:\n #print(inputs.shape, obs_mean.shape)\n obs_mean = torch.cat([obs_mean, inputs[:, self.num_inputs:self.num_inputs+1]], dim=1)\n #print(\"outout\", obs_mean)\n #obs_std = Variable(torch.sqrt(self.var).unsqueeze(0).expand_as(inputs))\n return torch.clamp(obs_mean, -10.0, 10.0)\n\n def reset(self):\n self.n = torch.zeros(self.num_inputs).share_memory_()\n self.mean = torch.zeros(self.num_inputs).share_memory_()\n self.mean_diff = torch.zeros(self.num_inputs).share_memory_()\n self.var = torch.zeros(self.num_inputs).share_memory_()"
] |
[
[
"torch.nn.functional.softmax",
"torch.ones",
"torch.max",
"torch.Tensor",
"torch.zeros",
"torch.cat",
"torch.randn",
"torch.nn.ModuleList",
"torch.exp",
"torch.nn.Linear",
"torch.distributions.Categorical",
"torch.cuda.is_available",
"torch.distributions.Normal",
"torch.clamp"
]
] |
Behery/marioai
|
[
"adbe1625e9acad55dde057a8df3cb2a7036f7eff"
] |
[
"marioai/utils.py"
] |
[
"import numpy\n\n__all__ = ['extractObservation']\n\n\npowsof2 = (1, 2, 4, 8, 16, 32, 64, 128,\n 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072)\n\ndef decode(estate):\n \"\"\"\n decodes the encoded state estate, which is a string of 61 chars\n \"\"\"\n# powsof2 = (1, 2, 4, 8, 16, 32, 64, 128)\n dstate = numpy.empty(shape = (22, 22), dtype = numpy.int)\n for i in range(22):\n for j in range(22):\n dstate[i, j] = 2\n row = 0\n col = 0\n totalBitsDecoded = 0\n reqSize = 31\n assert len(estate) == reqSize, \"Error in data size given %d! Required: %d \\n data: %s \" % (len(estate), reqSize, estate)\n check_sum = 0\n for i in range(len(estate)):\n cur_char = estate[i]\n if (ord(cur_char) != 0):\n check_sum += ord(cur_char)\n for j in range(16):\n totalBitsDecoded += 1\n if (col > 21):\n row += 1\n col = 0\n if ((int(powsof2[j]) & int(ord(cur_char))) != 0):\n dstate[row, col] = 1\n else:\n dstate[row, col] = 0\n col += 1\n if (totalBitsDecoded == 484):\n break\n print(\"totalBitsDecoded = \", totalBitsDecoded)\n return dstate, check_sum;\n\n\ndef extractObservation(data):\n \"\"\"\n parse the array of strings and return array 22 by 22 of doubles\n \"\"\"\n data = data.decode()\n\n obsLength = 487\n levelScene = numpy.empty(shape = (22, 22), dtype = numpy.int)\n enemiesFloats = []\n dummy = 0\n if(data[0] == 'E'):\n mayMarioJump = (data[1] == '1')\n isMarioOnGround = (data[2] == '1')\n levelScene, check_sum_got = decode(data[3:34])\n check_sum_recv = int(data[34:])\n if check_sum_got != check_sum_recv:\n print (\"Error check_sum! got %d != recv %d\" % (check_sum_got, check_sum_recv))\n\n return (mayMarioJump, isMarioOnGround, levelScene)\n data = data.split(' ')\n if (data[0] == 'FIT'):\n status = int(data[1])\n distance = float(data[2])\n timeLeft = int(data[3])\n marioMode = int(data[4])\n coins = int(data[5])\n \n return status, distance, timeLeft, marioMode, coins\n\n elif(data[0] == 'O'):\n mayMarioJump = (data[1] == 'true')\n isMarioOnGround = (data[2] == 'true')\n k = 0\n for i in range(22):\n for j in range(22):\n levelScene[i, j] = int(data[k + 3])\n k += 1\n k += 3\n marioFloats = (float(data[k]), float(data[k + 1]))\n k += 2 \n while k < len(data):\n enemiesFloats.append(float(data[k]))\n k += 1\n \n return (mayMarioJump, isMarioOnGround, marioFloats, enemiesFloats, levelScene, dummy)\n\n else:\n raise \"Wrong format or corrupted observation...\"\n"
] |
[
[
"numpy.empty"
]
] |
meng-zha/Det3D
|
[
"0cabfec8cb243e407506fad0bd57675f4410b0fb"
] |
[
"det3d/datasets/lvx/lvx_common.py"
] |
[
"import pathlib\nimport pickle\nimport re\nimport numpy as np\nimport open3d as o3d\n\nfrom collections import OrderedDict\nfrom pathlib import Path\nfrom skimage import io\nfrom tqdm import tqdm\n\nfrom det3d.core import box_np_ops\n\n\ndef _read_imageset_file(path):\n with open(path, \"r\") as f:\n lines = f.readlines()\n return [int(line) for line in lines]\n\n\ndef _calculate_num_points_in_gt(\n data_path, infos, relative_path, remove_outside=False, num_features=3\n):\n '''\n 计算bounding box内点的数量\n '''\n for info in infos:\n pc_info = info[\"point_cloud\"]\n if relative_path:\n v_path = str(Path(data_path) / pc_info[\"velodyne_path\"])\n else:\n v_path = pc_info[\"velodyne_path\"]\n pcd = o3d.io.read_point_cloud(str(v_path))\n points_v = np.asarray(pcd.points)\n \n if num_features >= 4:\n normals_v = np.asarray(pcd.normals)\n points_v = np.concatenate([points_v,normals_v],axis=1)[:,:num_features]\n\n annos = info[\"annos\"]\n dims = annos[\"dimensions\"]\n loc = annos[\"location\"]\n rots = annos[\"rotation_y\"]\n gt_boxes = np.concatenate([loc, dims, rots[..., np.newaxis]], axis=1)\n indices = box_np_ops.points_in_rbbox(points_v[:, :3], gt_boxes)\n num_points_in_gt = indices.sum(0)\n annos[\"num_points_in_gt\"] = num_points_in_gt \n\n\ndef create_lvx_info_file(data_path, save_path=None, relative_path=True):\n imageset_folder = Path(__file__).resolve().parent.parent / \"ImageSets\"\n train_img_ids = _read_imageset_file(str(imageset_folder / \"train_lvx.txt\"))\n val_img_ids = _read_imageset_file(str(imageset_folder / \"val_lvx.txt\"))\n test_img_ids = _read_imageset_file(str(imageset_folder / \"test_lvx.txt\"))\n\n print(\"Generate info. this may take several minutes.\")\n if save_path is None:\n save_path = Path(data_path)\n else:\n save_path = Path(save_path)\n\n lvx_infos_train = get_lvx_image_info(\n data_path,\n training=True,\n lidar=True,\n image_ids=train_img_ids,\n relative_path=relative_path,\n )\n _calculate_num_points_in_gt(data_path, lvx_infos_train, relative_path)\n filename = save_path / \"lvx_infos_train.pkl\"\n print(f\"Lvx info train file is saved to {filename}\")\n with open(filename, \"wb\") as f:\n pickle.dump(lvx_infos_train, f)\n lvx_infos_val = get_lvx_image_info(data_path,\n training=True,\n lidar=True,\n image_ids=val_img_ids,\n relative_path=relative_path)\n _calculate_num_points_in_gt(data_path, lvx_infos_val, relative_path)\n filename = save_path / 'lvx_infos_val.pkl'\n print(f\"Lvx info val file is saved to {filename}\")\n with open(filename, 'wb') as f:\n pickle.dump(lvx_infos_val, f)\n filename = save_path / 'lvx_infos_trainval.pkl'\n print(f\"Lvx info trainval file is saved to {filename}\")\n with open(filename, 'wb') as f:\n pickle.dump(lvx_infos_train + lvx_infos_val, f)\n lvx_infos_test = get_lvx_image_info(data_path,\n training=False,\n label_info=False,\n lidar=True,\n image_ids=test_img_ids,\n relative_path=relative_path)\n filename = save_path / 'lvx_infos_test.pkl'\n print(f\"lvx info test file is saved to {filename}\")\n with open(filename, 'wb') as f:\n pickle.dump(lvx_infos_test, f)\n\n\ndef area(boxes, add1=False):\n \"\"\"Computes area of boxes.\n\n Args:\n boxes: Numpy array with shape [N, 4] holding N boxes\n\n Returns:\n a numpy array with shape [N*1] representing box areas\n \"\"\"\n if add1:\n return (boxes[:, 2] - boxes[:, 0] + 1.0) * (boxes[:, 3] - boxes[:, 1] + 1.0)\n else:\n return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])\n\n\ndef intersection(boxes1, boxes2, add1=False):\n \"\"\"Compute pairwise intersection areas between boxes.\n\n Args:\n boxes1: a numpy array with shape [N, 4] holding N boxes\n boxes2: a numpy array with shape [M, 4] holding M boxes\n\n Returns:\n a numpy array with shape [N*M] representing pairwise intersection area\n \"\"\"\n [y_min1, x_min1, y_max1, x_max1] = np.split(boxes1, 4, axis=1)\n [y_min2, x_min2, y_max2, x_max2] = np.split(boxes2, 4, axis=1)\n\n all_pairs_min_ymax = np.minimum(y_max1, np.transpose(y_max2))\n all_pairs_max_ymin = np.maximum(y_min1, np.transpose(y_min2))\n if add1:\n all_pairs_min_ymax += 1.0\n intersect_heights = np.maximum(\n np.zeros(all_pairs_max_ymin.shape), all_pairs_min_ymax - all_pairs_max_ymin\n )\n\n all_pairs_min_xmax = np.minimum(x_max1, np.transpose(x_max2))\n all_pairs_max_xmin = np.maximum(x_min1, np.transpose(x_min2))\n if add1:\n all_pairs_min_xmax += 1.0\n intersect_widths = np.maximum(\n np.zeros(all_pairs_max_xmin.shape), all_pairs_min_xmax - all_pairs_max_xmin\n )\n return intersect_heights * intersect_widths\n\n\ndef iou(boxes1, boxes2, add1=False):\n \"\"\"Computes pairwise intersection-over-union between box collections.\n\n Args:\n boxes1: a numpy array with shape [N, 4] holding N boxes.\n boxes2: a numpy array with shape [M, 4] holding N boxes.\n\n Returns:\n a numpy array with shape [N, M] representing pairwise iou scores.\n \"\"\"\n intersect = intersection(boxes1, boxes2, add1)\n area1 = area(boxes1, add1)\n area2 = area(boxes2, add1)\n union = np.expand_dims(area1, axis=1) + np.expand_dims(area2, axis=0) - intersect\n return intersect / union\n\n\ndef get_image_index_str(img_idx):\n return f\"PC_{img_idx}\"\n\n\ndef get_lvx_info_path(\n idx,\n prefix,\n info_type=\"Lidar\",\n file_tail=\".pcd\",\n training=True,\n relative_path=True,\n exist_check=True,\n):\n img_idx_str = get_image_index_str(idx)\n img_idx_str += file_tail\n prefix = pathlib.Path(prefix)\n if training:\n file_path = pathlib.Path(\"training\") / info_type / img_idx_str\n else:\n file_path = pathlib.Path(\"testing\") / info_type / img_idx_str\n if exist_check and not (prefix / file_path).exists():\n raise ValueError(\"file not exist: {}\".format(file_path))\n if relative_path:\n return str(file_path)\n else:\n return str(prefix / file_path)\n\n\ndef get_label_path(idx, prefix, training=True, relative_path=True, exist_check=True):\n return get_lvx_info_path(\n idx, prefix, \"Label\", \".txt\", training, relative_path, exist_check\n )\n\n\ndef get_lidar_path(idx, prefix, training=True, relative_path=True, exist_check=True):\n return get_lvx_info_path(\n idx, prefix, \"Lidar\", \".pcd\", training, relative_path, exist_check\n )\n\n\ndef get_lvx_image_info(\n path,\n training=True,\n label_info=True,\n lidar=False,\n calib=False,\n image_ids=400,\n extend_matrix=True,\n num_worker=8,\n relative_path=True,\n):\n # image_infos = []\n \"\"\"\n KITTI annotation format version 2:\n {\n point_cloud: {\n num_features: 4\n velodyne_path: ...\n }\n annos: {\n location: [num_gt, 3] array\n dimensions: [num_gt, 3] array\n rotation_y: [num_gt] angle array\n name: [num_gt] ground truth name array\n [optional]difficulty: kitti difficulty\n [optional]group_ids: used for multi-part object\n }\n }\n \"\"\"\n root_path = pathlib.Path(path)\n if not isinstance(image_ids, list):\n image_ids = list(range(image_ids))\n\n def map_func(idx):\n info = {}\n pc_info = {\"num_features\": 3} \n calib_info = {}\n\n annotations = None\n if lidar:\n pc_info[\"velodyne_path\"] = get_lidar_path(\n idx, path, training, relative_path\n )\n if label_info:\n label_path = get_label_path(idx, path, training, relative_path)\n if relative_path:\n label_path = str(root_path / label_path)\n annotations = get_label_anno(label_path,idx)\n info[\"point_cloud\"] = pc_info\n info[\"token\"]=idx\n\n if annotations is not None:\n info[\"annos\"] = annotations\n return info\n\n image_infos = []\n for i in tqdm(image_ids):\n image_infos.append(map_func(i))\n\n return image_infos\n\n\ndef get_class_to_label_map():\n class_to_label = {\n \"Car\": 0,\n \"Pedestrian\": 1,\n \"Cyclist\": 2,\n \"Van\": 3,\n \"Person_sitting\": 4,\n \"Truck\": 5,\n \"Tram\": 6,\n \"Misc\": 7,\n \"DontCare\": -1,\n }\n return class_to_label\n\n\ndef get_classes():\n return get_class_to_label_map().keys()\n\ndef get_label_anno(label_path,idx):\n '''\n 构建label,其中dim,loc,rot应该有3帧的数据\n return {name\": [],\n \"truncated\": [],\n \"occluded\": [],\n \"alpha\": [],\n \"bbox\": [],\n \"dimensions\": [],\n \"location\": [],\n \"rotation_y\": [],\n \"dimensions_1\": [],\n \"location_1\": [],\n \"rotation_y_1\": [],\n \"dimensions_2\": [],\n \"location_2\": [],\n \"rotation_y_2\": [],\n \"token\":idx,}\n '''\n annotations = {}\n annotations.update(\n {\n \"name\": [],\n \"truncated\": [],\n \"occluded\": [],\n \"alpha\": [],\n \"bbox\": [],\n \"dimensions\": [],\n \"location\": [],\n \"rotation_y\": [],\n \"token\":idx,\n }\n )\n with open(label_path, \"r\") as f:\n lines = f.readlines()\n content = [line.strip().split(\" \") for line in lines]\n\n name = ['','Pedestrian','DontCare']\n num_objects = len([x[0] for x in content if float(x[0]) != -1])\n annotations[\"name\"] = np.array([name[int(float(x[0]))] for x in content])\n num_gt = len(annotations[\"name\"])\n annotations[\"truncated\"] = np.zeros((num_gt,))\n annotations[\"occluded\"] = np.zeros((num_gt,))\n annotations[\"alpha\"] = -10*np.ones((num_gt,))\n # fake bbox lack of images\n annotations[\"bbox\"] = np.array(\n [[0,0,500,500] for x in content]\n ).reshape(-1, 4)\n\n # track_id\n annotations[\"id\"] = np.array([int(float(x[8])) for x in content]).reshape(-1)\n\n # dimensions will convert wlh format to standard lwh(lvx) format.\n annotations[\"dimensions\"] = np.array(\n [[float(x[2]),float(x[1]),float(x[3])] for x in content]\n ).reshape(-1, 3)\n annotations[\"location\"] = np.array(\n [[float(info) for info in x[4:7]] for x in content]\n ).reshape(-1, 3)\n annotations[\"rotation_y\"] = -1*np.array([float(x[7]) for x in content]).reshape(-1)\n # 之前一帧的对应标注\n annotations[\"dimensions_1\"] = np.array(\n [[float(x[2+9]),float(x[1+9]),float(x[3+9])] for x in content]\n ).reshape(-1, 3)\n annotations[\"location_1\"] = np.array(\n [[float(info) for info in x[(4+9):(7+9)]] for x in content]\n ).reshape(-1, 3)\n annotations[\"rotation_y_1\"] = -1*np.array([float(x[7+9]) for x in content]).reshape(-1)\n\n annotations[\"dimensions_2\"] = np.array(\n [[float(x[2+9*2]),float(x[1+9*2]),float(x[3+9*2])] for x in content]\n ).reshape(-1, 3)\n annotations[\"location_2\"] = np.array(\n [[float(info) for info in x[(4+9*2):(7+9*2)]] for x in content]\n ).reshape(-1, 3)\n annotations[\"rotation_y_2\"] = -1*np.array([float(x[7+9*2]) for x in content]).reshape(-1)\n\n # T-2帧的label,用于gtbox 的 gtaug, T-2帧的点需要对应旋转缩放\n annotations[\"dimensions_3\"] = np.array(\n [[float(x[2+9*3]),float(x[1+9*3]),float(x[3+9*3])] for x in content]\n ).reshape(-1, 3)\n annotations[\"location_3\"] = np.array(\n [[float(info) for info in x[(4+9*3):(7+9*3)]] for x in content]\n ).reshape(-1, 3)\n annotations[\"rotation_y_3\"] = -1*np.array([float(x[7+9*3]) for x in content]).reshape(-1)\n index = list(range(num_objects)) + [-1] * (num_gt - num_objects)\n annotations[\"group_ids\"] = np.arange(num_gt, dtype=np.int32)\n return annotations\n\n\ndef get_start_result_anno():\n annotations = {}\n annotations.update(\n {\n # 'index': None,\n \"name\": [],\n \"truncated\": [],\n \"occluded\": [],\n \"alpha\": [],\n \"bbox\": [],\n \"dimensions\": [],\n \"location\": [],\n \"rotation_y\": [],\n \"dimensions_1\": [],\n \"location_1\": [],\n \"rotation_y_1\": [],\n \"dimensions_2\": [],\n \"location_2\": [],\n \"rotation_y_2\": [],\n \"score\": [],\n }\n )\n return annotations\n\n\ndef empty_result_anno():\n annotations = {}\n annotations.update(\n {\n \"name\": np.array([]),\n \"truncated\": np.array([]),\n \"occluded\": np.array([]),\n \"alpha\": np.array([]),\n \"bbox\": np.zeros([0, 4]),\n \"dimensions\": np.zeros([0, 3]),\n \"location\": np.zeros([0, 3]),\n \"rotation_y\": np.array([]),\n \"dimensions_1\": np.zeros([0, 3]),\n \"location_1\": np.zeros([0, 3]),\n \"rotation_y_1\": np.array([]),\n \"dimensions_2\": np.zeros([0, 3]),\n \"location_2\": np.zeros([0, 3]),\n \"rotation_y_2\": np.array([]),\n \"dimensions_3\": np.zeros([0, 3]),\n \"location_3\": np.zeros([0, 3]),\n \"rotation_y_3\": np.array([]),\n \"score\": np.array([]),\n }\n )\n return annotations\n\n\ndef get_label_annos(label_folder, image_ids=None):\n if image_ids is None:\n filepaths = pathlib.Path(label_folder).glob(\"*.txt\")\n prog = re.compile(r\"^\\d{6}.txt$\")\n filepaths = filter(lambda f: prog.match(f.name), filepaths)\n image_ids = [int(p.stem) for p in filepaths]\n image_ids = sorted(image_ids)\n if not isinstance(image_ids, list):\n image_ids = list(range(image_ids))\n annos = []\n label_folder = pathlib.Path(label_folder)\n for idx in image_ids:\n image_idx_str = get_image_index_str(idx)\n label_filename = label_folder / (image_idx_str + \".txt\")\n anno = get_label_anno(label_filename,idx)\n num_example = anno[\"name\"].shape[0]\n anno[\"image_idx\"] = np.array([idx] * num_example, dtype=np.int64)\n annos.append(anno)\n return annos\n\n\ndef anno_to_rbboxes(anno):\n loc = anno[\"location\"]\n dims = anno[\"dimensions\"]\n rots = anno[\"rotation_y\"]\n rbboxes = np.concatenate([loc, dims, rots[..., np.newaxis]], axis=1)\n return rbboxes\n"
] |
[
[
"numpy.split",
"numpy.expand_dims",
"numpy.asarray",
"numpy.arange",
"numpy.ones",
"numpy.concatenate",
"numpy.transpose",
"numpy.array",
"numpy.zeros"
]
] |
ashamraeva/cvxpy
|
[
"9e320f9c96c9232860d83a5756567ac6401dd51e"
] |
[
"cvxpy/atoms/affine/cumsum.py"
] |
[
"\"\"\"\nCopyright 2013 Steven Diamond\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom cvxpy.atoms.axis_atom import AxisAtom\nfrom cvxpy.atoms.affine.affine_atom import AffAtom\nfrom cvxpy.atoms.affine.binary_operators import MulExpression\nfrom cvxpy.expressions.variable import Variable\nimport cvxpy.lin_ops.lin_utils as lu\nimport numpy as np\nimport scipy.sparse as sp\n\n\ndef get_diff_mat(dim, axis):\n \"\"\"Return a sparse matrix representation of first order difference operator.\n\n Parameters\n ----------\n dim : int\n The length of the matrix dimensions.\n axis : int\n The axis to take the difference along.\n\n Returns\n -------\n SciPy CSC matrix\n A square matrix representing first order difference.\n \"\"\"\n # Construct a sparse matrix representation.\n val_arr = []\n row_arr = []\n col_arr = []\n for i in range(dim):\n val_arr.append(1.)\n row_arr.append(i)\n col_arr.append(i)\n if i > 0:\n val_arr.append(-1.)\n row_arr.append(i)\n col_arr.append(i-1)\n\n mat = sp.csc_matrix((val_arr, (row_arr, col_arr)),\n (dim, dim))\n if axis == 0:\n return mat\n else:\n return mat.T\n\n\nclass cumsum(AffAtom, AxisAtom):\n \"\"\"Cumulative sum.\n\n Attributes\n ----------\n expr : CVXPY expression\n The expression being summed.\n axis : int\n The axis to sum across if 2D.\n \"\"\"\n def __init__(self, expr, axis: int=0) -> None:\n super(cumsum, self).__init__(expr, axis)\n\n @AffAtom.numpy_numeric\n def numeric(self, values):\n \"\"\"Convolve the two values.\n \"\"\"\n return np.cumsum(values[0], axis=self.axis)\n\n def shape_from_args(self):\n \"\"\"The same as the input.\n \"\"\"\n return self.args[0].shape\n\n def _grad(self, values):\n \"\"\"Gives the (sub/super)gradient of the atom w.r.t. each argument.\n\n Matrix expressions are vectorized, so the gradient is a matrix.\n\n Args:\n values: A list of numeric values for the arguments.\n\n Returns:\n A list of SciPy CSC sparse matrices or None.\n \"\"\"\n # TODO inefficient\n dim = values[0].shape[self.axis]\n mat = np.zeros((dim, dim))\n for i in range(dim):\n for j in range(i+1):\n mat[i, j] = 1\n var = Variable(self.args[0].shape)\n if self.axis == 0:\n grad = MulExpression(mat, var)._grad(values)[1]\n else:\n grad = MulExpression(var, mat.T)._grad(values)[0]\n return [grad]\n\n def get_data(self):\n \"\"\"Returns the axis being summed.\n \"\"\"\n return [self.axis]\n\n def graph_implementation(self, arg_objs, shape, data=None):\n \"\"\"Cumulative sum via difference matrix.\n\n Parameters\n ----------\n arg_objs : list\n LinExpr for each argument.\n shape : tuple\n The shape of the resulting expression.\n data :\n Additional data required by the atom.\n\n Returns\n -------\n tuple\n (LinOp for objective, list of constraints)\n \"\"\"\n # Implicit O(n) definition:\n # X = Y[1:,:] - Y[:-1, :]\n Y = lu.create_var(shape)\n axis = data[0]\n dim = shape[axis]\n diff_mat = get_diff_mat(dim, axis)\n diff_mat = lu.create_const(diff_mat, (dim, dim), sparse=True)\n if axis == 0:\n diff = lu.mul_expr(diff_mat, Y)\n else:\n diff = lu.rmul_expr(Y, diff_mat)\n return (Y, [lu.create_eq(arg_objs[0], diff)])\n"
] |
[
[
"scipy.sparse.csc_matrix",
"numpy.zeros",
"numpy.cumsum"
]
] |
yu-sakana/dartspose
|
[
"7d65beaf037840511fac18cde8da07e5656c94e6",
"7d65beaf037840511fac18cde8da07e5656c94e6"
] |
[
"py_scripts/part_dtw.py",
"tf_pose/def_estimator.py"
] |
[
"import numpy as np\nimport pylab as plt\nimport pandas as pd\nimport matplotlib.gridspec as gridspec\n\ndef normalization(p):\n min_p = p.min()\n max_p = p.max()\n nor = (p - min_p) / (max_p - min_p)\n return nor\n\ndef plot_path(paths, A, B, D):\n plt.figure(figsize=(5,5))\n gs = gridspec.GridSpec(2, 2,\n width_ratios=[1,5],\n height_ratios=[5,1]\n )\n ax1 = plt.subplot(gs[0])\n ax2 = plt.subplot(gs[1])\n ax4 = plt.subplot(gs[3])\n\n ax2.pcolor(D, cmap=plt.cm.Blues)\n ax2.get_xaxis().set_ticks([])\n ax2.get_yaxis().set_ticks([])\n\n [ax2.plot(path[:,0]+0.5, path[:,1]+0.5, c=\"C3\") for path in paths]\n \n# for path in paths:\n# ax2.plot(path[:,0]+0.5, path[:,1]+0.5, c=\"C3\")\n \n ax4.plot(A)\n ax4.set_xlabel(\"$X$\")\n ax1.invert_xaxis()\n ax1.plot(B, range(len(B)), c=\"C1\")\n ax1.set_ylabel(\"$Y$\")\n\n ax2.set_xlim(0, len(A))\n ax2.set_ylim(0, len(B))\n plt.show()\n \ndef dist(x, y):\n return (x - y)**2\n\ndef get_min(m0, m1, m2, i, j):\n if m0 < m1:\n if m0 < m2:\n return i - 1, j, m0\n else:\n return i - 1, j - 1, m2\n else:\n if m1 < m2:\n return i, j - 1, m1\n else:\n return i - 1, j - 1, m2\n\ndef partial_dtw(x, y):\n Tx = len(x)\n Ty = len(y)\n\n C = np.zeros((Tx, Ty))\n B = np.zeros((Tx, Ty, 2), int)\n\n C[0, 0] = dist(x[0], y[0])\n for i in range(Tx):\n C[i, 0] = dist(x[i], y[0])\n B[i, 0] = [0, 0]\n\n for j in range(1, Ty):\n C[0, j] = C[0, j - 1] + dist(x[0], y[j])\n B[0, j] = [0, j - 1]\n\n for i in range(1, Tx):\n for j in range(1, Ty):\n pi, pj, m = get_min(C[i - 1, j],\n C[i, j - 1],\n C[i - 1, j - 1],\n i, j)\n C[i, j] = dist(x[i], y[j]) + m\n B[i, j] = [pi, pj]\n t_end = np.argmin(C[:,-1])\n cost = C[t_end, -1]\n \n path = [[t_end, Ty - 1]]\n i = t_end\n j = Ty - 1\n\n while (B[i, j][0] != 0 or B[i, j][1] != 0):\n path.append(B[i, j])\n i, j = B[i, j].astype(int)\n \n return np.array(path), cost\n\nif __name__ == '__main__':\n df = pd.read_csv('test.csv',header=None)\n #X:test,Y:train\n X = df[0]\n Y = df[1]\n Y = Y[~np.isnan(Y)]\n# print(X,Y)\n Y = normalization(Y)\n X = normalization(X)\n path, cost = partial_dtw(X, Y)\n print(cost)\n \n D = (np.array(X).reshape(1, -1) - np.array(Y).reshape(-1, 1))**2\n# plot_path([np.array(path)], X, Y, D)\n\n for line in path:\n plt.plot(line, [X[line[0]], Y[line[1]]], linewidth=0.8, c=\"gray\")\n plt.plot(X)\n plt.plot(Y)\n plt.plot(path[:,0], X[path[:,0]], c=\"C2\")\n plt.show()\n",
"import logging\nimport math\n\nimport slidingwindow as sw\n\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nimport time\n\nfrom tf_pose import common\nfrom tf_pose.common import CocoPart\nfrom tf_pose.tensblur.smoother import Smoother\nfrom tensorflow.python.compiler.tensorrt import trt_convert as trt\ntf.compat.v1.disable_eager_execution()\n\ntry:\n from tf_pose.pafprocess import pafprocess\nexcept ModuleNotFoundError as e:\n print(e)\n print('you need to build c++ library for pafprocess. See : https://github.com/ildoonet/tf-pose-estimation/tree/master/tf_pose/pafprocess')\n exit(-1)\n\nlogger = logging.getLogger('TfPoseEstimator')\nlogger.handlers.clear()\nlogger.setLevel(logging.INFO)\nch = logging.StreamHandler()\nformatter = logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s')\nch.setFormatter(formatter)\nlogger.addHandler(ch)\nlogger.setLevel(logging.INFO)\n\n\ndef _round(v):\n return int(round(v))\n\n\ndef _include_part(part_list, part_idx):\n for part in part_list:\n if part_idx == part.part_idx:\n return True, part\n return False, None\n\n\nclass Human:\n \"\"\"\n body_parts: list of BodyPart\n \"\"\"\n __slots__ = ('body_parts', 'pairs', 'uidx_list', 'score')\n\n def __init__(self, pairs):\n self.pairs = []\n self.uidx_list = set()\n self.body_parts = {}\n for pair in pairs:\n self.add_pair(pair)\n self.score = 0.0\n\n @staticmethod\n def _get_uidx(part_idx, idx):\n return '%d-%d' % (part_idx, idx)\n\n def add_pair(self, pair):\n self.pairs.append(pair)\n self.body_parts[pair.part_idx1] = BodyPart(Human._get_uidx(pair.part_idx1, pair.idx1),\n pair.part_idx1,\n pair.coord1[0], pair.coord1[1], pair.score)\n self.body_parts[pair.part_idx2] = BodyPart(Human._get_uidx(pair.part_idx2, pair.idx2),\n pair.part_idx2,\n pair.coord2[0], pair.coord2[1], pair.score)\n self.uidx_list.add(Human._get_uidx(pair.part_idx1, pair.idx1))\n self.uidx_list.add(Human._get_uidx(pair.part_idx2, pair.idx2))\n\n def is_connected(self, other):\n return len(self.uidx_list & other.uidx_list) > 0\n\n def merge(self, other):\n for pair in other.pairs:\n self.add_pair(pair)\n\n def part_count(self):\n return len(self.body_parts.keys())\n\n def get_max_score(self):\n return max([x.score for _, x in self.body_parts.items()])\n\n def get_face_box(self, img_w, img_h, mode=0):\n \"\"\"\n Get Face box compared to img size (w, h)\n :param img_w:\n :param img_h:\n :param mode:\n :return:\n \"\"\"\n # SEE : https://github.com/ildoonet/tf-pose-estimation/blob/master/tf_pose/common.py#L13\n _NOSE = CocoPart.Nose.value\n _NECK = CocoPart.Neck.value\n _REye = CocoPart.REye.value\n _LEye = CocoPart.LEye.value\n _REar = CocoPart.REar.value\n _LEar = CocoPart.LEar.value\n\n _THRESHOLD_PART_CONFIDENCE = 0.2\n parts = [part for idx, part in self.body_parts.items() if part.score > _THRESHOLD_PART_CONFIDENCE]\n\n is_nose, part_nose = _include_part(parts, _NOSE)\n if not is_nose:\n return None\n\n size = 0\n is_neck, part_neck = _include_part(parts, _NECK)\n if is_neck:\n size = max(size, img_h * (part_neck.y - part_nose.y) * 0.8)\n\n is_reye, part_reye = _include_part(parts, _REye)\n is_leye, part_leye = _include_part(parts, _LEye)\n if is_reye and is_leye:\n size = max(size, img_w * (part_reye.x - part_leye.x) * 2.0)\n size = max(size,\n img_w * math.sqrt((part_reye.x - part_leye.x) ** 2 + (part_reye.y - part_leye.y) ** 2) * 2.0)\n\n if mode == 1:\n if not is_reye and not is_leye:\n return None\n\n is_rear, part_rear = _include_part(parts, _REar)\n is_lear, part_lear = _include_part(parts, _LEar)\n if is_rear and is_lear:\n size = max(size, img_w * (part_rear.x - part_lear.x) * 1.6)\n\n if size <= 0:\n return None\n\n if not is_reye and is_leye:\n x = part_nose.x * img_w - (size // 3 * 2)\n elif is_reye and not is_leye:\n x = part_nose.x * img_w - (size // 3)\n else: # is_reye and is_leye:\n x = part_nose.x * img_w - size // 2\n\n x2 = x + size\n if mode == 0:\n y = part_nose.y * img_h - size // 3\n else:\n y = part_nose.y * img_h - _round(size / 2 * 1.2)\n y2 = y + size\n\n # fit into the image frame\n x = max(0, x)\n y = max(0, y)\n x2 = min(img_w - x, x2 - x) + x\n y2 = min(img_h - y, y2 - y) + y\n\n if _round(x2 - x) == 0.0 or _round(y2 - y) == 0.0:\n return None\n if mode == 0:\n return {\"x\": _round((x + x2) / 2),\n \"y\": _round((y + y2) / 2),\n \"w\": _round(x2 - x),\n \"h\": _round(y2 - y)}\n else:\n return {\"x\": _round(x),\n \"y\": _round(y),\n \"w\": _round(x2 - x),\n \"h\": _round(y2 - y)}\n\n def get_upper_body_box(self, img_w, img_h):\n \"\"\"\n Get Upper body box compared to img size (w, h)\n :param img_w:\n :param img_h:\n :return:\n \"\"\"\n\n if not (img_w > 0 and img_h > 0):\n raise Exception(\"img size should be positive\")\n\n _NOSE = CocoPart.Nose.value\n _NECK = CocoPart.Neck.value\n _RSHOULDER = CocoPart.RShoulder.value\n _LSHOULDER = CocoPart.LShoulder.value\n _THRESHOLD_PART_CONFIDENCE = 0.3\n parts = [part for idx, part in self.body_parts.items() if part.score > _THRESHOLD_PART_CONFIDENCE]\n part_coords = [(img_w * part.x, img_h * part.y) for part in parts if\n part.part_idx in [0, 1, 2, 5, 8, 11, 14, 15, 16, 17]]\n\n if len(part_coords) < 5:\n return None\n\n # Initial Bounding Box\n x = min([part[0] for part in part_coords])\n y = min([part[1] for part in part_coords])\n x2 = max([part[0] for part in part_coords])\n y2 = max([part[1] for part in part_coords])\n\n # # ------ Adjust heuristically +\n # if face points are detcted, adjust y value\n\n is_nose, part_nose = _include_part(parts, _NOSE)\n is_neck, part_neck = _include_part(parts, _NECK)\n torso_height = 0\n if is_nose and is_neck:\n y -= (part_neck.y * img_h - y) * 0.8\n torso_height = max(0, (part_neck.y - part_nose.y) * img_h * 2.5)\n #\n # # by using shoulder position, adjust width\n is_rshoulder, part_rshoulder = _include_part(parts, _RSHOULDER)\n is_lshoulder, part_lshoulder = _include_part(parts, _LSHOULDER)\n if is_rshoulder and is_lshoulder:\n half_w = x2 - x\n dx = half_w * 0.15\n x -= dx\n x2 += dx\n elif is_neck:\n if is_lshoulder and not is_rshoulder:\n half_w = abs(part_lshoulder.x - part_neck.x) * img_w * 1.15\n x = min(part_neck.x * img_w - half_w, x)\n x2 = max(part_neck.x * img_w + half_w, x2)\n elif not is_lshoulder and is_rshoulder:\n half_w = abs(part_rshoulder.x - part_neck.x) * img_w * 1.15\n x = min(part_neck.x * img_w - half_w, x)\n x2 = max(part_neck.x * img_w + half_w, x2)\n\n # ------ Adjust heuristically -\n\n # fit into the image frame\n x = max(0, x)\n y = max(0, y)\n x2 = min(img_w - x, x2 - x) + x\n y2 = min(img_h - y, y2 - y) + y\n\n if _round(x2 - x) == 0.0 or _round(y2 - y) == 0.0:\n return None\n return {\"x\": _round((x + x2) / 2),\n \"y\": _round((y + y2) / 2),\n \"w\": _round(x2 - x),\n \"h\": _round(y2 - y)}\n\n def __str__(self):\n return ' '.join([str(x) for x in self.body_parts.values()])\n\n def __repr__(self):\n return self.__str__()\n\n\nclass BodyPart:\n \"\"\"\n part_idx : part index(eg. 0 for nose)\n x, y: coordinate of body part\n score : confidence score\n \"\"\"\n __slots__ = ('uidx', 'part_idx', 'x', 'y', 'score')\n\n def __init__(self, uidx, part_idx, x, y, score):\n self.uidx = uidx\n self.part_idx = part_idx\n self.x, self.y = x, y\n self.score = score\n\n def get_part_name(self):\n return CocoPart(self.part_idx)\n\n def __str__(self):\n return 'BodyPart:%d-(%.2f, %.2f) score=%.2f' % (self.part_idx, self.x, self.y, self.score)\n\n def __repr__(self):\n return self.__str__()\n\n\nclass PoseEstimator:\n def __init__(self):\n pass\n\n @staticmethod\n def estimate_paf(peaks, heat_mat, paf_mat):\n pafprocess.process_paf(peaks, heat_mat, paf_mat)\n\n humans = []\n for human_id in range(pafprocess.get_num_humans()):\n human = Human([])\n is_added = False\n\n for part_idx in range(18):\n c_idx = int(pafprocess.get_part_cid(human_id, part_idx))\n if c_idx < 0:\n continue\n\n is_added = True\n human.body_parts[part_idx] = BodyPart(\n '%d-%d' % (human_id, part_idx), part_idx,\n float(pafprocess.get_part_x(c_idx)) / heat_mat.shape[1],\n float(pafprocess.get_part_y(c_idx)) / heat_mat.shape[0],\n pafprocess.get_part_score(c_idx)\n )\n\n if is_added:\n score = pafprocess.get_score(human_id)\n human.score = score\n humans.append(human)\n\n return humans\n\n\nclass TfPoseEstimator:\n # TODO : multi-scale\n\n def __init__(self, graph_path, target_size=(320, 240), tf_config=None, trt_bool=False):\n self.target_size = target_size\n\n # load graph\n logger.info('loading graph from %s(default size=%dx%d)' % (graph_path, target_size[0], target_size[1]))\n with tf.io.gfile.GFile(graph_path, 'rb') as f:\n graph_def = tf.compat.v1.GraphDef()\n graph_def.ParseFromString(f.read())\n\n if trt_bool is True:\n output_nodes = [\"Openpose/concat_stage7\"]\n graph_def = trt.create_inference_graph(\n graph_def,\n output_nodes,\n max_batch_size=1,\n max_workspace_size_bytes=1 << 20,\n precision_mode=\"FP16\",\n # precision_mode=\"INT8\",\n minimum_segment_size=3,\n is_dynamic_op=True,\n maximum_cached_engines=int(1e3),\n use_calibration=True,\n )\n\n self.graph = tf.compat.v1.get_default_graph()\n tf.import_graph_def(graph_def, name='TfPoseEstimator')\n self.persistent_sess = tf.compat.v1.Session(graph=self.graph, config=tf_config)\n\n for ts in [n.name for n in tf.compat.v1.get_default_graph().as_graph_def().node]:\n print(ts)\n\n self.tensor_image = self.graph.get_tensor_by_name('TfPoseEstimator/image:0')\n self.tensor_output = self.graph.get_tensor_by_name('TfPoseEstimator/Openpose/concat_stage7:0')\n self.tensor_heatMat = self.tensor_output[:, :, :, :19]\n self.tensor_pafMat = self.tensor_output[:, :, :, 19:]\n self.upsample_size = tf.compat.v1.placeholder(dtype=tf.int32, shape=(2,), name='upsample_size')\n self.tensor_heatMat_up = tf.compat.v1.image.resize(self.tensor_output[:, :, :, :19], self.upsample_size,\n align_corners=False, name='upsample_heatmat')\n self.tensor_pafMat_up = tf.compat.v1.image.resize(self.tensor_output[:, :, :, 19:], self.upsample_size,\n align_corners=False, name='upsample_pafmat')\n if trt_bool is True:\n smoother = Smoother({'data': self.tensor_heatMat_up}, 25, 3.0, 19)\n else:\n smoother = Smoother({'data': self.tensor_heatMat_up}, 25, 3.0)\n gaussian_heatMat = smoother.get_output()\n\n max_pooled_in_tensor = tf.nn.pool(gaussian_heatMat, window_shape=(3, 3), pooling_type='MAX', padding='SAME')\n self.tensor_peaks = tf.where(tf.equal(gaussian_heatMat, max_pooled_in_tensor), gaussian_heatMat,\n tf.zeros_like(gaussian_heatMat))\n\n self.heatMat = self.pafMat = None\n\n # warm-up\n self.persistent_sess.run(tf.compat.v1.variables_initializer(\n [v for v in tf.compat.v1.global_variables() if\n v.name.split(':')[0] in [x.decode('utf-8') for x in\n self.persistent_sess.run(tf.compat.v1.report_uninitialized_variables())]\n ])\n )\n self.persistent_sess.run(\n [self.tensor_peaks, self.tensor_heatMat_up, self.tensor_pafMat_up],\n feed_dict={\n self.tensor_image: [np.ndarray(shape=(target_size[1], target_size[0], 3), dtype=np.float32)],\n self.upsample_size: [target_size[1], target_size[0]]\n }\n )\n self.persistent_sess.run(\n [self.tensor_peaks, self.tensor_heatMat_up, self.tensor_pafMat_up],\n feed_dict={\n self.tensor_image: [np.ndarray(shape=(target_size[1], target_size[0], 3), dtype=np.float32)],\n self.upsample_size: [target_size[1] // 2, target_size[0] // 2]\n }\n )\n self.persistent_sess.run(\n [self.tensor_peaks, self.tensor_heatMat_up, self.tensor_pafMat_up],\n feed_dict={\n self.tensor_image: [np.ndarray(shape=(target_size[1], target_size[0], 3), dtype=np.float32)],\n self.upsample_size: [target_size[1] // 4, target_size[0] // 4]\n }\n )\n\n # logs\n if self.tensor_image.dtype == tf.quint8:\n logger.info('quantization mode enabled.')\n\n def __del__(self):\n # self.persistent_sess.close()\n pass\n\n def get_flops(self):\n flops = tf.profiler.profile(self.graph, options=tf.profiler.ProfileOptionBuilder.float_operation())\n return flops.total_float_ops\n\n @staticmethod\n def _quantize_img(npimg):\n npimg_q = npimg + 1.0\n npimg_q /= (2.0 / 2 ** 8)\n # npimg_q += 0.5\n npimg_q = npimg_q.astype(np.uint8)\n return npimg_q\n\n @staticmethod\n def draw_humans(npimg, humans, imgcopy=False):\n print('draw_humans',humans)\n if imgcopy:\n npimg = np.copy(npimg)\n image_h, image_w = npimg.shape[:2]\n centers = {}\n print('draw_humans type',type(humans))\n for human in humans:\n # draw point\n for i in range(common.CocoPart.Background.value):\n if i not in human.body_parts.keys():\n continue\n# print(human.body_parts)\n\n body_part = human.body_parts[i]\n print('body',body_part,'\\n')\n center = (int(body_part.x * image_w + 0.5), int(body_part.y * image_h + 0.5))\n print('center',center)\n centers[i] = center\n cv2.circle(npimg, center, 3, common.CocoColors[i], thickness=3, lineType=8, shift=0)\n\n # draw line\n for pair_order, pair in enumerate(common.CocoPairsRender):\n if pair[0] not in human.body_parts.keys() or pair[1] not in human.body_parts.keys():\n continue\n\n # npimg = cv2.line(npimg, centers[pair[0]], centers[pair[1]], common.CocoColors[pair_order], 3)\n cv2.line(npimg, centers[pair[0]], centers[pair[1]], common.CocoColors[pair_order], 3)\n\n return npimg\n\n def _get_scaled_img(self, npimg, scale):\n get_base_scale = lambda s, w, h: max(self.target_size[0] / float(h), self.target_size[1] / float(w)) * s\n img_h, img_w = npimg.shape[:2]\n\n if scale is None:\n if npimg.shape[:2] != (self.target_size[1], self.target_size[0]):\n # resize\n npimg = cv2.resize(npimg, self.target_size, interpolation=cv2.INTER_CUBIC)\n return [npimg], [(0.0, 0.0, 1.0, 1.0)]\n elif isinstance(scale, float):\n # scaling with center crop\n base_scale = get_base_scale(scale, img_w, img_h)\n npimg = cv2.resize(npimg, dsize=None, fx=base_scale, fy=base_scale, interpolation=cv2.INTER_CUBIC)\n\n o_size_h, o_size_w = npimg.shape[:2]\n if npimg.shape[0] < self.target_size[1] or npimg.shape[1] < self.target_size[0]:\n newimg = np.zeros(\n (max(self.target_size[1], npimg.shape[0]), max(self.target_size[0], npimg.shape[1]), 3),\n dtype=np.uint8)\n newimg[:npimg.shape[0], :npimg.shape[1], :] = npimg\n npimg = newimg\n\n windows = sw.generate(npimg, sw.DimOrder.HeightWidthChannel, self.target_size[0], self.target_size[1], 0.2)\n\n rois = []\n ratios = []\n for window in windows:\n indices = window.indices()\n roi = npimg[indices]\n rois.append(roi)\n ratio_x, ratio_y = float(indices[1].start) / o_size_w, float(indices[0].start) / o_size_h\n ratio_w, ratio_h = float(indices[1].stop - indices[1].start) / o_size_w, float(\n indices[0].stop - indices[0].start) / o_size_h\n ratios.append((ratio_x, ratio_y, ratio_w, ratio_h))\n\n return rois, ratios\n elif isinstance(scale, tuple) and len(scale) == 2:\n # scaling with sliding window : (scale, step)\n base_scale = get_base_scale(scale[0], img_w, img_h)\n npimg = cv2.resize(npimg, dsize=None, fx=base_scale, fy=base_scale, interpolation=cv2.INTER_CUBIC)\n o_size_h, o_size_w = npimg.shape[:2]\n if npimg.shape[0] < self.target_size[1] or npimg.shape[1] < self.target_size[0]:\n newimg = np.zeros(\n (max(self.target_size[1], npimg.shape[0]), max(self.target_size[0], npimg.shape[1]), 3),\n dtype=np.uint8)\n newimg[:npimg.shape[0], :npimg.shape[1], :] = npimg\n npimg = newimg\n\n window_step = scale[1]\n\n windows = sw.generate(npimg, sw.DimOrder.HeightWidthChannel, self.target_size[0], self.target_size[1],\n window_step)\n\n rois = []\n ratios = []\n for window in windows:\n indices = window.indices()\n roi = npimg[indices]\n rois.append(roi)\n ratio_x, ratio_y = float(indices[1].start) / o_size_w, float(indices[0].start) / o_size_h\n ratio_w, ratio_h = float(indices[1].stop - indices[1].start) / o_size_w, float(\n indices[0].stop - indices[0].start) / o_size_h\n ratios.append((ratio_x, ratio_y, ratio_w, ratio_h))\n\n return rois, ratios\n elif isinstance(scale, tuple) and len(scale) == 3:\n # scaling with ROI : (want_x, want_y, scale_ratio)\n base_scale = get_base_scale(scale[2], img_w, img_h)\n npimg = cv2.resize(npimg, dsize=None, fx=base_scale, fy=base_scale, interpolation=cv2.INTER_CUBIC)\n ratio_w = self.target_size[0] / float(npimg.shape[1])\n ratio_h = self.target_size[1] / float(npimg.shape[0])\n\n want_x, want_y = scale[:2]\n ratio_x = want_x - ratio_w / 2.\n ratio_y = want_y - ratio_h / 2.\n ratio_x = max(ratio_x, 0.0)\n ratio_y = max(ratio_y, 0.0)\n if ratio_x + ratio_w > 1.0:\n ratio_x = 1. - ratio_w\n if ratio_y + ratio_h > 1.0:\n ratio_y = 1. - ratio_h\n\n roi = self._crop_roi(npimg, ratio_x, ratio_y)\n return [roi], [(ratio_x, ratio_y, ratio_w, ratio_h)]\n\n def _crop_roi(self, npimg, ratio_x, ratio_y):\n target_w, target_h = self.target_size\n h, w = npimg.shape[:2]\n x = max(int(w * ratio_x - .5), 0)\n y = max(int(h * ratio_y - .5), 0)\n cropped = npimg[y:y + target_h, x:x + target_w]\n\n cropped_h, cropped_w = cropped.shape[:2]\n if cropped_w < target_w or cropped_h < target_h:\n npblank = np.zeros((self.target_size[1], self.target_size[0], 3), dtype=np.uint8)\n\n copy_x, copy_y = (target_w - cropped_w) // 2, (target_h - cropped_h) // 2\n npblank[copy_y:copy_y + cropped_h, copy_x:copy_x + cropped_w] = cropped\n else:\n return cropped\n\n def inference(self, npimg, resize_to_default=True, upsample_size=1.0):\n if npimg is None:\n raise Exception('The image is not valid. Please check your image exists.')\n\n if resize_to_default:\n upsample_size = [int(self.target_size[1] / 8 * upsample_size), int(self.target_size[0] / 8 * upsample_size)]\n else:\n upsample_size = [int(npimg.shape[0] / 8 * upsample_size), int(npimg.shape[1] / 8 * upsample_size)]\n\n if self.tensor_image.dtype == tf.quint8:\n # quantize input image\n npimg = TfPoseEstimator._quantize_img(npimg)\n pass\n\n logger.debug('inference+ original shape=%dx%d' % (npimg.shape[1], npimg.shape[0]))\n img = npimg\n if resize_to_default:\n img = self._get_scaled_img(npimg, None)[0][0]\n peaks, heatMat_up, pafMat_up = self.persistent_sess.run(\n [self.tensor_peaks, self.tensor_heatMat_up, self.tensor_pafMat_up], feed_dict={\n self.tensor_image: [img], self.upsample_size: upsample_size\n })\n peaks = peaks[0]\n self.heatMat = heatMat_up[0]\n self.pafMat = pafMat_up[0]\n logger.debug('inference- heatMat=%dx%d pafMat=%dx%d' % (\n self.heatMat.shape[1], self.heatMat.shape[0], self.pafMat.shape[1], self.pafMat.shape[0]))\n\n t = time.time()\n humans = PoseEstimator.estimate_paf(peaks, self.heatMat, self.pafMat)\n logger.debug('estimate time=%.5f' % (time.time() - t))\n return humans\n\n\nif __name__ == '__main__':\n import pickle\n\n f = open('./etcs/heatpaf1.pkl', 'rb')\n data = pickle.load(f)\n logger.info('size={}'.format(data['heatMat'].shape))\n f.close()\n\n t = time.time()\n humans = PoseEstimator.estimate_paf(data['peaks'], data['heatMat'], data['pafMat'])\n dt = time.time() - t;\n t = time.time()\n logger.info('elapsed #humans=%d time=%.8f' % (len(humans), dt))\n"
] |
[
[
"pandas.read_csv",
"numpy.isnan",
"numpy.argmin",
"matplotlib.gridspec.GridSpec",
"numpy.array",
"numpy.zeros"
],
[
"tensorflow.compat.v1.get_default_graph",
"tensorflow.import_graph_def",
"tensorflow.nn.pool",
"tensorflow.io.gfile.GFile",
"tensorflow.compat.v1.global_variables",
"tensorflow.equal",
"tensorflow.compat.v1.report_uninitialized_variables",
"numpy.ndarray",
"tensorflow.compat.v1.Session",
"tensorflow.zeros_like",
"tensorflow.compat.v1.placeholder",
"numpy.copy",
"tensorflow.compat.v1.disable_eager_execution",
"tensorflow.compat.v1.GraphDef",
"numpy.zeros",
"tensorflow.profiler.ProfileOptionBuilder.float_operation",
"tensorflow.compat.v1.image.resize"
]
] |
amykhoover/pyribs
|
[
"4e8a8c714bae0c722691554592cc050c9ad7e7b6",
"4e8a8c714bae0c722691554592cc050c9ad7e7b6"
] |
[
"benchmarks/cvt_add.py",
"ribs/emitters/_gaussian_emitter.py"
] |
[
"\"\"\"Compare performance of adding to the CVTArchive with and without k-D tree.\n\nIn CVTArchive, we use a k-D tree to identify the cell by finding the nearest\ncentroid to a solution in behavior space. Though a k-D tree is theoretically\nmore efficient than brute force, constant factors mean that brute force can be\nfaster than k-D tree for smaller numbers of centroids / cells. In this script, we\nwant to increase the number of cells in the archive and see when the k-D tree\nbecomes faster than brute force.\n\nIn this experiment, we construct archives with 10, 50, 100, 500, 1k, 5k, 10k,\n100k cells in the behavior space of [(-1, 1), (-1, 1)] and 100k samples (except\nfor 10k cells, where we use 200k samples so that the CVT generation does not drop\na cluster). In each archive, we then time how long it takes to add 100k random\nsolutions sampled u.a.r. from the behavior space. We run each experiment with\nbrute force and with the k-D tree, 5 times each, and take the minimum runtime\n(see https://docs.python.org/3/library/timeit.html#timeit.Timer.repeat).\n\nUsage:\n python cvt_add.py\n\nThis script will run for a while (~30 min) and produce two outputs. The first is\ncvt_add_times.json, which holds the raw times. The second is cvt_add_plot.png,\nwhich is a plot of the times with respect to number of cells.\n\nTo re-plot the results without re-running the benchmarks, modify plot_times and\nrun:\n\n import cvt_add # The name of this file.\n cvt_add.plot_times(*cvt_add.load_times())\n\"\"\"\nimport json\nimport timeit\nfrom functools import partial\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom ribs.archives import CVTArchive\n\n\ndef save_times(n_cells,\n brute_force_t,\n kd_tree_t,\n filename=\"cvt_add_times.json\"):\n \"\"\"Saves a dict of the results to the given file.\"\"\"\n with open(filename, \"w\") as file:\n json.dump(\n {\n \"n_cells\": n_cells,\n \"brute_force_t\": brute_force_t,\n \"kd_tree_t\": kd_tree_t,\n }, file)\n\n\ndef load_times(filename=\"cvt_add_times.json\"):\n \"\"\"Loads the results from the given file.\"\"\"\n with open(filename, \"r\") as file:\n data = json.load(file)\n return data[\"n_cells\"], data[\"brute_force_t\"], data[\"kd_tree_t\"]\n\n\ndef plot_times(n_cells, brute_force_t, kd_tree_t, filename=\"cvt_add_plot.png\"):\n \"\"\"Plots the results to the given file.\"\"\"\n fig, ax = plt.subplots(figsize=(4, 4))\n fig.tight_layout()\n ax.set_title(\"Runtime to insert 100k 2D entries into CVTArchive\")\n ax.set_xlabel(\"Archive cells\")\n ax.set_ylabel(\"Time (s)\")\n ax.set_yscale(\"log\")\n ax.semilogx(n_cells, brute_force_t, \"-o\", label=\"Brute Force\", c=\"#304FFE\")\n ax.semilogx(n_cells, kd_tree_t, \"-o\", label=\"k-D Tree\", c=\"#e62020\")\n ax.grid(True, which=\"major\", linestyle=\"--\", linewidth=1)\n ax.legend(loc=\"upper left\")\n fig.savefig(filename, bbox_inches=\"tight\", dpi=120)\n\n\ndef main():\n \"\"\"Creates archives, times insertion into them, and plots results.\"\"\"\n archive = None\n n_cells = [10, 50, 100, 500, 1_000, 5_000, 10_000, 100_000]\n\n # Pre-made solutions to insert.\n n_vals = 100_000\n solutions = np.random.uniform(-1, 1, (n_vals, 10))\n objective_values = np.random.randn(n_vals)\n behavior_values = np.random.uniform(-1, 1, (n_vals, 2))\n\n # Set up these archives so we can use the same centroids across all\n # experiments for a certain number of cells (and also save time).\n ref_archives = {\n cells: CVTArchive(\n cells,\n [(-1, 1), (-1, 1)],\n # Use 200k cells to avoid dropping clusters.\n samples=n_vals if cells != 10_000 else 200_000,\n use_kd_tree=False) for cells in n_cells\n }\n for cells, archive in ref_archives.items():\n print(f\"Setting up archive with {cells} cells\")\n archive.initialize(solutions.shape[1])\n\n def setup(cells, use_kd_tree):\n nonlocal archive\n archive = CVTArchive(cells, [(-1, 1), (-1, 1)],\n custom_centroids=ref_archives[cells].centroids,\n use_kd_tree=use_kd_tree)\n archive.initialize(solutions.shape[1])\n\n def add_100k_entries():\n nonlocal archive\n for i in range(n_vals):\n archive.add(solutions[i], objective_values[i], behavior_values[i])\n\n # Run the timing.\n brute_force_t = []\n kd_tree_t = []\n for cells in n_cells:\n for use_kd_tree in (False, True):\n print(f\"--------------\\n\"\n f\"Cells: {cells}\\n\"\n f\"Method: {'k-D Tree' if use_kd_tree else 'Brute Force'}\")\n setup_func = partial(setup, cells, use_kd_tree)\n res_t = min(\n timeit.repeat(add_100k_entries, setup_func, repeat=5, number=1))\n print(f\"Time: {res_t} s\")\n\n if use_kd_tree:\n kd_tree_t.append(res_t)\n else:\n brute_force_t.append(res_t)\n save_times(n_cells, brute_force_t, kd_tree_t, \"cvt_add_times.json\")\n\n # Save the results.\n plot_times(n_cells, brute_force_t, kd_tree_t)\n save_times(n_cells, brute_force_t, kd_tree_t)\n\n\nif __name__ == \"__main__\":\n main()\n",
"\"\"\"Provides the GaussianEmitter.\"\"\"\nimport numpy as np\nfrom numba import jit\n\nfrom ribs.emitters._emitter_base import EmitterBase\n\n\nclass GaussianEmitter(EmitterBase):\n \"\"\"Emits solutions by adding Gaussian noise to existing archive solutions.\n\n If the archive is empty, calls to :meth:`ask` will generate solutions from a\n user-specified Gaussian distribution with mean ``x0`` and standard deviation\n ``sigma0``. Otherwise, this emitter selects solutions from the archive and\n generates solutions from a Gaussian distribution centered around each\n solution with standard deviation ``sigma``.\n\n This is the classic variation operator presented in `Mouret 2015\n <https://arxiv.org/pdf/1504.04909.pdf>`_.\n\n Args:\n archive (ribs.archives.ArchiveBase): An archive to use when creating and\n inserting solutions. For instance, this can be\n :class:`ribs.archives.GridArchive`.\n x0 (array-like): Center of the Gaussian distribution from which to\n sample solutions when the archive is empty.\n sigma (float or array-like): Standard deviation of the Gaussian\n distribution when the archive is not empty. Note we assume\n the Gaussian is diagonal, so if this argument is an array, it\n must be 1D.\n sigma0 (float or array-like): Standard deviation of the Gaussian\n distribution when the archive is empty. If this argument is\n None, then it defaults to sigma. Note we assume the Gaussian is\n diagonal, so if this argument is an array, it must be 1D.\n bounds (None or array-like): Bounds of the solution space. Solutions are\n clipped to these bounds. Pass None to indicate there are no bounds.\n Alternatively, pass an array-like to specify the bounds for each\n dim. Each element in this array-like can be None to indicate no\n bound, or a tuple of ``(lower_bound, upper_bound)``, where\n ``lower_bound`` or ``upper_bound`` may be None to indicate no bound.\n batch_size (int): Number of solutions to return in :meth:`ask`.\n seed (int): Value to seed the random number generator. Set to None to\n avoid a fixed seed.\n Raises:\n ValueError: There is an error in the bounds configuration.\n \"\"\"\n\n def __init__(self,\n archive,\n x0,\n sigma,\n sigma0=None,\n bounds=None,\n batch_size=64,\n seed=None):\n self._rng = np.random.default_rng(seed)\n self._batch_size = batch_size\n self._x0 = np.array(x0, dtype=archive.dtype)\n self._sigma = archive.dtype(sigma) if isinstance(\n sigma,\n (float, np.floating)) else np.array(sigma, dtype=archive.dtype)\n self._sigma0 = self._sigma if sigma0 is None else (\n archive.dtype(sigma0) if isinstance(sigma0, (\n float, np.floating)) else np.array(sigma0, dtype=archive.dtype))\n\n EmitterBase.__init__(\n self,\n archive,\n len(self._x0),\n bounds,\n )\n\n @property\n def x0(self):\n \"\"\"numpy.ndarray: Center of the Gaussian distribution from which to\n sample solutions when the archive is empty.\"\"\"\n return self._x0\n\n @property\n def sigma(self):\n \"\"\"float or numpy.ndarray: Standard deviation of the (diagonal) Gaussian\n distribution when the archive is not empty.\"\"\"\n return self._sigma\n\n @property\n def sigma0(self):\n \"\"\"float or numpy.ndarray: Standard deviation of the (diagonal) Gaussian\n distribution when the archive is empty.\"\"\"\n return self._sigma0\n\n @property\n def batch_size(self):\n \"\"\"int: Number of solutions to return in :meth:`ask`.\"\"\"\n return self._batch_size\n\n @staticmethod\n @jit(nopython=True)\n def _ask_clip_helper(parents, noise, lower_bounds, upper_bounds):\n \"\"\"Numba equivalent of np.clip.\"\"\"\n return np.minimum(np.maximum(parents + noise, lower_bounds),\n upper_bounds)\n\n def ask(self):\n \"\"\"Creates solutions by adding Gaussian noise to elites in the archive.\n\n If the archive is empty, solutions are drawn from a (diagonal) Gaussian\n distribution centered at ``self.x0`` with standard deviation\n ``self.sigma0``. Otherwise, each solution is drawn from a distribution\n centered at a randomly chosen elite with standard deviation\n ``self.sigma``.\n\n Returns:\n ``(batch_size, solution_dim)`` array -- contains ``batch_size`` new\n solutions to evaluate.\n \"\"\"\n if self.archive.empty:\n sigma = self._sigma0\n parents = np.expand_dims(self._x0, axis=0)\n else:\n sigma = self._sigma\n parents = self.archive.sample_elites(\n self._batch_size).solution_batch\n\n noise = self._rng.normal(\n scale=sigma,\n size=(self._batch_size, self.solution_dim),\n ).astype(self.archive.dtype)\n\n return self._ask_clip_helper(parents, noise, self.lower_bounds,\n self.upper_bounds)\n"
] |
[
[
"numpy.random.uniform",
"numpy.random.randn",
"matplotlib.pyplot.subplots"
],
[
"numpy.expand_dims",
"numpy.array",
"numpy.maximum",
"numpy.random.default_rng"
]
] |
asonnino/key-transparency
|
[
"7d182abf1555f34a0efbdcd9a22c5cb7744ea1e5"
] |
[
"scripts/benchmark/plot.py"
] |
[
"from collections import defaultdict\nfrom re import findall, search, split\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as tick\nfrom glob import glob\nfrom itertools import cycle\n\nfrom benchmark.utils import PathMaker\nfrom benchmark.config import PlotParameters\nfrom benchmark.aggregate import LogAggregator\n\n\n@tick.FuncFormatter\ndef default_major_formatter(x, pos):\n if pos is None:\n return\n if x >= 1_000:\n return f'{x/1000:.0f}k'\n else:\n return f'{x:.0f}'\n\n\n@tick.FuncFormatter\ndef sec_major_formatter(x, pos):\n if pos is None:\n return\n return f'{float(x)/1000:.1f}'\n # return f'{x:,.0f}'\n\n\n@tick.FuncFormatter\ndef mb_major_formatter(x, pos):\n if pos is None:\n return\n return f'{x:,.0f}'\n\n\nclass PlotError(Exception):\n pass\n\n\nclass Ploter:\n def __init__(self, filenames):\n if not filenames:\n raise PlotError('No data to plot')\n\n self.results = []\n try:\n for filename in filenames:\n with open(filename, 'r') as f:\n self.results += [f.read().replace(',', '')]\n except OSError as e:\n raise PlotError(f'Failed to load log files: {e}')\n\n def _natural_keys(self, text):\n def try_cast(text): return int(text) if text.isdigit() else text\n return [try_cast(c) for c in split('(\\d+)', text)]\n\n def _tps(self, data):\n values = findall(r' TPS: (\\d+) \\+/- (\\d+)', data)\n values = [(int(x), int(y)) for x, y in values]\n return list(zip(*values))\n\n def _latency(self, data, scale=1):\n values = findall(r' Latency: (\\d+) \\+/- (\\d+)', data)\n values = [(float(x)/scale, float(y)/scale) for x, y in values]\n return list(zip(*values))\n\n def _variable(self, data):\n return [int(x) for x in findall(r'Variable value: X=(\\d+)', data)]\n\n def _plot(self, x_label, y_label, y_axis, z_axis, type, y_max=None):\n plt.figure(figsize=(6.4, 2.4))\n markers = cycle(['o', 'v', 's', 'p', 'D', 'P'])\n self.results.sort(key=self._natural_keys, reverse=(type == 'tps'))\n for result in self.results:\n y_values, y_err = y_axis(result)\n x_values = self._variable(result)\n if len(y_values) != len(y_err) or len(y_err) != len(x_values):\n raise PlotError('Unequal number of x, y, and y_err values')\n\n plt.errorbar(\n x_values, y_values, yerr=y_err, label=z_axis(result),\n linestyle='dotted', marker=next(markers), capsize=3\n )\n\n plt.legend(loc='upper center', bbox_to_anchor=(0.5, 1), ncol=2)\n plt.xlim(xmin=0)\n plt.ylim(bottom=0, top=y_max)\n plt.xlabel(x_label, fontweight='bold')\n plt.ylabel(y_label[0], fontweight='bold')\n plt.xticks(weight='bold')\n plt.yticks(weight='bold')\n plt.grid()\n ax = plt.gca()\n ax.xaxis.set_major_formatter(default_major_formatter)\n ax.yaxis.set_major_formatter(default_major_formatter)\n if 'latency' in type:\n ax.yaxis.set_major_formatter(sec_major_formatter)\n for x in ['pdf', 'png']:\n plt.savefig(PathMaker.plot_file(type, x), bbox_inches='tight')\n\n @staticmethod\n def nodes(data):\n batch_size = search(r'Batch size: (\\d+)', data).group(1)\n x = search(r'Committee size: (\\d+)', data).group(1)\n f = search(r'Faults: (\\d+)', data).group(1)\n faults = f' - {f} faulty' if f != '0' else ''\n return f'{x} nodes (batch size: {batch_size}){faults}'\n\n @staticmethod\n def shards(data):\n x = search(r'Shards per node: (\\d+)', data).group(1)\n f = search(r'Faults: (\\d+)', data).group(1)\n faults = f'({f} faulty)' if f != '0' else ''\n return f'{x} shards {faults}'\n\n @staticmethod\n def max_latency(data):\n x = search(r'Max latency: (\\d+)', data).group(1)\n f = search(r'Faults: (\\d+)', data).group(1)\n faults = f'({f} faulty)' if f != '0' else ''\n # return f'Max latency: {float(x) / 1000:,.1f} s {faults}'\n return f'Latency cap: {int(x):,} ms {faults}'\n\n @classmethod\n def plot_latency(cls, files, scalability, y_max=None):\n assert isinstance(files, list)\n assert all(isinstance(x, str) for x in files)\n z_axis = cls.shards if scalability else cls.nodes\n x_label = 'Throughput (tx/s)'\n y_label = ['Latency (s)']\n ploter = cls(files)\n ploter._plot(\n x_label, y_label, ploter._latency, z_axis, 'latency', y_max\n )\n\n @classmethod\n def plot_tps(cls, files, scalability):\n assert isinstance(files, list)\n assert all(isinstance(x, str) for x in files)\n z_axis = cls.max_latency\n x_label = 'Shards per authority' if scalability else 'Committee size'\n y_label = ['Throughput (tx/s)']\n ploter = cls(files)\n ploter._plot(x_label, y_label, ploter._tps, z_axis, 'tps', y_max=None)\n\n @classmethod\n def plot(cls, params_dict):\n try:\n params = PlotParameters(params_dict)\n except PlotError as e:\n raise PlotError('Invalid nodes or bench parameters', e)\n\n # Aggregate the logs.\n LogAggregator(params.max_latency).print()\n\n # Make the latency, tps, and robustness graphs.\n iterator = params.shards if params.scalability() else params.nodes\n latency_files, tps_files = [], []\n for f in params.faults:\n for x in iterator:\n latency_files += glob(\n PathMaker.agg_file(\n 'latency',\n f,\n x if not params.scalability() else params.nodes[0],\n x if params.scalability() else params.shards[0],\n params.collocate,\n 'any',\n params.batch_size,\n )\n )\n\n for l in params.max_latency:\n tps_files += glob(\n PathMaker.agg_file(\n 'tps',\n f,\n 'x' if not params.scalability() else params.nodes[0],\n 'x' if params.scalability() else params.shards[0],\n params.collocate,\n 'any',\n params.batch_size,\n max_latency=l,\n )\n )\n\n y_max = 30_000\n cls.plot_latency(latency_files, params.scalability(), y_max)\n cls.plot_tps(tps_files, params.scalability())\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.figure"
]
] |
brauliobarahona/RAPT-dataset
|
[
"ec842544fe8af39d2f44604c06784b4dd6e24108"
] |
[
"notebooks/House_B.py"
] |
[
"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport sys\nsys.path.insert(0,\"./../\") #so we can import our modules properly\n\n\n# In[ ]:\n\n\n# iPhython\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"<style>.container { width:90% !important; }</style>\"))\n\nfrom matplotlib import rcParams\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'notebook')\n\nimport numpy as np\nimport pandas as pd\n\n\n# In[ ]:\n\n\nget_ipython().run_line_magic('matplotlib', 'notebook')\n\n\n# # House B \n\n# In[ ]:\n\n\npath_to_house = \"./datasets/dfB_300s.hdf\"\ndf_house = pd.read_hdf(path_to_house)\nprint('\\n\\nStart time: {}'.format(df_house.index[1]))\nprint('End time: {}'.format(df_house.index[-1]))\nprint(df_house.columns)\n\n\n# ## Check that boiler power does not exceed total consumed power\n\n# In[ ]:\n\n\nmeters = ['B_boiler_power']\n\n# Investigate only points in time where all values are available\ncols = ['B_total_cons_power']\ncols.extend(meters)\ndf_house_noNAN = df_house.loc[:,cols].dropna(axis=0, how='any')\n\n# Check if total consumed power is larger than total of appliances\ndelta = df_house_noNAN.loc[:,meters].sum(axis=1) - df_house_noNAN.loc[:,'B_total_cons_power']\ntmt = delta > 0\n\nif np.any(tmt):\n print('Boiler Power is larger than total consumed power for some data points.')\n\n # investigate problematic cases\n print(\"Found {} out of {} ({:.2}%) values to be problematic.\".format(tmt.sum(), len(tmt), tmt.sum()/len(tmt)*100))\n print(\"\")\n print(\"Statistics of problematic values:\")\n print(delta[tmt].describe())\n print()\n print((delta[tmt]/df_house_noNAN.loc[tmt, 'B_total_cons_power']).describe())\nelse: \n print(\"Total of all appliances is smaller than total consumed energy for all measurement points.\")\n\n\n# In[ ]:\n\n\nl = ['Total Appliances = Boiler', 'Total Consumed']\nif np.any(tmt):\n print('Boiler Power is larger than total consumed power for some data points.')\n \n ## plot params ##\n ha = 6\n ncols = 8\n nrows = np.sum(tmt)//ncols+1\n fig, ax = plt.subplots(figsize=(17,3*nrows), ncols=ncols, nrows=nrows)\n idxs = np.nonzero(tmt)[0]\n for i, idx in enumerate(idxs):\n minidx = idx-ha\n maxidx = idx+ha\n df_house_noNAN.iloc[minidx:maxidx].loc[:,'B_boiler_power'].plot(ax=ax[i//ncols, i%ncols], label='Total Appliances')\n df_house_noNAN.iloc[minidx:maxidx].loc[:,'B_total_cons_power'].plot(ax=ax[i//ncols, i%ncols], label='Total Consumed')\n fig.legend(l, loc='upper center')\nelse: \n print(\"Total of all appliances is smaller than total consumed energy for all measurement points.\")\n\n\n# ## Visualize Boiler Variables\n\n# In[ ]:\n\n\nfig, ax = plt.subplots(ncols=1, nrows=3, figsize=(17,12), sharex=True)\ndf_house.loc[:,['B_boilertemp_top', 'B_boilertemp_bottom']].plot(ax=ax[0])\nax[0].legend()\nax2 = ax[0].twinx()\ndf_house.loc[:,'B_boiler_power'].plot(ax=ax2, color='green')\nax2.legend()\ndf_house.loc[:,['B_boiler_heater_1_on', 'B_boiler_heater_2_on', 'B_boiler_heater_3_on']].plot(ax=ax[1])\nax[1].legend()\ndf_house.loc[:,['B_boiler_on_thermostat']].plot(ax=ax[2])\nax[2].legend()\n\n\n# ## Check that `B_pv_prod_power` is the sum of `B_to_batt_power` + `B_direct_cons_power`+ `B_to_net_power`\n\n# In[ ]:\n\n\n# Investigate only points in time where all values are available\ndf_house_noNAN = df_house.loc[:,['B_pv_prod_power', 'B_to_batt_power', 'B_direct_cons_power', 'B_to_net_power']].dropna(axis=0, how='any')\ndelta = df_house_noNAN.loc[:,'B_pv_prod_power'] - df_house_noNAN.loc[:,['B_to_batt_power', 'B_direct_cons_power', 'B_to_net_power']].sum(axis=1)\nprint(\"Statistics of deviations:\")\ndelta.describe()\n\n\n# ## Check that `B_total_cons_power` is the sum of `B_direct_cons_power` + `B_from_batt_power` + `B_from_net_power`\n\n# In[ ]:\n\n\n# Investigate only points in time where all values are available\ndf_house_noNAN = df_house.loc[:,['B_total_cons_power', 'B_direct_cons_power', 'B_from_batt_power', 'B_from_net_power']].dropna(axis=0, how='any')\ndelta = df_house_noNAN.loc[:,'B_total_cons_power'] - df_house_noNAN.loc[:,['B_direct_cons_power', 'B_from_batt_power', 'B_from_net_power']].sum(axis=1)\nprint(\"Statistics of deviations:\")\ndelta.describe()\n\n\n# ## Visualize Batter Power Flows\n\n# In[ ]:\n\n\nfig, ax = plt.subplots(figsize=(17,4))\ndf_house.loc[:,['B_to_batt_power', 'B_from_batt_power']].plot(ax=ax)\nax.legend(loc='upper left')\nax2 = ax.twinx()\ndf_house.loc[:,'B_batt_state'].plot(ax=ax2, color='green')\nax2.legend(loc='lower left')\n\n\n# # House B - Raw Data\n\n# In[ ]:\n\n\nimport os\nbase_path = \"../rawData/B/\"\nfiles = os.listdir(path=base_path)\n\nblacklisted = [\"capPeriods.hdf\"]\nfor file in files:\n if file in blacklisted: continue\n print(file)\n print(os.path.join(base_path, file))\n df_rawData = pd.read_hdf(os.path.join(base_path, file))\n print(df_rawData.iloc[1,0]-df_rawData.iloc[0,0])\n print(df_rawData.iloc[-1,0]-df_rawData.iloc[-2,0])\n print()\n\n\n# In[ ]:\n\n\n\n\n"
] |
[
[
"pandas.read_hdf",
"numpy.nonzero",
"matplotlib.pyplot.subplots",
"numpy.any",
"numpy.sum"
]
] |
flaviovdf/ecmlpkdd-analytics-challenge-2014
|
[
"2e3cb71fec863bde97d2e7f1712beb240ba9ab33"
] |
[
"baselines.py"
] |
[
"#-*- coding: utf8\nfrom __future__ import division, print_function\n\nfrom gcv_ols import OLS\n\nfrom rbf import RidgeRBFModel\n\nfrom sklearn import cross_validation\nfrom sklearn import grid_search\n\nimport myio\nimport numpy as np\n\ndef rbf(X, Y):\n for sigma in [0.001, 0.01, 0.1, 1, 10, 100, 1000]:\n for num_dist in [10, 50, 100]:\n model = RidgeRBFModel(sigma=sigma, num_dists=num_dist)\n model.fit(X, Y)\n \n base = model.base_learner\n alphas = base.alphas\n best = base.alpha_\n \n best_idx = np.where(alphas == best)[0][0]\n cv_values = base.cv_values_[:, :, best_idx]\n \n print('sigma', 'num_dists', 'alpha', 'rmse')\n print(sigma, num_dist, best, np.sqrt(cv_values.mean(axis=0)))\n\nif __name__ == '__main__':\n \n X_ml_visits = myio.read_features_ml(test=False, series='visits')\n X_ml_facebook = myio.read_features_ml(test=False, series='facebook')\n X_ml_twitter = myio.read_features_ml(test=False, series='twitter')\n\n X_news = myio.read_features_news(test=False)\n Y_train = myio.read_response_train()\n \n print('ML visits')\n model = OLS()\n model.fit(X_ml_visits, Y_train)\n print(np.sqrt(model.G.mean(axis=0)))\n print()\n\n print('ML facebook')\n model = OLS()\n model.fit(X_ml_facebook, Y_train)\n print(np.sqrt(model.G.mean(axis=0)))\n print()\n\n print('ML twitter')\n model = OLS()\n model.fit(X_ml_twitter, Y_train)\n print(np.sqrt(model.G.mean(axis=0)))\n print()\n\n print('News')\n model = OLS()\n model.fit(X_news, Y_train)\n print(np.sqrt(model.G.mean(axis=0)))\n print()\n\n print('RBF visits')\n rbf(X_ml_visits, Y_train)\n print()\n\n print('RBF facebook')\n rbf(X_ml_facebook, Y_train)\n print()\n\n print('ML twitter')\n rbf(X_ml_twitter, Y_train)\n print()\n\n\n"
] |
[
[
"numpy.where"
]
] |
LeonieWeissweiler/EvalCharRNN
|
[
"b7830f53a3e256b28b80ddc6381fca14532a06aa"
] |
[
"src/data_huge.py"
] |
[
"#!/usr/bin/python3\r\nimport sys\r\nimport numpy as np\r\nimport regex\r\nimport os\r\n\r\ndata_dir = \"../data/wikipedia/\"\r\nletters = regex.compile(r'[^\\p{L}\\p{M}]')\r\nnumbers = regex.compile(r'[0-9]+')\r\nspaces = regex.compile(r'\\s+')\r\n\r\nsmall_count_token = 7474100\r\nsmall_count_type = 348843\r\n\r\n\r\ncut_token = small_count_token // 100\r\ncut_type = small_count_type // 100\r\n\r\nlanguages = [ name for name in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, name)) ]\r\n\r\ndef plot(model):\r\n def doLanguage(language):\r\n print(language, model)\r\n try:\r\n gen_dict = {}\r\n huge_file = open(data_dir + language + \"/huge.txt\")\r\n\r\n if os.stat(data_dir + language + \"/\" + model + \"/generated_wordlist.txt\").st_size == 0:\r\n print(\"empty file found for\", data_dir + language + \"/\" + model + \"/generated_wordlist.txt\")\r\n return\r\n gen_file = open(data_dir + language + \"/\" + model + \"/generated_wordlist.txt\")\r\n for line in gen_file:\r\n word, freq = line.split(\" \")\r\n gen_dict[word] = int(freq)\r\n gen_file.close()\r\n\r\n input_dict = {}\r\n input_file = open(data_dir + language + \"/input_wordlist.txt\")\r\n for line in input_file:\r\n word, freq = line.split(\" \")\r\n input_dict[word] = int(freq)\r\n input_file.close()\r\n\r\n i = 0\r\n huge_dict = {}\r\n huge_type_size = 0\r\n huge_token_size = 0\r\n huge_char_size = 0\r\n gen_good_tokens = 0\r\n gen_new_types = 0\r\n gen_total_tokens = sum(gen_dict.values())\r\n gen_total_types = len(gen_dict)\r\n char_x = []\r\n token_x = []\r\n type_x = []\r\n token_y_for_token_x = []\r\n token_y_for_type_x = []\r\n type_y_for_token_x = []\r\n type_y_for_type_x = []\r\n\r\n print(\"iterating\")\r\n\r\n for line in huge_file:\r\n line = line.strip()\r\n line = regex.sub(letters, \" \", line)\r\n line = regex.sub(numbers, \"0\", line)\r\n line = regex.sub(spaces, \" \", line)\r\n for word in line.split(\" \"):\r\n huge_token_size += 1\r\n huge_char_size += len(word) + 1 #add one for the space\r\n if word not in huge_dict:\r\n i += 1\r\n if i >= small_count_type:\r\n print(language, model, gen_good_tokens/gen_total_tokens, gen_new_types)\r\n return\r\n huge_dict[word] = 1\r\n huge_type_size += 1\r\n if word in gen_dict:\r\n gen_good_tokens += gen_dict[word]\r\n if word not in input_dict:\r\n gen_new_types += 1\r\n if huge_type_size % 100 == 0:\r\n type_x.append(huge_type_size)\r\n token_y_for_type_x.append(gen_good_tokens / gen_total_tokens)\r\n type_y_for_type_x.append(gen_new_types)\r\n if huge_token_size % 100 == 0:\r\n token_x.append(huge_token_size)\r\n char_x.append(huge_char_size)\r\n token_y_for_token_x.append(gen_good_tokens / gen_total_tokens)\r\n type_y_for_token_x.append(gen_new_types)\r\n\r\n gen_file.close()\r\n\r\n def write(x,y,name):\r\n outlist = np.array([np.array(x), np.array(y)])\r\n outfile = open(data_dir + language + \"/\" + model + \"/\" + name + \"_data.npy\", \"wb\")\r\n np.save(outfile, outlist)\r\n outfile.close()\r\n\r\n write(char_x, token_y_for_token_x,\"huge_char_token_performance\")\r\n write(char_x, type_y_for_token_x,\"huge_char_type_performance\")\r\n write(token_x, token_y_for_token_x,\"huge_token_token_performance\")\r\n write(token_x, type_y_for_token_x,\"huge_token_type_performance\")\r\n write(type_x, type_y_for_type_x,\"huge_type_type_performance\")\r\n write(type_x, token_y_for_type_x, \"huge_type_token_performance\")\r\n\r\n write(token_x[:cut_token], token_y_for_token_x[:cut_token],\"norm_huge_token_token_performance\")\r\n write(token_x[:cut_token], type_y_for_token_x[:cut_token],\"norm_huge_token_type_performance\")\r\n write(type_x[:cut_type], type_y_for_type_x[:cut_type],\"norm_huge_type_type_performance\")\r\n write(type_x[:cut_type], token_y_for_type_x[:cut_type], \"norm_huge_type_token_performance\")\r\n\r\n except OSError as error:\r\n print(error)\r\n print(\"no generated found for\", data_dir + language + \"/\" + model + \"/generated_wordlist.txt\")\r\n\r\n for language in languages:\r\n doLanguage(language)\r\n\r\nmodels = [\"lstm\", \"rnn\", \"nas\", \"gru\"]\r\nfor model in models:\r\n plot(model)\r\n"
] |
[
[
"numpy.array",
"numpy.save"
]
] |
sbuschjaeger/Pysembles
|
[
"7e69b0975a7d4373242c7026ade6c5fdbad4fe67"
] |
[
"pysembles/Metrics.py"
] |
[
"import numpy as np\nimport pandas as pd\nimport torch\nimport scipy\n\nimport torch\nfrom torch import nn\nfrom torch.autograd import Variable\nimport torchvision\nimport torchvision.transforms as transforms\n\nfrom sklearn.metrics import make_scorer, accuracy_score\n\nfrom pysembles.Utils import TransformTensorDataset\n\n'''\nSome common metrics and helper functions. \nTODO: Add detailed documentation for each function\n'''\n\ndef diversity(model, data_loader):\n if not hasattr(model, \"estimators_\"):\n return 0\n model.eval()\n \n diversities = []\n for batch in data_loader:\n data, target = batch[0], batch[1]\n data, target = data.cuda(), target.cuda()\n data, target = Variable(data), Variable(target)\n\n with torch.no_grad():\n f_bar, base_preds = model.forward_with_base(data)\n \n if isinstance(model.loss_function, nn.MSELoss): \n n_classes = f_bar.shape[1]\n n_preds = f_bar.shape[0]\n\n eye_matrix = torch.eye(n_classes).repeat(n_preds, 1, 1).cuda()\n D = 2.0*eye_matrix\n elif isinstance(model.loss_function, nn.NLLLoss):\n n_classes = f_bar.shape[1]\n n_preds = f_bar.shape[0]\n D = torch.eye(n_classes).repeat(n_preds, 1, 1).cuda()\n target_one_hot = torch.nn.functional.one_hot(target, num_classes = n_classes).type(model.get_float_type())\n\n eps = 1e-7\n diag_vector = target_one_hot*(1.0/(f_bar**2+eps))\n D.diagonal(dim1=-2, dim2=-1).copy_(diag_vector)\n elif isinstance(model.loss_function, nn.CrossEntropyLoss):\n n_preds = f_bar.shape[0]\n n_classes = f_bar.shape[1]\n f_bar_softmax = nn.functional.softmax(f_bar,dim=1)\n D = -1.0*torch.bmm(f_bar_softmax.unsqueeze(2), f_bar_softmax.unsqueeze(1))\n diag_vector = f_bar_softmax*(1.0-f_bar_softmax)\n D.diagonal(dim1=-2, dim2=-1).copy_(diag_vector)\n else:\n D = torch.tensor(1.0)\n\n batch_diversities = []\n for pred in base_preds:\n diff = pred - f_bar \n covar = torch.bmm(diff.unsqueeze(1), torch.bmm(D, diff.unsqueeze(2))).squeeze()\n div = 1.0/model.n_estimators * 0.5 * covar\n batch_diversities.append(div)\n\n diversities.append(torch.stack(batch_diversities, dim = 1))\n div = torch.cat(diversities,dim=0)\n return div.sum(dim=1).mean(dim=0).item()\n\ndef loss(model, data_loader):\n model.eval()\n \n losses = []\n for batch in data_loader:\n data, target = batch[0], batch[1]\n data, target = data.cuda(), target.cuda()\n data, target = Variable(data), Variable(target)\n\n with torch.no_grad():\n pred = model(data)\n \n losses.append(model.loss_function(pred, target).mean().item())\n \n return np.mean(losses)\n\ndef predict_proba(model, data_loader):\n preds = []\n for batch in data_loader:\n data, target = batch[0], batch[1]\n data, target = data.cuda(), target.cuda()\n data, target = Variable(data), Variable(target)\n with torch.no_grad():\n pred = model(data)\n preds.append(pred.detach().cpu().numpy())\n\n return np.concatenate(preds,axis=0)\n\ndef avg_loss(model, data_loader):\n if not hasattr(model, \"estimators_\"):\n return 0\n model.eval()\n losses = []\n for batch in data_loader:\n data, target = batch[0], batch[1]\n data, target = data.cuda(), target.cuda()\n data, target = Variable(data), Variable(target)\n\n with torch.no_grad():\n f_bar, base_preds = model.forward_with_base(data)\n \n ilosses = []\n for base in base_preds:\n ilosses.append(model.loss_function(base, target).mean().item())\n \n losses.append(np.mean(ilosses))\n\n return np.mean(losses)\n\ndef avg_accurcay(model, data_loader):\n if not hasattr(model, \"estimators_\"):\n return 0\n model.eval()\n \n accuracies = []\n for batch in data_loader:\n data, target = batch[0], batch[1]\n data, target = data.cuda(), target.cuda()\n data, target = Variable(data), Variable(target)\n\n with torch.no_grad():\n _, base_preds = model.forward_with_base(data)\n \n iaccuracies = []\n for base in base_preds:\n iaccuracies.append( 100.0*(base.argmax(1) == target).type(model.get_float_type()) )\n \n accuracies.append(torch.cat(iaccuracies,dim=0).mean().item())\n\n return np.mean(accuracies)\n\ndef accuracy(model, data_loader):\n model.eval()\n accuracies = []\n for batch in data_loader:\n data, target = batch[0], batch[1]\n data, target = data.cuda(), target.cuda()\n data, target = Variable(data), Variable(target)\n\n with torch.no_grad():\n pred = model(data)\n acc = (pred.argmax(1) == target).type(model.get_float_type()).mean().item()\n accuracies.append( acc )\n\n return 100.0*np.mean(accuracies)\n\n# def diversity(model, x, y):\n# # This is basically a copy/paste from the GNCLClasifier regularizer, which can also be used for \n# # other classifier. I tried to do it with numpy first and I think it should work but I did not \n# # really understand numpy's bmm variant, so I opted for the safe route here. \n# # Also, pytorch seems a little faster due to gpu support\n# if not hasattr(model, \"estimators_\"):\n# return 0\n# model.eval()\n \n# x_tensor = torch.tensor(x)\n# y_tensor = torch.tensor(y)\n# dataset = TransformTensorDataset(x_tensor, y_tensor, transform=None)\n# test_loader = torch.utils.data.DataLoader(dataset, batch_size = model.batch_size)\n \n# diversities = []\n# for batch in test_loader:\n# data, target = batch[0], batch[1]\n# data, target = data.cuda(), target.cuda()\n# data, target = Variable(data), Variable(target)\n\n# with torch.no_grad():\n# f_bar, base_preds = model.forward_with_base(data)\n \n# if isinstance(model.loss_function, nn.MSELoss): \n# n_classes = f_bar.shape[1]\n# n_preds = f_bar.shape[0]\n\n# eye_matrix = torch.eye(n_classes).repeat(n_preds, 1, 1).cuda()\n# D = 2.0*eye_matrix\n# elif isinstance(model.loss_function, nn.NLLLoss):\n# n_classes = f_bar.shape[1]\n# n_preds = f_bar.shape[0]\n# D = torch.eye(n_classes).repeat(n_preds, 1, 1).cuda()\n# target_one_hot = torch.nn.functional.one_hot(target, num_classes = n_classes).type(model.get_float_type())\n\n# eps = 1e-7\n# diag_vector = target_one_hot*(1.0/(f_bar**2+eps))\n# D.diagonal(dim1=-2, dim2=-1).copy_(diag_vector)\n# elif isinstance(model.loss_function, nn.CrossEntropyLoss):\n# n_preds = f_bar.shape[0]\n# n_classes = f_bar.shape[1]\n# f_bar_softmax = nn.functional.softmax(f_bar,dim=1)\n# D = -1.0*torch.bmm(f_bar_softmax.unsqueeze(2), f_bar_softmax.unsqueeze(1))\n# diag_vector = f_bar_softmax*(1.0-f_bar_softmax)\n# D.diagonal(dim1=-2, dim2=-1).copy_(diag_vector)\n# else:\n# D = torch.tensor(1.0)\n\n# batch_diversities = []\n# for pred in base_preds:\n# diff = pred - f_bar \n# covar = torch.bmm(diff.unsqueeze(1), torch.bmm(D, diff.unsqueeze(2))).squeeze()\n# div = 1.0/model.n_estimators * 0.5 * covar\n# batch_diversities.append(div)\n\n# diversities.append(torch.stack(batch_diversities, dim = 1))\n# div = torch.cat(diversities,dim=0)\n# return div.sum(dim=1).mean(dim=0).item()\n \n# # dsum = torch.sum(torch.cat(diversities,dim=0), dim = 0)\n# # return dsum\n# # base_preds = []\n# # for e in model.estimators_:\n# # ypred = apply_in_batches(e, x, 128)\n# # base_preds.append(ypred)\n \n# # f_bar = np.mean(base_preds, axis=0)\n# # if isinstance(model.loss_function, nn.MSELoss): \n# # n_classes = f_bar.shape[1]\n# # n_preds = f_bar.shape[0]\n\n# # eye_matrix = np.eye(n_classes).repeat(n_preds, 1, 1)\n# # D = 2.0*eye_matrix\n# # elif isinstance(model.loss_function, nn.NLLLoss):\n# # n_classes = f_bar.shape[1]\n# # n_preds = f_bar.shape[0]\n# # D = np.eye(n_classes).repeat(n_preds, 1, 1)\n# # target_one_hot = np.zeros((y.size, n_classes))\n# # target_one_hot[np.arange(y.size),y] = 1\n\n# # eps = 1e-7\n# # diag_vector = target_one_hot*(1.0/(f_bar**2+eps))\n# # #D[np.diag_indices(D.shape[0])] = diag_vector\n# # for i in range(D.shape[0]):\n# # np.fill_diagonal(D[i,:], diag_vector[i,:])\n# # elif isinstance(model.loss_function, nn.CrossEntropyLoss):\n# # n_preds = f_bar.shape[0]\n# # n_classes = f_bar.shape[1]\n# # f_bar_softmax = scipy.special.softmax(f_bar,axis=1)\n\n# # D = -1.0 * np.expand_dims(f_bar_softmax, axis=2) @ np.expand_dims(f_bar_softmax, axis=1)\n\n# # # D = -1.0*torch.bmm(f_bar_softmax.unsqueeze(2), f_bar_softmax.unsqueeze(1))\n# # diag_vector = f_bar_softmax*(1.0-f_bar_softmax)\n# # for i in range(D.shape[0]):\n# # np.fill_diagonal(D[i,:], diag_vector[i,:])\n# # else:\n# # D = np.array([1.0])\n\n# # diversities = []\n# # for pred in base_preds:\n# # # https://stackoverflow.com/questions/63301019/dot-product-of-two-numpy-arrays-with-3d-vectors\n# # # https://stackoverflow.com/questions/51479148/how-to-perform-a-stacked-element-wise-matrix-vector-multiplication-in-numpy\n# # diff = pred - f_bar \n# # tmp = np.sum(D * diff[:,:,None], axis=1)\n# # covar = np.sum(tmp*diff,axis=1)\n\n# # # covar = torch.bmm(diff.unsqueeze(1), torch.bmm(D, diff.unsqueeze(2))).squeeze()\n# # div = 1.0/model.n_estimators * 0.5 * covar\n# # diversities.append(np.mean(div))\n# #return np.sum(diversities)\n\n# def loss(model, x, y):\n# model.eval()\n \n# x_tensor = torch.tensor(x)\n# y_tensor = torch.tensor(y)\n# dataset = TransformTensorDataset(x_tensor, y_tensor, transform=None)\n# test_loader = torch.utils.data.DataLoader(dataset, batch_size = model.batch_size)\n \n# losses = []\n# for batch in test_loader:\n# data, target = batch[0], batch[1]\n# data, target = data.cuda(), target.cuda()\n# data, target = Variable(data), Variable(target)\n\n# with torch.no_grad():\n# pred = model(data)\n \n# losses.append(model.loss_function(pred, target).mean().item())\n \n# return np.mean(losses)\n\n# def avg_loss(model, x, y):\n# if not hasattr(model, \"estimators_\"):\n# return 0\n# model.eval()\n \n# x_tensor = torch.tensor(x)\n# y_tensor = torch.tensor(y)\n# dataset = TransformTensorDataset(x_tensor, y_tensor, transform=None)\n# test_loader = torch.utils.data.DataLoader(dataset, batch_size = model.batch_size)\n \n# losses = []\n# for batch in test_loader:\n# data, target = batch[0], batch[1]\n# data, target = data.cuda(), target.cuda()\n# data, target = Variable(data), Variable(target)\n\n# with torch.no_grad():\n# f_bar, base_preds = model.forward_with_base(data)\n \n# ilosses = []\n# for base in base_preds:\n# ilosses.append(model.loss_function(base, target).mean().item())\n \n# losses.append(np.mean(ilosses))\n\n# return np.mean(losses)\n\n# def avg_accurcay(model, x, y):\n# if not hasattr(model, \"estimators_\"):\n# return 0\n# model.eval()\n \n# x_tensor = torch.tensor(x)\n# y_tensor = torch.tensor(y)\n# dataset = TransformTensorDataset(x_tensor, y_tensor, transform=None)\n# test_loader = torch.utils.data.DataLoader(dataset, batch_size = model.batch_size)\n \n# accuracies = []\n# for batch in test_loader:\n# data, target = batch[0], batch[1]\n# data, target = data.cuda(), target.cuda()\n# data, target = Variable(data), Variable(target)\n\n# with torch.no_grad():\n# _, base_preds = model.forward_with_base(data)\n \n# iaccuracies = []\n# for base in base_preds:\n# iaccuracies.append( 100.0*(base.argmax(1) == target).type(model.get_float_type()) )\n \n# accuracies.append(torch.cat(iaccuracies,dim=0).mean().item())\n\n# return np.mean(accuracies)\n# # accuracies = torch.cat(accuracies,dim=0)\n# # return accuracies.mean().item()"
] |
[
[
"torch.nn.functional.softmax",
"torch.cat",
"torch.nn.functional.one_hot",
"torch.eye",
"torch.tensor",
"numpy.concatenate",
"torch.no_grad",
"numpy.mean",
"torch.stack",
"torch.autograd.Variable"
]
] |
sdrogers/ms2ldaviz
|
[
"ba311bc80891da595d2d6cef4abda95ab583c201"
] |
[
"ms2ldaviz/basicviz/views/views_lda_multi.py"
] |
[
"import json\nimport math\n\nimport jsonpickle\nimport networkx as nx\nimport numpy as np\nfrom django.http import HttpResponse, Http404\nfrom django.shortcuts import render\nfrom networkx.readwrite import json_graph\nfrom scipy.stats import ttest_ind\n\nfrom basicviz.forms import AlphaCorrelationForm, AlphaDEForm\nfrom massbank.forms import Mass2MotifMetadataForm\nfrom basicviz.models import Experiment, Mass2Motif, Mass2MotifInstance, MultiFileExperiment, MultiLink, Alpha, \\\n AlphaCorrOptions, Document\nfrom massbank.views import get_massbank_form\nfrom options.views import get_option\nfrom .views_index import index\nfrom .views_lda_single import get_docm2m, get_docm2m_bydoc\n\n\ndef get_individual_names(request, mf_id):\n mfe = MultiFileExperiment.objects.get(id=mf_id)\n links = MultiLink.objects.filter(multifileexperiment=mfe).order_by('experiment__name')\n individuals = [l.experiment for l in links]\n individual_names = [i.name for i in individuals]\n return HttpResponse(json.dumps(individual_names), content_type='application/json')\n\n\ndef get_alpha_matrix(request, mf_id):\n if True:\n mfe = MultiFileExperiment.objects.get(id=mf_id)\n\n if not mfe.alpha_matrix:\n\n links = MultiLink.objects.filter(multifileexperiment=mfe).order_by('experiment__name')\n individuals = [l.experiment for l in links]\n motifs = Mass2Motif.objects.filter(experiment=individuals[0])\n\n alp_vals = []\n for individual in individuals:\n motifs = individual.mass2motif_set.all().order_by('name')\n alp_vals.append([m.alpha_set.all()[0].value for m in motifs])\n\n alp_vals = map(list, zip(*alp_vals))\n alp_vals = [[motifs[i].name, motifs[i].annotation] + av + [float((np.array(av) / sum(av)).var())] for i, av\n in enumerate(alp_vals)]\n\n data = json.dumps(alp_vals)\n mfe.alpha_matrix = jsonpickle.encode(alp_vals)\n mfe.save()\n else:\n alp_vals = jsonpickle.decode(mfe.alpha_matrix)\n data = json.dumps(alp_vals)\n\n return HttpResponse(data, content_type='application/json')\n else:\n raise Http404\n\n\ndef get_degree_matrix(request, mf_id):\n if request.is_ajax():\n mfe = MultiFileExperiment.objects.get(id=mf_id)\n if not mfe.degree_matrix:\n links = MultiLink.objects.filter(multifileexperiment=mfe).order_by('experiment__name')\n individuals = [l.experiment for l in links]\n deg_vals = []\n\n for individual in individuals:\n\n # doc_m2m_threshold = get_option('doc_m2m_threshold', experiment=individual)\n # if doc_m2m_threshold:\n # doc_m2m_threshold = float(doc_m2m_threshold)\n # else:\n # doc_m2m_threshold = 0.0\n # default_score = get_option('default_doc_m2m_score', experiment=individual)\n # if not default_score:\n # default_score = 'probability'\n\n new_row = []\n motif_set = individual.mass2motif_set.all().order_by('name')\n for motif in motif_set:\n motif_name = motif.name\n m2m = Mass2Motif.objects.get(name=motif_name, experiment=individual)\n docs = get_docm2m(m2m)\n\n # Following modified to make the degrees here consistent with the plots\n \n # dm2m = motif.documentmass2motif_set.all()\n # if default_score == 'probability':\n # new_row.append(len([d for d in dm2m if d.probability > doc_m2m_threshold]))\n # else:\n # new_row.append(len([d for d in dm2m if d.overlap_score > doc_m2m_threshold]))\n\n new_row.append(len(docs))\n\n deg_vals.append(new_row)\n\n deg_vals = map(list, zip(*deg_vals))\n deg_vals = [[motif_set[i].name, motif_set[i].annotation] + dv for i, dv in enumerate(deg_vals)]\n\n data = json.dumps(deg_vals)\n mfe.degree_matrix = jsonpickle.encode(deg_vals)\n mfe.save()\n else:\n deg_vals = jsonpickle.decode(mfe.degree_matrix)\n data = json.dumps(deg_vals)\n return HttpResponse(data, content_type='application/json')\n else:\n raise Http404\n\n\ndef make_alpha_matrix(individuals, normalise=True):\n print(\"Creating alpha matrix\")\n alp_vals = []\n for individual in individuals:\n motifs = individual.mass2motif_set.all().order_by('name')\n alp_vals.append([m.alpha_set.all()[0].value for m in motifs])\n\n alp_vals = map(list, zip(*alp_vals))\n new_alp_vals = []\n if normalise:\n for av in alp_vals:\n s = sum(av)\n nav = [a / s for a in av]\n new_alp_vals.append(nav)\n alp_vals = new_alp_vals\n\n return alp_vals\n\n\ndef wipe_cache(request, mf_id):\n mfe = MultiFileExperiment.objects.get(id=mf_id)\n mfe.alpha_matrix = None\n mfe.degree_matrix = None\n mfe.save()\n return index(request)\n\n\ndef get_doc_table(request, mf_id, motif_name):\n mfe = MultiFileExperiment.objects.get(id=mf_id)\n links = MultiLink.objects.filter(multifileexperiment=mfe).order_by('experiment__name')\n individuals = [l.experiment for l in links]\n\n individual_motifs = {}\n for individual in individuals:\n thismotif = Mass2Motif.objects.get(experiment=individual, name=motif_name)\n individual_motifs[individual] = thismotif\n\n doc_table = []\n individual_names = []\n peaksets = {}\n peakset_list = []\n peakset_masses = []\n for i, individual in enumerate(individuals):\n individual_names.append(individual.name)\n docs = get_docm2m(individual_motifs[individual])\n for doc in docs:\n peakset_index = -1\n ii = doc.document.intensityinstance_set.all()\n if len(ii) > 0:\n ii = ii[0]\n ps = ii.peakset\n if not ps in peaksets:\n peaksets[ps] = {}\n peakset_list.append(ps)\n peakset_masses.append(ps.mz)\n peakset_index = peakset_list.index(ps)\n peaksets[ps][individual] = ii.intensity\n\n mz = 0\n rt = 0\n md = jsonpickle.decode(doc.document.metadata)\n if 'parentmass' in md:\n mz = md['parentmass']\n elif 'mz' in md:\n mz = md['mz']\n elif '_' in doc.document.name:\n split_name = doc.document.name.split('_')\n mz = float(split_name[0])\n if 'rt' in md:\n rt = md['rt']\n elif '_' in doc.document.name:\n split_name = doc.document.name.split('_')\n rt = float(split_name[1])\n\n doc_table.append([rt, mz, i, doc.probability, peakset_index])\n\n # Add the peaks to the peakset object that are not linked to a document\n # (i.e. the MS1 peak is present, but it wasn't fragmented)\n for ps in peaksets:\n # Grab the intensity instances for this peakset\n intensity_instances = ps.intensityinstance_set.all()\n # Extract the individual experiments that are represented\n individuals_present = [i.experiment for i in intensity_instances]\n # Loop over the experiment\n for individual in individuals:\n # If the experiment is not in the current peakset but there is an intensity instance\n if (not individual in peaksets[ps]) and individual in individuals_present:\n # Find the intensity instance\n int_int = filter(lambda x: x.experiment == individual, intensity_instances)\n peaksets[ps][individual] = int_int[0].intensity\n print(ps, individual, int_int[0].intensity)\n\n intensity_table = []\n unnormalised_intensity_table = []\n counts = []\n final_peaksets = []\n\n min_count_options = get_option('heatmap_minimum_display_count',experiment = individuals[0])\n # min_count_options = SystemOptions.objects.filter(key='heatmap_minimum_display_count')\n if len(min_count_options) > 0:\n min_count = int(min_count_options)\n else:\n min_count = 5\n\n log_intensities_options = get_option('log_peakset_intensities',experiment = individuals[0])\n # log_intensities_options = SystemOptions.objects.filter(key='log_peakset_intensities')\n if len(log_intensities_options) > 0:\n val = log_intensities_options\n if val == 'true':\n log_peakset_intensities = True\n else:\n log_peakset_intensities = False\n else:\n log_peakset_intensities = True\n \n normalise_heatmap_options = get_option('heatmap_normalisation',experiment = individuals[0])\n if len(normalise_heatmap_options) == 0:\n normalise_heatmap_options = 'none'\n\n for peakset in peaksets:\n new_row = []\n for individual in individuals:\n new_row.append(peaksets[peakset].get(individual, 0))\n count = sum([1 for i in new_row if i > 0])\n if min_count >= 0:\n nz_vals = [v for v in new_row if v > 0]\n if log_peakset_intensities:\n nz_vals = [np.log(v) for v in nz_vals]\n new_row = [np.log(v) if v > 0 else 0 for v in new_row]\n me = sum(nz_vals) / (1.0 * len(nz_vals))\n va = sum([v ** 2 for v in nz_vals]) / len(nz_vals) - me ** 2\n va = math.sqrt(va)\n maxval = max(nz_vals)\n\n if normalise_heatmap_options == 'none':\n intensity_table.append(new_row)\n unnormalised_intensity_table.append(new_row)\n counts.append(count)\n final_peaksets.append(peakset)\n elif normalise_heatmap_options == 'max':\n new_row_n = [v/maxval for v in new_row]\n intensity_table.append(new_row_n)\n unnormalised_intensity_table.append(new_row)\n counts.append(count)\n final_peaksets.append(peakset)\n elif normalise_heatmap_options == 'standard' and va > 0:\n # if variance is zero, skip...\n unnormalised_intensity_table.append(new_row)\n new_row_n = [(v - me) / va if v > 0 else 0 for v in new_row]\n intensity_table.append(new_row_n)\n counts.append(count)\n final_peaksets.append(peakset)\n\n # Order so that the most popular are at the top\n if len(final_peaksets) > 0:\n temp = zip(counts, intensity_table, final_peaksets)\n temp = sorted(temp, key=lambda x: x[0], reverse=True)\n counts, intensity_table, final_peaksets = zip(*temp)\n intensity_table = list(intensity_table)\n\n # Change the indexes in the doc table to match the new ordering\n for row in doc_table:\n old_ps_index = row[-1]\n if old_ps_index > -1:\n old_ps = peakset_list[old_ps_index]\n if old_ps in final_peaksets:\n new_ps_index = final_peaksets.index(old_ps)\n else:\n new_ps_index = -1\n row[-1] = new_ps_index\n\n final_peakset_masses = [p.mz for p in final_peaksets]\n final_peakset_rt = [p.rt for p in final_peaksets]\n\n final_peakset_rt_variance = np.array(final_peakset_rt).var()\n return HttpResponse(json.dumps((\n individual_names, doc_table, intensity_table, final_peakset_masses, final_peakset_rt,\n unnormalised_intensity_table,final_peakset_rt_variance)), content_type='application/json')\n\n\ndef view_multi_m2m(request, mf_id, motif_name):\n mfe = MultiFileExperiment.objects.get(id=mf_id)\n links = MultiLink.objects.filter(multifileexperiment=mfe).order_by('experiment__name')\n individuals = [l.experiment for l in links if l.experiment.status == \"1\"]\n context_dict = {'mfe': mfe}\n context_dict['motif_name'] = motif_name\n\n # get the features\n firstm2m = Mass2Motif.objects.get(name=motif_name, experiment=individuals[0])\n m2mfeatures = Mass2MotifInstance.objects.filter(mass2motif=firstm2m)\n m2mfeatures = sorted(m2mfeatures, key=lambda x: x.probability, reverse=True)\n context_dict['m2m_features'] = m2mfeatures\n\n individual_motifs = {}\n for individual in individuals:\n thism2m = Mass2Motif.objects.get(name=motif_name, experiment=individual)\n individual_motifs[individual] = thism2m\n\n context_dict['status'] = 'Edit metadata...'\n if request.method == 'POST':\n form = Mass2MotifMetadataForm(request.POST)\n if form.is_valid():\n new_annotation = form.cleaned_data['metadata']\n new_short_annotation = form.cleaned_data['short_annotation']\n for individual in individual_motifs:\n motif = individual_motifs[individual]\n md = jsonpickle.decode(motif.metadata)\n if len(new_annotation) > 0:\n md['annotation'] = new_annotation\n elif 'annotation' in md:\n del md['annotation']\n if len(new_short_annotation) > 0:\n md['short_annotation'] = new_short_annotation\n elif 'short_annotation' in md:\n del md['short_annotation']\n motif.metadata = jsonpickle.encode(md)\n motif.save()\n context_dict['status'] = 'Metadata saved...'\n\n firstm2m = Mass2Motif.objects.get(name=motif_name, experiment=individuals[0])\n metadata_form = Mass2MotifMetadataForm(\n initial={'metadata': firstm2m.annotation, 'short_annotation': firstm2m.short_annotation})\n context_dict['metadata_form'] = metadata_form\n\n massbank_form = get_massbank_form(firstm2m, m2mfeatures, mf_id=mf_id)\n context_dict['massbank_form'] = massbank_form\n\n # Get the m2m in the individual models\n individual_m2m = []\n alps = []\n doc_table = []\n individual_names = []\n peaksets = {}\n peakset_list = []\n peakset_masses = []\n for i, individual in enumerate(individuals):\n alpha = Alpha.objects.get(mass2motif=individual_motifs[individual])\n docs = get_docm2m(individual_motifs[individual])\n individual_m2m.append([individual, individual_motifs[individual], alpha, len(docs)])\n alps.append(alpha.value)\n\n # Compute the mean and variance\n tot_alps = sum(alps)\n m_alp = sum(alps) / len(alps)\n m_alp2 = sum([a ** 2 for a in alps]) / len(alps)\n var = m_alp2 - m_alp ** 2\n context_dict['alpha_variance'] = var\n context_dict['alphas'] = zip([i.name for i in individuals], alps)\n context_dict['individual_m2m'] = individual_m2m\n return render(request, 'basicviz/view_multi_m2m.html', context_dict)\n\n\ndef get_alphas(request, mf_id, motif_name):\n mfe = MultiFileExperiment.objects.get(id=mf_id)\n links = MultiLink.objects.filter(multifileexperiment=mfe).order_by('experiment__name')\n individuals = [l.experiment for l in links]\n alps = []\n for individual in individuals:\n m2m = Mass2Motif.objects.get(name=motif_name, experiment=individual)\n alpha = Alpha.objects.get(mass2motif=m2m)\n alps.append(alpha.value)\n\n alps = [[individuals[i].name, a] for i, a in enumerate(alps)]\n json_alps = json.dumps(alps)\n return HttpResponse(json_alps, content_type='application/json')\n\n\ndef get_degrees(request, mf_id, motif_name):\n mfe = MultiFileExperiment.objects.get(id=mf_id)\n links = MultiLink.objects.filter(multifileexperiment=mfe).order_by('experiment__name')\n individuals = [l.experiment for l in links]\n degs = []\n for individual in individuals:\n m2m = Mass2Motif.objects.get(name=motif_name, experiment=individual)\n docs = get_docm2m(m2m)\n degs.append(len(docs))\n\n degs = zip([i.name for i in individuals], degs)\n json_degs = json.dumps(degs)\n return HttpResponse(json_degs, content_type='application/json')\n\n\ndef alpha_pca(request, mf_id):\n # Returns a json object to be rendered into a pca plot\n # PCA is pre-computed\n mfe = MultiFileExperiment.objects.get(id=mf_id)\n if mfe.pca:\n pca_data = jsonpickle.decode(mfe.pca)\n else:\n pca_data = []\n return HttpResponse(json.dumps(pca_data), content_type='application/json')\n\n\ndef multi_alphas(request, mf_id):\n mfe = MultiFileExperiment.objects.get(id=mf_id)\n context_dict = {'mfe': mfe}\n links = MultiLink.objects.filter(multifileexperiment=mfe).order_by('experiment__name')\n individuals = [l.experiment for l in links if l.experiment.status == \"1\"]\n context_dict['individuals'] = individuals\n\n alp_vals = []\n degrees = []\n context_dict['alp_vals'] = alp_vals\n context_dict['degrees'] = degrees\n context_dict['url'] = '/basicviz/alpha_pca/{}/'.format(mfe.id)\n return render(request, 'basicviz/multi_alphas.html', context_dict)\n\n\ndef alpha_correlation(request, mf_id):\n mfe = MultiFileExperiment.objects.get(id=mf_id)\n context_dict = {}\n context_dict['mfe'] = mfe\n\n if request.method == 'POST':\n form = AlphaCorrelationForm(request.POST)\n if form.is_valid():\n distance_score = form.cleaned_data['distance_score']\n edge_thresh = form.cleaned_data['edge_thresh']\n normalise_alphas = form.cleaned_data['normalise_alphas']\n max_edges = form.cleaned_data['max_edges']\n just_annotated = form.cleaned_data['just_annotated']\n acviz = AlphaCorrOptions.objects.get_or_create(multifileexperiment=mfe,\n distance_score=distance_score,\n edge_thresh=edge_thresh,\n normalise_alphas=normalise_alphas,\n max_edges=max_edges,\n just_annotated=just_annotated)[0]\n context_dict['acviz'] = acviz\n else:\n context_dict['form'] = form\n else:\n context_dict['form'] = AlphaCorrelationForm()\n\n return render(request, 'basicviz/alpha_correlation.html', context_dict)\n\n\ndef get_alpha_correlation_graph(request, acviz_id):\n from itertools import combinations\n acviz = AlphaCorrOptions.objects.get(id=acviz_id)\n mfe = acviz.multifileexperiment\n links = mfe.multilink_set.all().order_by('experiment__name')\n individuals = [l.experiment for l in links]\n an_experiment = links[0].experiment\n motifs = Mass2Motif.objects.filter(experiment=an_experiment).order_by('name')\n\n if mfe.alpha_matrix:\n alp_vals_with_names = jsonpickle.decode(mfe.alpha_matrix)\n alp_vals = []\n for av in alp_vals_with_names:\n newav = av[2:-1]\n alp_vals.append(newav)\n\n else:\n alp_vals = make_alpha_matrix(individuals, normalise=True)\n\n motif_index = []\n an_motifs = []\n if acviz.just_annotated:\n for i, motif in enumerate(motifs):\n if 'annotation' in jsonpickle.decode(motif.metadata):\n an_motifs.append(motif)\n motif_index.append(i)\n motifs = an_motifs\n else:\n motif_index = range(len(motifs))\n\n # Add motifs as nodes\n G = nx.Graph()\n motif_names = []\n for motif in motifs:\n md = jsonpickle.decode(motif.metadata)\n name = motif.name\n if 'mass2motif' in name:\n tokens = name.split('_')\n name = tokens[1] # get the last part of e.g. 'mass2motif_11'\n display_name = md.get('annotation', md.get('short_annotation', name))\n\n motif_names.append(motif.name)\n if 'annotation' in md:\n G.add_node(motif.name, name=display_name, col='#FF0000')\n else:\n G.add_node(motif.name, name=display_name, col='#333333')\n\n # add edges where the score is > thresh\n scores = []\n for i, j in combinations(range(len(motifs)), 2):\n a1 = np.array(alp_vals[motif_index[i]])\n a2 = np.array(alp_vals[motif_index[j]])\n\n if acviz.normalise_alphas:\n a1n = a1 / np.linalg.norm(a1)\n a2n = a2 / np.linalg.norm(a2)\n else:\n a1n = a1\n a2n = a2\n\n if acviz.distance_score == 'cosine':\n score = np.dot(a1n, a2n)\n elif acviz.distance_score == 'euclidean':\n score = np.sqrt((a1n - a2n) ** 2)\n elif acviz.distance_score == 'rms':\n score = np.sqrt(((a1n - a2n) ** 2).mean())\n elif acviz.distance_score == 'pearson':\n score = ((a1n - a1n.mean()) * (a2n - a2n.mean())).mean() / (a1n.std() * a2n.std())\n\n scores.append((i, j, score))\n\n if acviz.distance_score == 'cosine' or acviz.distance_score == 'pearson':\n scores = sorted(scores, key=lambda x: x[2], reverse=True)\n else:\n scores = sorted(scores, key=lambda x: x[2])\n\n pos = 0\n while True:\n i, j, score = scores[pos]\n if (acviz.distance_score == 'cosine' or acviz.distance_score == 'pearson') and score > acviz.edge_thresh:\n G.add_edge(motif_names[i], motif_names[j], weight=score)\n elif (acviz.distance_score == 'euclidean' or acviz.distance_score == 'rms') and score > acviz.edge_thresh:\n G.add_edge(motif_names[i], motif_names[j])\n else:\n break\n pos += 1\n if pos > acviz.max_edges:\n break\n if pos >= len(scores):\n break\n\n # nx.write_gexf(G, \"network_%d.gexf\" % int(acviz_id))\n d = json_graph.node_link_data(G)\n return HttpResponse(json.dumps(d), content_type='application/json')\n\n\ndef alpha_de(request, mfe_id):\n mfe = MultiFileExperiment.objects.get(id=mfe_id)\n context_dict = {'mfe': mfe}\n links = mfe.multilink_set.all().order_by('experiment__name')\n individuals = [l.experiment for l in links]\n tu = zip(individuals, individuals)\n tu = sorted(tu, key=lambda x: x[0].name)\n if request.method == 'POST':\n form = AlphaDEForm(tu, request.POST)\n if form.is_valid():\n group1_experiments = form.cleaned_data['group1']\n group2_experiments = form.cleaned_data['group2']\n motifs = individuals[0].mass2motif_set.all().order_by('name')\n\n if mfe.alpha_matrix:\n alp_vals_with_names = jsonpickle.decode(mfe.alpha_matrix)\n alp_vals = []\n for av in alp_vals_with_names:\n newav = av[2:-1]\n alp_vals.append(newav)\n\n else:\n alp_vals = make_alpha_matrix(individuals, normalise=True)\n\n group1_index = []\n group2_index = []\n motif_scores = []\n for experiment_name in group1_experiments:\n experiment = Experiment.objects.get(name=experiment_name)\n group1_index.append(individuals.index(experiment))\n for experiment_name in group2_experiments:\n experiment = Experiment.objects.get(name=experiment_name)\n group2_index.append(individuals.index(experiment))\n for i, alp in enumerate(alp_vals):\n a = np.array(alp)\n g1 = a[group1_index]\n g2 = a[group2_index]\n de = (g1.mean() - g2.mean()) / (g1.std() + g2.std())\n t, p = ttest_ind(g1, g2, equal_var=False)\n motif_scores.append((motifs[i], de, p))\n context_dict['motif_scores'] = motif_scores\n\n\n\n else:\n context_dict['alpha_de_form'] = form\n else:\n form = AlphaDEForm(tu)\n context_dict['alpha_de_form'] = form\n return render(request, 'basicviz/alpha_de.html', context_dict)\n\n\ndef get_multifile_mass2motif_metadata(request, mf_id, motif_name):\n mfe = MultiFileExperiment.objects.get(id=mf_id)\n links = mfe.multilink_set.all().order_by('experiment__name')\n individuals = [l.experiment for l in links]\n first_experiment = individuals[0]\n mass2motif = Mass2Motif.objects.get(experiment=first_experiment, name=motif_name)\n md = jsonpickle.decode(mass2motif.metadata)\n return HttpResponse(json.dumps(md), content_type='application/json')\n\ndef get_individual_ids(request,mf_id):\n mfe = MultiFileExperiment.objects.get(id=mf_id)\n links = mfe.multilink_set.all().order_by('experiment__name')\n individuals = [l.experiment for l in links]\n output_data = [i.id for i in individuals]\n return HttpResponse(json.dumps(output_data),content_type = 'application/json') \n"
] |
[
[
"numpy.dot",
"numpy.log",
"numpy.sqrt",
"numpy.linalg.norm",
"numpy.array",
"scipy.stats.ttest_ind"
]
] |
underdogliu/audio
|
[
"38e530d77e5a194d4e5f91356cc1a191207a3b29"
] |
[
"examples/pipeline_wavernn/processing.py"
] |
[
"import torch\nimport torch.nn as nn\n\n\nclass NormalizeDB(nn.Module):\n r\"\"\"Normalize the spectrogram with a minimum db value\"\"\"\n\n def __init__(self, min_level_db, normalization):\n super().__init__()\n self.min_level_db = min_level_db\n self.normalization = normalization\n\n def forward(self, specgram):\n specgram = torch.log10(torch.clamp(specgram.squeeze(0), min=1e-5))\n if self.normalization:\n return torch.clamp((self.min_level_db - 20 * specgram) / self.min_level_db, min=0, max=1)\n return specgram\n\n\ndef normalized_waveform_to_bits(waveform: torch.Tensor, bits: int) -> torch.Tensor:\n r\"\"\"Transform waveform [-1, 1] to label [0, 2 ** bits - 1]\"\"\"\n\n assert abs(waveform).max() <= 1.0\n waveform = (waveform + 1.0) * (2**bits - 1) / 2\n return torch.clamp(waveform, 0, 2**bits - 1).int()\n\n\ndef bits_to_normalized_waveform(label: torch.Tensor, bits: int) -> torch.Tensor:\n r\"\"\"Transform label [0, 2 ** bits - 1] to waveform [-1, 1]\"\"\"\n\n return 2 * label / (2**bits - 1.0) - 1.0\n"
] |
[
[
"torch.clamp"
]
] |
msk-mind/data-processing
|
[
"282b5bd594cb5bf1ef2a7fdf56fca9bea5ad7102"
] |
[
"pyluna-pathology/luna/pathology/cli/dsa/utils.py"
] |
[
"from random import randint\n\nimport numpy as np\nfrom skimage import measure\nimport seaborn as sns\n\n\ndef get_color(name, line_colors={}, fill_colors={}, alpha = 100):\n \"\"\"Get colors for cells/regions based on discrete categories.\n\n Args:\n name (string): feature name e.g. Stroma, Tumor\n line_colors (dict, optional): line color map with {feature name:rgb values}\n fill_colors (dict, optional): fill color map with {feature name:rgba values}\n alpha (int, optional): alpha value for the fill color. 100 by default\n\n Returns:\n string: RGBA values for line and fill colors\n \"\"\"\n if name not in line_colors and name not in fill_colors:\n r = randint(0, 255)\n g = randint(0, 255)\n b = randint(0, 255)\n fill_colors[name] = \"rgba({}, {}, {}, {})\".format(r,g,b, alpha)\n line_colors[name] = \"rgb({}, {}, {})\".format(r,g,b)\n return line_colors[name], fill_colors[name]\n\n\ndef get_continuous_color(value, outline_color='same_as_fill', alpha = 100):\n \"\"\"Get RGBA line and fill colors for value.\n\n Use color palette `viridis` to set a fill value - the color ranges from purple to yellow,\n for the values from 0 to 1. This function is used in generating a heatmap.\n\n Args:\n value (float): continuous value in [0,1]\n outline_color (string, optional): manages the color used to outline the border of the annotation.\n by default, uses the same color as fill_color.\n alpha (int, optional): alpha value for the fill color. 100 by default\n\n Returns:\n string: RGBA line and fill colors\n \"\"\"\n c = sns.color_palette(\"viridis\", as_cmap=True)\n r,g,b,a = c(value, bytes=True)\n\n fill_color = \"rgba({}, {}, {}, {})\".format(r,g,b,alpha)\n if outline_color == 'same_as_fill':\n line_color = \"rgb({}, {}, {})\".format(r,g,b)\n elif outline_color == 'black':\n line_color = \"rgb({}, {}, {})\".format(0,0,0)\n elif outline_color == 'white':\n line_color = \"rgb({}, {}, {})\".format(255,255,255)\n else:\n return None,None\n return line_color, fill_color\n\n\ndef vectorize_np_array_bitmask_by_pixel_value(bitmask_np,\n label_num = 255, polygon_tolerance = 1, contour_level = .5):\n \"\"\"Get simplified contours from the bitmask\n\n Args:\n bitmask_np (np.array): a numpy bitmask\n label_num (int, optional): numeric value to filter the numpy array\n polygon_tolerance (float, optional): Maximum distance from original points of polygon\n to approximated polygonal chain. If tolerance is 0, the original coordinate array is returned.\n contour_level (float, optional): Value along which to find contours in the array.\n 0.5 by default\n\n Returns:\n list: simplified approximated contours\n \"\"\"\n mask = np.where(bitmask_np==label_num,1,0).astype(np.int8)\n contours = measure.find_contours(mask, level = contour_level)\n simplified_contours = [measure.approximate_polygon(c, tolerance=polygon_tolerance) for c in contours]\n for _, contour in enumerate(simplified_contours):\n for coord in contour:\n x = int(round(coord[0]))\n y = int(round(coord[1]))\n # switch coordinates, otherwise gets flipped\n coord[0] = y\n coord[1] = x\n\n return simplified_contours\n"
] |
[
[
"numpy.where"
]
] |
tony10101105/virtual-try-on-model
|
[
"d2cdc00ecdda3a4e40cb2a45b18c394953d7f28c"
] |
[
"utils.py"
] |
[
"import os\nimport torch\nimport torchvision\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms\nfrom torchvision.utils import save_image\nfrom torch.autograd import Variable\nfrom torch.utils.data.dataset import Dataset\nfrom PIL import Image\nimport argparse\n\n\ndef load_model(model_path, opt):\n\n Unet = models.Unet(n_channels = 3, n_classes = 3)\n Unet_checkpoint = torch.load(model_path)\n Unet_optimizer = torch.optim.Adam(Unet.parameters(), lr = opt.lr, betas = [0.5, 0.999])\n Unet_optimizer.load_state_dict(Unet_checkpoint['optimizer_state_dict'])\n Unet.load_state_dict(Unet_checkpoint['model_state_dict'])\n current_epoch = Unet_checkpoint['epoch']\n\n return Unet, Unet_optimizer, current_epoch\n\n"
] |
[
[
"torch.load"
]
] |
HouchangX-AI/Helmet-Detection
|
[
"3c8c3edaf435fbd011b41f74a3417c44f66f52b6"
] |
[
"yolo.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nClass definition of YOLO_v3 style detection model on image and video\n\"\"\"\n\nimport colorsys\nimport os\nfrom timeit import default_timer as timer\n\nimport numpy as np\nfrom keras import backend as K\nfrom keras.models import load_model\nfrom keras.layers import Input\nfrom PIL import Image, ImageFont, ImageDraw\n\nfrom yolo3.model import yolo_eval, yolo_body, tiny_yolo_body\nfrom yolo3.utils import letterbox_image\nimport os\nfrom keras.utils import multi_gpu_model\n\nclass YOLO(object):\n _defaults = {\n \"model_path\": 'trained_weights_stage_1.h5',\n \"anchors_path\": 'model_data/yolo_anchors.txt',\n \"classes_path\": 'model_data/voc_classes.txt',\n \"score\" : 0.3,\n \"iou\" : 0.45,\n \"model_image_size\" : (416, 416),\n \"gpu_num\" : 1,\n }\n\n @classmethod\n def get_defaults(cls, n):\n if n in cls._defaults:\n return cls._defaults[n]\n else:\n return \"Unrecognized attribute name '\" + n + \"'\"\n\n def __init__(self, **kwargs):\n self.__dict__.update(self._defaults) # set up default values\n self.__dict__.update(kwargs) # and update with user overrides\n self.class_names = self._get_class()\n self.anchors = self._get_anchors()\n self.sess = K.get_session()\n self.boxes, self.scores, self.classes = self.generate()\n\n def _get_class(self):\n classes_path = os.path.expanduser(self.classes_path)\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n return class_names\n\n def _get_anchors(self):\n anchors_path = os.path.expanduser(self.anchors_path)\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n return np.array(anchors).reshape(-1, 2)\n\n def generate(self):\n model_path = os.path.expanduser(self.model_path)\n assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'\n\n # Load model, or construct model and load weights.\n num_anchors = len(self.anchors)\n num_classes = len(self.class_names)\n is_tiny_version = num_anchors==6 # default setting\n try:\n self.yolo_model = load_model(model_path, compile=False)\n except:\n self.yolo_model = tiny_yolo_body(Input(shape=(None,None,3)), num_anchors//2, num_classes) \\\n if is_tiny_version else yolo_body(Input(shape=(None,None,3)), num_anchors//3, num_classes)\n self.yolo_model.load_weights(self.model_path) # make sure model, anchors and classes match\n else:\n assert self.yolo_model.layers[-1].output_shape[-1] == \\\n num_anchors/len(self.yolo_model.output) * (num_classes + 5), \\\n 'Mismatch between model and given anchor and class sizes'\n\n print('{} model, anchors, and classes loaded.'.format(model_path))\n\n # Generate colors for drawing bounding boxes.\n hsv_tuples = [(x / len(self.class_names), 1., 1.)\n for x in range(len(self.class_names))]\n self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))\n self.colors = list(\n map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),\n self.colors))\n np.random.seed(10101) # Fixed seed for consistent colors across runs.\n np.random.shuffle(self.colors) # Shuffle colors to decorrelate adjacent classes.\n np.random.seed(None) # Reset seed to default.\n\n # Generate output tensor targets for filtered bounding boxes.\n self.input_image_shape = K.placeholder(shape=(2, ))\n if self.gpu_num>=2:\n self.yolo_model = multi_gpu_model(self.yolo_model, gpus=self.gpu_num)\n boxes, scores, classes = yolo_eval(self.yolo_model.output, self.anchors,\n len(self.class_names), self.input_image_shape,\n score_threshold=self.score, iou_threshold=self.iou)\n return boxes, scores, classes\n\n def detect_image(self, image):\n start = timer()\n\n if self.model_image_size != (None, None):\n assert self.model_image_size[0]%32 == 0, 'Multiples of 32 required'\n assert self.model_image_size[1]%32 == 0, 'Multiples of 32 required'\n boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size)))\n else:\n new_image_size = (image.width - (image.width % 32),\n image.height - (image.height % 32))\n boxed_image = letterbox_image(image, new_image_size)\n image_data = np.array(boxed_image, dtype='float32')\n\n print(image_data.shape)\n image_data /= 255.\n image_data = np.expand_dims(image_data, 0) # Add batch dimension.\n\n out_boxes, out_scores, out_classes = self.sess.run(\n [self.boxes, self.scores, self.classes],\n feed_dict={\n self.yolo_model.input: image_data,\n self.input_image_shape: [image.size[1], image.size[0]],\n K.learning_phase(): 0\n })\n\n print('Found {} boxes for {}'.format(len(out_boxes), 'img'))\n\n font = ImageFont.truetype(font='font/FiraMono-Medium.otf',\n size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))\n thickness = (image.size[0] + image.size[1]) // 300\n\n for i, c in reversed(list(enumerate(out_classes))):\n predicted_class = self.class_names[c]\n box = out_boxes[i]\n score = out_scores[i]\n\n label = '{} {:.2f}'.format(predicted_class, score)\n draw = ImageDraw.Draw(image)\n label_size = draw.textsize(label, font)\n\n top, left, bottom, right = box\n top = max(0, np.floor(top + 0.5).astype('int32'))\n left = max(0, np.floor(left + 0.5).astype('int32'))\n bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))\n right = min(image.size[0], np.floor(right + 0.5).astype('int32'))\n print(label, (left, top), (right, bottom)) # 最后的标签和坐标\n\n if top - label_size[1] >= 0:\n text_origin = np.array([left, top - label_size[1]])\n else:\n text_origin = np.array([left, top + 1])\n\n # My kingdom for a good redistributable image drawing library.\n for i in range(thickness):\n draw.rectangle(\n [left + i, top + i, right - i, bottom - i],\n outline=self.colors[c])\n draw.rectangle(\n [tuple(text_origin), tuple(text_origin + label_size)],\n fill=self.colors[c])\n draw.text(text_origin, label, fill=(0, 0, 0), font=font)\n del draw\n\n end = timer()\n print('time:', end - start)\n return image\n\n def close_session(self):\n self.sess.close()\n\ndef detect_video(yolo, video_path, output_path=\"\"):\n import cv2\n vid = cv2.VideoCapture(video_path)\n if not vid.isOpened():\n raise IOError(\"Couldn't open webcam or video\")\n video_FourCC = int(vid.get(cv2.CAP_PROP_FOURCC))\n video_fps = vid.get(cv2.CAP_PROP_FPS)\n video_size = (int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)),\n int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n isOutput = True if output_path != \"\" else False\n if isOutput:\n print(\"!!! TYPE:\", type(output_path), type(video_FourCC), type(video_fps), type(video_size))\n out = cv2.VideoWriter(output_path, video_FourCC, video_fps, video_size)\n accum_time = 0\n curr_fps = 0\n fps = \"FPS: ??\"\n prev_time = timer()\n while True:\n return_value, frame = vid.read()\n image = Image.fromarray(frame)\n image = yolo.detect_image(image)\n result = np.asarray(image)\n curr_time = timer()\n exec_time = curr_time - prev_time\n prev_time = curr_time\n accum_time = accum_time + exec_time\n curr_fps = curr_fps + 1\n if accum_time > 1:\n accum_time = accum_time - 1\n fps = \"FPS: \" + str(curr_fps)\n curr_fps = 0\n cv2.putText(result, text=fps, org=(3, 15), fontFace=cv2.FONT_HERSHEY_SIMPLEX,\n fontScale=0.50, color=(255, 0, 0), thickness=2)\n cv2.namedWindow(\"result\", cv2.WINDOW_NORMAL)\n cv2.imshow(\"result\", result)\n if isOutput:\n out.write(result)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n yolo.close_session()\n\n"
] |
[
[
"numpy.expand_dims",
"numpy.random.seed",
"numpy.asarray",
"numpy.random.shuffle",
"numpy.floor",
"numpy.array"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.